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