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