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