864d2adbb67832e113b309c542b494302f15cca0
[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         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 == NULL)
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 != NULL) {
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 != NULL) {
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 gboolean 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) == NULL)
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) == NULL)
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 == NULL && lookup->ipv6_query == NULL)
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 == NULL)
554                 return;
555
556         if (nameserver->udp_watch > 0)
557                 g_source_remove(nameserver->udp_watch);
558
559         if (nameserver->udp_channel != NULL) {
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 == NULL)
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 == NULL)
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 == NULL)
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         ns_initparse(buf, len, &msg);
669
670         list = g_queue_find_custom(resolv->query_queue,
671                         GUINT_TO_POINTER(ns_msg_id(msg)), compare_query_msgid);
672         if (!list)
673                 return;
674
675         rcode = ns_msg_getflag(msg, ns_f_rcode);
676         count = ns_msg_count(msg, ns_s_an);
677
678         debug(resolv, "msg id: 0x%04x rcode: %d count: %d",
679                                         ns_msg_id(msg), rcode, count);
680
681         switch (rcode) {
682         case ns_r_noerror:
683                 status = G_RESOLV_RESULT_STATUS_SUCCESS;
684                 break;
685         case ns_r_formerr:
686                 status = G_RESOLV_RESULT_STATUS_FORMAT_ERROR;
687                 break;
688         case ns_r_servfail:
689                 status = G_RESOLV_RESULT_STATUS_SERVER_FAILURE;
690                 break;
691         case ns_r_nxdomain:
692                 status = G_RESOLV_RESULT_STATUS_NAME_ERROR;
693                 break;
694         case ns_r_notimpl:
695                 status = G_RESOLV_RESULT_STATUS_NOT_IMPLEMENTED;
696                 break;
697         case ns_r_refused:
698                 status = G_RESOLV_RESULT_STATUS_REFUSED;
699                 break;
700         default:
701                 status = G_RESOLV_RESULT_STATUS_ERROR;
702                 break;
703         }
704
705         query = list->data;
706         query->nr_ns--;
707
708         lookup = query->lookup;
709
710         if (query == lookup->ipv6_query)
711                 lookup->ipv6_status = status;
712         else if (query == lookup->ipv4_query)
713                 lookup->ipv4_status = status;
714
715         for (i = 0; i < count; i++) {
716                 ns_parserr(&msg, ns_s_an, i, &rr);
717
718                 if (ns_rr_class(rr) != ns_c_in)
719                         continue;
720
721                 g_assert(offsetof(struct sockaddr_in, sin_addr) ==
722                                 offsetof(struct sockaddr_in6, sin6_flowinfo));
723
724                 if (ns_rr_type(rr) == ns_t_a &&
725                                         ns_rr_rdlen(rr) == NS_INADDRSZ) {
726                         add_result(lookup, AF_INET, ns_rr_rdata(rr));
727                 } else if (ns_rr_type(rr) == ns_t_aaaa &&
728                                         ns_rr_rdlen(rr) == NS_IN6ADDRSZ) {
729                         add_result(lookup, AF_INET6, ns_rr_rdata(rr));
730                 }
731         }
732
733         if (status != G_RESOLV_RESULT_STATUS_SUCCESS && query->nr_ns > 0)
734                 return;
735
736         if (query == lookup->ipv6_query)
737                 lookup->ipv6_query = NULL;
738         else
739                 lookup->ipv4_query = NULL;
740
741         g_queue_remove(resolv->query_queue, query);
742         destroy_query(query);
743
744         if (lookup->ipv4_query == NULL && lookup->ipv6_query == NULL)
745                 sort_and_return_results(lookup);
746 }
747
748 static gboolean received_udp_data(GIOChannel *channel, GIOCondition cond,
749                                                         gpointer user_data)
750 {
751         struct resolv_nameserver *nameserver = user_data;
752         unsigned char buf[4096];
753         int sk, len;
754
755         if (cond & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
756                 nameserver->udp_watch = 0;
757                 return FALSE;
758         }
759
760         sk = g_io_channel_unix_get_fd(nameserver->udp_channel);
761
762         len = recv(sk, buf, sizeof(buf), 0);
763         if (len < 12)
764                 return TRUE;
765
766         parse_response(nameserver, buf, len);
767
768         return TRUE;
769 }
770
771 static int connect_udp_channel(struct resolv_nameserver *nameserver)
772 {
773         struct addrinfo hints, *rp;
774         char portnr[6];
775         int err, sk;
776
777         memset(&hints, 0, sizeof(hints));
778         hints.ai_family = AF_UNSPEC;
779         hints.ai_socktype = SOCK_DGRAM;
780         hints.ai_flags = AI_PASSIVE | AI_NUMERICSERV | AI_NUMERICHOST;
781
782         sprintf(portnr, "%d", nameserver->port);
783         err = getaddrinfo(nameserver->address, portnr, &hints, &rp);
784         if (err)
785                 return -EINVAL;
786
787         /*
788          * Do not blindly copy this code elsewhere; it doesn't loop over the
789          * results using ->ai_next as it should. That's OK in *this* case
790          * because it was a numeric lookup; we *know* there's only one.
791          */
792         if (!rp)
793                 return -EINVAL;
794
795         sk = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
796         if (sk < 0) {
797                 freeaddrinfo(rp);
798                 return -EIO;
799         }
800
801         /*
802          * If nameserver points to localhost ip, their is no need to
803          * bind the socket on any interface.
804          */
805         if (nameserver->resolv->index > 0 &&
806                         strncmp(nameserver->address, "127.0.0.1", 9) != 0) {
807                 char interface[IF_NAMESIZE];
808
809                 memset(interface, 0, IF_NAMESIZE);
810                 if (if_indextoname(nameserver->resolv->index,
811                                                 interface) != NULL) {
812                         if (setsockopt(sk, SOL_SOCKET, SO_BINDTODEVICE,
813                                                 interface, IF_NAMESIZE) < 0) {
814                                 close(sk);
815                                 freeaddrinfo(rp);
816                                 return -EIO;
817                         }
818                 }
819         }
820
821         if (connect(sk, rp->ai_addr, rp->ai_addrlen) < 0) {
822                 close(sk);
823                 freeaddrinfo(rp);
824                 return -EIO;
825         }
826
827         freeaddrinfo(rp);
828
829         nameserver->udp_channel = g_io_channel_unix_new(sk);
830         if (nameserver->udp_channel == NULL) {
831                 close(sk);
832                 return -ENOMEM;
833         }
834
835         g_io_channel_set_close_on_unref(nameserver->udp_channel, TRUE);
836
837         nameserver->udp_watch = g_io_add_watch(nameserver->udp_channel,
838                                 G_IO_IN | G_IO_NVAL | G_IO_ERR | G_IO_HUP,
839                                 received_udp_data, nameserver);
840
841         return 0;
842 }
843
844 GResolv *g_resolv_new(int index)
845 {
846         GResolv *resolv;
847
848         if (index < 0)
849                 return NULL;
850
851         resolv = g_try_new0(GResolv, 1);
852         if (resolv == NULL)
853                 return NULL;
854
855         resolv->ref_count = 1;
856
857         resolv->result_family = AF_UNSPEC;
858
859         resolv->next_lookup_id = 1;
860
861         resolv->query_queue = g_queue_new();
862         if (resolv->query_queue == NULL) {
863                 g_free(resolv);
864                 return NULL;
865         }
866
867         resolv->lookup_queue = g_queue_new();
868         if (resolv->lookup_queue == NULL) {
869                 g_queue_free(resolv->query_queue);
870                 g_free(resolv);
871                 return NULL;
872         }
873
874         resolv->index = index;
875         resolv->nameserver_list = NULL;
876
877         res_ninit(&resolv->res);
878
879         return resolv;
880 }
881
882 GResolv *g_resolv_ref(GResolv *resolv)
883 {
884         if (resolv == NULL)
885                 return NULL;
886
887         __sync_fetch_and_add(&resolv->ref_count, 1);
888
889         return resolv;
890 }
891
892 void g_resolv_unref(GResolv *resolv)
893 {
894         struct resolv_query *query;
895         struct resolv_lookup *lookup;
896
897         if (resolv == NULL)
898                 return;
899
900         if (__sync_fetch_and_sub(&resolv->ref_count, 1) != 1)
901                 return;
902
903         while ((lookup = g_queue_pop_head(resolv->lookup_queue))) {
904                 debug(resolv, "lookup %p id %d", lookup, lookup->id);
905                 destroy_lookup(lookup);
906         }
907
908         while ((query = g_queue_pop_head(resolv->query_queue))) {
909                 debug(resolv, "query %p", query);
910                 destroy_query(query);
911         }
912
913         g_queue_free(resolv->query_queue);
914         g_queue_free(resolv->lookup_queue);
915
916         flush_nameservers(resolv);
917
918         res_nclose(&resolv->res);
919
920         g_free(resolv);
921 }
922
923 void g_resolv_set_debug(GResolv *resolv, GResolvDebugFunc func,
924                                                 gpointer user_data)
925 {
926         if (resolv == NULL)
927                 return;
928
929         resolv->debug_func = func;
930         resolv->debug_data = user_data;
931 }
932
933 gboolean g_resolv_add_nameserver(GResolv *resolv, const char *address,
934                                         uint16_t port, unsigned long flags)
935 {
936         struct resolv_nameserver *nameserver;
937
938         if (resolv == NULL)
939                 return FALSE;
940
941         nameserver = g_try_new0(struct resolv_nameserver, 1);
942         if (nameserver == NULL)
943                 return FALSE;
944
945         nameserver->address = g_strdup(address);
946         nameserver->port = port;
947         nameserver->flags = flags;
948         nameserver->resolv = resolv;
949
950         if (connect_udp_channel(nameserver) < 0) {
951                 free_nameserver(nameserver);
952                 return FALSE;
953         }
954
955         resolv->nameserver_list = g_list_append(resolv->nameserver_list,
956                                                                 nameserver);
957
958         debug(resolv, "setting nameserver %s", address);
959
960         return TRUE;
961 }
962
963 void g_resolv_flush_nameservers(GResolv *resolv)
964 {
965         if (resolv == NULL)
966                 return;
967
968         flush_nameservers(resolv);
969 }
970
971 static gint add_query(struct resolv_lookup *lookup, const char *hostname, int type)
972 {
973         struct resolv_query *query = g_try_new0(struct resolv_query, 1);
974         unsigned char buf[4096];
975         int len;
976
977         if (query == NULL)
978                 return -ENOMEM;
979
980         len = res_mkquery(ns_o_query, hostname, ns_c_in, type,
981                                         NULL, 0, NULL, buf, sizeof(buf));
982
983         query->msgid = buf[0] << 8 | buf[1];
984
985         debug(lookup->resolv, "sending %d bytes", len);
986
987         query->nr_ns = send_query(lookup->resolv, buf, len);
988         if (query->nr_ns <= 0) {
989                 g_free(query);
990                 return -EIO;
991         }
992
993         query->resolv = lookup->resolv;
994         query->lookup = lookup;
995
996         g_queue_push_tail(lookup->resolv->query_queue, query);
997
998         debug(lookup->resolv, "lookup %p id %d query %p", lookup, lookup->id,
999                                                                         query);
1000
1001         query->timeout = g_timeout_add_seconds(5, query_timeout, query);
1002
1003         if (type == ns_t_aaaa)
1004                 lookup->ipv6_query = query;
1005         else
1006                 lookup->ipv4_query = query;
1007
1008         return 0;
1009 }
1010
1011 guint g_resolv_lookup_hostname(GResolv *resolv, const char *hostname,
1012                                 GResolvResultFunc func, gpointer user_data)
1013 {
1014         struct resolv_lookup *lookup;
1015
1016         if (resolv == NULL)
1017                 return 0;
1018
1019         debug(resolv, "hostname %s", hostname);
1020
1021         if (resolv->nameserver_list == NULL) {
1022                 int i;
1023
1024                 for (i = 0; i < resolv->res.nscount; i++) {
1025                         char buf[100];
1026                         int family = resolv->res.nsaddr_list[i].sin_family;
1027                         void *sa_addr = &resolv->res.nsaddr_list[i].sin_addr;
1028
1029                         if (family != AF_INET &&
1030                                         resolv->res._u._ext.nsaddrs[i]) {
1031                                 family = AF_INET6;
1032                                 sa_addr = &resolv->res._u._ext.nsaddrs[i]->sin6_addr;
1033                         }
1034
1035                         if (family != AF_INET && family != AF_INET6)
1036                                 continue;
1037
1038                         if (inet_ntop(family, sa_addr, buf, sizeof(buf)))
1039                                 g_resolv_add_nameserver(resolv, buf, 53, 0);
1040                 }
1041
1042                 if (resolv->nameserver_list == NULL)
1043                         g_resolv_add_nameserver(resolv, "127.0.0.1", 53, 0);
1044         }
1045
1046         lookup = g_try_new0(struct resolv_lookup, 1);
1047         if (lookup == NULL)
1048                 return 0;
1049
1050         lookup->resolv = resolv;
1051         lookup->result_func = func;
1052         lookup->result_data = user_data;
1053         lookup->id = resolv->next_lookup_id++;
1054
1055         if (resolv->result_family != AF_INET6) {
1056                 if (add_query(lookup, hostname, ns_t_a)) {
1057                         g_free(lookup);
1058                         return -EIO;
1059                 }
1060         }
1061
1062         if (resolv->result_family != AF_INET) {
1063                 if (add_query(lookup, hostname, ns_t_aaaa)) {
1064                         if (resolv->result_family != AF_INET6) {
1065                                 g_queue_remove(resolv->query_queue,
1066                                                 lookup->ipv4_query);
1067                                 destroy_query(lookup->ipv4_query);
1068                         }
1069
1070                         g_free(lookup);
1071                         return -EIO;
1072                 }
1073         }
1074
1075         g_queue_push_tail(resolv->lookup_queue, lookup);
1076
1077         debug(resolv, "lookup %p id %d", lookup, lookup->id);
1078
1079         return lookup->id;
1080 }
1081
1082 gboolean g_resolv_cancel_lookup(GResolv *resolv, guint id)
1083 {
1084         struct resolv_lookup *lookup;
1085         GList *list;
1086
1087         debug(resolv, "lookup id %d", id);
1088
1089         list = g_queue_find_custom(resolv->lookup_queue,
1090                                 GUINT_TO_POINTER(id), compare_lookup_id);
1091
1092         if (list == NULL)
1093                 return FALSE;
1094
1095         lookup = list->data;
1096
1097         debug(resolv, "lookup %p", lookup);
1098
1099         g_queue_remove(resolv->lookup_queue, lookup);
1100         destroy_lookup(lookup);
1101
1102         return TRUE;
1103 }
1104
1105 gboolean g_resolv_set_address_family(GResolv *resolv, int family)
1106 {
1107         if (resolv == NULL)
1108                 return FALSE;
1109
1110         if (family != AF_UNSPEC && family != AF_INET && family != AF_INET6)
1111                 return FALSE;
1112
1113         resolv->result_family = family;
1114
1115         return TRUE;
1116 }