VirtualBox

source: vbox/trunk/src/libs/curl-7.83.1/lib/hostip.c@ 97122

最後變更 在這個檔案從97122是 95312,由 vboxsync 提交於 3 年 前

libs/{curl,libxml2}: OSE export fixes, bugref:8515

  • 屬性 svn:eol-style 設為 native
檔案大小: 37.7 KB
 
1/***************************************************************************
2 * _ _ ____ _
3 * Project ___| | | | _ \| |
4 * / __| | | | |_) | |
5 * | (__| |_| | _ <| |___
6 * \___|\___/|_| \_\_____|
7 *
8 * Copyright (C) 1998 - 2022, Daniel Stenberg, <[email protected]>, 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 ***************************************************************************/
22
23#include "curl_setup.h"
24
25#ifdef HAVE_NETINET_IN_H
26#include <netinet/in.h>
27#endif
28#ifdef HAVE_NETINET_IN6_H
29#include <netinet/in6.h>
30#endif
31#ifdef HAVE_NETDB_H
32#include <netdb.h>
33#endif
34#ifdef HAVE_ARPA_INET_H
35#include <arpa/inet.h>
36#endif
37#ifdef __VMS
38#include <in.h>
39#include <inet.h>
40#endif
41
42#ifdef HAVE_SETJMP_H
43#include <setjmp.h>
44#endif
45#ifdef HAVE_SIGNAL_H
46#include <signal.h>
47#endif
48
49#ifdef HAVE_PROCESS_H
50#include <process.h>
51#endif
52
53#include "urldata.h"
54#include "sendf.h"
55#include "hostip.h"
56#include "hash.h"
57#include "rand.h"
58#include "share.h"
59#include "url.h"
60#include "inet_ntop.h"
61#include "inet_pton.h"
62#include "multiif.h"
63#include "doh.h"
64#include "warnless.h"
65#include "strcase.h"
66/* The last 3 #include files should be in this order */
67#include "curl_printf.h"
68#include "curl_memory.h"
69#include "memdebug.h"
70
71#if defined(ENABLE_IPV6) && defined(CURL_OSX_CALL_COPYPROXIES)
72#include <SystemConfiguration/SCDynamicStoreCopySpecific.h>
73#endif
74
75#if defined(CURLRES_SYNCH) && \
76 defined(HAVE_ALARM) && defined(SIGALRM) && defined(HAVE_SIGSETJMP)
77/* alarm-based timeouts can only be used with all the dependencies satisfied */
78#define USE_ALARM_TIMEOUT
79#endif
80
81#define MAX_HOSTCACHE_LEN (255 + 7) /* max FQDN + colon + port number + zero */
82
83/*
84 * hostip.c explained
85 * ==================
86 *
87 * The main COMPILE-TIME DEFINES to keep in mind when reading the host*.c
88 * source file are these:
89 *
90 * CURLRES_IPV6 - this host has getaddrinfo() and family, and thus we use
91 * that. The host may not be able to resolve IPv6, but we don't really have to
92 * take that into account. Hosts that aren't IPv6-enabled have CURLRES_IPV4
93 * defined.
94 *
95 * CURLRES_ARES - is defined if libcurl is built to use c-ares for
96 * asynchronous name resolves. This can be Windows or *nix.
97 *
98 * CURLRES_THREADED - is defined if libcurl is built to run under (native)
99 * Windows, and then the name resolve will be done in a new thread, and the
100 * supported API will be the same as for ares-builds.
101 *
102 * If any of the two previous are defined, CURLRES_ASYNCH is defined too. If
103 * libcurl is not built to use an asynchronous resolver, CURLRES_SYNCH is
104 * defined.
105 *
106 * The host*.c sources files are split up like this:
107 *
108 * hostip.c - method-independent resolver functions and utility functions
109 * hostasyn.c - functions for asynchronous name resolves
110 * hostsyn.c - functions for synchronous name resolves
111 * hostip4.c - IPv4 specific functions
112 * hostip6.c - IPv6 specific functions
113 *
114 * The two asynchronous name resolver backends are implemented in:
115 * asyn-ares.c - functions for ares-using name resolves
116 * asyn-thread.c - functions for threaded name resolves
117
118 * The hostip.h is the united header file for all this. It defines the
119 * CURLRES_* defines based on the config*.h and curl_setup.h defines.
120 */
121
122static void freednsentry(void *freethis);
123
124/*
125 * Return # of addresses in a Curl_addrinfo struct
126 */
127int Curl_num_addresses(const struct Curl_addrinfo *addr)
128{
129 int i = 0;
130 while(addr) {
131 addr = addr->ai_next;
132 i++;
133 }
134 return i;
135}
136
137/*
138 * Curl_printable_address() stores a printable version of the 1st address
139 * given in the 'ai' argument. The result will be stored in the buf that is
140 * bufsize bytes big.
141 *
142 * If the conversion fails, the target buffer is empty.
143 */
144void Curl_printable_address(const struct Curl_addrinfo *ai, char *buf,
145 size_t bufsize)
146{
147 DEBUGASSERT(bufsize);
148 buf[0] = 0;
149
150 switch(ai->ai_family) {
151 case AF_INET: {
152 const struct sockaddr_in *sa4 = (const void *)ai->ai_addr;
153 const struct in_addr *ipaddr4 = &sa4->sin_addr;
154 (void)Curl_inet_ntop(ai->ai_family, (const void *)ipaddr4, buf, bufsize);
155 break;
156 }
157#ifdef ENABLE_IPV6
158 case AF_INET6: {
159 const struct sockaddr_in6 *sa6 = (const void *)ai->ai_addr;
160 const struct in6_addr *ipaddr6 = &sa6->sin6_addr;
161 (void)Curl_inet_ntop(ai->ai_family, (const void *)ipaddr6, buf, bufsize);
162 break;
163 }
164#endif
165 default:
166 break;
167 }
168}
169
170/*
171 * Create a hostcache id string for the provided host + port, to be used by
172 * the DNS caching. Without alloc.
173 */
174static void
175create_hostcache_id(const char *name, int port, char *ptr, size_t buflen)
176{
177 size_t len = strlen(name);
178 if(len > (buflen - 7))
179 len = buflen - 7;
180 /* store and lower case the name */
181 while(len--)
182 *ptr++ = (char)TOLOWER(*name++);
183 msnprintf(ptr, 7, ":%u", port);
184}
185
186struct hostcache_prune_data {
187 long cache_timeout;
188 time_t now;
189};
190
191/*
192 * This function is set as a callback to be called for every entry in the DNS
193 * cache when we want to prune old unused entries.
194 *
195 * Returning non-zero means remove the entry, return 0 to keep it in the
196 * cache.
197 */
198static int
199hostcache_timestamp_remove(void *datap, void *hc)
200{
201 struct hostcache_prune_data *data =
202 (struct hostcache_prune_data *) datap;
203 struct Curl_dns_entry *c = (struct Curl_dns_entry *) hc;
204
205 return (0 != c->timestamp)
206 && (data->now - c->timestamp >= data->cache_timeout);
207}
208
209/*
210 * Prune the DNS cache. This assumes that a lock has already been taken.
211 */
212static void
213hostcache_prune(struct Curl_hash *hostcache, long cache_timeout, time_t now)
214{
215 struct hostcache_prune_data user;
216
217 user.cache_timeout = cache_timeout;
218 user.now = now;
219
220 Curl_hash_clean_with_criterium(hostcache,
221 (void *) &user,
222 hostcache_timestamp_remove);
223}
224
225/*
226 * Library-wide function for pruning the DNS cache. This function takes and
227 * returns the appropriate locks.
228 */
229void Curl_hostcache_prune(struct Curl_easy *data)
230{
231 time_t now;
232
233 if((data->set.dns_cache_timeout == -1) || !data->dns.hostcache)
234 /* cache forever means never prune, and NULL hostcache means
235 we can't do it */
236 return;
237
238 if(data->share)
239 Curl_share_lock(data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE);
240
241 time(&now);
242
243 /* Remove outdated and unused entries from the hostcache */
244 hostcache_prune(data->dns.hostcache,
245 data->set.dns_cache_timeout,
246 now);
247
248 if(data->share)
249 Curl_share_unlock(data, CURL_LOCK_DATA_DNS);
250}
251
252#ifdef HAVE_SIGSETJMP
253/* Beware this is a global and unique instance. This is used to store the
254 return address that we can jump back to from inside a signal handler. This
255 is not thread-safe stuff. */
256sigjmp_buf curl_jmpenv;
257#endif
258
259/* lookup address, returns entry if found and not stale */
260static struct Curl_dns_entry *fetch_addr(struct Curl_easy *data,
261 const char *hostname,
262 int port)
263{
264 struct Curl_dns_entry *dns = NULL;
265 size_t entry_len;
266 char entry_id[MAX_HOSTCACHE_LEN];
267
268 /* Create an entry id, based upon the hostname and port */
269 create_hostcache_id(hostname, port, entry_id, sizeof(entry_id));
270 entry_len = strlen(entry_id);
271
272 /* See if its already in our dns cache */
273 dns = Curl_hash_pick(data->dns.hostcache, entry_id, entry_len + 1);
274
275 /* No entry found in cache, check if we might have a wildcard entry */
276 if(!dns && data->state.wildcard_resolve) {
277 create_hostcache_id("*", port, entry_id, sizeof(entry_id));
278 entry_len = strlen(entry_id);
279
280 /* See if it's already in our dns cache */
281 dns = Curl_hash_pick(data->dns.hostcache, entry_id, entry_len + 1);
282 }
283
284 if(dns && (data->set.dns_cache_timeout != -1)) {
285 /* See whether the returned entry is stale. Done before we release lock */
286 struct hostcache_prune_data user;
287
288 time(&user.now);
289 user.cache_timeout = data->set.dns_cache_timeout;
290
291 if(hostcache_timestamp_remove(&user, dns)) {
292 infof(data, "Hostname in DNS cache was stale, zapped");
293 dns = NULL; /* the memory deallocation is being handled by the hash */
294 Curl_hash_delete(data->dns.hostcache, entry_id, entry_len + 1);
295 }
296 }
297
298 return dns;
299}
300
301/*
302 * Curl_fetch_addr() fetches a 'Curl_dns_entry' already in the DNS cache.
303 *
304 * Curl_resolv() checks initially and multi_runsingle() checks each time
305 * it discovers the handle in the state WAITRESOLVE whether the hostname
306 * has already been resolved and the address has already been stored in
307 * the DNS cache. This short circuits waiting for a lot of pending
308 * lookups for the same hostname requested by different handles.
309 *
310 * Returns the Curl_dns_entry entry pointer or NULL if not in the cache.
311 *
312 * The returned data *MUST* be "unlocked" with Curl_resolv_unlock() after
313 * use, or we'll leak memory!
314 */
315struct Curl_dns_entry *
316Curl_fetch_addr(struct Curl_easy *data,
317 const char *hostname,
318 int port)
319{
320 struct Curl_dns_entry *dns = NULL;
321
322 if(data->share)
323 Curl_share_lock(data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE);
324
325 dns = fetch_addr(data, hostname, port);
326
327 if(dns)
328 dns->inuse++; /* we use it! */
329
330 if(data->share)
331 Curl_share_unlock(data, CURL_LOCK_DATA_DNS);
332
333 return dns;
334}
335
336#ifndef CURL_DISABLE_SHUFFLE_DNS
337UNITTEST CURLcode Curl_shuffle_addr(struct Curl_easy *data,
338 struct Curl_addrinfo **addr);
339/*
340 * Curl_shuffle_addr() shuffles the order of addresses in a 'Curl_addrinfo'
341 * struct by re-linking its linked list.
342 *
343 * The addr argument should be the address of a pointer to the head node of a
344 * `Curl_addrinfo` list and it will be modified to point to the new head after
345 * shuffling.
346 *
347 * Not declared static only to make it easy to use in a unit test!
348 *
349 * @unittest: 1608
350 */
351UNITTEST CURLcode Curl_shuffle_addr(struct Curl_easy *data,
352 struct Curl_addrinfo **addr)
353{
354 CURLcode result = CURLE_OK;
355 const int num_addrs = Curl_num_addresses(*addr);
356
357 if(num_addrs > 1) {
358 struct Curl_addrinfo **nodes;
359 infof(data, "Shuffling %i addresses", num_addrs);
360
361 nodes = malloc(num_addrs*sizeof(*nodes));
362 if(nodes) {
363 int i;
364 unsigned int *rnd;
365 const size_t rnd_size = num_addrs * sizeof(*rnd);
366
367 /* build a plain array of Curl_addrinfo pointers */
368 nodes[0] = *addr;
369 for(i = 1; i < num_addrs; i++) {
370 nodes[i] = nodes[i-1]->ai_next;
371 }
372
373 rnd = malloc(rnd_size);
374 if(rnd) {
375 /* Fisher-Yates shuffle */
376 if(Curl_rand(data, (unsigned char *)rnd, rnd_size) == CURLE_OK) {
377 struct Curl_addrinfo *swap_tmp;
378 for(i = num_addrs - 1; i > 0; i--) {
379 swap_tmp = nodes[rnd[i] % (i + 1)];
380 nodes[rnd[i] % (i + 1)] = nodes[i];
381 nodes[i] = swap_tmp;
382 }
383
384 /* relink list in the new order */
385 for(i = 1; i < num_addrs; i++) {
386 nodes[i-1]->ai_next = nodes[i];
387 }
388
389 nodes[num_addrs-1]->ai_next = NULL;
390 *addr = nodes[0];
391 }
392 free(rnd);
393 }
394 else
395 result = CURLE_OUT_OF_MEMORY;
396 free(nodes);
397 }
398 else
399 result = CURLE_OUT_OF_MEMORY;
400 }
401 return result;
402}
403#endif
404
405/*
406 * Curl_cache_addr() stores a 'Curl_addrinfo' struct in the DNS cache.
407 *
408 * When calling Curl_resolv() has resulted in a response with a returned
409 * address, we call this function to store the information in the dns
410 * cache etc
411 *
412 * Returns the Curl_dns_entry entry pointer or NULL if the storage failed.
413 */
414struct Curl_dns_entry *
415Curl_cache_addr(struct Curl_easy *data,
416 struct Curl_addrinfo *addr,
417 const char *hostname,
418 int port)
419{
420 char entry_id[MAX_HOSTCACHE_LEN];
421 size_t entry_len;
422 struct Curl_dns_entry *dns;
423 struct Curl_dns_entry *dns2;
424
425#ifndef CURL_DISABLE_SHUFFLE_DNS
426 /* shuffle addresses if requested */
427 if(data->set.dns_shuffle_addresses) {
428 CURLcode result = Curl_shuffle_addr(data, &addr);
429 if(result)
430 return NULL;
431 }
432#endif
433
434 /* Create a new cache entry */
435 dns = calloc(1, sizeof(struct Curl_dns_entry));
436 if(!dns) {
437 return NULL;
438 }
439
440 /* Create an entry id, based upon the hostname and port */
441 create_hostcache_id(hostname, port, entry_id, sizeof(entry_id));
442 entry_len = strlen(entry_id);
443
444 dns->inuse = 1; /* the cache has the first reference */
445 dns->addr = addr; /* this is the address(es) */
446 time(&dns->timestamp);
447 if(dns->timestamp == 0)
448 dns->timestamp = 1; /* zero indicates permanent CURLOPT_RESOLVE entry */
449
450 /* Store the resolved data in our DNS cache. */
451 dns2 = Curl_hash_add(data->dns.hostcache, entry_id, entry_len + 1,
452 (void *)dns);
453 if(!dns2) {
454 free(dns);
455 return NULL;
456 }
457
458 dns = dns2;
459 dns->inuse++; /* mark entry as in-use */
460 return dns;
461}
462
463#ifdef ENABLE_IPV6
464/* return a static IPv6 resolve for 'localhost' */
465static struct Curl_addrinfo *get_localhost6(int port)
466{
467 struct Curl_addrinfo *ca;
468 const size_t ss_size = sizeof(struct sockaddr_in6);
469 const size_t hostlen = strlen("localhost");
470 struct sockaddr_in6 sa6;
471 unsigned char ipv6[16];
472 unsigned short port16 = (unsigned short)(port & 0xffff);
473 ca = calloc(sizeof(struct Curl_addrinfo) + ss_size + hostlen + 1, 1);
474 if(!ca)
475 return NULL;
476
477 sa6.sin6_family = AF_INET6;
478 sa6.sin6_port = htons(port16);
479 sa6.sin6_flowinfo = 0;
480 sa6.sin6_scope_id = 0;
481 if(Curl_inet_pton(AF_INET6, "::1", ipv6) < 1)
482 return NULL;
483 memcpy(&sa6.sin6_addr, ipv6, sizeof(ipv6));
484
485 ca->ai_flags = 0;
486 ca->ai_family = AF_INET6;
487 ca->ai_socktype = SOCK_STREAM;
488 ca->ai_protocol = IPPROTO_TCP;
489 ca->ai_addrlen = (curl_socklen_t)ss_size;
490 ca->ai_next = NULL;
491 ca->ai_addr = (void *)((char *)ca + sizeof(struct Curl_addrinfo));
492 memcpy(ca->ai_addr, &sa6, ss_size);
493 ca->ai_canonname = (char *)ca->ai_addr + ss_size;
494 strcpy(ca->ai_canonname, "localhost");
495 return ca;
496}
497#else
498#define get_localhost6(x) NULL
499#endif
500
501/* return a static IPv4 resolve for 'localhost' */
502static struct Curl_addrinfo *get_localhost(int port)
503{
504 struct Curl_addrinfo *ca;
505 const size_t ss_size = sizeof(struct sockaddr_in);
506 const size_t hostlen = strlen("localhost");
507 struct sockaddr_in sa;
508 unsigned int ipv4;
509 unsigned short port16 = (unsigned short)(port & 0xffff);
510
511 /* memset to clear the sa.sin_zero field */
512 memset(&sa, 0, sizeof(sa));
513 sa.sin_family = AF_INET;
514 sa.sin_port = htons(port16);
515 if(Curl_inet_pton(AF_INET, "127.0.0.1", (char *)&ipv4) < 1)
516 return NULL;
517 memcpy(&sa.sin_addr, &ipv4, sizeof(ipv4));
518
519 ca = calloc(sizeof(struct Curl_addrinfo) + ss_size + hostlen + 1, 1);
520 if(!ca)
521 return NULL;
522 ca->ai_flags = 0;
523 ca->ai_family = AF_INET;
524 ca->ai_socktype = SOCK_STREAM;
525 ca->ai_protocol = IPPROTO_TCP;
526 ca->ai_addrlen = (curl_socklen_t)ss_size;
527 ca->ai_addr = (void *)((char *)ca + sizeof(struct Curl_addrinfo));
528 memcpy(ca->ai_addr, &sa, ss_size);
529 ca->ai_canonname = (char *)ca->ai_addr + ss_size;
530 strcpy(ca->ai_canonname, "localhost");
531 ca->ai_next = get_localhost6(port);
532 return ca;
533}
534
535#ifdef ENABLE_IPV6
536/*
537 * Curl_ipv6works() returns TRUE if IPv6 seems to work.
538 */
539bool Curl_ipv6works(struct Curl_easy *data)
540{
541 if(data) {
542 /* the nature of most system is that IPv6 status doesn't come and go
543 during a program's lifetime so we only probe the first time and then we
544 have the info kept for fast re-use */
545 DEBUGASSERT(data);
546 DEBUGASSERT(data->multi);
547 return data->multi->ipv6_works;
548 }
549 else {
550 int ipv6_works = -1;
551 /* probe to see if we have a working IPv6 stack */
552 curl_socket_t s = socket(PF_INET6, SOCK_DGRAM, 0);
553 if(s == CURL_SOCKET_BAD)
554 /* an IPv6 address was requested but we can't get/use one */
555 ipv6_works = 0;
556 else {
557 ipv6_works = 1;
558 sclose(s);
559 }
560 return (ipv6_works>0)?TRUE:FALSE;
561 }
562}
563#endif /* ENABLE_IPV6 */
564
565/*
566 * Curl_host_is_ipnum() returns TRUE if the given string is a numerical IPv4
567 * (or IPv6 if supported) address.
568 */
569bool Curl_host_is_ipnum(const char *hostname)
570{
571 struct in_addr in;
572#ifdef ENABLE_IPV6
573 struct in6_addr in6;
574#endif
575 if(Curl_inet_pton(AF_INET, hostname, &in) > 0
576#ifdef ENABLE_IPV6
577 || Curl_inet_pton(AF_INET6, hostname, &in6) > 0
578#endif
579 )
580 return TRUE;
581 return FALSE;
582}
583
584/*
585 * Curl_resolv() is the main name resolve function within libcurl. It resolves
586 * a name and returns a pointer to the entry in the 'entry' argument (if one
587 * is provided). This function might return immediately if we're using asynch
588 * resolves. See the return codes.
589 *
590 * The cache entry we return will get its 'inuse' counter increased when this
591 * function is used. You MUST call Curl_resolv_unlock() later (when you're
592 * done using this struct) to decrease the counter again.
593 *
594 * Return codes:
595 *
596 * CURLRESOLV_ERROR (-1) = error, no pointer
597 * CURLRESOLV_RESOLVED (0) = OK, pointer provided
598 * CURLRESOLV_PENDING (1) = waiting for response, no pointer
599 */
600
601enum resolve_t Curl_resolv(struct Curl_easy *data,
602 const char *hostname,
603 int port,
604 bool allowDOH,
605 struct Curl_dns_entry **entry)
606{
607 struct Curl_dns_entry *dns = NULL;
608 CURLcode result;
609 enum resolve_t rc = CURLRESOLV_ERROR; /* default to failure */
610 struct connectdata *conn = data->conn;
611 *entry = NULL;
612#ifndef CURL_DISABLE_DOH
613 conn->bits.doh = FALSE; /* default is not */
614#else
615 (void)allowDOH;
616#endif
617
618 if(data->share)
619 Curl_share_lock(data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE);
620
621 dns = fetch_addr(data, hostname, port);
622
623 if(dns) {
624 infof(data, "Hostname %s was found in DNS cache", hostname);
625 dns->inuse++; /* we use it! */
626 rc = CURLRESOLV_RESOLVED;
627 }
628
629 if(data->share)
630 Curl_share_unlock(data, CURL_LOCK_DATA_DNS);
631
632 if(!dns) {
633 /* The entry was not in the cache. Resolve it to IP address */
634
635 struct Curl_addrinfo *addr = NULL;
636 int respwait = 0;
637#if !defined(CURL_DISABLE_DOH) || !defined(USE_RESOLVE_ON_IPS)
638 struct in_addr in;
639#endif
640#ifndef CURL_DISABLE_DOH
641#ifndef USE_RESOLVE_ON_IPS
642 const
643#endif
644 bool ipnum = FALSE;
645#endif
646
647 /* notify the resolver start callback */
648 if(data->set.resolver_start) {
649 int st;
650 Curl_set_in_callback(data, true);
651 st = data->set.resolver_start(
652#ifdef USE_CURL_ASYNC
653 data->state.async.resolver,
654#else
655 NULL,
656#endif
657 NULL,
658 data->set.resolver_start_client);
659 Curl_set_in_callback(data, false);
660 if(st)
661 return CURLRESOLV_ERROR;
662 }
663
664#if defined(ENABLE_IPV6) && defined(CURL_OSX_CALL_COPYPROXIES)
665 {
666 /*
667 * The automagic conversion from IPv4 literals to IPv6 literals only
668 * works if the SCDynamicStoreCopyProxies system function gets called
669 * first. As Curl currently doesn't support system-wide HTTP proxies, we
670 * therefore don't use any value this function might return.
671 *
672 * This function is only available on a macOS and is not needed for
673 * IPv4-only builds, hence the conditions above.
674 */
675 CFDictionaryRef dict = SCDynamicStoreCopyProxies(NULL);
676 if(dict)
677 CFRelease(dict);
678 }
679#endif
680
681#ifndef USE_RESOLVE_ON_IPS
682 /* First check if this is an IPv4 address string */
683 if(Curl_inet_pton(AF_INET, hostname, &in) > 0)
684 /* This is a dotted IP address 123.123.123.123-style */
685 addr = Curl_ip2addr(AF_INET, &in, hostname, port);
686#ifdef ENABLE_IPV6
687 if(!addr) {
688 struct in6_addr in6;
689 /* check if this is an IPv6 address string */
690 if(Curl_inet_pton(AF_INET6, hostname, &in6) > 0)
691 /* This is an IPv6 address literal */
692 addr = Curl_ip2addr(AF_INET6, &in6, hostname, port);
693 }
694#endif /* ENABLE_IPV6 */
695
696#else /* if USE_RESOLVE_ON_IPS */
697#ifndef CURL_DISABLE_DOH
698 /* First check if this is an IPv4 address string */
699 if(Curl_inet_pton(AF_INET, hostname, &in) > 0)
700 /* This is a dotted IP address 123.123.123.123-style */
701 ipnum = TRUE;
702#ifdef ENABLE_IPV6
703 else {
704 struct in6_addr in6;
705 /* check if this is an IPv6 address string */
706 if(Curl_inet_pton(AF_INET6, hostname, &in6) > 0)
707 /* This is an IPv6 address literal */
708 ipnum = TRUE;
709 }
710#endif /* ENABLE_IPV6 */
711#endif /* CURL_DISABLE_DOH */
712
713#endif /* !USE_RESOLVE_ON_IPS */
714
715 if(!addr) {
716 if(conn->ip_version == CURL_IPRESOLVE_V6 && !Curl_ipv6works(data))
717 return CURLRESOLV_ERROR;
718
719 if(strcasecompare(hostname, "localhost"))
720 addr = get_localhost(port);
721#ifndef CURL_DISABLE_DOH
722 else if(allowDOH && data->set.doh && !ipnum)
723 addr = Curl_doh(data, hostname, port, &respwait);
724#endif
725 else {
726 /* Check what IP specifics the app has requested and if we can provide
727 * it. If not, bail out. */
728 if(!Curl_ipvalid(data, conn))
729 return CURLRESOLV_ERROR;
730 /* If Curl_getaddrinfo() returns NULL, 'respwait' might be set to a
731 non-zero value indicating that we need to wait for the response to
732 the resolve call */
733 addr = Curl_getaddrinfo(data, hostname, port, &respwait);
734 }
735 }
736 if(!addr) {
737 if(respwait) {
738 /* the response to our resolve call will come asynchronously at
739 a later time, good or bad */
740 /* First, check that we haven't received the info by now */
741 result = Curl_resolv_check(data, &dns);
742 if(result) /* error detected */
743 return CURLRESOLV_ERROR;
744 if(dns)
745 rc = CURLRESOLV_RESOLVED; /* pointer provided */
746 else
747 rc = CURLRESOLV_PENDING; /* no info yet */
748 }
749 }
750 else {
751 if(data->share)
752 Curl_share_lock(data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE);
753
754 /* we got a response, store it in the cache */
755 dns = Curl_cache_addr(data, addr, hostname, port);
756
757 if(data->share)
758 Curl_share_unlock(data, CURL_LOCK_DATA_DNS);
759
760 if(!dns)
761 /* returned failure, bail out nicely */
762 Curl_freeaddrinfo(addr);
763 else
764 rc = CURLRESOLV_RESOLVED;
765 }
766 }
767
768 *entry = dns;
769
770 return rc;
771}
772
773#ifdef USE_ALARM_TIMEOUT
774/*
775 * This signal handler jumps back into the main libcurl code and continues
776 * execution. This effectively causes the remainder of the application to run
777 * within a signal handler which is nonportable and could lead to problems.
778 */
779static
780void alarmfunc(int sig)
781{
782 /* this is for "-ansi -Wall -pedantic" to stop complaining! (rabe) */
783 (void)sig;
784 siglongjmp(curl_jmpenv, 1);
785}
786#endif /* USE_ALARM_TIMEOUT */
787
788/*
789 * Curl_resolv_timeout() is the same as Curl_resolv() but specifies a
790 * timeout. This function might return immediately if we're using asynch
791 * resolves. See the return codes.
792 *
793 * The cache entry we return will get its 'inuse' counter increased when this
794 * function is used. You MUST call Curl_resolv_unlock() later (when you're
795 * done using this struct) to decrease the counter again.
796 *
797 * If built with a synchronous resolver and use of signals is not
798 * disabled by the application, then a nonzero timeout will cause a
799 * timeout after the specified number of milliseconds. Otherwise, timeout
800 * is ignored.
801 *
802 * Return codes:
803 *
804 * CURLRESOLV_TIMEDOUT(-2) = warning, time too short or previous alarm expired
805 * CURLRESOLV_ERROR (-1) = error, no pointer
806 * CURLRESOLV_RESOLVED (0) = OK, pointer provided
807 * CURLRESOLV_PENDING (1) = waiting for response, no pointer
808 */
809
810enum resolve_t Curl_resolv_timeout(struct Curl_easy *data,
811 const char *hostname,
812 int port,
813 struct Curl_dns_entry **entry,
814 timediff_t timeoutms)
815{
816#ifdef USE_ALARM_TIMEOUT
817#ifdef HAVE_SIGACTION
818 struct sigaction keep_sigact; /* store the old struct here */
819 volatile bool keep_copysig = FALSE; /* whether old sigact has been saved */
820 struct sigaction sigact;
821#else
822#ifdef HAVE_SIGNAL
823 void (*keep_sigact)(int); /* store the old handler here */
824#endif /* HAVE_SIGNAL */
825#endif /* HAVE_SIGACTION */
826 volatile long timeout;
827 volatile unsigned int prev_alarm = 0;
828#endif /* USE_ALARM_TIMEOUT */
829 enum resolve_t rc;
830
831 *entry = NULL;
832
833 if(timeoutms < 0)
834 /* got an already expired timeout */
835 return CURLRESOLV_TIMEDOUT;
836
837#ifdef USE_ALARM_TIMEOUT
838 if(data->set.no_signal)
839 /* Ignore the timeout when signals are disabled */
840 timeout = 0;
841 else
842 timeout = (timeoutms > LONG_MAX) ? LONG_MAX : (long)timeoutms;
843
844 if(!timeout)
845 /* USE_ALARM_TIMEOUT defined, but no timeout actually requested */
846 return Curl_resolv(data, hostname, port, TRUE, entry);
847
848 if(timeout < 1000) {
849 /* The alarm() function only provides integer second resolution, so if
850 we want to wait less than one second we must bail out already now. */
851 failf(data,
852 "remaining timeout of %ld too small to resolve via SIGALRM method",
853 timeout);
854 return CURLRESOLV_TIMEDOUT;
855 }
856 /* This allows us to time-out from the name resolver, as the timeout
857 will generate a signal and we will siglongjmp() from that here.
858 This technique has problems (see alarmfunc).
859 This should be the last thing we do before calling Curl_resolv(),
860 as otherwise we'd have to worry about variables that get modified
861 before we invoke Curl_resolv() (and thus use "volatile"). */
862 if(sigsetjmp(curl_jmpenv, 1)) {
863 /* this is coming from a siglongjmp() after an alarm signal */
864 failf(data, "name lookup timed out");
865 rc = CURLRESOLV_ERROR;
866 goto clean_up;
867 }
868 else {
869 /*************************************************************
870 * Set signal handler to catch SIGALRM
871 * Store the old value to be able to set it back later!
872 *************************************************************/
873#ifdef HAVE_SIGACTION
874 sigaction(SIGALRM, NULL, &sigact);
875 keep_sigact = sigact;
876 keep_copysig = TRUE; /* yes, we have a copy */
877 sigact.sa_handler = alarmfunc;
878#ifdef SA_RESTART
879 /* HPUX doesn't have SA_RESTART but defaults to that behavior! */
880 sigact.sa_flags &= ~SA_RESTART;
881#endif
882 /* now set the new struct */
883 sigaction(SIGALRM, &sigact, NULL);
884#else /* HAVE_SIGACTION */
885 /* no sigaction(), revert to the much lamer signal() */
886#ifdef HAVE_SIGNAL
887 keep_sigact = signal(SIGALRM, alarmfunc);
888#endif
889#endif /* HAVE_SIGACTION */
890
891 /* alarm() makes a signal get sent when the timeout fires off, and that
892 will abort system calls */
893 prev_alarm = alarm(curlx_sltoui(timeout/1000L));
894 }
895
896#else
897#ifndef CURLRES_ASYNCH
898 if(timeoutms)
899 infof(data, "timeout on name lookup is not supported");
900#else
901 (void)timeoutms; /* timeoutms not used with an async resolver */
902#endif
903#endif /* USE_ALARM_TIMEOUT */
904
905 /* Perform the actual name resolution. This might be interrupted by an
906 * alarm if it takes too long.
907 */
908 rc = Curl_resolv(data, hostname, port, TRUE, entry);
909
910#ifdef USE_ALARM_TIMEOUT
911clean_up:
912
913 if(!prev_alarm)
914 /* deactivate a possibly active alarm before uninstalling the handler */
915 alarm(0);
916
917#ifdef HAVE_SIGACTION
918 if(keep_copysig) {
919 /* we got a struct as it looked before, now put that one back nice
920 and clean */
921 sigaction(SIGALRM, &keep_sigact, NULL); /* put it back */
922 }
923#else
924#ifdef HAVE_SIGNAL
925 /* restore the previous SIGALRM handler */
926 signal(SIGALRM, keep_sigact);
927#endif
928#endif /* HAVE_SIGACTION */
929
930 /* switch back the alarm() to either zero or to what it was before minus
931 the time we spent until now! */
932 if(prev_alarm) {
933 /* there was an alarm() set before us, now put it back */
934 timediff_t elapsed_secs = Curl_timediff(Curl_now(),
935 data->conn->created) / 1000;
936
937 /* the alarm period is counted in even number of seconds */
938 unsigned long alarm_set = (unsigned long)(prev_alarm - elapsed_secs);
939
940 if(!alarm_set ||
941 ((alarm_set >= 0x80000000) && (prev_alarm < 0x80000000)) ) {
942 /* if the alarm time-left reached zero or turned "negative" (counted
943 with unsigned values), we should fire off a SIGALRM here, but we
944 won't, and zero would be to switch it off so we never set it to
945 less than 1! */
946 alarm(1);
947 rc = CURLRESOLV_TIMEDOUT;
948 failf(data, "Previous alarm fired off");
949 }
950 else
951 alarm((unsigned int)alarm_set);
952 }
953#endif /* USE_ALARM_TIMEOUT */
954
955 return rc;
956}
957
958/*
959 * Curl_resolv_unlock() unlocks the given cached DNS entry. When this has been
960 * made, the struct may be destroyed due to pruning. It is important that only
961 * one unlock is made for each Curl_resolv() call.
962 *
963 * May be called with 'data' == NULL for global cache.
964 */
965void Curl_resolv_unlock(struct Curl_easy *data, struct Curl_dns_entry *dns)
966{
967 if(data && data->share)
968 Curl_share_lock(data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE);
969
970 freednsentry(dns);
971
972 if(data && data->share)
973 Curl_share_unlock(data, CURL_LOCK_DATA_DNS);
974}
975
976/*
977 * File-internal: release cache dns entry reference, free if inuse drops to 0
978 */
979static void freednsentry(void *freethis)
980{
981 struct Curl_dns_entry *dns = (struct Curl_dns_entry *) freethis;
982 DEBUGASSERT(dns && (dns->inuse>0));
983
984 dns->inuse--;
985 if(dns->inuse == 0) {
986 Curl_freeaddrinfo(dns->addr);
987 free(dns);
988 }
989}
990
991/*
992 * Curl_init_dnscache() inits a new DNS cache.
993 */
994void Curl_init_dnscache(struct Curl_hash *hash)
995{
996 Curl_hash_init(hash, 7, Curl_hash_str, Curl_str_key_compare,
997 freednsentry);
998}
999
1000/*
1001 * Curl_hostcache_clean()
1002 *
1003 * This _can_ be called with 'data' == NULL but then of course no locking
1004 * can be done!
1005 */
1006
1007void Curl_hostcache_clean(struct Curl_easy *data,
1008 struct Curl_hash *hash)
1009{
1010 if(data && data->share)
1011 Curl_share_lock(data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE);
1012
1013 Curl_hash_clean(hash);
1014
1015 if(data && data->share)
1016 Curl_share_unlock(data, CURL_LOCK_DATA_DNS);
1017}
1018
1019
1020CURLcode Curl_loadhostpairs(struct Curl_easy *data)
1021{
1022 struct curl_slist *hostp;
1023 char hostname[256];
1024 int port = 0;
1025
1026 /* Default is no wildcard found */
1027 data->state.wildcard_resolve = false;
1028
1029 for(hostp = data->state.resolve; hostp; hostp = hostp->next) {
1030 char entry_id[MAX_HOSTCACHE_LEN];
1031 if(!hostp->data)
1032 continue;
1033 if(hostp->data[0] == '-') {
1034 size_t entry_len;
1035
1036 if(2 != sscanf(hostp->data + 1, "%255[^:]:%d", hostname, &port)) {
1037 infof(data, "Couldn't parse CURLOPT_RESOLVE removal entry '%s'",
1038 hostp->data);
1039 continue;
1040 }
1041
1042 /* Create an entry id, based upon the hostname and port */
1043 create_hostcache_id(hostname, port, entry_id, sizeof(entry_id));
1044 entry_len = strlen(entry_id);
1045
1046 if(data->share)
1047 Curl_share_lock(data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE);
1048
1049 /* delete entry, ignore if it didn't exist */
1050 Curl_hash_delete(data->dns.hostcache, entry_id, entry_len + 1);
1051
1052 if(data->share)
1053 Curl_share_unlock(data, CURL_LOCK_DATA_DNS);
1054 }
1055 else {
1056 struct Curl_dns_entry *dns;
1057 struct Curl_addrinfo *head = NULL, *tail = NULL;
1058 size_t entry_len;
1059 char address[64];
1060#if !defined(CURL_DISABLE_VERBOSE_STRINGS)
1061 char *addresses = NULL;
1062#endif
1063 char *addr_begin;
1064 char *addr_end;
1065 char *port_ptr;
1066 char *end_ptr;
1067 bool permanent = TRUE;
1068 char *host_begin;
1069 char *host_end;
1070 unsigned long tmp_port;
1071 bool error = true;
1072
1073 host_begin = hostp->data;
1074 if(host_begin[0] == '+') {
1075 host_begin++;
1076 permanent = FALSE;
1077 }
1078 host_end = strchr(host_begin, ':');
1079 if(!host_end ||
1080 ((host_end - host_begin) >= (ptrdiff_t)sizeof(hostname)))
1081 goto err;
1082
1083 memcpy(hostname, host_begin, host_end - host_begin);
1084 hostname[host_end - host_begin] = '\0';
1085
1086 port_ptr = host_end + 1;
1087 tmp_port = strtoul(port_ptr, &end_ptr, 10);
1088 if(tmp_port > USHRT_MAX || end_ptr == port_ptr || *end_ptr != ':')
1089 goto err;
1090
1091 port = (int)tmp_port;
1092#if !defined(CURL_DISABLE_VERBOSE_STRINGS)
1093 addresses = end_ptr + 1;
1094#endif
1095
1096 while(*end_ptr) {
1097 size_t alen;
1098 struct Curl_addrinfo *ai;
1099
1100 addr_begin = end_ptr + 1;
1101 addr_end = strchr(addr_begin, ',');
1102 if(!addr_end)
1103 addr_end = addr_begin + strlen(addr_begin);
1104 end_ptr = addr_end;
1105
1106 /* allow IP(v6) address within [brackets] */
1107 if(*addr_begin == '[') {
1108 if(addr_end == addr_begin || *(addr_end - 1) != ']')
1109 goto err;
1110 ++addr_begin;
1111 --addr_end;
1112 }
1113
1114 alen = addr_end - addr_begin;
1115 if(!alen)
1116 continue;
1117
1118 if(alen >= sizeof(address))
1119 goto err;
1120
1121 memcpy(address, addr_begin, alen);
1122 address[alen] = '\0';
1123
1124#ifndef ENABLE_IPV6
1125 if(strchr(address, ':')) {
1126 infof(data, "Ignoring resolve address '%s', missing IPv6 support.",
1127 address);
1128 continue;
1129 }
1130#endif
1131
1132 ai = Curl_str2addr(address, port);
1133 if(!ai) {
1134 infof(data, "Resolve address '%s' found illegal", address);
1135 goto err;
1136 }
1137
1138 if(tail) {
1139 tail->ai_next = ai;
1140 tail = tail->ai_next;
1141 }
1142 else {
1143 head = tail = ai;
1144 }
1145 }
1146
1147 if(!head)
1148 goto err;
1149
1150 error = false;
1151 err:
1152 if(error) {
1153 failf(data, "Couldn't parse CURLOPT_RESOLVE entry '%s'",
1154 hostp->data);
1155 Curl_freeaddrinfo(head);
1156 return CURLE_SETOPT_OPTION_SYNTAX;
1157 }
1158
1159 /* Create an entry id, based upon the hostname and port */
1160 create_hostcache_id(hostname, port, entry_id, sizeof(entry_id));
1161 entry_len = strlen(entry_id);
1162
1163 if(data->share)
1164 Curl_share_lock(data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE);
1165
1166 /* See if it's already in our dns cache */
1167 dns = Curl_hash_pick(data->dns.hostcache, entry_id, entry_len + 1);
1168
1169 if(dns) {
1170 infof(data, "RESOLVE %s:%d is - old addresses discarded",
1171 hostname, port);
1172 /* delete old entry, there are two reasons for this
1173 1. old entry may have different addresses.
1174 2. even if entry with correct addresses is already in the cache,
1175 but if it is close to expire, then by the time next http
1176 request is made, it can get expired and pruned because old
1177 entry is not necessarily marked as permanent.
1178 3. when adding a non-permanent entry, we want it to remove and
1179 replace an existing permanent entry.
1180 4. when adding a non-permanent entry, we want it to get a "fresh"
1181 timeout that starts _now_. */
1182
1183 Curl_hash_delete(data->dns.hostcache, entry_id, entry_len + 1);
1184 }
1185
1186 /* put this new host in the cache */
1187 dns = Curl_cache_addr(data, head, hostname, port);
1188 if(dns) {
1189 if(permanent)
1190 dns->timestamp = 0; /* mark as permanent */
1191 /* release the returned reference; the cache itself will keep the
1192 * entry alive: */
1193 dns->inuse--;
1194 }
1195
1196 if(data->share)
1197 Curl_share_unlock(data, CURL_LOCK_DATA_DNS);
1198
1199 if(!dns) {
1200 Curl_freeaddrinfo(head);
1201 return CURLE_OUT_OF_MEMORY;
1202 }
1203 infof(data, "Added %s:%d:%s to DNS cache%s",
1204 hostname, port, addresses, permanent ? "" : " (non-permanent)");
1205
1206 /* Wildcard hostname */
1207 if(hostname[0] == '*' && hostname[1] == '\0') {
1208 infof(data, "RESOLVE %s:%d is wildcard, enabling wildcard checks",
1209 hostname, port);
1210 data->state.wildcard_resolve = true;
1211 }
1212 }
1213 }
1214 data->state.resolve = NULL; /* dealt with now */
1215
1216 return CURLE_OK;
1217}
1218
1219CURLcode Curl_resolv_check(struct Curl_easy *data,
1220 struct Curl_dns_entry **dns)
1221{
1222#if defined(CURL_DISABLE_DOH) && !defined(CURLRES_ASYNCH)
1223 (void)data;
1224 (void)dns;
1225#endif
1226#ifndef CURL_DISABLE_DOH
1227 if(data->conn->bits.doh)
1228 return Curl_doh_is_resolved(data, dns);
1229#endif
1230 return Curl_resolver_is_resolved(data, dns);
1231}
1232
1233int Curl_resolv_getsock(struct Curl_easy *data,
1234 curl_socket_t *socks)
1235{
1236#ifdef CURLRES_ASYNCH
1237#ifndef CURL_DISABLE_DOH
1238 if(data->conn->bits.doh)
1239 /* nothing to wait for during DoH resolve, those handles have their own
1240 sockets */
1241 return GETSOCK_BLANK;
1242#endif
1243 return Curl_resolver_getsock(data, socks);
1244#else
1245 (void)data;
1246 (void)socks;
1247 return GETSOCK_BLANK;
1248#endif
1249}
1250
1251/* Call this function after Curl_connect() has returned async=TRUE and
1252 then a successful name resolve has been received.
1253
1254 Note: this function disconnects and frees the conn data in case of
1255 resolve failure */
1256CURLcode Curl_once_resolved(struct Curl_easy *data, bool *protocol_done)
1257{
1258 CURLcode result;
1259 struct connectdata *conn = data->conn;
1260
1261#ifdef USE_CURL_ASYNC
1262 if(data->state.async.dns) {
1263 conn->dns_entry = data->state.async.dns;
1264 data->state.async.dns = NULL;
1265 }
1266#endif
1267
1268 result = Curl_setup_conn(data, protocol_done);
1269
1270 if(result) {
1271 Curl_detach_connection(data);
1272 Curl_conncache_remove_conn(data, conn, TRUE);
1273 Curl_disconnect(data, conn, TRUE);
1274 }
1275 return result;
1276}
1277
1278/*
1279 * Curl_resolver_error() calls failf() with the appropriate message after a
1280 * resolve error
1281 */
1282
1283#ifdef USE_CURL_ASYNC
1284CURLcode Curl_resolver_error(struct Curl_easy *data)
1285{
1286 const char *host_or_proxy;
1287 CURLcode result;
1288
1289#ifndef CURL_DISABLE_PROXY
1290 struct connectdata *conn = data->conn;
1291 if(conn->bits.httpproxy) {
1292 host_or_proxy = "proxy";
1293 result = CURLE_COULDNT_RESOLVE_PROXY;
1294 }
1295 else
1296#endif
1297 {
1298 host_or_proxy = "host";
1299 result = CURLE_COULDNT_RESOLVE_HOST;
1300 }
1301
1302 failf(data, "Could not resolve %s: %s", host_or_proxy,
1303 data->state.async.hostname);
1304
1305 return result;
1306}
1307#endif /* USE_CURL_ASYNC */
注意: 瀏覽 TracBrowser 來幫助您使用儲存庫瀏覽器

© 2025 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette