• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /***************************************************************************
2  *                                  _   _ ____  _
3  *  Project                     ___| | | |  _ \| |
4  *                             / __| | | | |_) | |
5  *                            | (__| |_| |  _ <| |___
6  *                             \___|\___/|_| \_\_____|
7  *
8  * Copyright (C) 1998 - 2017, 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 https://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_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 "share.h"
58 #include "strerror.h"
59 #include "url.h"
60 #include "inet_ntop.h"
61 #include "warnless.h"
62 /* The last 3 #include files should be in this order */
63 #include "curl_printf.h"
64 #include "curl_memory.h"
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  */
Curl_global_host_cache_init(void)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  */
Curl_global_host_cache_dtor(void)140 void Curl_global_host_cache_dtor(void)
141 {
142   if(host_cache_initialized) {
143     Curl_hash_destroy(&hostname_cache);
144     host_cache_initialized = 0;
145   }
146 }
147 
148 /*
149  * Return # of addresses in a Curl_addrinfo struct
150  */
Curl_num_addresses(const Curl_addrinfo * addr)151 int Curl_num_addresses(const Curl_addrinfo *addr)
152 {
153   int i = 0;
154   while(addr) {
155     addr = addr->ai_next;
156     i++;
157   }
158   return i;
159 }
160 
161 /*
162  * Curl_printable_address() returns a printable version of the 1st address
163  * given in the 'ai' argument. The result will be stored in the buf that is
164  * bufsize bytes big.
165  *
166  * If the conversion fails, it returns NULL.
167  */
168 const char *
Curl_printable_address(const Curl_addrinfo * ai,char * buf,size_t bufsize)169 Curl_printable_address(const Curl_addrinfo *ai, char *buf, size_t bufsize)
170 {
171   const struct sockaddr_in *sa4;
172   const struct in_addr *ipaddr4;
173 #ifdef ENABLE_IPV6
174   const struct sockaddr_in6 *sa6;
175   const struct in6_addr *ipaddr6;
176 #endif
177 
178   switch(ai->ai_family) {
179     case AF_INET:
180       sa4 = (const void *)ai->ai_addr;
181       ipaddr4 = &sa4->sin_addr;
182       return Curl_inet_ntop(ai->ai_family, (const void *)ipaddr4, buf,
183                             bufsize);
184 #ifdef ENABLE_IPV6
185     case AF_INET6:
186       sa6 = (const void *)ai->ai_addr;
187       ipaddr6 = &sa6->sin6_addr;
188       return Curl_inet_ntop(ai->ai_family, (const void *)ipaddr6, buf,
189                             bufsize);
190 #endif
191     default:
192       break;
193   }
194   return NULL;
195 }
196 
197 /*
198  * Return a hostcache id string for the provided host + port, to be used by
199  * the DNS caching.
200  */
201 static char *
create_hostcache_id(const char * name,int port)202 create_hostcache_id(const char *name, int port)
203 {
204   /* create and return the new allocated entry */
205   char *id = aprintf("%s:%d", name, port);
206   char *ptr = id;
207   if(ptr) {
208     /* lower case the name part */
209     while(*ptr && (*ptr != ':')) {
210       *ptr = (char)TOLOWER(*ptr);
211       ptr++;
212     }
213   }
214   return id;
215 }
216 
217 struct hostcache_prune_data {
218   long cache_timeout;
219   time_t now;
220 };
221 
222 /*
223  * This function is set as a callback to be called for every entry in the DNS
224  * cache when we want to prune old unused entries.
225  *
226  * Returning non-zero means remove the entry, return 0 to keep it in the
227  * cache.
228  */
229 static int
hostcache_timestamp_remove(void * datap,void * hc)230 hostcache_timestamp_remove(void *datap, void *hc)
231 {
232   struct hostcache_prune_data *data =
233     (struct hostcache_prune_data *) datap;
234   struct Curl_dns_entry *c = (struct Curl_dns_entry *) hc;
235 
236   return (0 != c->timestamp)
237     && (data->now - c->timestamp >= data->cache_timeout);
238 }
239 
240 /*
241  * Prune the DNS cache. This assumes that a lock has already been taken.
242  */
243 static void
hostcache_prune(struct curl_hash * hostcache,long cache_timeout,time_t now)244 hostcache_prune(struct curl_hash *hostcache, long cache_timeout, time_t now)
245 {
246   struct hostcache_prune_data user;
247 
248   user.cache_timeout = cache_timeout;
249   user.now = now;
250 
251   Curl_hash_clean_with_criterium(hostcache,
252                                  (void *) &user,
253                                  hostcache_timestamp_remove);
254 }
255 
256 /*
257  * Library-wide function for pruning the DNS cache. This function takes and
258  * returns the appropriate locks.
259  */
Curl_hostcache_prune(struct Curl_easy * data)260 void Curl_hostcache_prune(struct Curl_easy *data)
261 {
262   time_t now;
263 
264   if((data->set.dns_cache_timeout == -1) || !data->dns.hostcache)
265     /* cache forever means never prune, and NULL hostcache means
266        we can't do it */
267     return;
268 
269   if(data->share)
270     Curl_share_lock(data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE);
271 
272   time(&now);
273 
274   /* Remove outdated and unused entries from the hostcache */
275   hostcache_prune(data->dns.hostcache,
276                   data->set.dns_cache_timeout,
277                   now);
278 
279   if(data->share)
280     Curl_share_unlock(data, CURL_LOCK_DATA_DNS);
281 }
282 
283 #ifdef HAVE_SIGSETJMP
284 /* Beware this is a global and unique instance. This is used to store the
285    return address that we can jump back to from inside a signal handler. This
286    is not thread-safe stuff. */
287 sigjmp_buf curl_jmpenv;
288 #endif
289 
290 /* lookup address, returns entry if found and not stale */
291 static struct Curl_dns_entry *
fetch_addr(struct connectdata * conn,const char * hostname,int port)292 fetch_addr(struct connectdata *conn,
293                 const char *hostname,
294                 int port)
295 {
296   char *entry_id = NULL;
297   struct Curl_dns_entry *dns = NULL;
298   size_t entry_len;
299   struct Curl_easy *data = conn->data;
300 
301   /* Create an entry id, based upon the hostname and port */
302   entry_id = create_hostcache_id(hostname, port);
303   /* If we can't create the entry id, fail */
304   if(!entry_id)
305     return dns;
306 
307   entry_len = strlen(entry_id);
308 
309   /* See if its already in our dns cache */
310   dns = Curl_hash_pick(data->dns.hostcache, entry_id, entry_len + 1);
311 
312   if(dns && (data->set.dns_cache_timeout != -1)) {
313     /* See whether the returned entry is stale. Done before we release lock */
314     struct hostcache_prune_data user;
315 
316     time(&user.now);
317     user.cache_timeout = data->set.dns_cache_timeout;
318 
319     if(hostcache_timestamp_remove(&user, dns)) {
320       infof(data, "Hostname in DNS cache was stale, zapped\n");
321       dns = NULL; /* the memory deallocation is being handled by the hash */
322       Curl_hash_delete(data->dns.hostcache, entry_id, entry_len + 1);
323     }
324   }
325 
326   /* free the allocated entry_id again */
327   free(entry_id);
328 
329   return dns;
330 }
331 
332 /*
333  * Curl_fetch_addr() fetches a 'Curl_dns_entry' already in the DNS cache.
334  *
335  * Curl_resolv() checks initially and multi_runsingle() checks each time
336  * it discovers the handle in the state WAITRESOLVE whether the hostname
337  * has already been resolved and the address has already been stored in
338  * the DNS cache. This short circuits waiting for a lot of pending
339  * lookups for the same hostname requested by different handles.
340  *
341  * Returns the Curl_dns_entry entry pointer or NULL if not in the cache.
342  *
343  * The returned data *MUST* be "unlocked" with Curl_resolv_unlock() after
344  * use, or we'll leak memory!
345  */
346 struct Curl_dns_entry *
Curl_fetch_addr(struct connectdata * conn,const char * hostname,int port)347 Curl_fetch_addr(struct connectdata *conn,
348                 const char *hostname,
349                 int port)
350 {
351   struct Curl_easy *data = conn->data;
352   struct Curl_dns_entry *dns = NULL;
353 
354   if(data->share)
355     Curl_share_lock(data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE);
356 
357   dns = fetch_addr(conn, hostname, port);
358 
359   if(dns)
360     dns->inuse++; /* we use it! */
361 
362   if(data->share)
363     Curl_share_unlock(data, CURL_LOCK_DATA_DNS);
364 
365   return dns;
366 }
367 
368 /*
369  * Curl_cache_addr() stores a 'Curl_addrinfo' struct in the DNS cache.
370  *
371  * When calling Curl_resolv() has resulted in a response with a returned
372  * address, we call this function to store the information in the dns
373  * cache etc
374  *
375  * Returns the Curl_dns_entry entry pointer or NULL if the storage failed.
376  */
377 struct Curl_dns_entry *
Curl_cache_addr(struct Curl_easy * data,Curl_addrinfo * addr,const char * hostname,int port)378 Curl_cache_addr(struct Curl_easy *data,
379                 Curl_addrinfo *addr,
380                 const char *hostname,
381                 int port)
382 {
383   char *entry_id;
384   size_t entry_len;
385   struct Curl_dns_entry *dns;
386   struct Curl_dns_entry *dns2;
387 
388   /* Create an entry id, based upon the hostname and port */
389   entry_id = create_hostcache_id(hostname, port);
390   /* If we can't create the entry id, fail */
391   if(!entry_id)
392     return NULL;
393   entry_len = strlen(entry_id);
394 
395   /* Create a new cache entry */
396   dns = calloc(1, sizeof(struct Curl_dns_entry));
397   if(!dns) {
398     free(entry_id);
399     return NULL;
400   }
401 
402   dns->inuse = 1;   /* the cache has the first reference */
403   dns->addr = addr; /* this is the address(es) */
404   time(&dns->timestamp);
405   if(dns->timestamp == 0)
406     dns->timestamp = 1;   /* zero indicates CURLOPT_RESOLVE entry */
407 
408   /* Store the resolved data in our DNS cache. */
409   dns2 = Curl_hash_add(data->dns.hostcache, entry_id, entry_len + 1,
410                        (void *)dns);
411   if(!dns2) {
412     free(dns);
413     free(entry_id);
414     return NULL;
415   }
416 
417   dns = dns2;
418   dns->inuse++;         /* mark entry as in-use */
419 
420   /* free the allocated entry_id */
421   free(entry_id);
422 
423   return dns;
424 }
425 
426 /*
427  * Curl_resolv() is the main name resolve function within libcurl. It resolves
428  * a name and returns a pointer to the entry in the 'entry' argument (if one
429  * is provided). This function might return immediately if we're using asynch
430  * resolves. See the return codes.
431  *
432  * The cache entry we return will get its 'inuse' counter increased when this
433  * function is used. You MUST call Curl_resolv_unlock() later (when you're
434  * done using this struct) to decrease the counter again.
435  *
436  * In debug mode, we specifically test for an interface name "LocalHost"
437  * and resolve "localhost" instead as a means to permit test cases
438  * to connect to a local test server with any host name.
439  *
440  * Return codes:
441  *
442  * CURLRESOLV_ERROR   (-1) = error, no pointer
443  * CURLRESOLV_RESOLVED (0) = OK, pointer provided
444  * CURLRESOLV_PENDING  (1) = waiting for response, no pointer
445  */
446 
Curl_resolv(struct connectdata * conn,const char * hostname,int port,struct Curl_dns_entry ** entry)447 int Curl_resolv(struct connectdata *conn,
448                 const char *hostname,
449                 int port,
450                 struct Curl_dns_entry **entry)
451 {
452   struct Curl_dns_entry *dns = NULL;
453   struct Curl_easy *data = conn->data;
454   CURLcode result;
455   int rc = CURLRESOLV_ERROR; /* default to failure */
456 
457   *entry = NULL;
458 
459   if(data->share)
460     Curl_share_lock(data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE);
461 
462   dns = fetch_addr(conn, hostname, port);
463 
464   if(dns) {
465     infof(data, "Hostname %s was found in DNS cache\n", hostname);
466     dns->inuse++; /* we use it! */
467     rc = CURLRESOLV_RESOLVED;
468   }
469 
470   if(data->share)
471     Curl_share_unlock(data, CURL_LOCK_DATA_DNS);
472 
473   if(!dns) {
474     /* The entry was not in the cache. Resolve it to IP address */
475 
476     Curl_addrinfo *addr;
477     int respwait;
478 
479     /* Check what IP specifics the app has requested and if we can provide it.
480      * If not, bail out. */
481     if(!Curl_ipvalid(conn))
482       return CURLRESOLV_ERROR;
483 
484     /* If Curl_getaddrinfo() returns NULL, 'respwait' might be set to a
485        non-zero value indicating that we need to wait for the response to the
486        resolve call */
487     addr = Curl_getaddrinfo(conn,
488 #ifdef DEBUGBUILD
489                             (data->set.str[STRING_DEVICE]
490                              && !strcmp(data->set.str[STRING_DEVICE],
491                                         "LocalHost"))?"localhost":
492 #endif
493                             hostname, port, &respwait);
494 
495     if(!addr) {
496       if(respwait) {
497         /* the response to our resolve call will come asynchronously at
498            a later time, good or bad */
499         /* First, check that we haven't received the info by now */
500         result = Curl_resolver_is_resolved(conn, &dns);
501         if(result) /* error detected */
502           return CURLRESOLV_ERROR;
503         if(dns)
504           rc = CURLRESOLV_RESOLVED; /* pointer provided */
505         else
506           rc = CURLRESOLV_PENDING; /* no info yet */
507       }
508     }
509     else {
510       if(data->share)
511         Curl_share_lock(data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE);
512 
513       /* we got a response, store it in the cache */
514       dns = Curl_cache_addr(data, addr, hostname, port);
515 
516       if(data->share)
517         Curl_share_unlock(data, CURL_LOCK_DATA_DNS);
518 
519       if(!dns)
520         /* returned failure, bail out nicely */
521         Curl_freeaddrinfo(addr);
522       else
523         rc = CURLRESOLV_RESOLVED;
524     }
525   }
526 
527   *entry = dns;
528 
529   return rc;
530 }
531 
532 #ifdef USE_ALARM_TIMEOUT
533 /*
534  * This signal handler jumps back into the main libcurl code and continues
535  * execution.  This effectively causes the remainder of the application to run
536  * within a signal handler which is nonportable and could lead to problems.
537  */
538 static
alarmfunc(int sig)539 RETSIGTYPE alarmfunc(int sig)
540 {
541   /* this is for "-ansi -Wall -pedantic" to stop complaining!   (rabe) */
542   (void)sig;
543   siglongjmp(curl_jmpenv, 1);
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 
Curl_resolv_timeout(struct connectdata * conn,const char * hostname,int port,struct Curl_dns_entry ** entry,time_t timeoutms)569 int Curl_resolv_timeout(struct connectdata *conn,
570                         const char *hostname,
571                         int port,
572                         struct Curl_dns_entry **entry,
573                         time_t 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; /* whether 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 Curl_easy *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 > LONG_MAX) ? LONG_MAX : (long)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     failf(data,
612         "remaining timeout of %ld too small to resolve via SIGALRM method",
613         timeout);
614     return CURLRESOLV_TIMEDOUT;
615   }
616   /* This allows us to time-out from the name resolver, as the timeout
617      will generate a signal and we will siglongjmp() from that here.
618      This technique has problems (see alarmfunc).
619      This should be the last thing we do before calling Curl_resolv(),
620      as otherwise we'd have to worry about variables that get modified
621      before we invoke Curl_resolv() (and thus use "volatile"). */
622   if(sigsetjmp(curl_jmpenv, 1)) {
623     /* this is coming from a siglongjmp() after an alarm signal */
624     failf(data, "name lookup timed out");
625     rc = CURLRESOLV_ERROR;
626     goto clean_up;
627   }
628   else {
629     /*************************************************************
630      * Set signal handler to catch SIGALRM
631      * Store the old value to be able to set it back later!
632      *************************************************************/
633 #ifdef HAVE_SIGACTION
634     sigaction(SIGALRM, NULL, &sigact);
635     keep_sigact = sigact;
636     keep_copysig = TRUE; /* yes, we have a copy */
637     sigact.sa_handler = alarmfunc;
638 #ifdef SA_RESTART
639     /* HPUX doesn't have SA_RESTART but defaults to that behaviour! */
640     sigact.sa_flags &= ~SA_RESTART;
641 #endif
642     /* now set the new struct */
643     sigaction(SIGALRM, &sigact, NULL);
644 #else /* HAVE_SIGACTION */
645     /* no sigaction(), revert to the much lamer signal() */
646 #ifdef HAVE_SIGNAL
647     keep_sigact = signal(SIGALRM, alarmfunc);
648 #endif
649 #endif /* HAVE_SIGACTION */
650 
651     /* alarm() makes a signal get sent when the timeout fires off, and that
652        will abort system calls */
653     prev_alarm = alarm(curlx_sltoui(timeout/1000L));
654   }
655 
656 #else
657 #ifndef CURLRES_ASYNCH
658   if(timeoutms)
659     infof(conn->data, "timeout on name lookup is not supported\n");
660 #else
661   (void)timeoutms; /* timeoutms not used with an async resolver */
662 #endif
663 #endif /* USE_ALARM_TIMEOUT */
664 
665   /* Perform the actual name resolution. This might be interrupted by an
666    * alarm if it takes too long.
667    */
668   rc = Curl_resolv(conn, hostname, port, entry);
669 
670 #ifdef USE_ALARM_TIMEOUT
671 clean_up:
672 
673   if(!prev_alarm)
674     /* deactivate a possibly active alarm before uninstalling the handler */
675     alarm(0);
676 
677 #ifdef HAVE_SIGACTION
678   if(keep_copysig) {
679     /* we got a struct as it looked before, now put that one back nice
680        and clean */
681     sigaction(SIGALRM, &keep_sigact, NULL); /* put it back */
682   }
683 #else
684 #ifdef HAVE_SIGNAL
685   /* restore the previous SIGALRM handler */
686   signal(SIGALRM, keep_sigact);
687 #endif
688 #endif /* HAVE_SIGACTION */
689 
690   /* switch back the alarm() to either zero or to what it was before minus
691      the time we spent until now! */
692   if(prev_alarm) {
693     /* there was an alarm() set before us, now put it back */
694     timediff_t elapsed_secs = Curl_timediff(Curl_now(),
695                                             conn->created) / 1000;
696 
697     /* the alarm period is counted in even number of seconds */
698     unsigned long alarm_set = prev_alarm - elapsed_secs;
699 
700     if(!alarm_set ||
701        ((alarm_set >= 0x80000000) && (prev_alarm < 0x80000000)) ) {
702       /* if the alarm time-left reached zero or turned "negative" (counted
703          with unsigned values), we should fire off a SIGALRM here, but we
704          won't, and zero would be to switch it off so we never set it to
705          less than 1! */
706       alarm(1);
707       rc = CURLRESOLV_TIMEDOUT;
708       failf(data, "Previous alarm fired off!");
709     }
710     else
711       alarm((unsigned int)alarm_set);
712   }
713 #endif /* USE_ALARM_TIMEOUT */
714 
715   return rc;
716 }
717 
718 /*
719  * Curl_resolv_unlock() unlocks the given cached DNS entry. When this has been
720  * made, the struct may be destroyed due to pruning. It is important that only
721  * one unlock is made for each Curl_resolv() call.
722  *
723  * May be called with 'data' == NULL for global cache.
724  */
Curl_resolv_unlock(struct Curl_easy * data,struct Curl_dns_entry * dns)725 void Curl_resolv_unlock(struct Curl_easy *data, struct Curl_dns_entry *dns)
726 {
727   if(data && data->share)
728     Curl_share_lock(data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE);
729 
730   freednsentry(dns);
731 
732   if(data && data->share)
733     Curl_share_unlock(data, CURL_LOCK_DATA_DNS);
734 }
735 
736 /*
737  * File-internal: release cache dns entry reference, free if inuse drops to 0
738  */
freednsentry(void * freethis)739 static void freednsentry(void *freethis)
740 {
741   struct Curl_dns_entry *dns = (struct Curl_dns_entry *) freethis;
742   DEBUGASSERT(dns && (dns->inuse>0));
743 
744   dns->inuse--;
745   if(dns->inuse == 0) {
746     Curl_freeaddrinfo(dns->addr);
747     free(dns);
748   }
749 }
750 
751 /*
752  * Curl_mk_dnscache() inits a new DNS cache and returns success/failure.
753  */
Curl_mk_dnscache(struct curl_hash * hash)754 int Curl_mk_dnscache(struct curl_hash *hash)
755 {
756   return Curl_hash_init(hash, 7, Curl_hash_str, Curl_str_key_compare,
757                         freednsentry);
758 }
759 
760 /*
761  * Curl_hostcache_clean()
762  *
763  * This _can_ be called with 'data' == NULL but then of course no locking
764  * can be done!
765  */
766 
Curl_hostcache_clean(struct Curl_easy * data,struct curl_hash * hash)767 void Curl_hostcache_clean(struct Curl_easy *data,
768                           struct curl_hash *hash)
769 {
770   if(data && data->share)
771     Curl_share_lock(data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE);
772 
773   Curl_hash_clean(hash);
774 
775   if(data && data->share)
776     Curl_share_unlock(data, CURL_LOCK_DATA_DNS);
777 }
778 
779 
Curl_loadhostpairs(struct Curl_easy * data)780 CURLcode Curl_loadhostpairs(struct Curl_easy *data)
781 {
782   struct curl_slist *hostp;
783   char hostname[256];
784   int port;
785 
786   for(hostp = data->change.resolve; hostp; hostp = hostp->next) {
787     if(!hostp->data)
788       continue;
789     if(hostp->data[0] == '-') {
790       char *entry_id;
791       size_t entry_len;
792 
793       if(2 != sscanf(hostp->data + 1, "%255[^:]:%d", hostname, &port)) {
794         infof(data, "Couldn't parse CURLOPT_RESOLVE removal entry '%s'!\n",
795               hostp->data);
796         continue;
797       }
798 
799       /* Create an entry id, based upon the hostname and port */
800       entry_id = create_hostcache_id(hostname, port);
801       /* If we can't create the entry id, fail */
802       if(!entry_id) {
803         return CURLE_OUT_OF_MEMORY;
804       }
805 
806       entry_len = strlen(entry_id);
807 
808       if(data->share)
809         Curl_share_lock(data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE);
810 
811       /* delete entry, ignore if it didn't exist */
812       Curl_hash_delete(data->dns.hostcache, entry_id, entry_len + 1);
813 
814       if(data->share)
815         Curl_share_unlock(data, CURL_LOCK_DATA_DNS);
816 
817       /* free the allocated entry_id again */
818       free(entry_id);
819     }
820     else {
821       struct Curl_dns_entry *dns;
822       Curl_addrinfo *addr;
823       char *entry_id;
824       size_t entry_len;
825       char buffer[256];
826       char *address = &buffer[0];
827 
828       if(3 != sscanf(hostp->data, "%255[^:]:%d:%255s", hostname, &port,
829                      address)) {
830         infof(data, "Couldn't parse CURLOPT_RESOLVE entry '%s'!\n",
831               hostp->data);
832         continue;
833       }
834 
835       /* allow IP(v6) address within [brackets] */
836       if(address[0] == '[') {
837         size_t alen = strlen(address);
838         if(address[alen-1] != ']')
839           /* it needs to also end with ] to be valid */
840           continue;
841         address[alen-1] = 0; /* zero terminate there */
842         address++; /* pass the open bracket */
843       }
844 
845       addr = Curl_str2addr(address, port);
846       if(!addr) {
847         infof(data, "Address in '%s' found illegal!\n", hostp->data);
848         continue;
849       }
850 
851       /* Create an entry id, based upon the hostname and port */
852       entry_id = create_hostcache_id(hostname, port);
853       /* If we can't create the entry id, fail */
854       if(!entry_id) {
855         Curl_freeaddrinfo(addr);
856         return CURLE_OUT_OF_MEMORY;
857       }
858 
859       entry_len = strlen(entry_id);
860 
861       if(data->share)
862         Curl_share_lock(data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE);
863 
864       /* See if its already in our dns cache */
865       dns = Curl_hash_pick(data->dns.hostcache, entry_id, entry_len + 1);
866 
867       /* free the allocated entry_id again */
868       free(entry_id);
869 
870       if(!dns) {
871         /* if not in the cache already, put this host in the cache */
872         dns = Curl_cache_addr(data, addr, hostname, port);
873         if(dns) {
874           dns->timestamp = 0; /* mark as added by CURLOPT_RESOLVE */
875           /* release the returned reference; the cache itself will keep the
876            * entry alive: */
877           dns->inuse--;
878         }
879       }
880       else {
881         /* this is a duplicate, free it again */
882         infof(data, "RESOLVE %s:%d is already cached, %s not stored!\n",
883               hostname, port, address);
884         Curl_freeaddrinfo(addr);
885       }
886 
887       if(data->share)
888         Curl_share_unlock(data, CURL_LOCK_DATA_DNS);
889 
890       if(!dns) {
891         Curl_freeaddrinfo(addr);
892         return CURLE_OUT_OF_MEMORY;
893       }
894       infof(data, "Added %s:%d:%s to DNS cache\n",
895             hostname, port, address);
896     }
897   }
898   data->change.resolve = NULL; /* dealt with now */
899 
900   return CURLE_OK;
901 }
902