1 /*
2  * Original file name getaddrinfo.c
3  * Lifted from the 'Android Bionic' project with the BSD license.
4  */
5 
6 /*
7  * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
8  * Copyright (C) 2018 The Android Open Source Project
9  * Copyright (C) 2019 Andrew Selivanov
10  * All rights reserved.
11  *
12  * Redistribution and use in source and binary forms, with or without
13  * modification, are permitted provided that the following conditions
14  * are met:
15  * 1. Redistributions of source code must retain the above copyright
16  *    notice, this list of conditions and the following disclaimer.
17  * 2. Redistributions in binary form must reproduce the above copyright
18  *    notice, this list of conditions and the following disclaimer in the
19  *    documentation and/or other materials provided with the distribution.
20  * 3. Neither the name of the project nor the names of its contributors
21  *    may be used to endorse or promote products derived from this software
22  *    without specific prior written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34  * SUCH DAMAGE.
35  *
36  * SPDX-License-Identifier: BSD-3-Clause
37  */
38 
39 #include "ares_setup.h"
40 
41 #ifdef HAVE_NETINET_IN_H
42 #  include <netinet/in.h>
43 #endif
44 #ifdef HAVE_NETDB_H
45 #  include <netdb.h>
46 #endif
47 #ifdef HAVE_STRINGS_H
48 #  include <strings.h>
49 #endif
50 
51 #include <assert.h>
52 #include <limits.h>
53 
54 #include "ares.h"
55 #include "ares_private.h"
56 
57 struct addrinfo_sort_elem {
58   struct ares_addrinfo_node *ai;
59   ares_bool_t                has_src_addr;
60   ares_sockaddr              src_addr;
61   size_t                     original_order;
62 };
63 
64 #define ARES_IPV6_ADDR_MC_SCOPE(a) ((a)->s6_addr[1] & 0x0f)
65 
66 #define ARES_IPV6_ADDR_SCOPE_NODELOCAL    0x01
67 #define ARES_IPV6_ADDR_SCOPE_INTFACELOCAL 0x01
68 #define ARES_IPV6_ADDR_SCOPE_LINKLOCAL    0x02
69 #define ARES_IPV6_ADDR_SCOPE_SITELOCAL    0x05
70 #define ARES_IPV6_ADDR_SCOPE_ORGLOCAL     0x08
71 #define ARES_IPV6_ADDR_SCOPE_GLOBAL       0x0e
72 
73 #define ARES_IN_LOOPBACK(a) \
74   ((((long unsigned int)(a)) & 0xff000000) == 0x7f000000)
75 
76 /* RFC 4193. */
77 #define ARES_IN6_IS_ADDR_ULA(a) (((a)->s6_addr[0] & 0xfe) == 0xfc)
78 
79 /* These macros are modelled after the ones in <netinet/in6.h>. */
80 /* RFC 4380, section 2.6 */
81 #define ARES_IN6_IS_ADDR_TEREDO(a)                             \
82   ((*(const unsigned int *)(const void *)(&(a)->s6_addr[0]) == \
83     ntohl(0x20010000)))
84 /* RFC 3056, section 2. */
85 #define ARES_IN6_IS_ADDR_6TO4(a) \
86   (((a)->s6_addr[0] == 0x20) && ((a)->s6_addr[1] == 0x02))
87 /* 6bone testing address area (3ffe::/16), deprecated in RFC 3701. */
88 #define ARES_IN6_IS_ADDR_6BONE(a) \
89   (((a)->s6_addr[0] == 0x3f) && ((a)->s6_addr[1] == 0xfe))
90 
get_scope(const struct sockaddr *addr)91 static int get_scope(const struct sockaddr *addr)
92 {
93   if (addr->sa_family == AF_INET6) {
94     const struct sockaddr_in6 *addr6 =
95       CARES_INADDR_CAST(const struct sockaddr_in6 *, addr);
96     if (IN6_IS_ADDR_MULTICAST(&addr6->sin6_addr)) {
97       return ARES_IPV6_ADDR_MC_SCOPE(&addr6->sin6_addr);
98     } else if (IN6_IS_ADDR_LOOPBACK(&addr6->sin6_addr) ||
99                IN6_IS_ADDR_LINKLOCAL(&addr6->sin6_addr)) {
100       /*
101        * RFC 4291 section 2.5.3 says loopback is to be treated as having
102        * link-local scope.
103        */
104       return ARES_IPV6_ADDR_SCOPE_LINKLOCAL;
105     } else if (IN6_IS_ADDR_SITELOCAL(&addr6->sin6_addr)) {
106       return ARES_IPV6_ADDR_SCOPE_SITELOCAL;
107     } else {
108       return ARES_IPV6_ADDR_SCOPE_GLOBAL;
109     }
110   } else if (addr->sa_family == AF_INET) {
111     const struct sockaddr_in *addr4 =
112       CARES_INADDR_CAST(const struct sockaddr_in *, addr);
113     unsigned long int na = ntohl(addr4->sin_addr.s_addr);
114     if (ARES_IN_LOOPBACK(na) ||          /* 127.0.0.0/8 */
115         (na & 0xffff0000) == 0xa9fe0000) /* 169.254.0.0/16 */
116     {
117       return ARES_IPV6_ADDR_SCOPE_LINKLOCAL;
118     } else {
119       /*
120        * RFC 6724 section 3.2. Other IPv4 addresses, including private
121        * addresses and shared addresses (100.64.0.0/10), are assigned global
122        * scope.
123        */
124       return ARES_IPV6_ADDR_SCOPE_GLOBAL;
125     }
126   } else {
127     /*
128      * This should never happen.
129      * Return a scope with low priority as a last resort.
130      */
131     return ARES_IPV6_ADDR_SCOPE_NODELOCAL;
132   }
133 }
134 
get_label(const struct sockaddr *addr)135 static int get_label(const struct sockaddr *addr)
136 {
137   if (addr->sa_family == AF_INET) {
138     return 4;
139   } else if (addr->sa_family == AF_INET6) {
140     const struct sockaddr_in6 *addr6 =
141       CARES_INADDR_CAST(const struct sockaddr_in6 *, addr);
142     if (IN6_IS_ADDR_LOOPBACK(&addr6->sin6_addr)) {
143       return 0;
144     } else if (IN6_IS_ADDR_V4MAPPED(&addr6->sin6_addr)) {
145       return 4;
146     } else if (ARES_IN6_IS_ADDR_6TO4(&addr6->sin6_addr)) {
147       return 2;
148     } else if (ARES_IN6_IS_ADDR_TEREDO(&addr6->sin6_addr)) {
149       return 5;
150     } else if (ARES_IN6_IS_ADDR_ULA(&addr6->sin6_addr)) {
151       return 13;
152     } else if (IN6_IS_ADDR_V4COMPAT(&addr6->sin6_addr)) {
153       return 3;
154     } else if (IN6_IS_ADDR_SITELOCAL(&addr6->sin6_addr)) {
155       return 11;
156     } else if (ARES_IN6_IS_ADDR_6BONE(&addr6->sin6_addr)) {
157       return 12;
158     } else {
159       /* All other IPv6 addresses, including global unicast addresses. */
160       return 1;
161     }
162   } else {
163     /*
164      * This should never happen.
165      * Return a semi-random label as a last resort.
166      */
167     return 1;
168   }
169 }
170 
171 /*
172  * Get the precedence for a given IPv4/IPv6 address.
173  * RFC 6724, section 2.1.
174  */
get_precedence(const struct sockaddr *addr)175 static int get_precedence(const struct sockaddr *addr)
176 {
177   if (addr->sa_family == AF_INET) {
178     return 35;
179   } else if (addr->sa_family == AF_INET6) {
180     const struct sockaddr_in6 *addr6 =
181       CARES_INADDR_CAST(const struct sockaddr_in6 *, addr);
182     if (IN6_IS_ADDR_LOOPBACK(&addr6->sin6_addr)) {
183       return 50;
184     } else if (IN6_IS_ADDR_V4MAPPED(&addr6->sin6_addr)) {
185       return 35;
186     } else if (ARES_IN6_IS_ADDR_6TO4(&addr6->sin6_addr)) {
187       return 30;
188     } else if (ARES_IN6_IS_ADDR_TEREDO(&addr6->sin6_addr)) {
189       return 5;
190     } else if (ARES_IN6_IS_ADDR_ULA(&addr6->sin6_addr)) {
191       return 3;
192     } else if (IN6_IS_ADDR_V4COMPAT(&addr6->sin6_addr) ||
193                IN6_IS_ADDR_SITELOCAL(&addr6->sin6_addr) ||
194                ARES_IN6_IS_ADDR_6BONE(&addr6->sin6_addr)) {
195       return 1;
196     } else {
197       /* All other IPv6 addresses, including global unicast addresses. */
198       return 40;
199     }
200   } else {
201     return 1;
202   }
203 }
204 
205 /*
206  * Find number of matching initial bits between the two addresses a1 and a2.
207  */
common_prefix_len(const struct in6_addr *a1, const struct in6_addr *a2)208 static size_t common_prefix_len(const struct in6_addr *a1,
209                                 const struct in6_addr *a2)
210 {
211   const unsigned char *p1 = (const unsigned char *)a1;
212   const unsigned char *p2 = (const unsigned char *)a2;
213   size_t               i;
214   for (i = 0; i < sizeof(*a1); ++i) {
215     unsigned char x;
216     size_t        j;
217     if (p1[i] == p2[i]) {
218       continue;
219     }
220     x = p1[i] ^ p2[i];
221     for (j = 0; j < CHAR_BIT; ++j) {
222       if (x & (1 << (CHAR_BIT - 1))) {
223         return i * CHAR_BIT + j;
224       }
225       x <<= 1;
226     }
227   }
228   return sizeof(*a1) * CHAR_BIT;
229 }
230 
231 /*
232  * Compare two source/destination address pairs.
233  * RFC 6724, section 6.
234  */
rfc6724_compare(const void *ptr1, const void *ptr2)235 static int rfc6724_compare(const void *ptr1, const void *ptr2)
236 {
237   const struct addrinfo_sort_elem *a1 = (const struct addrinfo_sort_elem *)ptr1;
238   const struct addrinfo_sort_elem *a2 = (const struct addrinfo_sort_elem *)ptr2;
239   int                              scope_src1;
240   int                              scope_dst1;
241   int                              scope_match1;
242   int                              scope_src2;
243   int                              scope_dst2;
244   int                              scope_match2;
245   int                              label_src1;
246   int                              label_dst1;
247   int                              label_match1;
248   int                              label_src2;
249   int                              label_dst2;
250   int                              label_match2;
251   int                              precedence1;
252   int                              precedence2;
253   size_t                           prefixlen1;
254   size_t                           prefixlen2;
255 
256   /* Rule 1: Avoid unusable destinations. */
257   if (a1->has_src_addr != a2->has_src_addr) {
258     return ((int)a2->has_src_addr) - ((int)a1->has_src_addr);
259   }
260 
261   /* Rule 2: Prefer matching scope. */
262   scope_src1 = ARES_IPV6_ADDR_SCOPE_NODELOCAL;
263   if (a1->has_src_addr) {
264     scope_src1 = get_scope(&a1->src_addr.sa);
265   }
266   scope_dst1   = get_scope(a1->ai->ai_addr);
267   scope_match1 = (scope_src1 == scope_dst1);
268 
269   scope_src2 = ARES_IPV6_ADDR_SCOPE_NODELOCAL;
270   if (a2->has_src_addr) {
271     scope_src2 = get_scope(&a2->src_addr.sa);
272   }
273   scope_dst2   = get_scope(a2->ai->ai_addr);
274   scope_match2 = (scope_src2 == scope_dst2);
275 
276   if (scope_match1 != scope_match2) {
277     return scope_match2 - scope_match1;
278   }
279 
280   /* Rule 3: Avoid deprecated addresses.  */
281 
282   /* Rule 4: Prefer home addresses.  */
283 
284   /* Rule 5: Prefer matching label. */
285   label_src1 = 1;
286   if (a1->has_src_addr) {
287     label_src1 = get_label(&a1->src_addr.sa);
288   }
289   label_dst1   = get_label(a1->ai->ai_addr);
290   label_match1 = (label_src1 == label_dst1);
291 
292   label_src2 = 1;
293   if (a2->has_src_addr) {
294     label_src2 = get_label(&a2->src_addr.sa);
295   }
296   label_dst2   = get_label(a2->ai->ai_addr);
297   label_match2 = (label_src2 == label_dst2);
298 
299   if (label_match1 != label_match2) {
300     return label_match2 - label_match1;
301   }
302 
303   /* Rule 6: Prefer higher precedence. */
304   precedence1 = get_precedence(a1->ai->ai_addr);
305   precedence2 = get_precedence(a2->ai->ai_addr);
306   if (precedence1 != precedence2) {
307     return precedence2 - precedence1;
308   }
309 
310   /* Rule 7: Prefer native transport.  */
311 
312   /* Rule 8: Prefer smaller scope. */
313   if (scope_dst1 != scope_dst2) {
314     return scope_dst1 - scope_dst2;
315   }
316 
317   /* Rule 9: Use longest matching prefix. */
318   if (a1->has_src_addr && a1->ai->ai_addr->sa_family == AF_INET6 &&
319       a2->has_src_addr && a2->ai->ai_addr->sa_family == AF_INET6) {
320     const struct sockaddr_in6 *a1_src = &a1->src_addr.sa6;
321     const struct sockaddr_in6 *a1_dst =
322       CARES_INADDR_CAST(const struct sockaddr_in6 *, a1->ai->ai_addr);
323     const struct sockaddr_in6 *a2_src = &a2->src_addr.sa6;
324     const struct sockaddr_in6 *a2_dst =
325       CARES_INADDR_CAST(const struct sockaddr_in6 *, a2->ai->ai_addr);
326     prefixlen1 = common_prefix_len(&a1_src->sin6_addr, &a1_dst->sin6_addr);
327     prefixlen2 = common_prefix_len(&a2_src->sin6_addr, &a2_dst->sin6_addr);
328     if (prefixlen1 != prefixlen2) {
329       return (int)prefixlen2 - (int)prefixlen1;
330     }
331   }
332 
333   /*
334    * Rule 10: Leave the order unchanged.
335    * We need this since qsort() is not necessarily stable.
336    */
337   return ((int)a1->original_order) - ((int)a2->original_order);
338 }
339 
340 /*
341  * Find the source address that will be used if trying to connect to the given
342  * address.
343  *
344  * Returns 1 if a source address was found, 0 if the address is unreachable
345  * and -1 if a fatal error occurred. If 0 or 1, the contents of src_addr are
346  * undefined.
347  */
find_src_addr(ares_channel_t *channel, const struct sockaddr *addr, struct sockaddr *src_addr)348 static int find_src_addr(ares_channel_t *channel, const struct sockaddr *addr,
349                          struct sockaddr *src_addr)
350 {
351   ares_socket_t  sock;
352   int            ret;
353   ares_socklen_t len;
354 
355   switch (addr->sa_family) {
356     case AF_INET:
357       len = sizeof(struct sockaddr_in);
358       break;
359     case AF_INET6:
360       len = sizeof(struct sockaddr_in6);
361       break;
362     default:
363       /* No known usable source address for non-INET families. */
364       return 0;
365   }
366 
367   sock = ares__open_socket(channel, addr->sa_family, SOCK_DGRAM, IPPROTO_UDP);
368   if (sock == ARES_SOCKET_BAD) {
369     if (errno == EAFNOSUPPORT) {
370       return 0;
371     } else {
372       return -1;
373     }
374   }
375 
376   do {
377     ret = ares__connect_socket(channel, sock, addr, len);
378   } while (ret == -1 && errno == EINTR);
379 
380   if (ret == -1) {
381     ares__close_socket(channel, sock);
382     return 0;
383   }
384 
385   if (getsockname(sock, src_addr, &len) != 0) {
386     ares__close_socket(channel, sock);
387     return -1;
388   }
389   ares__close_socket(channel, sock);
390   return 1;
391 }
392 
393 /*
394  * Sort the linked list starting at sentinel->ai_next in RFC6724 order.
395  * Will leave the list unchanged if an error occurs.
396  */
ares__sortaddrinfo(ares_channel_t *channel, struct ares_addrinfo_node *list_sentinel)397 ares_status_t ares__sortaddrinfo(ares_channel_t            *channel,
398                                  struct ares_addrinfo_node *list_sentinel)
399 {
400   struct ares_addrinfo_node *cur;
401   size_t                     nelem = 0;
402   size_t                     i;
403   int                        has_src_addr;
404   struct addrinfo_sort_elem *elems;
405 
406   cur = list_sentinel->ai_next;
407   while (cur) {
408     ++nelem;
409     cur = cur->ai_next;
410   }
411 
412   if (!nelem) {
413     return ARES_ENODATA;
414   }
415 
416   elems = (struct addrinfo_sort_elem *)ares_malloc(
417     nelem * sizeof(struct addrinfo_sort_elem));
418   if (!elems) {
419     return ARES_ENOMEM;
420   }
421 
422   /*
423    * Convert the linked list to an array that also contains the candidate
424    * source address for each destination address.
425    */
426   for (i = 0, cur = list_sentinel->ai_next; i < nelem;
427        ++i, cur   = cur->ai_next) {
428     assert(cur != NULL);
429     elems[i].ai             = cur;
430     elems[i].original_order = i;
431     has_src_addr = find_src_addr(channel, cur->ai_addr, &elems[i].src_addr.sa);
432     if (has_src_addr == -1) {
433       ares_free(elems);
434       return ARES_ENOTFOUND;
435     }
436     elems[i].has_src_addr = (has_src_addr == 1) ? ARES_TRUE : ARES_FALSE;
437   }
438 
439   /* Sort the addresses, and rearrange the linked list so it matches the sorted
440    * order. */
441   qsort((void *)elems, nelem, sizeof(struct addrinfo_sort_elem),
442         rfc6724_compare);
443 
444   list_sentinel->ai_next = elems[0].ai;
445   for (i = 0; i < nelem - 1; ++i) {
446     elems[i].ai->ai_next = elems[i + 1].ai;
447   }
448   elems[nelem - 1].ai->ai_next = NULL;
449 
450   ares_free(elems);
451   return ARES_SUCCESS;
452 }
453