merge tag upstream/1.38
[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 <stdio.h>
32 #include <resolv.h>
33 #include <sys/types.h>
34 #include <sys/socket.h>
35 #include <netdb.h>
36 #include <arpa/inet.h>
37 #include <arpa/nameser.h>
38 #include <net/if.h>
39
40 #include "gresolv.h"
41
42 struct sort_result {
43         int precedence;
44         int src_scope;
45         int dst_scope;
46         int src_label;
47         int dst_label;
48         bool reachable;
49         union {
50                 struct sockaddr sa;
51                 struct sockaddr_in sin;
52                 struct sockaddr_in6 sin6;
53         } src;
54         union {
55                 struct sockaddr sa;
56                 struct sockaddr_in sin;
57                 struct sockaddr_in6 sin6;
58         } dst;
59 };
60
61 struct resolv_query;
62
63 struct resolv_lookup {
64         GResolv *resolv;
65         guint id;
66
67         int nr_results;
68         struct sort_result *results;
69
70         struct resolv_query *ipv4_query;
71         struct resolv_query *ipv6_query;
72
73         guint ipv4_status;
74         guint ipv6_status;
75
76         GResolvResultFunc result_func;
77         gpointer result_data;
78 };
79
80 struct resolv_query {
81         GResolv *resolv;
82
83         int nr_ns;
84         guint timeout;
85
86         uint16_t msgid;
87
88         struct resolv_lookup *lookup;
89 };
90
91 struct resolv_nameserver {
92         GResolv *resolv;
93
94         char *address;
95         uint16_t port;
96         unsigned long flags;
97
98         GIOChannel *udp_channel;
99         guint udp_watch;
100 };
101
102 struct _GResolv {
103         int ref_count;
104
105         int result_family;
106
107         guint next_lookup_id;
108         GQueue *lookup_queue;
109         GQueue *query_queue;
110
111         int index;
112         GList *nameserver_list;
113
114         struct __res_state res;
115
116         GResolvDebugFunc debug_func;
117         gpointer debug_data;
118 };
119
120 #define debug(resolv, format, arg...)                           \
121         _debug(resolv, __FILE__, __func__, format, ## arg)
122
123 static void _debug(GResolv *resolv, const char *file, const char *caller,
124                                                 const char *format, ...)
125 {
126         char str[256];
127         va_list ap;
128         int len;
129
130         if (!resolv->debug_func)
131                 return;
132
133         va_start(ap, format);
134
135         if ((len = snprintf(str, sizeof(str), "%s:%s() resolv %p ",
136                                                 file, caller, resolv)) > 0) {
137                 if (vsnprintf(str + len, sizeof(str) - len, format, ap) > 0)
138                         resolv->debug_func(str, resolv->debug_data);
139         }
140
141         va_end(ap);
142 }
143
144 static void destroy_query(struct resolv_query *query)
145 {
146         debug(query->resolv, "query %p timeout %d", query, query->timeout);
147
148         if (query->timeout > 0)
149                 g_source_remove(query->timeout);
150
151         g_free(query);
152 }
153
154 static void destroy_lookup(struct resolv_lookup *lookup)
155 {
156         debug(lookup->resolv, "lookup %p id %d ipv4 %p ipv6 %p",
157                 lookup, lookup->id, lookup->ipv4_query, lookup->ipv6_query);
158
159         if (lookup->ipv4_query) {
160                 g_queue_remove(lookup->resolv->query_queue,
161                                                 lookup->ipv4_query);
162                 destroy_query(lookup->ipv4_query);
163         }
164
165         if (lookup->ipv6_query) {
166                 g_queue_remove(lookup->resolv->query_queue,
167                                                 lookup->ipv6_query);
168                 destroy_query(lookup->ipv6_query);
169         }
170
171         g_free(lookup->results);
172         g_free(lookup);
173 }
174
175 static void find_srcaddr(struct sort_result *res)
176 {
177         socklen_t sl = sizeof(res->src);
178         int fd;
179
180         fd = socket(res->dst.sa.sa_family, SOCK_DGRAM | SOCK_CLOEXEC,
181                         IPPROTO_IP);
182         if (fd < 0)
183                 return;
184
185         if (connect(fd, &res->dst.sa, sizeof(res->dst)) < 0)
186                 goto out;
187
188         if (getsockname(fd, &res->src.sa, &sl) < 0)
189                 goto out;
190
191         res->reachable = true;
192
193 out:
194         close(fd);
195 }
196
197 struct gai_table
198 {
199         unsigned char addr[NS_IN6ADDRSZ];
200         int mask;
201         int value;
202 };
203
204 static const struct gai_table gai_labels[] = {
205         {
206                 .addr = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
207                           0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01 },
208                 .mask = 128,
209                 .value = 0,
210         }, {
211                 .addr = { 0x20, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
212                           0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 },
213                 .mask = 16,
214                 .value = 2,
215         }, {
216                 .addr = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
217                           0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 },
218                 .mask = 96,
219                 .value = 3,
220         }, {
221                 .addr = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
222                           0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00 },
223                 .mask = 96,
224                 .value = 4,
225         }, {
226                 /* Variations from RFC 3484, matching glibc behaviour */
227                 .addr = { 0xfe, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
228                           0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 },
229                 .mask = 10,
230                 .value = 5,
231         }, {
232                 .addr = { 0xfc, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
233                           0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 },
234                 .mask = 7,
235                 .value = 6,
236         }, {
237                 .addr = { 0x20, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
238                           0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 },
239                 .mask = 32,
240                 .value = 7,
241         }, {
242                 /* catch-all */
243                 .addr = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
244                           0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 },
245                 .mask = 0,
246                 .value = 1,
247         }
248 };
249
250 static const struct gai_table gai_precedences[] = {
251         {
252                 .addr = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
253                           0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01 },
254                 .mask = 128,
255                 .value = 50,
256         }, {
257                 .addr = { 0x20, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
258                           0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 },
259                 .mask = 16,
260                 .value = 30,
261         }, {
262                 .addr = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
263                           0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 },
264                 .mask = 96,
265                 .value = 20,
266         }, {
267                 .addr = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
268                           0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00 },
269                 .mask = 96,
270                 .value = 10,
271         }, {
272                 .addr = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
273                           0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 },
274                 .mask = 0,
275                 .value = 40,
276         }
277 };
278
279 static unsigned char v4mapped[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
280                                     0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00 };
281
282 static bool mask_compare(const unsigned char *one,
283                                         const unsigned char *two, int mask)
284 {
285         if (mask > 8) {
286                 if (memcmp(one, two, mask / 8))
287                         return false;
288                 one += mask / 8;
289                 two += mask / 8;
290                 mask %= 8;
291         }
292
293         if (mask && ((*one ^ *two) >> (8 - mask)))
294                 return false;
295
296         return true;
297 }
298
299 static int match_gai_table(struct sockaddr *sa, const struct gai_table *tbl)
300 {
301         struct sockaddr_in *sin = (void *)sa;
302         struct sockaddr_in6 *sin6 = (void *)sa;
303         void *addr;
304
305         if (sa->sa_family == AF_INET) {
306                 addr = v4mapped;
307                 memcpy(v4mapped+12, &sin->sin_addr, NS_INADDRSZ);
308         } else
309                 addr = &sin6->sin6_addr;
310
311         while (1) {
312                 if (mask_compare(addr, tbl->addr, tbl->mask))
313                         return tbl->value;
314                 tbl++;
315         }
316 }
317
318 #define DQUAD(_a,_b,_c,_d) ( (((uint32_t)_a)<<24) | (((uint32_t)_b)<<16) | \
319                                 (((uint32_t)_c)<<8) | ((uint32_t)_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                 uint32_t 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-1);
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                 if (count > 0)
685                         status = G_RESOLV_RESULT_STATUS_SUCCESS;
686                 else
687                         status = G_RESOLV_RESULT_STATUS_NO_ANSWER;
688                 break;
689         case ns_r_formerr:
690                 status = G_RESOLV_RESULT_STATUS_FORMAT_ERROR;
691                 break;
692         case ns_r_servfail:
693                 status = G_RESOLV_RESULT_STATUS_SERVER_FAILURE;
694                 break;
695         case ns_r_nxdomain:
696                 status = G_RESOLV_RESULT_STATUS_NAME_ERROR;
697                 break;
698         case ns_r_notimpl:
699                 status = G_RESOLV_RESULT_STATUS_NOT_IMPLEMENTED;
700                 break;
701         case ns_r_refused:
702                 status = G_RESOLV_RESULT_STATUS_REFUSED;
703                 break;
704         default:
705                 status = G_RESOLV_RESULT_STATUS_ERROR;
706                 break;
707         }
708
709         query = list->data;
710         query->nr_ns--;
711
712         lookup = query->lookup;
713
714         if (query == lookup->ipv6_query)
715                 lookup->ipv6_status = status;
716         else if (query == lookup->ipv4_query)
717                 lookup->ipv4_status = status;
718
719         for (i = 0; i < count; i++) {
720                 if (ns_parserr(&msg, ns_s_an, i, &rr) < 0)
721                         continue;
722
723                 if (ns_rr_class(rr) != ns_c_in)
724                         continue;
725
726                 g_assert(offsetof(struct sockaddr_in, sin_addr) ==
727                                 offsetof(struct sockaddr_in6, sin6_flowinfo));
728
729                 if (ns_rr_type(rr) == ns_t_a &&
730                                         ns_rr_rdlen(rr) == NS_INADDRSZ) {
731                         add_result(lookup, AF_INET, ns_rr_rdata(rr));
732                 } else if (ns_rr_type(rr) == ns_t_aaaa &&
733                                         ns_rr_rdlen(rr) == NS_IN6ADDRSZ) {
734                         add_result(lookup, AF_INET6, ns_rr_rdata(rr));
735                 }
736         }
737
738         if (status != G_RESOLV_RESULT_STATUS_SUCCESS && query->nr_ns > 0)
739                 return;
740
741         if (query == lookup->ipv6_query)
742                 lookup->ipv6_query = NULL;
743         else
744                 lookup->ipv4_query = NULL;
745
746         g_queue_remove(resolv->query_queue, query);
747         destroy_query(query);
748
749         if (!lookup->ipv4_query && !lookup->ipv6_query)
750                 sort_and_return_results(lookup);
751 }
752
753 static gboolean received_udp_data(GIOChannel *channel, GIOCondition cond,
754                                                         gpointer user_data)
755 {
756         struct resolv_nameserver *nameserver = user_data;
757         unsigned char buf[4096];
758         int sk, len;
759
760         if (cond & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
761                 nameserver->udp_watch = 0;
762                 return FALSE;
763         }
764
765         sk = g_io_channel_unix_get_fd(nameserver->udp_channel);
766
767         len = recv(sk, buf, sizeof(buf), 0);
768         if (len < 12)
769                 return TRUE;
770
771         parse_response(nameserver, buf, len);
772
773         return TRUE;
774 }
775
776 static int connect_udp_channel(struct resolv_nameserver *nameserver)
777 {
778         struct addrinfo hints, *rp;
779         char portnr[6];
780         int err, sk;
781
782         memset(&hints, 0, sizeof(hints));
783         hints.ai_family = AF_UNSPEC;
784         hints.ai_socktype = SOCK_DGRAM;
785         hints.ai_flags = AI_PASSIVE | AI_NUMERICSERV | AI_NUMERICHOST;
786
787         sprintf(portnr, "%d", nameserver->port);
788         err = getaddrinfo(nameserver->address, portnr, &hints, &rp);
789         if (err)
790                 return -EINVAL;
791
792         /*
793          * Do not blindly copy this code elsewhere; it doesn't loop over the
794          * results using ->ai_next as it should. That's OK in *this* case
795          * because it was a numeric lookup; we *know* there's only one.
796          */
797         if (!rp)
798                 return -EINVAL;
799
800         sk = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
801         if (sk < 0) {
802                 freeaddrinfo(rp);
803                 return -EIO;
804         }
805
806         /*
807          * If nameserver points to localhost ip, their is no need to
808          * bind the socket on any interface.
809          */
810         if (nameserver->resolv->index > 0 &&
811                         strncmp(nameserver->address, "127.0.0.1", 9) != 0) {
812                 char interface[IF_NAMESIZE];
813
814                 memset(interface, 0, IF_NAMESIZE);
815                 if (if_indextoname(nameserver->resolv->index, interface)) {
816                         if (setsockopt(sk, SOL_SOCKET, SO_BINDTODEVICE,
817                                                 interface, IF_NAMESIZE) < 0) {
818                                 close(sk);
819                                 freeaddrinfo(rp);
820                                 return -EIO;
821                         }
822                 }
823         }
824
825         if (connect(sk, rp->ai_addr, rp->ai_addrlen) < 0) {
826                 close(sk);
827                 freeaddrinfo(rp);
828                 return -EIO;
829         }
830
831         freeaddrinfo(rp);
832
833         nameserver->udp_channel = g_io_channel_unix_new(sk);
834         if (!nameserver->udp_channel) {
835                 close(sk);
836                 return -ENOMEM;
837         }
838
839         g_io_channel_set_close_on_unref(nameserver->udp_channel, TRUE);
840
841         nameserver->udp_watch = g_io_add_watch(nameserver->udp_channel,
842                                 G_IO_IN | G_IO_NVAL | G_IO_ERR | G_IO_HUP,
843                                 received_udp_data, nameserver);
844
845         return 0;
846 }
847
848 GResolv *g_resolv_new(int index)
849 {
850         GResolv *resolv;
851
852         if (index < 0)
853                 return NULL;
854
855         resolv = g_try_new0(GResolv, 1);
856         if (!resolv)
857                 return NULL;
858
859         resolv->ref_count = 1;
860
861         resolv->result_family = AF_UNSPEC;
862
863         resolv->next_lookup_id = 1;
864
865         resolv->query_queue = g_queue_new();
866         if (!resolv->query_queue) {
867                 g_free(resolv);
868                 return NULL;
869         }
870
871         resolv->lookup_queue = g_queue_new();
872         if (!resolv->lookup_queue) {
873                 g_queue_free(resolv->query_queue);
874                 g_free(resolv);
875                 return NULL;
876         }
877
878         resolv->index = index;
879         resolv->nameserver_list = NULL;
880
881         res_ninit(&resolv->res);
882
883         return resolv;
884 }
885
886 GResolv *g_resolv_ref(GResolv *resolv)
887 {
888         if (!resolv)
889                 return NULL;
890
891         __sync_fetch_and_add(&resolv->ref_count, 1);
892
893         return resolv;
894 }
895
896 void g_resolv_unref(GResolv *resolv)
897 {
898         struct resolv_query *query;
899         struct resolv_lookup *lookup;
900
901         if (!resolv)
902                 return;
903
904         if (__sync_fetch_and_sub(&resolv->ref_count, 1) != 1)
905                 return;
906
907         while ((lookup = g_queue_pop_head(resolv->lookup_queue))) {
908                 debug(resolv, "lookup %p id %d", lookup, lookup->id);
909                 destroy_lookup(lookup);
910         }
911
912         while ((query = g_queue_pop_head(resolv->query_queue))) {
913                 debug(resolv, "query %p", query);
914                 destroy_query(query);
915         }
916
917         g_queue_free(resolv->query_queue);
918         g_queue_free(resolv->lookup_queue);
919
920         flush_nameservers(resolv);
921
922         res_nclose(&resolv->res);
923
924         g_free(resolv);
925 }
926
927 void g_resolv_set_debug(GResolv *resolv, GResolvDebugFunc func,
928                                                 gpointer user_data)
929 {
930         if (!resolv)
931                 return;
932
933         resolv->debug_func = func;
934         resolv->debug_data = user_data;
935 }
936
937 bool g_resolv_add_nameserver(GResolv *resolv, const char *address,
938                                         uint16_t port, unsigned long flags)
939 {
940         struct resolv_nameserver *nameserver;
941
942         if (!resolv)
943                 return false;
944
945         nameserver = g_try_new0(struct resolv_nameserver, 1);
946         if (!nameserver)
947                 return false;
948
949         nameserver->address = g_strdup(address);
950         nameserver->port = port;
951         nameserver->flags = flags;
952         nameserver->resolv = resolv;
953
954         if (connect_udp_channel(nameserver) < 0) {
955                 free_nameserver(nameserver);
956                 return false;
957         }
958
959         resolv->nameserver_list = g_list_append(resolv->nameserver_list,
960                                                                 nameserver);
961
962         debug(resolv, "setting nameserver %s", address);
963
964         return true;
965 }
966
967 void g_resolv_flush_nameservers(GResolv *resolv)
968 {
969         if (!resolv)
970                 return;
971
972         flush_nameservers(resolv);
973 }
974
975 static gint add_query(struct resolv_lookup *lookup, const char *hostname, int type)
976 {
977         struct resolv_query *query = g_try_new0(struct resolv_query, 1);
978         unsigned char buf[4096];
979         int len;
980
981         if (!query)
982                 return -ENOMEM;
983
984         len = res_mkquery(ns_o_query, hostname, ns_c_in, type,
985                                         NULL, 0, NULL, buf, sizeof(buf));
986
987         query->msgid = buf[0] << 8 | buf[1];
988
989         debug(lookup->resolv, "sending %d bytes", len);
990
991         query->nr_ns = send_query(lookup->resolv, buf, len);
992         if (query->nr_ns <= 0) {
993                 g_free(query);
994                 return -EIO;
995         }
996
997         query->resolv = lookup->resolv;
998         query->lookup = lookup;
999
1000         g_queue_push_tail(lookup->resolv->query_queue, query);
1001
1002         debug(lookup->resolv, "lookup %p id %d query %p", lookup, lookup->id,
1003                                                                         query);
1004
1005         query->timeout = g_timeout_add_seconds(5, query_timeout, query);
1006
1007         if (type == ns_t_aaaa)
1008                 lookup->ipv6_query = query;
1009         else
1010                 lookup->ipv4_query = query;
1011
1012         return 0;
1013 }
1014
1015 guint g_resolv_lookup_hostname(GResolv *resolv, const char *hostname,
1016                                 GResolvResultFunc func, gpointer user_data)
1017 {
1018         struct resolv_lookup *lookup;
1019
1020         if (!resolv)
1021                 return 0;
1022
1023         debug(resolv, "hostname %s", hostname);
1024
1025         if (!resolv->nameserver_list) {
1026                 int i;
1027
1028                 for (i = 0; i < resolv->res.nscount; i++) {
1029                         char buf[100];
1030                         int family = resolv->res.nsaddr_list[i].sin_family;
1031                         void *sa_addr = &resolv->res.nsaddr_list[i].sin_addr;
1032
1033                         if (family != AF_INET &&
1034                                         resolv->res._u._ext.nsaddrs[i]) {
1035                                 family = AF_INET6;
1036                                 sa_addr = &resolv->res._u._ext.nsaddrs[i]->sin6_addr;
1037                         }
1038
1039                         if (family != AF_INET && family != AF_INET6)
1040                                 continue;
1041
1042                         if (inet_ntop(family, sa_addr, buf, sizeof(buf)))
1043                                 g_resolv_add_nameserver(resolv, buf, 53, 0);
1044                 }
1045
1046                 if (!resolv->nameserver_list)
1047                         g_resolv_add_nameserver(resolv, "127.0.0.1", 53, 0);
1048         }
1049
1050         lookup = g_try_new0(struct resolv_lookup, 1);
1051         if (!lookup)
1052                 return 0;
1053
1054         lookup->resolv = resolv;
1055         lookup->result_func = func;
1056         lookup->result_data = user_data;
1057         lookup->id = resolv->next_lookup_id++;
1058
1059         if (resolv->result_family != AF_INET6) {
1060                 if (add_query(lookup, hostname, ns_t_a)) {
1061                         g_free(lookup);
1062                         return -EIO;
1063                 }
1064         }
1065
1066         if (resolv->result_family != AF_INET) {
1067                 if (add_query(lookup, hostname, ns_t_aaaa)) {
1068                         if (resolv->result_family != AF_INET6) {
1069                                 g_queue_remove(resolv->query_queue,
1070                                                 lookup->ipv4_query);
1071                                 destroy_query(lookup->ipv4_query);
1072                         }
1073
1074                         g_free(lookup);
1075                         return -EIO;
1076                 }
1077         }
1078
1079         g_queue_push_tail(resolv->lookup_queue, lookup);
1080
1081         debug(resolv, "lookup %p id %d", lookup, lookup->id);
1082
1083         return lookup->id;
1084 }
1085
1086 bool g_resolv_cancel_lookup(GResolv *resolv, guint id)
1087 {
1088         struct resolv_lookup *lookup;
1089         GList *list;
1090
1091         debug(resolv, "lookup id %d", id);
1092
1093         list = g_queue_find_custom(resolv->lookup_queue,
1094                                 GUINT_TO_POINTER(id), compare_lookup_id);
1095
1096         if (!list)
1097                 return false;
1098
1099         lookup = list->data;
1100
1101         debug(resolv, "lookup %p", lookup);
1102
1103         g_queue_remove(resolv->lookup_queue, lookup);
1104         destroy_lookup(lookup);
1105
1106         return true;
1107 }
1108
1109 bool g_resolv_set_address_family(GResolv *resolv, int family)
1110 {
1111         if (!resolv)
1112                 return false;
1113
1114         if (family != AF_UNSPEC && family != AF_INET && family != AF_INET6)
1115                 return false;
1116
1117         resolv->result_family = family;
1118
1119         return true;
1120 }