gweb: Some coding style cleanup on resolver code
[platform/upstream/connman.git] / gweb / gresolv.c
1 /*
2  *
3  *  Resolver library with GLib integration
4  *
5  *  Copyright (C) 2009-2010  Intel Corporation. All rights reserved.
6  *
7  *  This program is free software; you can redistribute it and/or modify
8  *  it under the terms of the GNU General Public License version 2 as
9  *  published by the Free Software Foundation.
10  *
11  *  This program is distributed in the hope that it will be useful,
12  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
13  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  *  GNU General Public License for more details.
15  *
16  *  You should have received a copy of the GNU General Public License
17  *  along with this program; if not, write to the Free Software
18  *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
19  *
20  */
21
22 #ifdef HAVE_CONFIG_H
23 #include <config.h>
24 #endif
25
26 #include <errno.h>
27 #include <unistd.h>
28 #include <stdarg.h>
29 #include <string.h>
30 #include <stdlib.h>
31 #include <resolv.h>
32 #include <sys/types.h>
33 #include <sys/socket.h>
34 #include <netdb.h>
35 #include <arpa/inet.h>
36 #include <arpa/nameser.h>
37
38 #include "gresolv.h"
39
40 struct sort_result {
41         int precedence;
42         int src_scope;
43         int dst_scope;
44         int src_label;
45         int dst_label;
46         gboolean reachable;
47         union {
48                 struct sockaddr sa;
49                 struct sockaddr_in sin;
50                 struct sockaddr_in6 sin6;
51         } src;
52         union {
53                 struct sockaddr sa;
54                 struct sockaddr_in sin;
55                 struct sockaddr_in6 sin6;
56         } dst;
57 };
58
59 struct resolv_query;
60
61 struct resolv_lookup {
62         GResolv *resolv;
63         guint id;
64
65         int nr_results;
66         struct sort_result *results;
67
68         struct resolv_query *ipv4_query;
69         struct resolv_query *ipv6_query;
70
71         guint ipv4_status;
72         guint ipv6_status;
73
74         GResolvResultFunc result_func;
75         gpointer result_data;
76 };
77
78 struct resolv_query {
79         GResolv *resolv;
80
81         guint timeout;
82
83         uint16_t msgid;
84
85         struct resolv_lookup *lookup;
86 };
87
88 struct resolv_nameserver {
89         GResolv *resolv;
90
91         char *address;
92         uint16_t port;
93         unsigned long flags;
94
95         GIOChannel *udp_channel;
96         guint udp_watch;
97 };
98
99 struct _GResolv {
100         gint ref_count;
101
102         guint next_lookup_id;
103         GQueue *lookup_queue;
104         GQueue *query_queue;
105
106         int index;
107         GList *nameserver_list;
108
109         struct __res_state res;
110
111         GResolvDebugFunc debug_func;
112         gpointer debug_data;
113 };
114
115 static void sort_and_return_results(struct resolv_lookup *lookup);
116 static void rfc3484_sort_results(struct resolv_lookup *lookup);
117
118 static inline void debug(GResolv *resolv, const char *format, ...)
119 {
120         char str[256];
121         va_list ap;
122
123         if (resolv->debug_func == NULL)
124                 return;
125
126         va_start(ap, format);
127
128         if (vsnprintf(str, sizeof(str), format, ap) > 0)
129                 resolv->debug_func(str, resolv->debug_data);
130
131         va_end(ap);
132 }
133
134 static void destroy_query(struct resolv_query *query)
135 {
136         if (query->timeout > 0)
137                 g_source_remove(query->timeout);
138
139         g_free(query);
140 }
141
142 static void destroy_lookup(struct resolv_lookup *lookup)
143 {
144         if (lookup->ipv4_query != NULL) {
145                 g_queue_remove(lookup->resolv->query_queue,
146                                                 lookup->ipv4_query);
147                 destroy_query(lookup->ipv4_query);
148         }
149
150         if (lookup->ipv6_query != NULL) {
151                 g_queue_remove(lookup->resolv->query_queue,
152                                                 lookup->ipv6_query);
153                 destroy_query(lookup->ipv6_query);
154         }
155
156         g_free(lookup->results);
157         g_free(lookup);
158 }
159
160 static gboolean query_timeout(gpointer user_data)
161 {
162         struct resolv_query *query = user_data;
163         struct resolv_lookup *lookup = query->lookup;
164         GResolv *resolv = query->resolv;
165
166         query->timeout = 0;
167
168         if (query == lookup->ipv4_query) {
169                 lookup->ipv4_status = G_RESOLV_RESULT_STATUS_NO_RESPONSE;
170                 lookup->ipv4_query = NULL;
171         } else if (query == lookup->ipv6_query) {
172                 lookup->ipv6_status = G_RESOLV_RESULT_STATUS_NO_RESPONSE;
173                 lookup->ipv6_query = NULL;
174         }
175
176         if (lookup->ipv4_query == NULL && lookup->ipv4_query == NULL)
177                 sort_and_return_results(lookup);
178
179         destroy_query(query);
180         g_queue_remove(resolv->query_queue, query);
181
182         return FALSE;
183 }
184
185 static void free_nameserver(struct resolv_nameserver *nameserver)
186 {
187         if (nameserver == NULL)
188                 return;
189
190         if (nameserver->udp_watch > 0)
191                 g_source_remove(nameserver->udp_watch);
192
193         if (nameserver->udp_channel != NULL)
194                 g_io_channel_unref(nameserver->udp_channel);
195
196         g_free(nameserver->address);
197         g_free(nameserver);
198 }
199
200 static void flush_nameservers(GResolv *resolv)
201 {
202         GList *list;
203
204         for (list = g_list_first(resolv->nameserver_list);
205                                         list; list = g_list_next(list))
206                 free_nameserver(list->data);
207
208         g_list_free(resolv->nameserver_list);
209         resolv->nameserver_list = NULL;
210 }
211
212 static int send_query(GResolv *resolv, const unsigned char *buf, int len)
213 {
214         GList *list;
215
216         if (resolv->nameserver_list == NULL)
217                 return -ENOENT;
218
219         for (list = g_list_first(resolv->nameserver_list);
220                                         list; list = g_list_next(list)) {
221                 struct resolv_nameserver *nameserver = list->data;
222                 int sk, sent;
223
224                 if (nameserver->udp_channel == NULL)
225                         continue;
226
227                 sk = g_io_channel_unix_get_fd(nameserver->udp_channel);
228
229                 sent = send(sk, buf, len, 0);
230         }
231
232         return 0;
233 }
234
235 static gint compare_lookup_id(gconstpointer a, gconstpointer b)
236 {
237         const struct resolv_lookup *lookup = a;
238         guint id = GPOINTER_TO_UINT(b);
239
240         if (lookup->id < id)
241                 return -1;
242
243         if (lookup->id > id)
244                 return 1;
245
246         return 0;
247 }
248
249 static gint compare_query_msgid(gconstpointer a, gconstpointer b)
250 {
251         const struct resolv_query *query = a;
252         uint16_t msgid = GPOINTER_TO_UINT(b);
253
254         if (query->msgid < msgid)
255                 return -1;
256
257         if (query->msgid > msgid)
258                 return 1;
259
260         return 0;
261 }
262
263 static void add_result(struct resolv_lookup *lookup, int family,
264                                                         const void *data)
265 {
266         int n = lookup->nr_results++;
267         lookup->results = g_realloc(lookup->results,
268                                         sizeof(struct sort_result) * (n + 1));
269
270         memset(&lookup->results[n], 0, sizeof(struct sort_result));
271
272         lookup->results[n].dst.sa.sa_family = family;
273         if (family == AF_INET)
274                 memcpy(&lookup->results[n].dst.sin.sin_addr,
275                                                 data, NS_INADDRSZ);
276         else
277                 memcpy(&lookup->results[n].dst.sin6.sin6_addr,
278                                                 data, NS_IN6ADDRSZ);
279 }
280
281 static void parse_response(struct resolv_nameserver *nameserver,
282                                         const unsigned char *buf, int len)
283 {
284         GResolv *resolv = nameserver->resolv;
285         GResolvResultStatus status;
286         struct resolv_query *query;
287         struct resolv_lookup *lookup;
288         GList *list;
289         ns_msg msg;
290         ns_rr rr;
291         int i, n, rcode, count;
292
293         debug(resolv, "response from %s", nameserver->address);
294
295         ns_initparse(buf, len, &msg);
296
297         rcode = ns_msg_getflag(msg, ns_f_rcode);
298         count = ns_msg_count(msg, ns_s_an);
299
300         debug(resolv, "msg id: 0x%04x rcode: %d count: %d",
301                                         ns_msg_id(msg), rcode, count);
302
303         switch (rcode) {
304         case 0:
305                 status = G_RESOLV_RESULT_STATUS_SUCCESS;
306                 break;
307         case 1:
308                 status = G_RESOLV_RESULT_STATUS_FORMAT_ERROR;
309                 break;
310         case 2:
311                 status = G_RESOLV_RESULT_STATUS_SERVER_FAILURE;
312                 break;
313         case 3:
314                 status = G_RESOLV_RESULT_STATUS_NAME_ERROR;
315                 break;
316         case 4:
317                 status = G_RESOLV_RESULT_STATUS_NOT_IMPLEMENTED;
318                 break;
319         case 5:
320                 status = G_RESOLV_RESULT_STATUS_REFUSED;
321                 break;
322         default:
323                 status = G_RESOLV_RESULT_STATUS_ERROR;
324                 break;
325         }
326
327         list = g_queue_find_custom(resolv->query_queue,
328                         GUINT_TO_POINTER(ns_msg_id(msg)), compare_query_msgid);
329         if (!list)
330                 return;
331
332         query = list->data;
333         lookup = query->lookup;
334
335         if (query == lookup->ipv6_query) {
336                 lookup->ipv6_status = status;
337                 lookup->ipv6_query = NULL;
338         } else if (query == lookup->ipv4_query) {
339                 lookup->ipv4_status = status;
340                 lookup->ipv4_query = NULL;
341         }
342
343         for (i = 0, n = 0; i < count; i++) {
344                 ns_parserr(&msg, ns_s_an, i, &rr);
345
346                 if (ns_rr_class(rr) != ns_c_in)
347                         continue;
348
349                 g_assert(offsetof(struct sockaddr_in, sin_addr) ==
350                                 offsetof(struct sockaddr_in6, sin6_flowinfo));
351
352                 if (ns_rr_type(rr) == ns_t_a &&
353                                         ns_rr_rdlen(rr) == NS_INADDRSZ) {
354                         add_result(lookup, AF_INET, ns_rr_rdata(rr));
355                 } else if (ns_rr_type(rr) == ns_t_aaaa &&
356                                         ns_rr_rdlen(rr) == NS_IN6ADDRSZ) {
357                         add_result(lookup, AF_INET6, ns_rr_rdata(rr));
358                 }
359         }
360
361         if (lookup->ipv4_query == NULL && lookup->ipv6_query == NULL)
362                 sort_and_return_results(lookup);
363
364         destroy_query(query);
365         g_queue_remove(resolv->query_queue, query);
366 }
367
368 static gboolean received_udp_data(GIOChannel *channel, GIOCondition cond,
369                                                         gpointer user_data)
370 {
371         struct resolv_nameserver *nameserver = user_data;
372         unsigned char buf[4096];
373         int sk, len;
374
375         if (cond & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
376                 nameserver->udp_watch = 0;
377                 return FALSE;
378         }
379
380         sk = g_io_channel_unix_get_fd(nameserver->udp_channel);
381
382         len = recv(sk, buf, sizeof(buf), 0);
383         if (len < 12)
384                 return TRUE;
385
386         parse_response(nameserver, buf, len);
387
388         return TRUE;
389 }
390
391 static int connect_udp_channel(struct resolv_nameserver *nameserver)
392 {
393         struct addrinfo hints, *rp;
394         char portnr[6];
395         int err, sk;
396
397         memset(&hints, 0, sizeof(hints));
398         hints.ai_family = AF_UNSPEC;
399         hints.ai_socktype = SOCK_DGRAM;
400         hints.ai_flags = AI_PASSIVE | AI_NUMERICSERV | AI_NUMERICHOST;
401
402         sprintf(portnr, "%d", nameserver->port);
403         err = getaddrinfo(nameserver->address, portnr, &hints, &rp);
404         if (err)
405                 return -EINVAL;
406
407         /*
408          * Do not blindly copy this code elsewhere; it doesn't loop over the
409          * results using ->ai_next as it should. That's OK in *this* case
410          * because it was a numeric lookup; we *know* there's only one.
411          */
412         if (!rp)
413                 return -EINVAL;
414
415         sk = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
416         if (sk < 0) {
417                 freeaddrinfo(rp);
418                 return -EIO;
419         }
420
421         if (connect(sk, rp->ai_addr, rp->ai_addrlen) < 0) {
422                 close(sk);
423                 freeaddrinfo(rp);
424                 return -EIO;
425         }
426
427         freeaddrinfo(rp);
428
429         nameserver->udp_channel = g_io_channel_unix_new(sk);
430         if (nameserver->udp_channel == NULL) {
431                 close(sk);
432                 return -ENOMEM;
433         }
434
435         g_io_channel_set_close_on_unref(nameserver->udp_channel, TRUE);
436
437         nameserver->udp_watch = g_io_add_watch(nameserver->udp_channel,
438                                 G_IO_IN | G_IO_NVAL | G_IO_ERR | G_IO_HUP,
439                                 received_udp_data, nameserver);
440
441         return 0;
442 }
443
444 GResolv *g_resolv_new(int index)
445 {
446         GResolv *resolv;
447
448         if (index < 0)
449                 return NULL;
450
451         resolv = g_try_new0(GResolv, 1);
452         if (resolv == NULL)
453                 return NULL;
454
455         resolv->ref_count = 1;
456
457         resolv->next_lookup_id = 1;
458
459         resolv->query_queue = g_queue_new();
460         if (resolv->query_queue == NULL) {
461                 g_free(resolv);
462                 return NULL;
463         }
464
465         resolv->lookup_queue = g_queue_new();
466         if (resolv->lookup_queue == NULL) {
467                 g_queue_free(resolv->query_queue);
468                 g_free(resolv);
469                 return NULL;
470         }
471
472         resolv->index = index;
473         resolv->nameserver_list = NULL;
474
475         res_ninit(&resolv->res);
476
477         return resolv;
478 }
479
480 GResolv *g_resolv_ref(GResolv *resolv)
481 {
482         if (resolv == NULL)
483                 return NULL;
484
485         g_atomic_int_inc(&resolv->ref_count);
486
487         return resolv;
488 }
489
490 void g_resolv_unref(GResolv *resolv)
491 {
492         struct resolv_query *query;
493
494         if (resolv == NULL)
495                 return;
496
497         if (g_atomic_int_dec_and_test(&resolv->ref_count) == FALSE)
498                 return;
499
500         while ((query = g_queue_pop_head(resolv->query_queue)))
501                 destroy_query(query);
502
503         g_queue_free(resolv->query_queue);
504         g_queue_free(resolv->lookup_queue);
505
506         flush_nameservers(resolv);
507
508         res_nclose(&resolv->res);
509
510         g_free(resolv);
511 }
512
513 void g_resolv_set_debug(GResolv *resolv, GResolvDebugFunc func,
514                                                 gpointer user_data)
515 {
516         if (resolv == NULL)
517                 return;
518
519         resolv->debug_func = func;
520         resolv->debug_data = user_data;
521 }
522
523 gboolean g_resolv_add_nameserver(GResolv *resolv, const char *address,
524                                         uint16_t port, unsigned long flags)
525 {
526         struct resolv_nameserver *nameserver;
527
528         if (resolv == NULL)
529                 return FALSE;
530
531         nameserver = g_try_new0(struct resolv_nameserver, 1);
532         if (nameserver == NULL)
533                 return FALSE;
534
535         nameserver->address = g_strdup(address);
536         nameserver->port = port;
537         nameserver->flags = flags;
538
539         if (connect_udp_channel(nameserver) < 0) {
540                 free_nameserver(nameserver);
541                 return FALSE;
542         }
543
544         nameserver->resolv = resolv;
545
546         resolv->nameserver_list = g_list_append(resolv->nameserver_list,
547                                                                 nameserver);
548
549         debug(resolv, "setting nameserver %s", address);
550
551         return TRUE;
552 }
553
554 void g_resolv_flush_nameservers(GResolv *resolv)
555 {
556         if (resolv == NULL)
557                 return;
558
559         flush_nameservers(resolv);
560 }
561
562 static void sort_and_return_results(struct resolv_lookup *lookup)
563 {
564         char buf[100];
565         GResolvResultStatus status;
566         char **results = g_try_new0(char *, lookup->nr_results + 1);
567         int i, n = 0;
568
569         if (!results)
570                 return;
571
572         rfc3484_sort_results(lookup);
573
574         for (i = 0; i < lookup->nr_results; i++) {
575                 if (lookup->results[i].dst.sa.sa_family == AF_INET) {
576                         if (inet_ntop(AF_INET,
577                                         &lookup->results[i].dst.sin.sin_addr,
578                                         buf, sizeof(buf)) == NULL)
579                                 continue;
580                 } else if (lookup->results[i].dst.sa.sa_family == AF_INET6) {
581                         if (inet_ntop(AF_INET6,
582                                         &lookup->results[i].dst.sin6.sin6_addr,
583                                         buf, sizeof(buf)) == NULL)
584                                 continue;
585                 } else
586                         continue;
587
588                 results[n++] = strdup(buf);
589         }
590
591         results[n++] = NULL;
592
593         status = lookup->ipv4_status;
594
595         if (status == G_RESOLV_RESULT_STATUS_SUCCESS)
596                 status = lookup->ipv6_status;
597
598         lookup->result_func(status, results, lookup->result_data);
599
600         g_strfreev(results);
601         g_queue_remove(lookup->resolv->lookup_queue, lookup);
602         destroy_lookup(lookup);
603 }
604
605 static gint add_query(struct resolv_lookup *lookup, const char *hostname, int type)
606 {
607         struct resolv_query *query = g_try_new0(struct resolv_query, 1);
608         unsigned char buf[4096];
609         int len;
610
611         if (query == NULL)
612                 return -ENOMEM;
613
614         len = res_mkquery(ns_o_query, hostname, ns_c_in, type,
615                                         NULL, 0, NULL, buf, sizeof(buf));
616
617         query->msgid = buf[0] << 8 | buf[1];
618
619         if (send_query(lookup->resolv, buf, len) < 0)
620                 return -EIO;
621
622         query->resolv = lookup->resolv;
623         query->lookup = lookup;
624
625         g_queue_push_tail(lookup->resolv->query_queue, query);
626
627         query->timeout = g_timeout_add_seconds(5, query_timeout, query);
628
629         if (type == ns_t_aaaa)
630                 lookup->ipv6_query = query;
631         else
632                 lookup->ipv4_query = query;
633
634         return 0;
635 }
636
637 guint g_resolv_lookup_hostname(GResolv *resolv, const char *hostname,
638                                 GResolvResultFunc func, gpointer user_data)
639 {
640         struct resolv_lookup *lookup;
641
642         debug(resolv, "lookup hostname %s", hostname);
643
644         if (resolv == NULL)
645                 return 0;
646
647         if (resolv->nameserver_list == NULL) {
648                 int i;
649
650                 for (i = 0; i < resolv->res.nscount; i++) {
651                         char buf[100];
652                         int family = resolv->res.nsaddr_list[i].sin_family;
653                         void *sa_addr = &resolv->res.nsaddr_list[i].sin_addr;
654
655                         if (family != AF_INET &&
656                                         resolv->res._u._ext.nsaddrs[i]) {
657                                 family = AF_INET6;
658                                 sa_addr = &resolv->res._u._ext.nsaddrs[i]->sin6_addr;
659                         }
660
661                         if (family != AF_INET && family != AF_INET6)
662                                 continue;
663
664                         if (inet_ntop(family, sa_addr, buf, sizeof(buf)))
665                                 g_resolv_add_nameserver(resolv, buf, 53, 0);
666                 }
667
668                 if (resolv->nameserver_list == NULL)
669                         g_resolv_add_nameserver(resolv, "127.0.0.1", 53, 0);
670         }
671
672         lookup = g_try_new0(struct resolv_lookup, 1);
673         if (lookup == NULL)
674                 return 0;
675
676         lookup->resolv = resolv;
677         lookup->result_func = func;
678         lookup->result_data = user_data;
679         lookup->id = resolv->next_lookup_id++;
680
681         if (add_query(lookup, hostname, ns_t_a)) {
682                 g_free(lookup);
683                 return -EIO;
684         }
685
686         if (add_query(lookup, hostname, ns_t_aaaa)) {
687                 destroy_query(lookup->ipv4_query);
688                 g_queue_remove(resolv->query_queue, lookup->ipv4_query);
689                 g_free(lookup);
690                 return -EIO;
691         }
692
693         g_queue_push_tail(resolv->lookup_queue, lookup);
694         return lookup->id;
695 }
696
697 gboolean g_resolv_cancel_lookup(GResolv *resolv, guint id)
698 {
699         GList *list;
700
701         list = g_queue_find_custom(resolv->lookup_queue,
702                                 GUINT_TO_POINTER(id), compare_lookup_id);
703
704         if (list == NULL)
705                 return FALSE;
706
707         destroy_lookup(list->data);
708         g_queue_remove(resolv->query_queue, list->data);
709
710         return TRUE;
711 }
712
713 static void find_srcaddr(struct sort_result *res)
714 {
715         socklen_t sl = sizeof(res->src);
716         int fd;
717
718         fd = socket(res->dst.sa.sa_family, SOCK_DGRAM, IPPROTO_IP);
719         if (fd < 0)
720                 return;
721
722         if (connect(fd, &res->dst.sa, sizeof(res->dst)) < 0) {
723                 close(fd);
724                 return;
725         }
726
727         if (getsockname(fd, &res->src.sa, &sl) < 0) {
728                 close(fd);
729                 return;
730         }
731
732         res->reachable = TRUE;
733         close(fd);
734 }
735
736 struct gai_table
737 {
738         unsigned char addr[NS_IN6ADDRSZ];
739         int mask;
740         int value;
741 };
742
743 static const struct gai_table gai_labels[] = {
744         {
745                 .addr = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
746                           0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01 },
747                 .mask = 128,
748                 .value = 0,
749         }, {
750                 .addr = { 0x20, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
751                           0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 },
752                 .mask = 16,
753                 .value = 2,
754         }, {
755                 .addr = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
756                           0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 },
757                 .mask = 96,
758                 .value = 3,
759         }, {
760                 .addr = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
761                           0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00 },
762                 .mask = 96,
763                 .value = 4,
764         }, {
765                 /* Variations from RFC 3484, matching glibc behaviour */
766                 .addr = { 0xfe, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
767                           0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 },
768                 .mask = 10,
769                 .value = 5,
770         }, {
771                 .addr = { 0xfc, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
772                           0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 },
773                 .mask = 7,
774                 .value = 6,
775         }, {
776                 .addr = { 0x20, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
777                           0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 },
778                 .mask = 32,
779                 .value = 7,
780         }, {
781                 /* catch-all */
782                 .addr = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
783                           0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 },
784                 .mask = 0,
785                 .value = 1,
786         }
787 };
788
789 static const struct gai_table gai_precedences[] = {
790         {
791                 .addr = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
792                           0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01 },
793                 .mask = 128,
794                 .value = 50,
795         }, {
796                 .addr = { 0x20, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
797                           0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 },
798                 .mask = 16,
799                 .value = 30,
800         }, {
801                 .addr = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
802                           0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 },
803                 .mask = 96,
804                 .value = 20,
805         }, {
806                 .addr = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
807                           0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00 },
808                 .mask = 96,
809                 .value = 10,
810         }, {
811                 .addr = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
812                           0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 },
813                 .mask = 0,
814                 .value = 40,
815         }
816 };
817
818 static unsigned char v4mapped[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
819                                     0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00 };
820
821 static gboolean mask_compare(const unsigned char *one,
822                                         const unsigned char *two, int mask)
823 {
824         if (mask > 8) {
825                 if (memcmp(one, two, mask / 8))
826                         return FALSE;
827                 one += mask / 8;
828                 two += mask / 8;
829                 mask %= 8;
830         }
831
832         if (mask && ((*one ^ *two) >> (8 - mask)))
833                 return FALSE;
834
835         return TRUE;
836 }
837
838 static int match_gai_table(struct sockaddr *sa, const struct gai_table *tbl)
839 {
840         struct sockaddr_in *sin = (void *)sa;
841         struct sockaddr_in6 *sin6 = (void *)sa;
842         void *addr;
843
844         if (sa->sa_family == AF_INET) {
845                 addr = v4mapped;
846                 memcpy(v4mapped+12, &sin->sin_addr, NS_INADDRSZ);
847         } else
848                 addr = &sin6->sin6_addr;
849
850         while (1) {
851                 if (mask_compare(addr, tbl->addr, tbl->mask))
852                         return tbl->value;
853                 tbl++;
854         }
855 }
856
857 #define DQUAD(_a,_b,_c,_d) ( ((_a)<<24) | ((_b)<<16) | ((_c)<<8) | (_d) )
858 #define V4MATCH(addr, a,b,c,d, m) ( ((addr) ^ DQUAD(a,b,c,d)) >> (32 - (m)) )
859
860 #define RFC3484_SCOPE_LINK      2
861 #define RFC3484_SCOPE_SITE      5
862 #define RFC3484_SCOPE_GLOBAL    14
863
864 static int addr_scope(struct sockaddr *sa)
865 {
866         if (sa->sa_family == AF_INET) {
867                 struct sockaddr_in *sin = (void *)sa;
868                 guint32 addr = ntohl(sin->sin_addr.s_addr);
869
870                 if (V4MATCH(addr, 169,254,0,0, 16) ||
871                                         V4MATCH(addr, 127,0,0,0, 8))
872                         return RFC3484_SCOPE_LINK;
873
874                 /* Site-local */
875                 if (V4MATCH(addr, 10,0,0,0, 8) ||
876                                 V4MATCH(addr, 172,16,0,0, 12) ||
877                                 V4MATCH(addr, 192,168,0,0, 16))
878                         return RFC3484_SCOPE_SITE;
879
880                 /* Global */
881                 return RFC3484_SCOPE_GLOBAL;
882         } else {
883                 struct sockaddr_in6 *sin6 = (void *)sa;
884
885                 /* Multicast addresses have a 4-bit scope field */
886                 if (IN6_IS_ADDR_MULTICAST(&sin6->sin6_addr))
887                         return sin6->sin6_addr.s6_addr[1] & 0xf;
888
889                 if (IN6_IS_ADDR_LINKLOCAL(&sin6->sin6_addr) ||
890                                 IN6_IS_ADDR_LOOPBACK(&sin6->sin6_addr))
891                         return RFC3484_SCOPE_LINK;
892
893                 if (IN6_IS_ADDR_SITELOCAL(&sin6->sin6_addr))
894                         return RFC3484_SCOPE_SITE;
895
896                 return RFC3484_SCOPE_GLOBAL;
897         }
898 }
899
900 static int rfc3484_compare(const void *__one, const void *__two)
901 {
902         const struct sort_result *one = __one;
903         const struct sort_result *two = __two;
904
905         /* Rule 1: Avoid unusable destinations */
906         if (one->reachable && !two->reachable)
907                 return -1;
908         else if (two->reachable && !one->reachable)
909                 return 1;
910
911         /* Rule 2: Prefer matching scope */
912         if (one->dst_scope == one->src_scope &&
913                                 two->dst_scope != two->src_scope)
914                 return -1;
915         else if (two->dst_scope == two->src_scope &&
916                                 one->dst_scope != one->src_scope)
917                 return 1;
918
919         /* Rule 3: Avoid deprecated addresses */
920
921         /* Rule 4: Prefer home addresses */
922
923         /* Rule 5: Prefer matching label */
924         if (one->dst_label == one->src_label &&
925                                 two->dst_label != two->src_label)
926                 return -1;
927         else if (two->dst_label == two->src_label &&
928                                 one->dst_label != one->src_label)
929                 return 1;
930
931         /* Rule 6: Prefer higher precedence */
932         if (one->precedence > two->precedence)
933                 return -1;
934         else if (two->precedence > one->precedence)
935                 return 1;
936
937         /* Rule 7: Prefer native transport */
938
939         /* Rule 8: Prefer smaller scope */
940         if (one->dst_scope != two->dst_scope)
941                 return one->dst_scope - two->dst_scope;
942
943         /* Rule 9: Use longest matching prefix */
944         if (one->dst.sa.sa_family == AF_INET) {
945                 /*
946                  * Rule 9 is meaningless and counterproductive for Legacy IP
947                  * unless perhaps we can tell that it's actually on the local
948                  * subnet. But we don't (yet) have local interface config
949                  * information, so do nothing here for Legacy IP for now.
950                  */
951         } else {
952                 int i;
953
954                 for (i = 0; i < 4; i++) {
955                         guint32 cmp_one, cmp_two;
956
957                         cmp_one = one->src.sin6.sin6_addr.s6_addr32[i] ^
958                                         one->dst.sin6.sin6_addr.s6_addr32[i];
959                         cmp_two = two->src.sin6.sin6_addr.s6_addr32[i] ^
960                                         two->dst.sin6.sin6_addr.s6_addr32[i];
961
962                         if (!cmp_two && !cmp_one)
963                                 continue;
964
965                         if (cmp_one && !cmp_two)
966                                 return 1;
967                         if (cmp_two && !cmp_one)
968                                 return -1;
969
970                         /* g_bit_storage() is effectively fls() */
971                         cmp_one = g_bit_storage(ntohl(cmp_one));
972                         cmp_two = g_bit_storage(ntohl(cmp_two));
973
974                         if (cmp_one == cmp_two)
975                                 break;
976
977                         return cmp_one - cmp_two;
978                 }
979         }
980
981
982         /* Rule 10: Otherwise, leave the order unchanged */
983         if (one < two)
984                 return -1;
985         else
986                 return 1;
987 }
988
989 static void rfc3484_sort_results(struct resolv_lookup *lookup)
990 {
991         int i;
992
993         for (i = 0; i < lookup->nr_results; i++) {
994                 struct sort_result *res = &lookup->results[i];
995                 find_srcaddr(res);
996                 res->precedence = match_gai_table(&res->dst.sa,
997                                                         gai_precedences);
998                 res->dst_label = match_gai_table(&res->dst.sa, gai_labels);
999                 res->src_label = match_gai_table(&res->src.sa, gai_labels);
1000                 res->dst_scope = addr_scope(&res->dst.sa);
1001                 res->src_scope = addr_scope(&res->src.sa);
1002         }
1003
1004         qsort(lookup->results, lookup->nr_results,
1005                         sizeof(struct sort_result), rfc3484_compare);
1006 }