Revert "Update to 7.40.1"
[platform/upstream/curl.git] / lib / hostip.c
1 /***************************************************************************
2  *                                  _   _ ____  _
3  *  Project                     ___| | | |  _ \| |
4  *                             / __| | | | |_) | |
5  *                            | (__| |_| |  _ <| |___
6  *                             \___|\___/|_| \_\_____|
7  *
8  * Copyright (C) 1998 - 2013, 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 /*
323  * Curl_cache_addr() stores a 'Curl_addrinfo' struct in the DNS cache.
324  *
325  * When calling Curl_resolv() has resulted in a response with a returned
326  * address, we call this function to store the information in the dns
327  * cache etc
328  *
329  * Returns the Curl_dns_entry entry pointer or NULL if the storage failed.
330  */
331 struct Curl_dns_entry *
332 Curl_cache_addr(struct SessionHandle *data,
333                 Curl_addrinfo *addr,
334                 const char *hostname,
335                 int port)
336 {
337   char *entry_id;
338   size_t entry_len;
339   struct Curl_dns_entry *dns;
340   struct Curl_dns_entry *dns2;
341
342   /* Create an entry id, based upon the hostname and port */
343   entry_id = create_hostcache_id(hostname, port);
344   /* If we can't create the entry id, fail */
345   if(!entry_id)
346     return NULL;
347   entry_len = strlen(entry_id);
348
349   /* Create a new cache entry */
350   dns = calloc(1, sizeof(struct Curl_dns_entry));
351   if(!dns) {
352     free(entry_id);
353     return NULL;
354   }
355
356   dns->inuse = 0;   /* init to not used */
357   dns->addr = addr; /* this is the address(es) */
358   time(&dns->timestamp);
359   if(dns->timestamp == 0)
360     dns->timestamp = 1;   /* zero indicates that entry isn't in hash table */
361
362   /* Store the resolved data in our DNS cache. */
363   dns2 = Curl_hash_add(data->dns.hostcache, entry_id, entry_len+1,
364                        (void *)dns);
365   if(!dns2) {
366     free(dns);
367     free(entry_id);
368     return NULL;
369   }
370
371   dns = dns2;
372   dns->inuse++;         /* mark entry as in-use */
373
374   /* free the allocated entry_id */
375   free(entry_id);
376
377   return dns;
378 }
379
380 /*
381  * Curl_resolv() is the main name resolve function within libcurl. It resolves
382  * a name and returns a pointer to the entry in the 'entry' argument (if one
383  * is provided). This function might return immediately if we're using asynch
384  * resolves. See the return codes.
385  *
386  * The cache entry we return will get its 'inuse' counter increased when this
387  * function is used. You MUST call Curl_resolv_unlock() later (when you're
388  * done using this struct) to decrease the counter again.
389  *
390  * In debug mode, we specifically test for an interface name "LocalHost"
391  * and resolve "localhost" instead as a means to permit test cases
392  * to connect to a local test server with any host name.
393  *
394  * Return codes:
395  *
396  * CURLRESOLV_ERROR   (-1) = error, no pointer
397  * CURLRESOLV_RESOLVED (0) = OK, pointer provided
398  * CURLRESOLV_PENDING  (1) = waiting for response, no pointer
399  */
400
401 int Curl_resolv(struct connectdata *conn,
402                 const char *hostname,
403                 int port,
404                 struct Curl_dns_entry **entry)
405 {
406   char *entry_id = NULL;
407   struct Curl_dns_entry *dns = NULL;
408   size_t entry_len;
409   struct SessionHandle *data = conn->data;
410   CURLcode result;
411   int rc = CURLRESOLV_ERROR; /* default to failure */
412
413   *entry = NULL;
414
415   /* Create an entry id, based upon the hostname and port */
416   entry_id = create_hostcache_id(hostname, port);
417   /* If we can't create the entry id, fail */
418   if(!entry_id)
419     return rc;
420
421   entry_len = strlen(entry_id);
422
423   if(data->share)
424     Curl_share_lock(data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE);
425
426   /* See if its already in our dns cache */
427   dns = Curl_hash_pick(data->dns.hostcache, entry_id, entry_len+1);
428
429   /* free the allocated entry_id again */
430   free(entry_id);
431
432   infof(data, "Hostname was %sfound in DNS cache\n", dns?"":"NOT ");
433
434   /* See whether the returned entry is stale. Done before we release lock */
435   if(remove_entry_if_stale(data, dns)) {
436     infof(data, "Hostname in DNS cache was stale, zapped\n");
437     dns = NULL; /* the memory deallocation is being handled by the hash */
438   }
439
440   if(dns) {
441     dns->inuse++; /* we use it! */
442     rc = CURLRESOLV_RESOLVED;
443   }
444
445   if(data->share)
446     Curl_share_unlock(data, CURL_LOCK_DATA_DNS);
447
448   if(!dns) {
449     /* The entry was not in the cache. Resolve it to IP address */
450
451     Curl_addrinfo *addr;
452     int respwait;
453
454     /* Check what IP specifics the app has requested and if we can provide it.
455      * If not, bail out. */
456     if(!Curl_ipvalid(conn))
457       return CURLRESOLV_ERROR;
458
459     /* If Curl_getaddrinfo() returns NULL, 'respwait' might be set to a
460        non-zero value indicating that we need to wait for the response to the
461        resolve call */
462     addr = Curl_getaddrinfo(conn,
463 #ifdef DEBUGBUILD
464                             (data->set.str[STRING_DEVICE]
465                              && !strcmp(data->set.str[STRING_DEVICE],
466                                         "LocalHost"))?"localhost":
467 #endif
468                             hostname, port, &respwait);
469
470     if(!addr) {
471       if(respwait) {
472         /* the response to our resolve call will come asynchronously at
473            a later time, good or bad */
474         /* First, check that we haven't received the info by now */
475         result = Curl_resolver_is_resolved(conn, &dns);
476         if(result) /* error detected */
477           return CURLRESOLV_ERROR;
478         if(dns)
479           rc = CURLRESOLV_RESOLVED; /* pointer provided */
480         else
481           rc = CURLRESOLV_PENDING; /* no info yet */
482       }
483     }
484     else {
485       if(data->share)
486         Curl_share_lock(data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE);
487
488       /* we got a response, store it in the cache */
489       dns = Curl_cache_addr(data, addr, hostname, port);
490
491       if(data->share)
492         Curl_share_unlock(data, CURL_LOCK_DATA_DNS);
493
494       if(!dns)
495         /* returned failure, bail out nicely */
496         Curl_freeaddrinfo(addr);
497       else
498         rc = CURLRESOLV_RESOLVED;
499     }
500   }
501
502   *entry = dns;
503
504   return rc;
505 }
506
507 #ifdef USE_ALARM_TIMEOUT
508 /*
509  * This signal handler jumps back into the main libcurl code and continues
510  * execution.  This effectively causes the remainder of the application to run
511  * within a signal handler which is nonportable and could lead to problems.
512  */
513 static
514 RETSIGTYPE alarmfunc(int sig)
515 {
516   /* this is for "-ansi -Wall -pedantic" to stop complaining!   (rabe) */
517   (void)sig;
518   siglongjmp(curl_jmpenv, 1);
519   return;
520 }
521 #endif /* USE_ALARM_TIMEOUT */
522
523 /*
524  * Curl_resolv_timeout() is the same as Curl_resolv() but specifies a
525  * timeout.  This function might return immediately if we're using asynch
526  * resolves. See the return codes.
527  *
528  * The cache entry we return will get its 'inuse' counter increased when this
529  * function is used. You MUST call Curl_resolv_unlock() later (when you're
530  * done using this struct) to decrease the counter again.
531  *
532  * If built with a synchronous resolver and use of signals is not
533  * disabled by the application, then a nonzero timeout will cause a
534  * timeout after the specified number of milliseconds. Otherwise, timeout
535  * is ignored.
536  *
537  * Return codes:
538  *
539  * CURLRESOLV_TIMEDOUT(-2) = warning, time too short or previous alarm expired
540  * CURLRESOLV_ERROR   (-1) = error, no pointer
541  * CURLRESOLV_RESOLVED (0) = OK, pointer provided
542  * CURLRESOLV_PENDING  (1) = waiting for response, no pointer
543  */
544
545 int Curl_resolv_timeout(struct connectdata *conn,
546                         const char *hostname,
547                         int port,
548                         struct Curl_dns_entry **entry,
549                         long timeoutms)
550 {
551 #ifdef USE_ALARM_TIMEOUT
552 #ifdef HAVE_SIGACTION
553   struct sigaction keep_sigact;   /* store the old struct here */
554   volatile bool keep_copysig = FALSE; /* wether old sigact has been saved */
555   struct sigaction sigact;
556 #else
557 #ifdef HAVE_SIGNAL
558   void (*keep_sigact)(int);       /* store the old handler here */
559 #endif /* HAVE_SIGNAL */
560 #endif /* HAVE_SIGACTION */
561   volatile long timeout;
562   volatile unsigned int prev_alarm = 0;
563   struct SessionHandle *data = conn->data;
564 #endif /* USE_ALARM_TIMEOUT */
565   int rc;
566
567   *entry = NULL;
568
569   if(timeoutms < 0)
570     /* got an already expired timeout */
571     return CURLRESOLV_TIMEDOUT;
572
573 #ifdef USE_ALARM_TIMEOUT
574   if(data->set.no_signal)
575     /* Ignore the timeout when signals are disabled */
576     timeout = 0;
577   else
578     timeout = timeoutms;
579
580   if(!timeout)
581     /* USE_ALARM_TIMEOUT defined, but no timeout actually requested */
582     return Curl_resolv(conn, hostname, port, entry);
583
584   if(timeout < 1000)
585     /* The alarm() function only provides integer second resolution, so if
586        we want to wait less than one second we must bail out already now. */
587     return CURLRESOLV_TIMEDOUT;
588
589   /*************************************************************
590    * Set signal handler to catch SIGALRM
591    * Store the old value to be able to set it back later!
592    *************************************************************/
593 #ifdef HAVE_SIGACTION
594   sigaction(SIGALRM, NULL, &sigact);
595   keep_sigact = sigact;
596   keep_copysig = TRUE; /* yes, we have a copy */
597   sigact.sa_handler = alarmfunc;
598 #ifdef SA_RESTART
599   /* HPUX doesn't have SA_RESTART but defaults to that behaviour! */
600   sigact.sa_flags &= ~SA_RESTART;
601 #endif
602   /* now set the new struct */
603   sigaction(SIGALRM, &sigact, NULL);
604 #else /* HAVE_SIGACTION */
605   /* no sigaction(), revert to the much lamer signal() */
606 #ifdef HAVE_SIGNAL
607   keep_sigact = signal(SIGALRM, alarmfunc);
608 #endif
609 #endif /* HAVE_SIGACTION */
610
611   /* alarm() makes a signal get sent when the timeout fires off, and that
612      will abort system calls */
613   prev_alarm = alarm(curlx_sltoui(timeout/1000L));
614
615   /* This allows us to time-out from the name resolver, as the timeout
616      will generate a signal and we will siglongjmp() from that here.
617      This technique has problems (see alarmfunc).
618      This should be the last thing we do before calling Curl_resolv(),
619      as otherwise we'd have to worry about variables that get modified
620      before we invoke Curl_resolv() (and thus use "volatile"). */
621   if(sigsetjmp(curl_jmpenv, 1)) {
622     /* this is coming from a siglongjmp() after an alarm signal */
623     failf(data, "name lookup timed out");
624     rc = CURLRESOLV_ERROR;
625     goto clean_up;
626   }
627
628 #else
629 #ifndef CURLRES_ASYNCH
630   if(timeoutms)
631     infof(conn->data, "timeout on name lookup is not supported\n");
632 #else
633   (void)timeoutms; /* timeoutms not used with an async resolver */
634 #endif
635 #endif /* USE_ALARM_TIMEOUT */
636
637   /* Perform the actual name resolution. This might be interrupted by an
638    * alarm if it takes too long.
639    */
640   rc = Curl_resolv(conn, hostname, port, entry);
641
642 #ifdef USE_ALARM_TIMEOUT
643 clean_up:
644
645   if(!prev_alarm)
646     /* deactivate a possibly active alarm before uninstalling the handler */
647     alarm(0);
648
649 #ifdef HAVE_SIGACTION
650   if(keep_copysig) {
651     /* we got a struct as it looked before, now put that one back nice
652        and clean */
653     sigaction(SIGALRM, &keep_sigact, NULL); /* put it back */
654   }
655 #else
656 #ifdef HAVE_SIGNAL
657   /* restore the previous SIGALRM handler */
658   signal(SIGALRM, keep_sigact);
659 #endif
660 #endif /* HAVE_SIGACTION */
661
662   /* switch back the alarm() to either zero or to what it was before minus
663      the time we spent until now! */
664   if(prev_alarm) {
665     /* there was an alarm() set before us, now put it back */
666     unsigned long elapsed_ms = Curl_tvdiff(Curl_tvnow(), conn->created);
667
668     /* the alarm period is counted in even number of seconds */
669     unsigned long alarm_set = prev_alarm - elapsed_ms/1000;
670
671     if(!alarm_set ||
672        ((alarm_set >= 0x80000000) && (prev_alarm < 0x80000000)) ) {
673       /* if the alarm time-left reached zero or turned "negative" (counted
674          with unsigned values), we should fire off a SIGALRM here, but we
675          won't, and zero would be to switch it off so we never set it to
676          less than 1! */
677       alarm(1);
678       rc = CURLRESOLV_TIMEDOUT;
679       failf(data, "Previous alarm fired off!");
680     }
681     else
682       alarm((unsigned int)alarm_set);
683   }
684 #endif /* USE_ALARM_TIMEOUT */
685
686   return rc;
687 }
688
689 /*
690  * Curl_resolv_unlock() unlocks the given cached DNS entry. When this has been
691  * made, the struct may be destroyed due to pruning. It is important that only
692  * one unlock is made for each Curl_resolv() call.
693  *
694  * May be called with 'data' == NULL for global cache.
695  */
696 void Curl_resolv_unlock(struct SessionHandle *data, struct Curl_dns_entry *dns)
697 {
698   DEBUGASSERT(dns && (dns->inuse>0));
699
700   if(data && data->share)
701     Curl_share_lock(data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE);
702
703   dns->inuse--;
704   /* only free if nobody is using AND it is not in hostcache (timestamp ==
705      0) */
706   if(dns->inuse == 0 && dns->timestamp == 0) {
707     Curl_freeaddrinfo(dns->addr);
708     free(dns);
709   }
710
711   if(data && data->share)
712     Curl_share_unlock(data, CURL_LOCK_DATA_DNS);
713 }
714
715 /*
716  * File-internal: free a cache dns entry.
717  */
718 static void freednsentry(void *freethis)
719 {
720   struct Curl_dns_entry *p = (struct Curl_dns_entry *) freethis;
721
722   /* mark the entry as not in hostcache */
723   p->timestamp = 0;
724   if(p->inuse == 0) {
725     Curl_freeaddrinfo(p->addr);
726     free(p);
727   }
728 }
729
730 /*
731  * Curl_mk_dnscache() creates a new DNS cache and returns the handle for it.
732  */
733 struct curl_hash *Curl_mk_dnscache(void)
734 {
735   return Curl_hash_alloc(7, Curl_hash_str, Curl_str_key_compare, freednsentry);
736 }
737
738 static int hostcache_inuse(void *data, void *hc)
739 {
740   struct Curl_dns_entry *c = (struct Curl_dns_entry *) hc;
741
742   if(c->inuse == 1)
743     Curl_resolv_unlock(data, c);
744
745   return 1; /* free all entries */
746 }
747
748 /*
749  * Curl_hostcache_clean()
750  *
751  * This _can_ be called with 'data' == NULL but then of course no locking
752  * can be done!
753  */
754
755 void Curl_hostcache_clean(struct SessionHandle *data,
756                           struct curl_hash *hash)
757 {
758   /* Entries added to the hostcache with the CURLOPT_RESOLVE function are
759    * still present in the cache with the inuse counter set to 1. Detect them
760    * and cleanup!
761    */
762   Curl_hash_clean_with_criterium(hash, data, hostcache_inuse);
763 }
764
765
766 CURLcode Curl_loadhostpairs(struct SessionHandle *data)
767 {
768   struct curl_slist *hostp;
769   char hostname[256];
770   char address[256];
771   int port;
772
773   for(hostp = data->change.resolve; hostp; hostp = hostp->next ) {
774     if(!hostp->data)
775       continue;
776     if(hostp->data[0] == '-') {
777       /* TODO: mark an entry for removal */
778     }
779     else if(3 == sscanf(hostp->data, "%255[^:]:%d:%255s", hostname, &port,
780                         address)) {
781       struct Curl_dns_entry *dns;
782       Curl_addrinfo *addr;
783       char *entry_id;
784       size_t entry_len;
785
786       addr = Curl_str2addr(address, port);
787       if(!addr) {
788         infof(data, "Resolve %s found illegal!\n", hostp->data);
789         continue;
790       }
791
792       /* Create an entry id, based upon the hostname and port */
793       entry_id = create_hostcache_id(hostname, port);
794       /* If we can't create the entry id, fail */
795       if(!entry_id) {
796         Curl_freeaddrinfo(addr);
797         return CURLE_OUT_OF_MEMORY;
798       }
799
800       entry_len = strlen(entry_id);
801
802       if(data->share)
803         Curl_share_lock(data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE);
804
805       /* See if its already in our dns cache */
806       dns = Curl_hash_pick(data->dns.hostcache, entry_id, entry_len+1);
807
808       /* free the allocated entry_id again */
809       free(entry_id);
810
811       if(!dns)
812         /* if not in the cache already, put this host in the cache */
813         dns = Curl_cache_addr(data, addr, hostname, port);
814       else
815         /* this is a duplicate, free it again */
816         Curl_freeaddrinfo(addr);
817
818       if(data->share)
819         Curl_share_unlock(data, CURL_LOCK_DATA_DNS);
820
821       if(!dns) {
822         Curl_freeaddrinfo(addr);
823         return CURLE_OUT_OF_MEMORY;
824       }
825       infof(data, "Added %s:%d:%s to DNS cache\n",
826             hostname, port, address);
827     }
828   }
829   data->change.resolve = NULL; /* dealt with now */
830
831   return CURLE_OK;
832 }