Revert "Imported Upstream version 7.44.0"
[platform/upstream/curl.git] / lib / hostip.c
1 /***************************************************************************
2  *                                  _   _ ____  _
3  *  Project                     ___| | | |  _ \| |
4  *                             / __| | | | |_) | |
5  *                            | (__| |_| |  _ <| |___
6  *                             \___|\___/|_| \_\_____|
7  *
8  * Copyright (C) 1998 - 2015, 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 http://curl.haxx.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_NETDB_H
29 #include <netdb.h>
30 #endif
31 #ifdef HAVE_ARPA_INET_H
32 #include <arpa/inet.h>
33 #endif
34 #ifdef __VMS
35 #include <in.h>
36 #include <inet.h>
37 #endif
38
39 #ifdef HAVE_SETJMP_H
40 #include <setjmp.h>
41 #endif
42 #ifdef HAVE_SIGNAL_H
43 #include <signal.h>
44 #endif
45
46 #ifdef HAVE_PROCESS_H
47 #include <process.h>
48 #endif
49
50 #include "urldata.h"
51 #include "sendf.h"
52 #include "hostip.h"
53 #include "hash.h"
54 #include "share.h"
55 #include "strerror.h"
56 #include "url.h"
57 #include "inet_ntop.h"
58 #include "warnless.h"
59
60 #define _MPRINTF_REPLACE /* use our functions only */
61 #include <curl/mprintf.h>
62
63 #include "curl_memory.h"
64 /* The last #include file should be: */
65 #include "memdebug.h"
66
67 #if defined(CURLRES_SYNCH) && \
68     defined(HAVE_ALARM) && defined(SIGALRM) && defined(HAVE_SIGSETJMP)
69 /* alarm-based timeouts can only be used with all the dependencies satisfied */
70 #define USE_ALARM_TIMEOUT
71 #endif
72
73 /*
74  * hostip.c explained
75  * ==================
76  *
77  * The main COMPILE-TIME DEFINES to keep in mind when reading the host*.c
78  * source file are these:
79  *
80  * CURLRES_IPV6 - this host has getaddrinfo() and family, and thus we use
81  * that. The host may not be able to resolve IPv6, but we don't really have to
82  * take that into account. Hosts that aren't IPv6-enabled have CURLRES_IPV4
83  * defined.
84  *
85  * CURLRES_ARES - is defined if libcurl is built to use c-ares for
86  * asynchronous name resolves. This can be Windows or *nix.
87  *
88  * CURLRES_THREADED - is defined if libcurl is built to run under (native)
89  * Windows, and then the name resolve will be done in a new thread, and the
90  * supported API will be the same as for ares-builds.
91  *
92  * If any of the two previous are defined, CURLRES_ASYNCH is defined too. If
93  * libcurl is not built to use an asynchronous resolver, CURLRES_SYNCH is
94  * defined.
95  *
96  * The host*.c sources files are split up like this:
97  *
98  * hostip.c   - method-independent resolver functions and utility functions
99  * hostasyn.c - functions for asynchronous name resolves
100  * hostsyn.c  - functions for synchronous name resolves
101  * hostip4.c  - IPv4 specific functions
102  * hostip6.c  - IPv6 specific functions
103  *
104  * The two asynchronous name resolver backends are implemented in:
105  * asyn-ares.c   - functions for ares-using name resolves
106  * asyn-thread.c - functions for threaded name resolves
107
108  * The hostip.h is the united header file for all this. It defines the
109  * CURLRES_* defines based on the config*.h and curl_setup.h defines.
110  */
111
112 /* These two symbols are for the global DNS cache */
113 static struct curl_hash hostname_cache;
114 static int host_cache_initialized;
115
116 static void freednsentry(void *freethis);
117
118 /*
119  * Curl_global_host_cache_init() initializes and sets up a global DNS cache.
120  * Global DNS cache is general badness. Do not use. This will be removed in
121  * a future version. Use the share interface instead!
122  *
123  * Returns a struct curl_hash pointer on success, NULL on failure.
124  */
125 struct curl_hash *Curl_global_host_cache_init(void)
126 {
127   int rc = 0;
128   if(!host_cache_initialized) {
129     rc = Curl_hash_init(&hostname_cache, 7, Curl_hash_str,
130                         Curl_str_key_compare, freednsentry);
131     if(!rc)
132       host_cache_initialized = 1;
133   }
134   return rc?NULL:&hostname_cache;
135 }
136
137 /*
138  * Destroy and cleanup the global DNS cache
139  */
140 void Curl_global_host_cache_dtor(void)
141 {
142   if(host_cache_initialized) {
143     /* first make sure that any custom "CURLOPT_RESOLVE" names are
144        cleared off */
145     Curl_hostcache_clean(NULL, &hostname_cache);
146     /* then free the remaining hash completely */
147     Curl_hash_clean(&hostname_cache);
148     host_cache_initialized = 0;
149   }
150 }
151
152 /*
153  * Return # of adresses in a Curl_addrinfo struct
154  */
155 int Curl_num_addresses(const Curl_addrinfo *addr)
156 {
157   int i = 0;
158   while(addr) {
159     addr = addr->ai_next;
160     i++;
161   }
162   return i;
163 }
164
165 /*
166  * Curl_printable_address() returns a printable version of the 1st address
167  * given in the 'ai' argument. The result will be stored in the buf that is
168  * bufsize bytes big.
169  *
170  * If the conversion fails, it returns NULL.
171  */
172 const char *
173 Curl_printable_address(const Curl_addrinfo *ai, char *buf, size_t bufsize)
174 {
175   const struct sockaddr_in *sa4;
176   const struct in_addr *ipaddr4;
177 #ifdef ENABLE_IPV6
178   const struct sockaddr_in6 *sa6;
179   const struct in6_addr *ipaddr6;
180 #endif
181
182   switch (ai->ai_family) {
183     case AF_INET:
184       sa4 = (const void *)ai->ai_addr;
185       ipaddr4 = &sa4->sin_addr;
186       return Curl_inet_ntop(ai->ai_family, (const void *)ipaddr4, buf,
187                             bufsize);
188 #ifdef ENABLE_IPV6
189     case AF_INET6:
190       sa6 = (const void *)ai->ai_addr;
191       ipaddr6 = &sa6->sin6_addr;
192       return Curl_inet_ntop(ai->ai_family, (const void *)ipaddr6, buf,
193                             bufsize);
194 #endif
195     default:
196       break;
197   }
198   return NULL;
199 }
200
201 /*
202  * Return a hostcache id string for the provided host + port, to be used by
203  * the DNS caching.
204  */
205 static char *
206 create_hostcache_id(const char *name, int port)
207 {
208   /* create and return the new allocated entry */
209   char *id = aprintf("%s:%d", name, port);
210   char *ptr = id;
211   if(ptr) {
212     /* lower case the name part */
213     while(*ptr && (*ptr != ':')) {
214       *ptr = (char)TOLOWER(*ptr);
215       ptr++;
216     }
217   }
218   return id;
219 }
220
221 struct hostcache_prune_data {
222   long cache_timeout;
223   time_t now;
224 };
225
226 /*
227  * This function is set as a callback to be called for every entry in the DNS
228  * cache when we want to prune old unused entries.
229  *
230  * Returning non-zero means remove the entry, return 0 to keep it in the
231  * cache.
232  */
233 static int
234 hostcache_timestamp_remove(void *datap, void *hc)
235 {
236   struct hostcache_prune_data *data =
237     (struct hostcache_prune_data *) datap;
238   struct Curl_dns_entry *c = (struct Curl_dns_entry *) hc;
239
240   return !c->inuse && (data->now - c->timestamp >= data->cache_timeout);
241 }
242
243 /*
244  * Prune the DNS cache. This assumes that a lock has already been taken.
245  */
246 static void
247 hostcache_prune(struct curl_hash *hostcache, long cache_timeout, time_t now)
248 {
249   struct hostcache_prune_data user;
250
251   user.cache_timeout = cache_timeout;
252   user.now = now;
253
254   Curl_hash_clean_with_criterium(hostcache,
255                                  (void *) &user,
256                                  hostcache_timestamp_remove);
257 }
258
259 /*
260  * Library-wide function for pruning the DNS cache. This function takes and
261  * returns the appropriate locks.
262  */
263 void Curl_hostcache_prune(struct SessionHandle *data)
264 {
265   time_t now;
266
267   if((data->set.dns_cache_timeout == -1) || !data->dns.hostcache)
268     /* cache forever means never prune, and NULL hostcache means
269        we can't do it */
270     return;
271
272   if(data->share)
273     Curl_share_lock(data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE);
274
275   time(&now);
276
277   /* Remove outdated and unused entries from the hostcache */
278   hostcache_prune(data->dns.hostcache,
279                   data->set.dns_cache_timeout,
280                   now);
281
282   if(data->share)
283     Curl_share_unlock(data, CURL_LOCK_DATA_DNS);
284 }
285
286 /*
287  * Check if the entry should be pruned. Assumes a locked cache.
288  */
289 static int
290 remove_entry_if_stale(struct SessionHandle *data, struct Curl_dns_entry *dns)
291 {
292   struct hostcache_prune_data user;
293
294   if(!dns || (data->set.dns_cache_timeout == -1) || !data->dns.hostcache ||
295      dns->inuse)
296     /* cache forever means never prune, and NULL hostcache means we can't do
297        it, if it still is in use then we leave it */
298     return 0;
299
300   time(&user.now);
301   user.cache_timeout = data->set.dns_cache_timeout;
302
303   if(!hostcache_timestamp_remove(&user,dns) )
304     return 0;
305
306   Curl_hash_clean_with_criterium(data->dns.hostcache,
307                                  (void *) &user,
308                                  hostcache_timestamp_remove);
309
310   return 1;
311 }
312
313
314 #ifdef HAVE_SIGSETJMP
315 /* Beware this is a global and unique instance. This is used to store the
316    return address that we can jump back to from inside a signal handler. This
317    is not thread-safe stuff. */
318 sigjmp_buf curl_jmpenv;
319 #endif
320
321 /*
322  * Curl_fetch_addr() fetches a 'Curl_dns_entry' already in the DNS cache.
323  *
324  * Curl_resolv() checks initially and multi_runsingle() checks each time
325  * it discovers the handle in the state WAITRESOLVE whether the hostname
326  * has already been resolved and the address has already been stored in
327  * the DNS cache. This short circuits waiting for a lot of pending
328  * lookups for the same hostname requested by different handles.
329  *
330  * Returns the Curl_dns_entry entry pointer or NULL if not in the cache.
331  */
332 struct Curl_dns_entry *
333 Curl_fetch_addr(struct connectdata *conn,
334                 const char *hostname,
335                 int port)
336 {
337   char *entry_id = NULL;
338   struct Curl_dns_entry *dns = NULL;
339   size_t entry_len;
340   struct SessionHandle *data = conn->data;
341   int stale;
342
343   /* Create an entry id, based upon the hostname and port */
344   entry_id = create_hostcache_id(hostname, port);
345   /* If we can't create the entry id, fail */
346   if(!entry_id)
347     return dns;
348
349   entry_len = strlen(entry_id);
350
351   /* See if its already in our dns cache */
352   dns = Curl_hash_pick(data->dns.hostcache, entry_id, entry_len+1);
353
354   /* free the allocated entry_id again */
355   free(entry_id);
356
357   /* See whether the returned entry is stale. Done before we release lock */
358   stale = remove_entry_if_stale(data, dns);
359   if(stale) {
360     infof(data, "Hostname in DNS cache was stale, zapped\n");
361     dns = NULL; /* the memory deallocation is being handled by the hash */
362   }
363
364   return dns;
365 }
366
367 /*
368  * Curl_cache_addr() stores a 'Curl_addrinfo' struct in the DNS cache.
369  *
370  * When calling Curl_resolv() has resulted in a response with a returned
371  * address, we call this function to store the information in the dns
372  * cache etc
373  *
374  * Returns the Curl_dns_entry entry pointer or NULL if the storage failed.
375  */
376 struct Curl_dns_entry *
377 Curl_cache_addr(struct SessionHandle *data,
378                 Curl_addrinfo *addr,
379                 const char *hostname,
380                 int port)
381 {
382   char *entry_id;
383   size_t entry_len;
384   struct Curl_dns_entry *dns;
385   struct Curl_dns_entry *dns2;
386
387   /* Create an entry id, based upon the hostname and port */
388   entry_id = create_hostcache_id(hostname, port);
389   /* If we can't create the entry id, fail */
390   if(!entry_id)
391     return NULL;
392   entry_len = strlen(entry_id);
393
394   /* Create a new cache entry */
395   dns = calloc(1, sizeof(struct Curl_dns_entry));
396   if(!dns) {
397     free(entry_id);
398     return NULL;
399   }
400
401   dns->inuse = 0;   /* init to not used */
402   dns->addr = addr; /* this is the address(es) */
403   time(&dns->timestamp);
404   if(dns->timestamp == 0)
405     dns->timestamp = 1;   /* zero indicates that entry isn't in hash table */
406
407   /* Store the resolved data in our DNS cache. */
408   dns2 = Curl_hash_add(data->dns.hostcache, entry_id, entry_len+1,
409                        (void *)dns);
410   if(!dns2) {
411     free(dns);
412     free(entry_id);
413     return NULL;
414   }
415
416   dns = dns2;
417   dns->inuse++;         /* mark entry as in-use */
418
419   /* free the allocated entry_id */
420   free(entry_id);
421
422   return dns;
423 }
424
425 /*
426  * Curl_resolv() is the main name resolve function within libcurl. It resolves
427  * a name and returns a pointer to the entry in the 'entry' argument (if one
428  * is provided). This function might return immediately if we're using asynch
429  * resolves. See the return codes.
430  *
431  * The cache entry we return will get its 'inuse' counter increased when this
432  * function is used. You MUST call Curl_resolv_unlock() later (when you're
433  * done using this struct) to decrease the counter again.
434  *
435  * In debug mode, we specifically test for an interface name "LocalHost"
436  * and resolve "localhost" instead as a means to permit test cases
437  * to connect to a local test server with any host name.
438  *
439  * Return codes:
440  *
441  * CURLRESOLV_ERROR   (-1) = error, no pointer
442  * CURLRESOLV_RESOLVED (0) = OK, pointer provided
443  * CURLRESOLV_PENDING  (1) = waiting for response, no pointer
444  */
445
446 int Curl_resolv(struct connectdata *conn,
447                 const char *hostname,
448                 int port,
449                 struct Curl_dns_entry **entry)
450 {
451   struct Curl_dns_entry *dns = NULL;
452   struct SessionHandle *data = conn->data;
453   CURLcode result;
454   int rc = CURLRESOLV_ERROR; /* default to failure */
455
456   *entry = NULL;
457
458   if(data->share)
459     Curl_share_lock(data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE);
460
461   dns = Curl_fetch_addr(conn, hostname, port);
462
463   if(dns) {
464     infof(data, "Hostname %s was found in DNS cache\n", hostname);
465     dns->inuse++; /* we use it! */
466     rc = CURLRESOLV_RESOLVED;
467   }
468
469   if(data->share)
470     Curl_share_unlock(data, CURL_LOCK_DATA_DNS);
471
472   if(!dns) {
473     /* The entry was not in the cache. Resolve it to IP address */
474
475     Curl_addrinfo *addr;
476     int respwait;
477
478     /* Check what IP specifics the app has requested and if we can provide it.
479      * If not, bail out. */
480     if(!Curl_ipvalid(conn))
481       return CURLRESOLV_ERROR;
482
483     /* If Curl_getaddrinfo() returns NULL, 'respwait' might be set to a
484        non-zero value indicating that we need to wait for the response to the
485        resolve call */
486     addr = Curl_getaddrinfo(conn,
487 #ifdef DEBUGBUILD
488                             (data->set.str[STRING_DEVICE]
489                              && !strcmp(data->set.str[STRING_DEVICE],
490                                         "LocalHost"))?"localhost":
491 #endif
492                             hostname, port, &respwait);
493
494     if(!addr) {
495       if(respwait) {
496         /* the response to our resolve call will come asynchronously at
497            a later time, good or bad */
498         /* First, check that we haven't received the info by now */
499         result = Curl_resolver_is_resolved(conn, &dns);
500         if(result) /* error detected */
501           return CURLRESOLV_ERROR;
502         if(dns)
503           rc = CURLRESOLV_RESOLVED; /* pointer provided */
504         else
505           rc = CURLRESOLV_PENDING; /* no info yet */
506       }
507     }
508     else {
509       if(data->share)
510         Curl_share_lock(data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE);
511
512       /* we got a response, store it in the cache */
513       dns = Curl_cache_addr(data, addr, hostname, port);
514
515       if(data->share)
516         Curl_share_unlock(data, CURL_LOCK_DATA_DNS);
517
518       if(!dns)
519         /* returned failure, bail out nicely */
520         Curl_freeaddrinfo(addr);
521       else
522         rc = CURLRESOLV_RESOLVED;
523     }
524   }
525
526   *entry = dns;
527
528   return rc;
529 }
530
531 #ifdef USE_ALARM_TIMEOUT
532 /*
533  * This signal handler jumps back into the main libcurl code and continues
534  * execution.  This effectively causes the remainder of the application to run
535  * within a signal handler which is nonportable and could lead to problems.
536  */
537 static
538 RETSIGTYPE alarmfunc(int sig)
539 {
540   /* this is for "-ansi -Wall -pedantic" to stop complaining!   (rabe) */
541   (void)sig;
542   siglongjmp(curl_jmpenv, 1);
543   return;
544 }
545 #endif /* USE_ALARM_TIMEOUT */
546
547 /*
548  * Curl_resolv_timeout() is the same as Curl_resolv() but specifies a
549  * timeout.  This function might return immediately if we're using asynch
550  * resolves. See the return codes.
551  *
552  * The cache entry we return will get its 'inuse' counter increased when this
553  * function is used. You MUST call Curl_resolv_unlock() later (when you're
554  * done using this struct) to decrease the counter again.
555  *
556  * If built with a synchronous resolver and use of signals is not
557  * disabled by the application, then a nonzero timeout will cause a
558  * timeout after the specified number of milliseconds. Otherwise, timeout
559  * is ignored.
560  *
561  * Return codes:
562  *
563  * CURLRESOLV_TIMEDOUT(-2) = warning, time too short or previous alarm expired
564  * CURLRESOLV_ERROR   (-1) = error, no pointer
565  * CURLRESOLV_RESOLVED (0) = OK, pointer provided
566  * CURLRESOLV_PENDING  (1) = waiting for response, no pointer
567  */
568
569 int Curl_resolv_timeout(struct connectdata *conn,
570                         const char *hostname,
571                         int port,
572                         struct Curl_dns_entry **entry,
573                         long timeoutms)
574 {
575 #ifdef USE_ALARM_TIMEOUT
576 #ifdef HAVE_SIGACTION
577   struct sigaction keep_sigact;   /* store the old struct here */
578   volatile bool keep_copysig = FALSE; /* wether old sigact has been saved */
579   struct sigaction sigact;
580 #else
581 #ifdef HAVE_SIGNAL
582   void (*keep_sigact)(int);       /* store the old handler here */
583 #endif /* HAVE_SIGNAL */
584 #endif /* HAVE_SIGACTION */
585   volatile long timeout;
586   volatile unsigned int prev_alarm = 0;
587   struct SessionHandle *data = conn->data;
588 #endif /* USE_ALARM_TIMEOUT */
589   int rc;
590
591   *entry = NULL;
592
593   if(timeoutms < 0)
594     /* got an already expired timeout */
595     return CURLRESOLV_TIMEDOUT;
596
597 #ifdef USE_ALARM_TIMEOUT
598   if(data->set.no_signal)
599     /* Ignore the timeout when signals are disabled */
600     timeout = 0;
601   else
602     timeout = timeoutms;
603
604   if(!timeout)
605     /* USE_ALARM_TIMEOUT defined, but no timeout actually requested */
606     return Curl_resolv(conn, hostname, port, entry);
607
608   if(timeout < 1000)
609     /* The alarm() function only provides integer second resolution, so if
610        we want to wait less than one second we must bail out already now. */
611     return CURLRESOLV_TIMEDOUT;
612
613   /*************************************************************
614    * Set signal handler to catch SIGALRM
615    * Store the old value to be able to set it back later!
616    *************************************************************/
617 #ifdef HAVE_SIGACTION
618   sigaction(SIGALRM, NULL, &sigact);
619   keep_sigact = sigact;
620   keep_copysig = TRUE; /* yes, we have a copy */
621   sigact.sa_handler = alarmfunc;
622 #ifdef SA_RESTART
623   /* HPUX doesn't have SA_RESTART but defaults to that behaviour! */
624   sigact.sa_flags &= ~SA_RESTART;
625 #endif
626   /* now set the new struct */
627   sigaction(SIGALRM, &sigact, NULL);
628 #else /* HAVE_SIGACTION */
629   /* no sigaction(), revert to the much lamer signal() */
630 #ifdef HAVE_SIGNAL
631   keep_sigact = signal(SIGALRM, alarmfunc);
632 #endif
633 #endif /* HAVE_SIGACTION */
634
635   /* alarm() makes a signal get sent when the timeout fires off, and that
636      will abort system calls */
637   prev_alarm = alarm(curlx_sltoui(timeout/1000L));
638
639   /* This allows us to time-out from the name resolver, as the timeout
640      will generate a signal and we will siglongjmp() from that here.
641      This technique has problems (see alarmfunc).
642      This should be the last thing we do before calling Curl_resolv(),
643      as otherwise we'd have to worry about variables that get modified
644      before we invoke Curl_resolv() (and thus use "volatile"). */
645   if(sigsetjmp(curl_jmpenv, 1)) {
646     /* this is coming from a siglongjmp() after an alarm signal */
647     failf(data, "name lookup timed out");
648     rc = CURLRESOLV_ERROR;
649     goto clean_up;
650   }
651
652 #else
653 #ifndef CURLRES_ASYNCH
654   if(timeoutms)
655     infof(conn->data, "timeout on name lookup is not supported\n");
656 #else
657   (void)timeoutms; /* timeoutms not used with an async resolver */
658 #endif
659 #endif /* USE_ALARM_TIMEOUT */
660
661   /* Perform the actual name resolution. This might be interrupted by an
662    * alarm if it takes too long.
663    */
664   rc = Curl_resolv(conn, hostname, port, entry);
665
666 #ifdef USE_ALARM_TIMEOUT
667 clean_up:
668
669   if(!prev_alarm)
670     /* deactivate a possibly active alarm before uninstalling the handler */
671     alarm(0);
672
673 #ifdef HAVE_SIGACTION
674   if(keep_copysig) {
675     /* we got a struct as it looked before, now put that one back nice
676        and clean */
677     sigaction(SIGALRM, &keep_sigact, NULL); /* put it back */
678   }
679 #else
680 #ifdef HAVE_SIGNAL
681   /* restore the previous SIGALRM handler */
682   signal(SIGALRM, keep_sigact);
683 #endif
684 #endif /* HAVE_SIGACTION */
685
686   /* switch back the alarm() to either zero or to what it was before minus
687      the time we spent until now! */
688   if(prev_alarm) {
689     /* there was an alarm() set before us, now put it back */
690     unsigned long elapsed_ms = Curl_tvdiff(Curl_tvnow(), conn->created);
691
692     /* the alarm period is counted in even number of seconds */
693     unsigned long alarm_set = prev_alarm - elapsed_ms/1000;
694
695     if(!alarm_set ||
696        ((alarm_set >= 0x80000000) && (prev_alarm < 0x80000000)) ) {
697       /* if the alarm time-left reached zero or turned "negative" (counted
698          with unsigned values), we should fire off a SIGALRM here, but we
699          won't, and zero would be to switch it off so we never set it to
700          less than 1! */
701       alarm(1);
702       rc = CURLRESOLV_TIMEDOUT;
703       failf(data, "Previous alarm fired off!");
704     }
705     else
706       alarm((unsigned int)alarm_set);
707   }
708 #endif /* USE_ALARM_TIMEOUT */
709
710   return rc;
711 }
712
713 /*
714  * Curl_resolv_unlock() unlocks the given cached DNS entry. When this has been
715  * made, the struct may be destroyed due to pruning. It is important that only
716  * one unlock is made for each Curl_resolv() call.
717  *
718  * May be called with 'data' == NULL for global cache.
719  */
720 void Curl_resolv_unlock(struct SessionHandle *data, struct Curl_dns_entry *dns)
721 {
722   DEBUGASSERT(dns && (dns->inuse>0));
723
724   if(data && data->share)
725     Curl_share_lock(data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE);
726
727   dns->inuse--;
728   /* only free if nobody is using AND it is not in hostcache (timestamp ==
729      0) */
730   if(dns->inuse == 0 && dns->timestamp == 0) {
731     Curl_freeaddrinfo(dns->addr);
732     free(dns);
733   }
734
735   if(data && data->share)
736     Curl_share_unlock(data, CURL_LOCK_DATA_DNS);
737 }
738
739 /*
740  * File-internal: free a cache dns entry.
741  */
742 static void freednsentry(void *freethis)
743 {
744   struct Curl_dns_entry *p = (struct Curl_dns_entry *) freethis;
745
746   /* mark the entry as not in hostcache */
747   p->timestamp = 0;
748   if(p->inuse == 0) {
749     Curl_freeaddrinfo(p->addr);
750     free(p);
751   }
752 }
753
754 /*
755  * Curl_mk_dnscache() creates a new DNS cache and returns the handle for it.
756  */
757 struct curl_hash *Curl_mk_dnscache(void)
758 {
759   return Curl_hash_alloc(7, Curl_hash_str, Curl_str_key_compare, freednsentry);
760 }
761
762 static int hostcache_inuse(void *data, void *hc)
763 {
764   struct Curl_dns_entry *c = (struct Curl_dns_entry *) hc;
765
766   if(c->inuse == 1)
767     Curl_resolv_unlock(data, c);
768
769   return 1; /* free all entries */
770 }
771
772 /*
773  * Curl_hostcache_clean()
774  *
775  * This _can_ be called with 'data' == NULL but then of course no locking
776  * can be done!
777  */
778
779 void Curl_hostcache_clean(struct SessionHandle *data,
780                           struct curl_hash *hash)
781 {
782   /* Entries added to the hostcache with the CURLOPT_RESOLVE function are
783    * still present in the cache with the inuse counter set to 1. Detect them
784    * and cleanup!
785    */
786   Curl_hash_clean_with_criterium(hash, data, hostcache_inuse);
787 }
788
789
790 CURLcode Curl_loadhostpairs(struct SessionHandle *data)
791 {
792   struct curl_slist *hostp;
793   char hostname[256];
794   char address[256];
795   int port;
796
797   for(hostp = data->change.resolve; hostp; hostp = hostp->next ) {
798     if(!hostp->data)
799       continue;
800     if(hostp->data[0] == '-') {
801       /* TODO: mark an entry for removal */
802     }
803     else if(3 == sscanf(hostp->data, "%255[^:]:%d:%255s", hostname, &port,
804                         address)) {
805       struct Curl_dns_entry *dns;
806       Curl_addrinfo *addr;
807       char *entry_id;
808       size_t entry_len;
809
810       addr = Curl_str2addr(address, port);
811       if(!addr) {
812         infof(data, "Resolve %s found illegal!\n", hostp->data);
813         continue;
814       }
815
816       /* Create an entry id, based upon the hostname and port */
817       entry_id = create_hostcache_id(hostname, port);
818       /* If we can't create the entry id, fail */
819       if(!entry_id) {
820         Curl_freeaddrinfo(addr);
821         return CURLE_OUT_OF_MEMORY;
822       }
823
824       entry_len = strlen(entry_id);
825
826       if(data->share)
827         Curl_share_lock(data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE);
828
829       /* See if its already in our dns cache */
830       dns = Curl_hash_pick(data->dns.hostcache, entry_id, entry_len+1);
831
832       /* free the allocated entry_id again */
833       free(entry_id);
834
835       if(!dns)
836         /* if not in the cache already, put this host in the cache */
837         dns = Curl_cache_addr(data, addr, hostname, port);
838       else
839         /* this is a duplicate, free it again */
840         Curl_freeaddrinfo(addr);
841
842       if(data->share)
843         Curl_share_unlock(data, CURL_LOCK_DATA_DNS);
844
845       if(!dns) {
846         Curl_freeaddrinfo(addr);
847         return CURLE_OUT_OF_MEMORY;
848       }
849       infof(data, "Added %s:%d:%s to DNS cache\n",
850             hostname, port, address);
851     }
852   }
853   data->change.resolve = NULL; /* dealt with now */
854
855   return CURLE_OK;
856 }