attempt to fix or allow further detection of an elusive icc SIGSEGV
[platform/upstream/curl.git] / lib / hostip.c
1 /***************************************************************************
2  *                                  _   _ ____  _
3  *  Project                     ___| | | |  _ \| |
4  *                             / __| | | | |_) | |
5  *                            | (__| |_| |  _ <| |___
6  *                             \___|\___/|_| \_\_____|
7  *
8  * Copyright (C) 1998 - 2008, 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  * $Id$
22  ***************************************************************************/
23
24 #include "setup.h"
25
26 #include <string.h>
27
28 #ifdef NEED_MALLOC_H
29 #include <malloc.h>
30 #endif
31 #ifdef HAVE_SYS_SOCKET_H
32 #include <sys/socket.h>
33 #endif
34 #ifdef HAVE_NETINET_IN_H
35 #include <netinet/in.h>
36 #endif
37 #ifdef HAVE_NETDB_H
38 #include <netdb.h>
39 #endif
40 #ifdef HAVE_ARPA_INET_H
41 #include <arpa/inet.h>
42 #endif
43 #ifdef HAVE_STDLIB_H
44 #include <stdlib.h>     /* required for free() prototypes */
45 #endif
46 #ifdef HAVE_UNISTD_H
47 #include <unistd.h>     /* for the close() proto */
48 #endif
49 #ifdef  VMS
50 #include <in.h>
51 #include <inet.h>
52 #include <stdlib.h>
53 #endif
54
55 #ifdef HAVE_SETJMP_H
56 #include <setjmp.h>
57 #endif
58 #ifdef HAVE_SIGNAL_H
59 #include <signal.h>
60 #endif
61
62 #ifdef HAVE_PROCESS_H
63 #include <process.h>
64 #endif
65
66 #include "urldata.h"
67 #include "sendf.h"
68 #include "hostip.h"
69 #include "hash.h"
70 #include "share.h"
71 #include "strerror.h"
72 #include "url.h"
73 #include "inet_ntop.h"
74
75 #define _MPRINTF_REPLACE /* use our functions only */
76 #include <curl/mprintf.h>
77
78 #include "memory.h"
79 /* The last #include file should be: */
80 #include "memdebug.h"
81
82 #if defined(HAVE_ALARM) && defined(SIGALRM) && defined(HAVE_SIGSETJMP) \
83     && !defined(USE_ARES)
84 /* alarm-based timeouts can only be used with all the dependencies satisfied */
85 #define USE_ALARM_TIMEOUT
86 #endif
87
88 /*
89  * hostip.c explained
90  * ==================
91  *
92  * The main COMPILE-TIME DEFINES to keep in mind when reading the host*.c
93  * source file are these:
94  *
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
98  * defined.
99  *
100  * CURLRES_ARES - is defined if libcurl is built to use c-ares for
101  * asynchronous name resolves. This can be Windows or *nix.
102  *
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.
106  *
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
109  * defined.
110  *
111  * The host*.c sources files are split up like this:
112  *
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
120  *
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.
123  */
124
125 /* These two symbols are for the global DNS cache */
126 static struct curl_hash hostname_cache;
127 static int host_cache_initialized;
128
129 static void freednsentry(void *freethis);
130
131 /*
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!
135  *
136  * Returns a struct curl_hash pointer on success, NULL on failure.
137  */
138 struct curl_hash *Curl_global_host_cache_init(void)
139 {
140   int rc = 0;
141   if(!host_cache_initialized) {
142     rc = Curl_hash_init(&hostname_cache, 7, Curl_hash_str,
143                         Curl_str_key_compare, freednsentry);
144     if(!rc)
145       host_cache_initialized = 1;
146   }
147   return rc?NULL:&hostname_cache;
148 }
149
150 /*
151  * Destroy and cleanup the global DNS cache
152  */
153 void Curl_global_host_cache_dtor(void)
154 {
155   if(host_cache_initialized) {
156     Curl_hash_clean(&hostname_cache);
157     host_cache_initialized = 0;
158   }
159 }
160
161 /*
162  * Return # of adresses in a Curl_addrinfo struct
163  */
164 int Curl_num_addresses(const Curl_addrinfo *addr)
165 {
166   int i = 0;
167   while(addr) {
168     addr = addr->ai_next;
169     i++;
170   }
171   return i;
172 }
173
174 /*
175  * Curl_printable_address() returns a printable version of the 1st address
176  * given in the 'ai' argument. The result will be stored in the buf that is
177  * bufsize bytes big.
178  *
179  * If the conversion fails, it returns NULL.
180  */
181 const char *
182 Curl_printable_address(const Curl_addrinfo *ai, char *buf, size_t bufsize)
183 {
184   struct sockaddr_in *sa4;
185   struct in_addr *ipaddr4;
186 #ifdef ENABLE_IPV6
187   struct sockaddr_in6 *sa6;
188   struct in6_addr *ipaddr6;
189 #endif
190
191   switch (ai->ai_family) {
192     case AF_INET:
193       sa4 = (struct sockaddr_in *)ai->ai_addr;
194       ipaddr4 = &sa4->sin_addr;
195       return Curl_inet_ntop(ai->ai_family, (const void *)ipaddr4, buf, bufsize);
196 #ifdef ENABLE_IPV6
197     case AF_INET6:
198       sa6 = (struct sockaddr_in6 *)ai->ai_addr;
199       ipaddr6 = &sa6->sin6_addr;
200       return Curl_inet_ntop(ai->ai_family, (const void *)ipaddr6, buf, bufsize);
201 #endif
202     default:
203       break;
204   }
205   return NULL;
206 }
207
208 /*
209  * Return a hostcache id string for the providing host + port, to be used by
210  * the DNS caching.
211  */
212 static char *
213 create_hostcache_id(const char *server, int port)
214 {
215   /* create and return the new allocated entry */
216   return aprintf("%s:%d", server, port);
217 }
218
219 struct hostcache_prune_data {
220   long cache_timeout;
221   time_t now;
222 };
223
224 /*
225  * This function is set as a callback to be called for every entry in the DNS
226  * cache when we want to prune old unused entries.
227  *
228  * Returning non-zero means remove the entry, return 0 to keep it in the
229  * cache.
230  */
231 static int
232 hostcache_timestamp_remove(void *datap, void *hc)
233 {
234   struct hostcache_prune_data *data =
235     (struct hostcache_prune_data *) datap;
236   struct Curl_dns_entry *c = (struct Curl_dns_entry *) hc;
237
238   if((data->now - c->timestamp < data->cache_timeout) ||
239       c->inuse) {
240     /* please don't remove */
241     return 0;
242   }
243
244   /* fine, remove */
245   return 1;
246 }
247
248 /*
249  * Prune the DNS cache. This assumes that a lock has already been taken.
250  */
251 static void
252 hostcache_prune(struct curl_hash *hostcache, long cache_timeout, time_t now)
253 {
254   struct hostcache_prune_data user;
255
256   user.cache_timeout = cache_timeout;
257   user.now = now;
258
259   Curl_hash_clean_with_criterium(hostcache,
260                                  (void *) &user,
261                                  hostcache_timestamp_remove);
262 }
263
264 /*
265  * Library-wide function for pruning the DNS cache. This function takes and
266  * returns the appropriate locks.
267  */
268 void Curl_hostcache_prune(struct SessionHandle *data)
269 {
270   time_t now;
271
272   if((data->set.dns_cache_timeout == -1) || !data->dns.hostcache)
273     /* cache forever means never prune, and NULL hostcache means
274        we can't do it */
275     return;
276
277   if(data->share)
278     Curl_share_lock(data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE);
279
280   time(&now);
281
282   /* Remove outdated and unused entries from the hostcache */
283   hostcache_prune(data->dns.hostcache,
284                   data->set.dns_cache_timeout,
285                   now);
286
287   if(data->share)
288     Curl_share_unlock(data, CURL_LOCK_DATA_DNS);
289 }
290
291 /*
292  * Check if the entry should be pruned. Assumes a locked cache.
293  */
294 static int
295 remove_entry_if_stale(struct SessionHandle *data, struct Curl_dns_entry *dns)
296 {
297   struct hostcache_prune_data user;
298
299   if( !dns || (data->set.dns_cache_timeout == -1) || !data->dns.hostcache)
300     /* cache forever means never prune, and NULL hostcache means
301        we can't do it */
302     return 0;
303
304   time(&user.now);
305   user.cache_timeout = data->set.dns_cache_timeout;
306
307   if( !hostcache_timestamp_remove(&user,dns) )
308     return 0;
309
310   Curl_hash_clean_with_criterium(data->dns.hostcache,
311                                  (void *) &user,
312                                  hostcache_timestamp_remove);
313
314   return 1;
315 }
316
317
318 #ifdef HAVE_SIGSETJMP
319 /* Beware this is a global and unique instance. This is used to store the
320    return address that we can jump back to from inside a signal handler. This
321    is not thread-safe stuff. */
322 sigjmp_buf curl_jmpenv;
323 #endif
324
325
326 /*
327  * Curl_cache_addr() stores a 'Curl_addrinfo' struct in the DNS cache.
328  *
329  * When calling Curl_resolv() has resulted in a response with a returned
330  * address, we call this function to store the information in the dns
331  * cache etc
332  *
333  * Returns the Curl_dns_entry entry pointer or NULL if the storage failed.
334  */
335 struct Curl_dns_entry *
336 Curl_cache_addr(struct SessionHandle *data,
337                 Curl_addrinfo *addr,
338                 const char *hostname,
339                 int port)
340 {
341   char *entry_id;
342   size_t entry_len;
343   struct Curl_dns_entry *dns;
344   struct Curl_dns_entry *dns2;
345   time_t now;
346
347   /* Create an entry id, based upon the hostname and port */
348   entry_id = create_hostcache_id(hostname, port);
349   /* If we can't create the entry id, fail */
350   if(!entry_id)
351     return NULL;
352   entry_len = strlen(entry_id);
353
354   /* Create a new cache entry */
355   dns = calloc(sizeof(struct Curl_dns_entry), 1);
356   if(!dns) {
357     free(entry_id);
358     return NULL;
359   }
360
361   dns->inuse = 0;   /* init to not used */
362   dns->addr = addr; /* this is the address(es) */
363
364   /* Store the resolved data in our DNS cache. This function may return a
365      pointer to an existing struct already present in the hash, and it may
366      return the same argument we pass in. Make no assumptions. */
367   dns2 = Curl_hash_add(data->dns.hostcache, entry_id, entry_len+1,
368                        (void *)dns);
369   if(!dns2) {
370     /* Major badness, run away. */
371     free(dns);
372     free(entry_id);
373     return NULL;
374   }
375   time(&now);
376   dns = dns2;
377
378   dns->timestamp = now; /* used now */
379   dns->inuse++;         /* mark entry as in-use */
380
381   /* free the allocated entry_id again */
382   free(entry_id);
383
384   return dns;
385 }
386
387 /*
388  * Curl_resolv() is the main name resolve function within libcurl. It resolves
389  * a name and returns a pointer to the entry in the 'entry' argument (if one
390  * is provided). This function might return immediately if we're using asynch
391  * resolves. See the return codes.
392  *
393  * The cache entry we return will get its 'inuse' counter increased when this
394  * function is used. You MUST call Curl_resolv_unlock() later (when you're
395  * done using this struct) to decrease the counter again.
396  *
397  * Return codes:
398  *
399  * CURLRESOLV_ERROR   (-1) = error, no pointer
400  * CURLRESOLV_RESOLVED (0) = OK, pointer provided
401  * CURLRESOLV_PENDING  (1) = waiting for response, no pointer
402  */
403
404 int Curl_resolv(struct connectdata *conn,
405                 const char *hostname,
406                 int port,
407                 struct Curl_dns_entry **entry)
408 {
409   char *entry_id = NULL;
410   struct Curl_dns_entry *dns = NULL;
411   size_t entry_len;
412   struct SessionHandle *data = conn->data;
413   CURLcode result;
414   int rc = CURLRESOLV_ERROR; /* default to failure */
415
416   *entry = NULL;
417
418   /* Create an entry id, based upon the hostname and port */
419   entry_id = create_hostcache_id(hostname, port);
420   /* If we can't create the entry id, fail */
421   if(!entry_id)
422     return rc;
423
424   entry_len = strlen(entry_id);
425
426   if(data->share)
427     Curl_share_lock(data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE);
428
429   /* See if its already in our dns cache */
430   dns = Curl_hash_pick(data->dns.hostcache, entry_id, entry_len+1);
431
432   /* See whether the returned entry is stale. Done before we release lock */
433   if( remove_entry_if_stale(data, dns) )
434     dns = NULL; /* the memory deallocation is being handled by the hash */
435
436   if(dns) {
437     dns->inuse++; /* we use it! */
438     rc = CURLRESOLV_RESOLVED;
439   }
440
441   if(data->share)
442     Curl_share_unlock(data, CURL_LOCK_DATA_DNS);
443
444   /* free the allocated entry_id again */
445   free(entry_id);
446
447   if(!dns) {
448     /* The entry was not in the cache. Resolve it to IP address */
449
450     Curl_addrinfo *addr;
451     int respwait;
452
453     /* Check what IP specifics the app has requested and if we can provide it.
454      * If not, bail out. */
455     if(!Curl_ipvalid(data))
456       return CURLRESOLV_ERROR;
457
458     /* If Curl_getaddrinfo() returns NULL, 'respwait' might be set to a
459        non-zero value indicating that we need to wait for the response to the
460        resolve call */
461     addr = Curl_getaddrinfo(conn, hostname, port, &respwait);
462
463     if(!addr) {
464       if(respwait) {
465         /* the response to our resolve call will come asynchronously at
466            a later time, good or bad */
467         /* First, check that we haven't received the info by now */
468         result = Curl_is_resolved(conn, &dns);
469         if(result) /* error detected */
470           return CURLRESOLV_ERROR;
471         if(dns)
472           rc = CURLRESOLV_RESOLVED; /* pointer provided */
473         else
474           rc = CURLRESOLV_PENDING; /* no info yet */
475       }
476     }
477     else {
478       if(data->share)
479         Curl_share_lock(data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE);
480
481       /* we got a response, store it in the cache */
482       dns = Curl_cache_addr(data, addr, hostname, port);
483
484       if(data->share)
485         Curl_share_unlock(data, CURL_LOCK_DATA_DNS);
486
487       if(!dns)
488         /* returned failure, bail out nicely */
489         Curl_freeaddrinfo(addr);
490       else
491         rc = CURLRESOLV_RESOLVED;
492     }
493   }
494
495   *entry = dns;
496
497   return rc;
498 }
499
500 #ifdef USE_ALARM_TIMEOUT 
501 /*
502  * This signal handler jumps back into the main libcurl code and continues
503  * execution.  This effectively causes the remainder of the application to run
504  * within a signal handler which is nonportable and could lead to problems.
505  */
506 static
507 RETSIGTYPE alarmfunc(int sig)
508 {
509   /* this is for "-ansi -Wall -pedantic" to stop complaining!   (rabe) */
510   (void)sig;
511   siglongjmp(curl_jmpenv, 1);
512   return;
513 }
514 #endif /* USE_ALARM_TIMEOUT */
515
516 /*
517  * Curl_resolv_timeout() is the same as Curl_resolv() but specifies a
518  * timeout.  This function might return immediately if we're using asynch
519  * resolves. See the return codes.
520  *
521  * The cache entry we return will get its 'inuse' counter increased when this
522  * function is used. You MUST call Curl_resolv_unlock() later (when you're
523  * done using this struct) to decrease the counter again.
524  *
525  * If built with a synchronous resolver and use of signals is not
526  * disabled by the application, then a nonzero timeout will cause a
527  * timeout after the specified number of milliseconds. Otherwise, timeout
528  * is ignored.
529  *
530  * Return codes:
531  *
532  * CURLRESOLV_TIMEDOUT(-2) = warning, time too short or previous alarm expired
533  * CURLRESOLV_ERROR   (-1) = error, no pointer
534  * CURLRESOLV_RESOLVED (0) = OK, pointer provided
535  * CURLRESOLV_PENDING  (1) = waiting for response, no pointer
536  */
537
538 int Curl_resolv_timeout(struct connectdata *conn,
539                         const char *hostname,
540                         int port,
541                         struct Curl_dns_entry **entry,
542                         long timeoutms)
543 {
544 #ifdef USE_ALARM_TIMEOUT 
545 #ifdef HAVE_SIGACTION
546   struct sigaction keep_sigact;   /* store the old struct here */
547   bool keep_copysig=FALSE;        /* did copy it? */
548   struct sigaction sigact;
549 #else
550 #ifdef HAVE_SIGNAL
551   void (*keep_sigact)(int);       /* store the old handler here */
552 #endif /* HAVE_SIGNAL */
553 #endif /* HAVE_SIGACTION */
554   volatile long timeout;
555   unsigned int prev_alarm=0;
556   struct SessionHandle *data = conn->data;
557 #endif /* USE_ALARM_TIMEOUT */
558   int rc;
559
560   *entry = NULL;
561
562 #ifdef USE_ALARM_TIMEOUT 
563   if (data->set.no_signal)
564     /* Ignore the timeout when signals are disabled */
565     timeout = 0;
566   else
567     timeout = timeoutms;
568
569   if(timeout && timeout < 1000)
570     /* The alarm() function only provides integer second resolution, so if
571        we want to wait less than one second we must bail out already now. */
572     return CURLRESOLV_TIMEDOUT;
573
574   if (timeout > 0) {
575     /* This allows us to time-out from the name resolver, as the timeout
576        will generate a signal and we will siglongjmp() from that here.
577        This technique has problems (see alarmfunc). */
578       if(sigsetjmp(curl_jmpenv, 1)) {
579         /* this is coming from a siglongjmp() after an alarm signal */
580         failf(data, "name lookup timed out");
581         return CURLRESOLV_ERROR;
582       }
583
584     /*************************************************************
585      * Set signal handler to catch SIGALRM
586      * Store the old value to be able to set it back later!
587      *************************************************************/
588 #ifdef HAVE_SIGACTION
589     sigaction(SIGALRM, NULL, &sigact);
590     keep_sigact = sigact;
591     keep_copysig = TRUE; /* yes, we have a copy */
592     sigact.sa_handler = alarmfunc;
593 #ifdef SA_RESTART
594     /* HPUX doesn't have SA_RESTART but defaults to that behaviour! */
595     sigact.sa_flags &= ~SA_RESTART;
596 #endif
597     /* now set the new struct */
598     sigaction(SIGALRM, &sigact, NULL);
599 #else /* HAVE_SIGACTION */
600     /* no sigaction(), revert to the much lamer signal() */
601 #ifdef HAVE_SIGNAL
602     keep_sigact = signal(SIGALRM, alarmfunc);
603 #endif
604 #endif /* HAVE_SIGACTION */
605
606     /* alarm() makes a signal get sent when the timeout fires off, and that
607        will abort system calls */
608     prev_alarm = alarm((unsigned int) (timeout/1000L));
609   }
610
611 #else
612 #ifndef CURLRES_ASYNCH
613   if(timeoutms)
614     infof(conn->data, "timeout on name lookup is not supported\n");
615 #else
616   (void)timeoutms; /* timeoutms not used with an async resolver */
617 #endif
618 #endif /* USE_ALARM_TIMEOUT */
619
620   /* Perform the actual name resolution. This might be interrupted by an
621    * alarm if it takes too long.
622    */
623   rc = Curl_resolv(conn, hostname, port, entry);
624
625 #ifdef USE_ALARM_TIMEOUT 
626   if (timeout > 0) {
627
628 #ifdef HAVE_SIGACTION
629     if(keep_copysig) {
630       /* we got a struct as it looked before, now put that one back nice
631          and clean */
632       sigaction(SIGALRM, &keep_sigact, NULL); /* put it back */
633     }
634 #else
635 #ifdef HAVE_SIGNAL
636     /* restore the previous SIGALRM handler */
637     signal(SIGALRM, keep_sigact);
638 #endif
639 #endif /* HAVE_SIGACTION */
640
641     /* switch back the alarm() to either zero or to what it was before minus
642        the time we spent until now! */
643     if(prev_alarm) {
644       /* there was an alarm() set before us, now put it back */
645       unsigned long elapsed_ms = Curl_tvdiff(Curl_tvnow(), conn->created);
646
647       /* the alarm period is counted in even number of seconds */
648       unsigned long alarm_set = prev_alarm - elapsed_ms/1000;
649
650       if(!alarm_set ||
651          ((alarm_set >= 0x80000000) && (prev_alarm < 0x80000000)) ) {
652         /* if the alarm time-left reached zero or turned "negative" (counted
653            with unsigned values), we should fire off a SIGALRM here, but we
654            won't, and zero would be to switch it off so we never set it to
655            less than 1! */
656         alarm(1);
657         rc = CURLRESOLV_TIMEDOUT;
658         failf(data, "Previous alarm fired off!");
659       }
660       else
661         alarm((unsigned int)alarm_set);
662     }
663     else
664       alarm(0); /* just shut it off */
665   }
666 #endif /* USE_ALARM_TIMEOUT */
667
668   return rc;
669 }
670
671 /*
672  * Curl_resolv_unlock() unlocks the given cached DNS entry. When this has been
673  * made, the struct may be destroyed due to pruning. It is important that only
674  * one unlock is made for each Curl_resolv() call.
675  */
676 void Curl_resolv_unlock(struct SessionHandle *data, struct Curl_dns_entry *dns)
677 {
678   DEBUGASSERT(dns && (dns->inuse>0));
679
680   if(data->share)
681     Curl_share_lock(data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE);
682
683   dns->inuse--;
684
685   if(data->share)
686     Curl_share_unlock(data, CURL_LOCK_DATA_DNS);
687 }
688
689 /*
690  * File-internal: free a cache dns entry.
691  */
692 static void freednsentry(void *freethis)
693 {
694   struct Curl_dns_entry *p = (struct Curl_dns_entry *) freethis;
695
696   Curl_freeaddrinfo(p->addr);
697
698   memset(p, 0, sizeof(struct Curl_dns_entry));
699   free(p);
700 }
701
702 /*
703  * Curl_mk_dnscache() creates a new DNS cache and returns the handle for it.
704  */
705 struct curl_hash *Curl_mk_dnscache(void)
706 {
707   return Curl_hash_alloc(7, Curl_hash_str, Curl_str_key_compare, freednsentry);
708 }
709
710 #ifdef CURLRES_ADDRINFO_COPY
711
712 /* align on even 64bit boundaries */
713 #define MEMALIGN(x) ((x)+(8-(((unsigned long)(x))&0x7)))
714
715 /*
716  * Curl_addrinfo_copy() performs a "deep" copy of a hostent into a buffer and
717  * returns a pointer to the malloc()ed copy. You need to call free() on the
718  * returned buffer when you're done with it.
719  */
720 Curl_addrinfo *Curl_addrinfo_copy(const void *org, int port)
721 {
722   const struct hostent *orig = org;
723
724   return Curl_he2ai(orig, port);
725 }
726 #endif /* CURLRES_ADDRINFO_COPY */
727
728 /***********************************************************************
729  * Only for plain-ipv4 and c-ares builds (NOTE: c-ares builds can be IPv6
730  * enabled)
731  **********************************************************************/
732
733 #if defined(CURLRES_IPV4) || defined(CURLRES_ARES)
734 /*
735  * This is a function for freeing name information in a protocol independent
736  * way.
737  */
738 void Curl_freeaddrinfo(Curl_addrinfo *ai)
739 {
740   Curl_addrinfo *next;
741
742   /* walk over the list and free all entries */
743   while(ai) {
744     next = ai->ai_next;
745     if(ai->ai_addr)
746       free(ai->ai_addr);
747     if(ai->ai_canonname)
748       free(ai->ai_canonname);
749     memset(ai, 0, sizeof(Curl_addrinfo));
750     free(ai);
751     ai = next;
752   }
753 }
754
755 struct namebuf4 {
756   struct hostent hostentry;
757   struct in_addr addrentry;
758   char *h_addr_list[2];
759 };
760
761 /*
762  * Curl_ip2addr() takes a 32bit ipv4 internet address as input parameter
763  * together with a pointer to the string version of the address, and it
764  * returns a Curl_addrinfo chain filled in correctly with information for this
765  * address/host.
766  *
767  * The input parameters ARE NOT checked for validity but they are expected
768  * to have been checked already when this is called.
769  */
770 Curl_addrinfo *Curl_ip2addr(in_addr_t num, const char *hostname, int port)
771 {
772   Curl_addrinfo *ai;
773
774 #if defined(VMS) && \
775     defined(__INITIAL_POINTER_SIZE) && (__INITIAL_POINTER_SIZE == 64)
776 #pragma pointer_size save
777 #pragma pointer_size short
778 #pragma message disable PTRMISMATCH
779 #endif
780
781   struct hostent  *h;
782   struct in_addr  *addrentry;
783   struct namebuf4 *buf;
784   char  *hoststr;
785
786   DEBUGASSERT(hostname);
787
788   buf = malloc(sizeof(struct namebuf4));
789   if(!buf)
790     return NULL;
791
792   hoststr = strdup(hostname);
793   if(!hoststr) {
794     free(buf);
795     return NULL;
796   }
797
798   addrentry = &buf->addrentry;
799 #ifdef _CRAYC
800   /* On UNICOS, s_addr is a bit field and for some reason assigning to it
801    * doesn't work.  There must be a better fix than this ugly hack.
802    */
803   memcpy(addrentry, &num, SIZEOF_in_addr);
804 #else
805   addrentry->s_addr = num;
806 #endif
807
808   h = &buf->hostentry;
809   h->h_name = hoststr;
810   h->h_aliases = NULL;
811   h->h_addrtype = AF_INET;
812   h->h_length = sizeof(struct in_addr);
813   h->h_addr_list = &buf->h_addr_list[0];
814   h->h_addr_list[0] = (char*)addrentry;
815   h->h_addr_list[1] = NULL; /* terminate list of entries */
816
817 #if defined(VMS) && \
818     defined(__INITIAL_POINTER_SIZE) && (__INITIAL_POINTER_SIZE == 64)
819 #pragma pointer_size restore
820 #pragma message enable PTRMISMATCH
821 #endif
822
823   ai = Curl_he2ai(h, port);
824
825   free(hoststr);
826   free(buf);
827
828   return ai;
829 }
830
831 /*
832  * Curl_he2ai() translates from a hostent struct to a Curl_addrinfo struct.
833  * The Curl_addrinfo is meant to work like the addrinfo struct does for IPv6
834  * stacks, but for all hosts and environments.
835  *
836  *   Curl_addrinfo defined in "lib/hostip.h"
837  *
838  *     struct Curl_addrinfo {
839  *       int                   ai_flags;
840  *       int                   ai_family;
841  *       int                   ai_socktype;
842  *       int                   ai_protocol;
843  *       socklen_t             ai_addrlen;   * Follow rfc3493 struct addrinfo *
844  *       char                 *ai_canonname;
845  *       struct sockaddr      *ai_addr;
846  *       struct Curl_addrinfo *ai_next;
847  *     };
848  *
849  *   hostent defined in <netdb.h>
850  *
851  *     struct hostent {
852  *       char    *h_name;
853  *       char    **h_aliases;
854  *       int     h_addrtype;
855  *       int     h_length;
856  *       char    **h_addr_list;
857  *     };
858  *
859  *   for backward compatibility:
860  *
861  *     #define h_addr  h_addr_list[0]
862  */
863
864 Curl_addrinfo *Curl_he2ai(const struct hostent *he, int port)
865 {
866   Curl_addrinfo *ai;
867   Curl_addrinfo *prevai = NULL;
868   Curl_addrinfo *firstai = NULL;
869   struct sockaddr_in *addr;
870 #ifdef CURLRES_IPV6
871   struct sockaddr_in6 *addr6;
872 #endif /* CURLRES_IPV6 */
873   CURLcode result = CURLE_OK;
874   int i;
875   char *curr;
876
877   if(!he)
878     /* no input == no output! */
879     return NULL;
880
881   for(i=0; (curr = he->h_addr_list[i]) != NULL; i++) {
882
883     int ss_size;
884 #ifdef CURLRES_IPV6
885     if (he->h_addrtype == AF_INET6)
886       ss_size = sizeof (struct sockaddr_in6);
887     else
888 #endif /* CURLRES_IPV6 */
889       ss_size = sizeof (struct sockaddr_in);
890
891     if((ai = calloc(1, sizeof(Curl_addrinfo))) == NULL) {
892       result = CURLE_OUT_OF_MEMORY;
893       break;
894     }
895     if((ai->ai_canonname = strdup(he->h_name)) == NULL) {
896       result = CURLE_OUT_OF_MEMORY;
897       free(ai);
898       break;
899     }
900     if((ai->ai_addr = calloc(1, ss_size)) == NULL) {
901       result = CURLE_OUT_OF_MEMORY;
902       free(ai->ai_canonname);
903       free(ai);
904       break;
905     }
906
907     if(!firstai)
908       /* store the pointer we want to return from this function */
909       firstai = ai;
910
911     if(prevai)
912       /* make the previous entry point to this */
913       prevai->ai_next = ai;
914
915     ai->ai_family = he->h_addrtype;
916
917     /* we return all names as STREAM, so when using this address for TFTP
918        the type must be ignored and conn->socktype be used instead! */
919     ai->ai_socktype = SOCK_STREAM;
920
921     ai->ai_addrlen = ss_size;
922
923     /* leave the rest of the struct filled with zero */
924
925     switch (ai->ai_family) {
926     case AF_INET:
927       addr = (struct sockaddr_in *)ai->ai_addr; /* storage area for this info */
928
929       memcpy(&addr->sin_addr, curr, sizeof(struct in_addr));
930       addr->sin_family = (unsigned short)(he->h_addrtype);
931       addr->sin_port = htons((unsigned short)port);
932       break;
933
934 #ifdef CURLRES_IPV6
935     case AF_INET6:
936       addr6 = (struct sockaddr_in6 *)ai->ai_addr; /* storage area for this info */
937
938       memcpy(&addr6->sin6_addr, curr, sizeof(struct in6_addr));
939       addr6->sin6_family = (unsigned short)(he->h_addrtype);
940       addr6->sin6_port = htons((unsigned short)port);
941       break;
942 #endif /* CURLRES_IPV6 */
943     }
944
945     prevai = ai;
946   }
947
948   if(result != CURLE_OK) {
949     Curl_freeaddrinfo(firstai);
950     firstai = NULL;
951   }
952
953   return firstai;
954 }
955
956 #endif /* CURLRES_IPV4 || CURLRES_ARES */