1 /***************************************************************************
3 * Project ___| | | | _ \| |
5 * | (__| |_| | _ <| |___
6 * \___|\___/|_| \_\_____|
8 * Copyright (C) 1998 - 2008, Daniel Stenberg, <daniel@haxx.se>, et al.
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 http://curl.haxx.se/docs/copyright.html.
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.
18 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
19 * KIND, either express or implied.
22 ***************************************************************************/
31 #ifdef HAVE_SYS_SOCKET_H
32 #include <sys/socket.h>
34 #ifdef HAVE_NETINET_IN_H
35 #include <netinet/in.h>
40 #ifdef HAVE_ARPA_INET_H
41 #include <arpa/inet.h>
44 #include <stdlib.h> /* required for free() prototypes */
47 #include <unistd.h> /* for the close() proto */
73 #include "inet_ntop.h"
75 #define _MPRINTF_REPLACE /* use our functions only */
76 #include <curl/mprintf.h>
79 /* The last #include file should be: */
82 #if defined(HAVE_ALARM) && defined(SIGALRM) && defined(HAVE_SIGSETJMP) \
84 /* alarm-based timeouts can only be used with all the dependencies satisfied */
85 #define USE_ALARM_TIMEOUT
92 * The main COMPILE-TIME DEFINES to keep in mind when reading the host*.c
93 * source file are these:
95 * CURLRES_IPV6 - this host has getaddrinfo() and family, and thus we use
96 * that. The host may not be able to resolve IPv6, but we don't really have to
97 * take that into account. Hosts that aren't IPv6-enabled have CURLRES_IPV4
100 * CURLRES_ARES - is defined if libcurl is built to use c-ares for
101 * asynchronous name resolves. This can be Windows or *nix.
103 * CURLRES_THREADED - is defined if libcurl is built to run under (native)
104 * Windows, and then the name resolve will be done in a new thread, and the
105 * supported API will be the same as for ares-builds.
107 * If any of the two previous are defined, CURLRES_ASYNCH is defined too. If
108 * libcurl is not built to use an asynchronous resolver, CURLRES_SYNCH is
111 * The host*.c sources files are split up like this:
113 * hostip.c - method-independent resolver functions and utility functions
114 * hostasyn.c - functions for asynchronous name resolves
115 * hostsyn.c - functions for synchronous name resolves
116 * hostares.c - functions for ares-using name resolves
117 * hostthre.c - functions for threaded name resolves
118 * hostip4.c - ipv4-specific functions
119 * hostip6.c - ipv6-specific functions
121 * The hostip.h is the united header file for all this. It defines the
122 * CURLRES_* defines based on the config*.h and setup.h defines.
125 /* These two symbols are for the global DNS cache */
126 static struct curl_hash hostname_cache;
127 static int host_cache_initialized;
129 static void freednsentry(void *freethis);
132 * Curl_global_host_cache_init() initializes and sets up a global DNS cache.
133 * Global DNS cache is general badness. Do not use. This will be removed in
134 * a future version. Use the share interface instead!
136 * Returns a struct curl_hash pointer on success, NULL on failure.
138 struct curl_hash *Curl_global_host_cache_init(void)
141 if(!host_cache_initialized) {
142 rc = Curl_hash_init(&hostname_cache, 7, Curl_hash_str,
143 Curl_str_key_compare, freednsentry);
145 host_cache_initialized = 1;
147 return rc?NULL:&hostname_cache;
151 * Destroy and cleanup the global DNS cache
153 void Curl_global_host_cache_dtor(void)
155 if(host_cache_initialized) {
156 Curl_hash_clean(&hostname_cache);
157 host_cache_initialized = 0;
162 * Return # of adresses in a Curl_addrinfo struct
164 int Curl_num_addresses(const Curl_addrinfo *addr)
167 for (i = 0; addr; addr = addr->ai_next, i++)
173 * Curl_printable_address() returns a printable version of the 1st address
174 * given in the 'ip' argument. The result will be stored in the buf that is
177 * If the conversion fails, it returns NULL.
179 const char *Curl_printable_address(const Curl_addrinfo *ip,
180 char *buf, size_t bufsize)
182 const void *ip4 = &((const struct sockaddr_in*)ip->ai_addr)->sin_addr;
183 int af = ip->ai_family;
185 const void *ip6 = &((const struct sockaddr_in6*)ip->ai_addr)->sin6_addr;
187 const void *ip6 = NULL;
190 return Curl_inet_ntop(af, af == AF_INET ? ip4 : ip6, buf, bufsize);
194 * Return a hostcache id string for the providing host + port, to be used by
198 create_hostcache_id(const char *server, int port)
200 /* create and return the new allocated entry */
201 return aprintf("%s:%d", server, port);
204 struct hostcache_prune_data {
210 * This function is set as a callback to be called for every entry in the DNS
211 * cache when we want to prune old unused entries.
213 * Returning non-zero means remove the entry, return 0 to keep it in the
217 hostcache_timestamp_remove(void *datap, void *hc)
219 struct hostcache_prune_data *data =
220 (struct hostcache_prune_data *) datap;
221 struct Curl_dns_entry *c = (struct Curl_dns_entry *) hc;
223 if((data->now - c->timestamp < data->cache_timeout) ||
225 /* please don't remove */
234 * Prune the DNS cache. This assumes that a lock has already been taken.
237 hostcache_prune(struct curl_hash *hostcache, long cache_timeout, time_t now)
239 struct hostcache_prune_data user;
241 user.cache_timeout = cache_timeout;
244 Curl_hash_clean_with_criterium(hostcache,
246 hostcache_timestamp_remove);
250 * Library-wide function for pruning the DNS cache. This function takes and
251 * returns the appropriate locks.
253 void Curl_hostcache_prune(struct SessionHandle *data)
257 if((data->set.dns_cache_timeout == -1) || !data->dns.hostcache)
258 /* cache forever means never prune, and NULL hostcache means
263 Curl_share_lock(data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE);
267 /* Remove outdated and unused entries from the hostcache */
268 hostcache_prune(data->dns.hostcache,
269 data->set.dns_cache_timeout,
273 Curl_share_unlock(data, CURL_LOCK_DATA_DNS);
277 * Check if the entry should be pruned. Assumes a locked cache.
280 remove_entry_if_stale(struct SessionHandle *data, struct Curl_dns_entry *dns)
282 struct hostcache_prune_data user;
284 if( !dns || (data->set.dns_cache_timeout == -1) || !data->dns.hostcache)
285 /* cache forever means never prune, and NULL hostcache means
290 user.cache_timeout = data->set.dns_cache_timeout;
292 if( !hostcache_timestamp_remove(&user,dns) )
295 Curl_hash_clean_with_criterium(data->dns.hostcache,
297 hostcache_timestamp_remove);
303 #ifdef HAVE_SIGSETJMP
304 /* Beware this is a global and unique instance. This is used to store the
305 return address that we can jump back to from inside a signal handler. This
306 is not thread-safe stuff. */
307 sigjmp_buf curl_jmpenv;
312 * Curl_cache_addr() stores a 'Curl_addrinfo' struct in the DNS cache.
314 * When calling Curl_resolv() has resulted in a response with a returned
315 * address, we call this function to store the information in the dns
318 * Returns the Curl_dns_entry entry pointer or NULL if the storage failed.
320 struct Curl_dns_entry *
321 Curl_cache_addr(struct SessionHandle *data,
323 const char *hostname,
328 struct Curl_dns_entry *dns;
329 struct Curl_dns_entry *dns2;
332 /* Create an entry id, based upon the hostname and port */
333 entry_id = create_hostcache_id(hostname, port);
334 /* If we can't create the entry id, fail */
337 entry_len = strlen(entry_id);
339 /* Create a new cache entry */
340 dns = calloc(sizeof(struct Curl_dns_entry), 1);
346 dns->inuse = 0; /* init to not used */
347 dns->addr = addr; /* this is the address(es) */
349 /* Store the resolved data in our DNS cache. This function may return a
350 pointer to an existing struct already present in the hash, and it may
351 return the same argument we pass in. Make no assumptions. */
352 dns2 = Curl_hash_add(data->dns.hostcache, entry_id, entry_len+1,
355 /* Major badness, run away. */
363 dns->timestamp = now; /* used now */
364 dns->inuse++; /* mark entry as in-use */
366 /* free the allocated entry_id again */
373 * Curl_resolv() is the main name resolve function within libcurl. It resolves
374 * a name and returns a pointer to the entry in the 'entry' argument (if one
375 * is provided). This function might return immediately if we're using asynch
376 * resolves. See the return codes.
378 * The cache entry we return will get its 'inuse' counter increased when this
379 * function is used. You MUST call Curl_resolv_unlock() later (when you're
380 * done using this struct) to decrease the counter again.
384 * CURLRESOLV_ERROR (-1) = error, no pointer
385 * CURLRESOLV_RESOLVED (0) = OK, pointer provided
386 * CURLRESOLV_PENDING (1) = waiting for response, no pointer
389 int Curl_resolv(struct connectdata *conn,
390 const char *hostname,
392 struct Curl_dns_entry **entry)
394 char *entry_id = NULL;
395 struct Curl_dns_entry *dns = NULL;
397 struct SessionHandle *data = conn->data;
399 int rc = CURLRESOLV_ERROR; /* default to failure */
403 /* Create an entry id, based upon the hostname and port */
404 entry_id = create_hostcache_id(hostname, port);
405 /* If we can't create the entry id, fail */
409 entry_len = strlen(entry_id);
412 Curl_share_lock(data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE);
414 /* See if its already in our dns cache */
415 dns = Curl_hash_pick(data->dns.hostcache, entry_id, entry_len+1);
417 /* See whether the returned entry is stale. Done before we release lock */
418 if( remove_entry_if_stale(data, dns) )
419 dns = NULL; /* the memory deallocation is being handled by the hash */
422 dns->inuse++; /* we use it! */
423 rc = CURLRESOLV_RESOLVED;
427 Curl_share_unlock(data, CURL_LOCK_DATA_DNS);
429 /* free the allocated entry_id again */
433 /* The entry was not in the cache. Resolve it to IP address */
438 /* Check what IP specifics the app has requested and if we can provide it.
439 * If not, bail out. */
440 if(!Curl_ipvalid(data))
441 return CURLRESOLV_ERROR;
443 /* If Curl_getaddrinfo() returns NULL, 'respwait' might be set to a
444 non-zero value indicating that we need to wait for the response to the
446 addr = Curl_getaddrinfo(conn, hostname, port, &respwait);
450 /* the response to our resolve call will come asynchronously at
451 a later time, good or bad */
452 /* First, check that we haven't received the info by now */
453 result = Curl_is_resolved(conn, &dns);
454 if(result) /* error detected */
455 return CURLRESOLV_ERROR;
457 rc = CURLRESOLV_RESOLVED; /* pointer provided */
459 rc = CURLRESOLV_PENDING; /* no info yet */
464 Curl_share_lock(data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE);
466 /* we got a response, store it in the cache */
467 dns = Curl_cache_addr(data, addr, hostname, port);
470 Curl_share_unlock(data, CURL_LOCK_DATA_DNS);
473 /* returned failure, bail out nicely */
474 Curl_freeaddrinfo(addr);
476 rc = CURLRESOLV_RESOLVED;
485 #ifdef USE_ALARM_TIMEOUT
487 * This signal handler jumps back into the main libcurl code and continues
488 * execution. This effectively causes the remainder of the application to run
489 * within a signal handler which is nonportable and could lead to problems.
492 RETSIGTYPE alarmfunc(int sig)
494 /* this is for "-ansi -Wall -pedantic" to stop complaining! (rabe) */
496 siglongjmp(curl_jmpenv, 1);
499 #endif /* USE_ALARM_TIMEOUT */
502 * Curl_resolv_timeout() is the same as Curl_resolv() but specifies a
503 * timeout. This function might return immediately if we're using asynch
504 * resolves. See the return codes.
506 * The cache entry we return will get its 'inuse' counter increased when this
507 * function is used. You MUST call Curl_resolv_unlock() later (when you're
508 * done using this struct) to decrease the counter again.
510 * If built with a synchronous resolver and use of signals is not
511 * disabled by the application, then a nonzero timeout will cause a
512 * timeout after the specified number of milliseconds. Otherwise, timeout
517 * CURLRESOLV_TIMEDOUT(-2) = warning, time too short or previous alarm expired
518 * CURLRESOLV_ERROR (-1) = error, no pointer
519 * CURLRESOLV_RESOLVED (0) = OK, pointer provided
520 * CURLRESOLV_PENDING (1) = waiting for response, no pointer
523 int Curl_resolv_timeout(struct connectdata *conn,
524 const char *hostname,
526 struct Curl_dns_entry **entry,
529 #ifdef USE_ALARM_TIMEOUT
530 #ifdef HAVE_SIGACTION
531 struct sigaction keep_sigact; /* store the old struct here */
532 bool keep_copysig=FALSE; /* did copy it? */
533 struct sigaction sigact;
536 void (*keep_sigact)(int); /* store the old handler here */
537 #endif /* HAVE_SIGNAL */
538 #endif /* HAVE_SIGACTION */
539 volatile long timeout;
540 unsigned int prev_alarm=0;
541 struct SessionHandle *data = conn->data;
542 #endif /* USE_ALARM_TIMEOUT */
547 #ifdef USE_ALARM_TIMEOUT
548 if (data->set.no_signal)
549 /* Ignore the timeout when signals are disabled */
554 if(timeout && timeout < 1000)
555 /* The alarm() function only provides integer second resolution, so if
556 we want to wait less than one second we must bail out already now. */
557 return CURLRESOLV_TIMEDOUT;
560 /* This allows us to time-out from the name resolver, as the timeout
561 will generate a signal and we will siglongjmp() from that here.
562 This technique has problems (see alarmfunc). */
563 if(sigsetjmp(curl_jmpenv, 1)) {
564 /* this is coming from a siglongjmp() after an alarm signal */
565 failf(data, "name lookup timed out");
566 return CURLRESOLV_ERROR;
569 /*************************************************************
570 * Set signal handler to catch SIGALRM
571 * Store the old value to be able to set it back later!
572 *************************************************************/
573 #ifdef HAVE_SIGACTION
574 sigaction(SIGALRM, NULL, &sigact);
575 keep_sigact = sigact;
576 keep_copysig = TRUE; /* yes, we have a copy */
577 sigact.sa_handler = alarmfunc;
579 /* HPUX doesn't have SA_RESTART but defaults to that behaviour! */
580 sigact.sa_flags &= ~SA_RESTART;
582 /* now set the new struct */
583 sigaction(SIGALRM, &sigact, NULL);
584 #else /* HAVE_SIGACTION */
585 /* no sigaction(), revert to the much lamer signal() */
587 keep_sigact = signal(SIGALRM, alarmfunc);
589 #endif /* HAVE_SIGACTION */
591 /* alarm() makes a signal get sent when the timeout fires off, and that
592 will abort system calls */
593 prev_alarm = alarm((unsigned int) (timeout ? timeout/1000L : timeout));
597 #ifndef CURLRES_ASYNCH
599 infof(conn->data, "timeout on name lookup is not supported\n");
601 (void)timeoutms; /* timeoutms not used with an async resolver */
603 #endif /* USE_ALARM_TIMEOUT */
605 /* Perform the actual name resolution. This might be interrupted by an
606 * alarm if it takes too long.
608 rc = Curl_resolv(conn, hostname, port, entry);
610 #ifdef USE_ALARM_TIMEOUT
613 #ifdef HAVE_SIGACTION
615 /* we got a struct as it looked before, now put that one back nice
617 sigaction(SIGALRM, &keep_sigact, NULL); /* put it back */
621 /* restore the previous SIGALRM handler */
622 signal(SIGALRM, keep_sigact);
624 #endif /* HAVE_SIGACTION */
626 /* switch back the alarm() to either zero or to what it was before minus
627 the time we spent until now! */
629 /* there was an alarm() set before us, now put it back */
630 unsigned long elapsed_ms = Curl_tvdiff(Curl_tvnow(), conn->created);
632 /* the alarm period is counted in even number of seconds */
633 unsigned long alarm_set = prev_alarm - elapsed_ms/1000;
636 ((alarm_set >= 0x80000000) && (prev_alarm < 0x80000000)) ) {
637 /* if the alarm time-left reached zero or turned "negative" (counted
638 with unsigned values), we should fire off a SIGALRM here, but we
639 won't, and zero would be to switch it off so we never set it to
642 rc = CURLRESOLV_TIMEDOUT;
643 failf(data, "Previous alarm fired off!");
646 alarm((unsigned int)alarm_set);
649 alarm(0); /* just shut it off */
651 #endif /* USE_ALARM_TIMEOUT */
657 * Curl_resolv_unlock() unlocks the given cached DNS entry. When this has been
658 * made, the struct may be destroyed due to pruning. It is important that only
659 * one unlock is made for each Curl_resolv() call.
661 void Curl_resolv_unlock(struct SessionHandle *data, struct Curl_dns_entry *dns)
663 DEBUGASSERT(dns && (dns->inuse>0));
666 Curl_share_lock(data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE);
671 Curl_share_unlock(data, CURL_LOCK_DATA_DNS);
675 * File-internal: free a cache dns entry.
677 static void freednsentry(void *freethis)
679 struct Curl_dns_entry *p = (struct Curl_dns_entry *) freethis;
681 Curl_freeaddrinfo(p->addr);
687 * Curl_mk_dnscache() creates a new DNS cache and returns the handle for it.
689 struct curl_hash *Curl_mk_dnscache(void)
691 return Curl_hash_alloc(7, Curl_hash_str, Curl_str_key_compare, freednsentry);
694 #ifdef CURLRES_ADDRINFO_COPY
696 /* align on even 64bit boundaries */
697 #define MEMALIGN(x) ((x)+(8-(((unsigned long)(x))&0x7)))
700 * Curl_addrinfo_copy() performs a "deep" copy of a hostent into a buffer and
701 * returns a pointer to the malloc()ed copy. You need to call free() on the
702 * returned buffer when you're done with it.
704 Curl_addrinfo *Curl_addrinfo_copy(const void *org, int port)
706 const struct hostent *orig = org;
708 return Curl_he2ai(orig, port);
710 #endif /* CURLRES_ADDRINFO_COPY */
712 /***********************************************************************
713 * Only for plain-ipv4 and c-ares builds (NOTE: c-ares builds can be IPv6
715 **********************************************************************/
717 #if defined(CURLRES_IPV4) || defined(CURLRES_ARES)
719 * This is a function for freeing name information in a protocol independent
722 void Curl_freeaddrinfo(Curl_addrinfo *ai)
726 /* walk over the list and free all entries */
732 free(ai->ai_canonname);
739 struct hostent hostentry;
740 struct in_addr addrentry;
741 char *h_addr_list[2];
745 * Curl_ip2addr() takes a 32bit ipv4 internet address as input parameter
746 * together with a pointer to the string version of the address, and it
747 * returns a Curl_addrinfo chain filled in correctly with information for this
750 * The input parameters ARE NOT checked for validity but they are expected
751 * to have been checked already when this is called.
753 Curl_addrinfo *Curl_ip2addr(in_addr_t num, const char *hostname, int port)
757 #if defined(VMS) && \
758 defined(__INITIAL_POINTER_SIZE) && (__INITIAL_POINTER_SIZE == 64)
759 #pragma pointer_size save
760 #pragma pointer_size short
761 #pragma message disable PTRMISMATCH
765 struct in_addr *addrentry;
766 struct namebuf4 *buf;
769 DEBUGASSERT(hostname);
771 buf = malloc(sizeof(struct namebuf4));
775 hoststr = strdup(hostname);
781 addrentry = &buf->addrentry;
783 /* On UNICOS, s_addr is a bit field and for some reason assigning to it
784 * doesn't work. There must be a better fix than this ugly hack.
786 memcpy(addrentry, &num, SIZEOF_in_addr);
788 addrentry->s_addr = num;
794 h->h_addrtype = AF_INET;
795 h->h_length = sizeof(struct in_addr);
796 h->h_addr_list = &buf->h_addr_list[0];
797 h->h_addr_list[0] = (char*)addrentry;
798 h->h_addr_list[1] = NULL; /* terminate list of entries */
800 #if defined(VMS) && \
801 defined(__INITIAL_POINTER_SIZE) && (__INITIAL_POINTER_SIZE == 64)
802 #pragma pointer_size restore
803 #pragma message enable PTRMISMATCH
806 ai = Curl_he2ai(h, port);
815 * Curl_he2ai() translates from a hostent struct to a Curl_addrinfo struct.
816 * The Curl_addrinfo is meant to work like the addrinfo struct does for IPv6
817 * stacks, but for all hosts and environments.
819 * Curl_addrinfo defined in "lib/hostip.h"
821 * struct Curl_addrinfo {
826 * socklen_t ai_addrlen; * Follow rfc3493 struct addrinfo *
827 * char *ai_canonname;
828 * struct sockaddr *ai_addr;
829 * struct Curl_addrinfo *ai_next;
832 * hostent defined in <netdb.h>
839 * char **h_addr_list;
842 * for backward compatibility:
844 * #define h_addr h_addr_list[0]
847 Curl_addrinfo *Curl_he2ai(const struct hostent *he, int port)
850 Curl_addrinfo *prevai = NULL;
851 Curl_addrinfo *firstai = NULL;
852 struct sockaddr_in *addr;
854 struct sockaddr_in6 *addr6;
855 #endif /* CURLRES_IPV6 */
856 CURLcode result = CURLE_OK;
861 /* no input == no output! */
864 for(i=0; (curr = he->h_addr_list[i]) != NULL; i++) {
868 if (he->h_addrtype == AF_INET6)
869 ss_size = sizeof (struct sockaddr_in6);
871 #endif /* CURLRES_IPV6 */
872 ss_size = sizeof (struct sockaddr_in);
874 if((ai = calloc(1, sizeof(Curl_addrinfo))) == NULL) {
875 result = CURLE_OUT_OF_MEMORY;
878 if((ai->ai_canonname = strdup(he->h_name)) == NULL) {
879 result = CURLE_OUT_OF_MEMORY;
883 if((ai->ai_addr = calloc(1, ss_size)) == NULL) {
884 result = CURLE_OUT_OF_MEMORY;
885 free(ai->ai_canonname);
891 /* store the pointer we want to return from this function */
895 /* make the previous entry point to this */
896 prevai->ai_next = ai;
898 ai->ai_family = he->h_addrtype;
900 /* we return all names as STREAM, so when using this address for TFTP
901 the type must be ignored and conn->socktype be used instead! */
902 ai->ai_socktype = SOCK_STREAM;
904 ai->ai_addrlen = ss_size;
906 /* leave the rest of the struct filled with zero */
908 switch (ai->ai_family) {
910 addr = (struct sockaddr_in *)ai->ai_addr; /* storage area for this info */
912 memcpy(&addr->sin_addr, curr, sizeof(struct in_addr));
913 addr->sin_family = (unsigned short)(he->h_addrtype);
914 addr->sin_port = htons((unsigned short)port);
919 addr6 = (struct sockaddr_in6 *)ai->ai_addr; /* storage area for this info */
921 memcpy(&addr6->sin6_addr, curr, sizeof(struct in6_addr));
922 addr6->sin6_family = (unsigned short)(he->h_addrtype);
923 addr6->sin6_port = htons((unsigned short)port);
925 #endif /* CURLRES_IPV6 */
931 if(result != CURLE_OK)
932 Curl_freeaddrinfo(firstai);
937 #endif /* CURLRES_IPV4 || CURLRES_ARES */