Remove DefaultDependencies=false at connman.service
[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) ( ((_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         GResolvResultFunc result_func = lookup->result_func;
475         void *result_data = lookup->result_data;
476         int i, n = 0;
477
478         if (!results)
479                 return;
480
481         memset(buf, 0, INET6_ADDRSTRLEN + 1);
482
483         rfc3484_sort_results(lookup);
484
485         for (i = 0; i < lookup->nr_results; i++) {
486                 if (lookup->results[i].dst.sa.sa_family == AF_INET) {
487                         if (!inet_ntop(AF_INET,
488                                         &lookup->results[i].dst.sin.sin_addr,
489                                         buf, sizeof(buf) - 1))
490                                 continue;
491                 } else if (lookup->results[i].dst.sa.sa_family == AF_INET6) {
492                         if (!inet_ntop(AF_INET6,
493                                         &lookup->results[i].dst.sin6.sin6_addr,
494                                         buf, sizeof(buf) - 1))
495                                 continue;
496                 } else
497                         continue;
498
499                 results[n++] = g_strdup(buf);
500         }
501
502         results[n++] = NULL;
503
504         if (lookup->resolv->result_family == AF_INET)
505                 status = lookup->ipv4_status;
506         else if (lookup->resolv->result_family == AF_INET6)
507                 status = lookup->ipv6_status;
508         else {
509                 if (lookup->ipv6_status == G_RESOLV_RESULT_STATUS_SUCCESS)
510                         status = lookup->ipv6_status;
511                 else
512                         status = lookup->ipv4_status;
513         }
514
515         debug(lookup->resolv, "lookup %p received %d results", lookup, n-1);
516
517         g_queue_remove(lookup->resolv->lookup_queue, lookup);
518         destroy_lookup(lookup);
519
520         result_func(status, results, result_data);
521
522         g_strfreev(results);
523 }
524
525 static gboolean query_timeout(gpointer user_data)
526 {
527         struct resolv_query *query = user_data;
528         struct resolv_lookup *lookup = query->lookup;
529         GResolv *resolv = query->resolv;
530
531         query->timeout = 0;
532
533         if (query == lookup->ipv4_query) {
534                 lookup->ipv4_status = G_RESOLV_RESULT_STATUS_NO_RESPONSE;
535                 lookup->ipv4_query = NULL;
536         } else if (query == lookup->ipv6_query) {
537                 lookup->ipv6_status = G_RESOLV_RESULT_STATUS_NO_RESPONSE;
538                 lookup->ipv6_query = NULL;
539         }
540
541         g_queue_remove(resolv->query_queue, query);
542         destroy_query(query);
543
544         if (!lookup->ipv4_query && !lookup->ipv6_query)
545                 sort_and_return_results(lookup);
546
547         return FALSE;
548 }
549
550 static void free_nameserver(struct resolv_nameserver *nameserver)
551 {
552         if (!nameserver)
553                 return;
554
555         if (nameserver->udp_watch > 0)
556                 g_source_remove(nameserver->udp_watch);
557
558         if (nameserver->udp_channel) {
559                 g_io_channel_shutdown(nameserver->udp_channel, TRUE, NULL);
560                 g_io_channel_unref(nameserver->udp_channel);
561         }
562
563         g_free(nameserver->address);
564         g_free(nameserver);
565 }
566
567 static void flush_nameservers(GResolv *resolv)
568 {
569         GList *list;
570
571         for (list = g_list_first(resolv->nameserver_list);
572                                         list; list = g_list_next(list))
573                 free_nameserver(list->data);
574
575         g_list_free(resolv->nameserver_list);
576         resolv->nameserver_list = NULL;
577 }
578
579 static int send_query(GResolv *resolv, const unsigned char *buf, int len)
580 {
581         GList *list;
582         int nr_ns;
583
584         if (!resolv->nameserver_list)
585                 return -ENOENT;
586
587         for (list = g_list_first(resolv->nameserver_list), nr_ns = 0;
588                                 list; list = g_list_next(list), nr_ns++) {
589                 struct resolv_nameserver *nameserver = list->data;
590                 int sk, sent;
591
592                 if (!nameserver->udp_channel)
593                         continue;
594
595                 sk = g_io_channel_unix_get_fd(nameserver->udp_channel);
596
597                 sent = send(sk, buf, len, 0);
598                 if (sent < 0)
599                         continue;
600         }
601
602         return nr_ns;
603 }
604
605 static gint compare_lookup_id(gconstpointer a, gconstpointer b)
606 {
607         const struct resolv_lookup *lookup = a;
608         guint id = GPOINTER_TO_UINT(b);
609
610         if (lookup->id < id)
611                 return -1;
612
613         if (lookup->id > id)
614                 return 1;
615
616         return 0;
617 }
618
619 static gint compare_query_msgid(gconstpointer a, gconstpointer b)
620 {
621         const struct resolv_query *query = a;
622         uint16_t msgid = GPOINTER_TO_UINT(b);
623
624         if (query->msgid < msgid)
625                 return -1;
626
627         if (query->msgid > msgid)
628                 return 1;
629
630         return 0;
631 }
632
633 static void add_result(struct resolv_lookup *lookup, int family,
634                                                         const void *data)
635 {
636         int n = lookup->nr_results++;
637         lookup->results = g_try_realloc(lookup->results,
638                                         sizeof(struct sort_result) * (n + 1));
639         if (!lookup->results)
640                 return;
641
642         memset(&lookup->results[n], 0, sizeof(struct sort_result));
643
644         lookup->results[n].dst.sa.sa_family = family;
645         if (family == AF_INET)
646                 memcpy(&lookup->results[n].dst.sin.sin_addr,
647                                                 data, NS_INADDRSZ);
648         else
649                 memcpy(&lookup->results[n].dst.sin6.sin6_addr,
650                                                 data, NS_IN6ADDRSZ);
651 }
652
653 static void parse_response(struct resolv_nameserver *nameserver,
654                                         const unsigned char *buf, int len)
655 {
656         GResolv *resolv = nameserver->resolv;
657         GResolvResultStatus status;
658         struct resolv_query *query;
659         struct resolv_lookup *lookup;
660         GList *list;
661         ns_msg msg;
662         ns_rr rr;
663         int i, rcode, count;
664
665         debug(resolv, "response from %s", nameserver->address);
666
667         if (ns_initparse(buf, len, &msg) < 0)
668                 return;
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                 if (count > 0)
684                         status = G_RESOLV_RESULT_STATUS_SUCCESS;
685                 else
686                         status = G_RESOLV_RESULT_STATUS_NO_ANSWER;
687                 break;
688         case ns_r_formerr:
689                 status = G_RESOLV_RESULT_STATUS_FORMAT_ERROR;
690                 break;
691         case ns_r_servfail:
692                 status = G_RESOLV_RESULT_STATUS_SERVER_FAILURE;
693                 break;
694         case ns_r_nxdomain:
695                 status = G_RESOLV_RESULT_STATUS_NAME_ERROR;
696                 break;
697         case ns_r_notimpl:
698                 status = G_RESOLV_RESULT_STATUS_NOT_IMPLEMENTED;
699                 break;
700         case ns_r_refused:
701                 status = G_RESOLV_RESULT_STATUS_REFUSED;
702                 break;
703         default:
704                 status = G_RESOLV_RESULT_STATUS_ERROR;
705                 break;
706         }
707
708         query = list->data;
709         query->nr_ns--;
710
711         lookup = query->lookup;
712
713         if (query == lookup->ipv6_query)
714                 lookup->ipv6_status = status;
715         else if (query == lookup->ipv4_query)
716                 lookup->ipv4_status = status;
717
718         for (i = 0; i < count; i++) {
719                 if (ns_parserr(&msg, ns_s_an, i, &rr) < 0)
720                         continue;
721
722                 if (ns_rr_class(rr) != ns_c_in)
723                         continue;
724
725                 g_assert(offsetof(struct sockaddr_in, sin_addr) ==
726                                 offsetof(struct sockaddr_in6, sin6_flowinfo));
727
728                 if (ns_rr_type(rr) == ns_t_a &&
729                                         ns_rr_rdlen(rr) == NS_INADDRSZ) {
730                         add_result(lookup, AF_INET, ns_rr_rdata(rr));
731                 } else if (ns_rr_type(rr) == ns_t_aaaa &&
732                                         ns_rr_rdlen(rr) == NS_IN6ADDRSZ) {
733                         add_result(lookup, AF_INET6, ns_rr_rdata(rr));
734                 }
735         }
736
737         if (status != G_RESOLV_RESULT_STATUS_SUCCESS && query->nr_ns > 0)
738                 return;
739
740         if (query == lookup->ipv6_query)
741                 lookup->ipv6_query = NULL;
742         else
743                 lookup->ipv4_query = NULL;
744
745         g_queue_remove(resolv->query_queue, query);
746         destroy_query(query);
747
748         if (!lookup->ipv4_query && !lookup->ipv6_query)
749                 sort_and_return_results(lookup);
750 }
751
752 static gboolean received_udp_data(GIOChannel *channel, GIOCondition cond,
753                                                         gpointer user_data)
754 {
755         struct resolv_nameserver *nameserver = user_data;
756         unsigned char buf[4096];
757         int sk, len;
758
759         if (cond & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
760                 nameserver->udp_watch = 0;
761                 return FALSE;
762         }
763
764         sk = g_io_channel_unix_get_fd(nameserver->udp_channel);
765
766         len = recv(sk, buf, sizeof(buf), 0);
767         if (len < 12)
768                 return TRUE;
769
770         parse_response(nameserver, buf, len);
771
772         return TRUE;
773 }
774
775 static int connect_udp_channel(struct resolv_nameserver *nameserver)
776 {
777         struct addrinfo hints, *rp;
778         char portnr[6];
779         int err, sk;
780
781         memset(&hints, 0, sizeof(hints));
782         hints.ai_family = AF_UNSPEC;
783         hints.ai_socktype = SOCK_DGRAM;
784         hints.ai_flags = AI_PASSIVE | AI_NUMERICSERV | AI_NUMERICHOST;
785
786         sprintf(portnr, "%d", nameserver->port);
787         err = getaddrinfo(nameserver->address, portnr, &hints, &rp);
788         if (err)
789                 return -EINVAL;
790
791         /*
792          * Do not blindly copy this code elsewhere; it doesn't loop over the
793          * results using ->ai_next as it should. That's OK in *this* case
794          * because it was a numeric lookup; we *know* there's only one.
795          */
796         if (!rp)
797                 return -EINVAL;
798
799         sk = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
800         if (sk < 0) {
801                 freeaddrinfo(rp);
802                 return -EIO;
803         }
804
805         /*
806          * If nameserver points to localhost ip, their is no need to
807          * bind the socket on any interface.
808          */
809         if (nameserver->resolv->index > 0 &&
810                         strncmp(nameserver->address, "127.0.0.1", 9) != 0) {
811                 char interface[IF_NAMESIZE];
812
813                 memset(interface, 0, IF_NAMESIZE);
814                 if (if_indextoname(nameserver->resolv->index, interface)) {
815                         if (setsockopt(sk, SOL_SOCKET, SO_BINDTODEVICE,
816                                                 interface, IF_NAMESIZE) < 0) {
817                                 close(sk);
818                                 freeaddrinfo(rp);
819                                 return -EIO;
820                         }
821                 }
822         }
823
824         if (connect(sk, rp->ai_addr, rp->ai_addrlen) < 0) {
825                 close(sk);
826                 freeaddrinfo(rp);
827                 return -EIO;
828         }
829
830         freeaddrinfo(rp);
831
832         nameserver->udp_channel = g_io_channel_unix_new(sk);
833         if (!nameserver->udp_channel) {
834                 close(sk);
835                 return -ENOMEM;
836         }
837
838         g_io_channel_set_close_on_unref(nameserver->udp_channel, TRUE);
839
840         nameserver->udp_watch = g_io_add_watch(nameserver->udp_channel,
841                                 G_IO_IN | G_IO_NVAL | G_IO_ERR | G_IO_HUP,
842                                 received_udp_data, nameserver);
843
844         return 0;
845 }
846
847 GResolv *g_resolv_new(int index)
848 {
849         GResolv *resolv;
850
851         if (index < 0)
852                 return NULL;
853
854         resolv = g_try_new0(GResolv, 1);
855         if (!resolv)
856                 return NULL;
857
858         resolv->ref_count = 1;
859
860         resolv->result_family = AF_UNSPEC;
861
862         resolv->next_lookup_id = 1;
863
864         resolv->query_queue = g_queue_new();
865         if (!resolv->query_queue) {
866                 g_free(resolv);
867                 return NULL;
868         }
869
870         resolv->lookup_queue = g_queue_new();
871         if (!resolv->lookup_queue) {
872                 g_queue_free(resolv->query_queue);
873                 g_free(resolv);
874                 return NULL;
875         }
876
877         resolv->index = index;
878         resolv->nameserver_list = NULL;
879
880         res_ninit(&resolv->res);
881
882         return resolv;
883 }
884
885 GResolv *g_resolv_ref(GResolv *resolv)
886 {
887         if (!resolv)
888                 return NULL;
889
890         __sync_fetch_and_add(&resolv->ref_count, 1);
891
892         return resolv;
893 }
894
895 void g_resolv_unref(GResolv *resolv)
896 {
897         struct resolv_query *query;
898         struct resolv_lookup *lookup;
899
900         if (!resolv)
901                 return;
902
903         if (__sync_fetch_and_sub(&resolv->ref_count, 1) != 1)
904                 return;
905
906         while ((lookup = g_queue_pop_head(resolv->lookup_queue))) {
907                 debug(resolv, "lookup %p id %d", lookup, lookup->id);
908                 destroy_lookup(lookup);
909         }
910
911         while ((query = g_queue_pop_head(resolv->query_queue))) {
912                 debug(resolv, "query %p", query);
913                 destroy_query(query);
914         }
915
916         g_queue_free(resolv->query_queue);
917         g_queue_free(resolv->lookup_queue);
918
919         flush_nameservers(resolv);
920
921         res_nclose(&resolv->res);
922
923         g_free(resolv);
924 }
925
926 void g_resolv_set_debug(GResolv *resolv, GResolvDebugFunc func,
927                                                 gpointer user_data)
928 {
929         if (!resolv)
930                 return;
931
932         resolv->debug_func = func;
933         resolv->debug_data = user_data;
934 }
935
936 bool g_resolv_add_nameserver(GResolv *resolv, const char *address,
937                                         uint16_t port, unsigned long flags)
938 {
939         struct resolv_nameserver *nameserver;
940
941         if (!resolv)
942                 return false;
943
944         nameserver = g_try_new0(struct resolv_nameserver, 1);
945         if (!nameserver)
946                 return false;
947
948         nameserver->address = g_strdup(address);
949         nameserver->port = port;
950         nameserver->flags = flags;
951         nameserver->resolv = resolv;
952
953         if (connect_udp_channel(nameserver) < 0) {
954                 free_nameserver(nameserver);
955                 return false;
956         }
957
958         resolv->nameserver_list = g_list_append(resolv->nameserver_list,
959                                                                 nameserver);
960
961         debug(resolv, "setting nameserver %s", address);
962
963         return true;
964 }
965
966 void g_resolv_flush_nameservers(GResolv *resolv)
967 {
968         if (!resolv)
969                 return;
970
971         flush_nameservers(resolv);
972 }
973
974 static gint add_query(struct resolv_lookup *lookup, const char *hostname, int type)
975 {
976         struct resolv_query *query = g_try_new0(struct resolv_query, 1);
977         unsigned char buf[4096];
978         int len;
979
980         if (!query)
981                 return -ENOMEM;
982
983         len = res_mkquery(ns_o_query, hostname, ns_c_in, type,
984                                         NULL, 0, NULL, buf, sizeof(buf));
985
986         query->msgid = buf[0] << 8 | buf[1];
987
988         debug(lookup->resolv, "sending %d bytes", len);
989
990         query->nr_ns = send_query(lookup->resolv, buf, len);
991         if (query->nr_ns <= 0) {
992                 g_free(query);
993                 return -EIO;
994         }
995
996         query->resolv = lookup->resolv;
997         query->lookup = lookup;
998
999         g_queue_push_tail(lookup->resolv->query_queue, query);
1000
1001         debug(lookup->resolv, "lookup %p id %d query %p", lookup, lookup->id,
1002                                                                         query);
1003
1004         query->timeout = g_timeout_add_seconds(5, query_timeout, query);
1005
1006         if (type == ns_t_aaaa)
1007                 lookup->ipv6_query = query;
1008         else
1009                 lookup->ipv4_query = query;
1010
1011         return 0;
1012 }
1013
1014 guint g_resolv_lookup_hostname(GResolv *resolv, const char *hostname,
1015                                 GResolvResultFunc func, gpointer user_data)
1016 {
1017         struct resolv_lookup *lookup;
1018
1019         if (!resolv)
1020                 return 0;
1021
1022         debug(resolv, "hostname %s", hostname);
1023
1024         if (!resolv->nameserver_list) {
1025                 int i;
1026
1027                 for (i = 0; i < resolv->res.nscount; i++) {
1028                         char buf[100];
1029                         int family = resolv->res.nsaddr_list[i].sin_family;
1030                         void *sa_addr = &resolv->res.nsaddr_list[i].sin_addr;
1031
1032                         if (family != AF_INET &&
1033                                         resolv->res._u._ext.nsaddrs[i]) {
1034                                 family = AF_INET6;
1035                                 sa_addr = &resolv->res._u._ext.nsaddrs[i]->sin6_addr;
1036                         }
1037
1038                         if (family != AF_INET && family != AF_INET6)
1039                                 continue;
1040
1041                         if (inet_ntop(family, sa_addr, buf, sizeof(buf)))
1042                                 g_resolv_add_nameserver(resolv, buf, 53, 0);
1043                 }
1044
1045                 if (!resolv->nameserver_list)
1046                         g_resolv_add_nameserver(resolv, "127.0.0.1", 53, 0);
1047         }
1048
1049         lookup = g_try_new0(struct resolv_lookup, 1);
1050         if (!lookup)
1051                 return 0;
1052
1053         lookup->resolv = resolv;
1054         lookup->result_func = func;
1055         lookup->result_data = user_data;
1056         lookup->id = resolv->next_lookup_id++;
1057
1058         if (resolv->result_family != AF_INET6) {
1059                 if (add_query(lookup, hostname, ns_t_a)) {
1060                         g_free(lookup);
1061                         return -EIO;
1062                 }
1063         }
1064
1065         if (resolv->result_family != AF_INET) {
1066                 if (add_query(lookup, hostname, ns_t_aaaa)) {
1067                         if (resolv->result_family != AF_INET6) {
1068                                 g_queue_remove(resolv->query_queue,
1069                                                 lookup->ipv4_query);
1070                                 destroy_query(lookup->ipv4_query);
1071                         }
1072
1073                         g_free(lookup);
1074                         return -EIO;
1075                 }
1076         }
1077
1078         g_queue_push_tail(resolv->lookup_queue, lookup);
1079
1080         debug(resolv, "lookup %p id %d", lookup, lookup->id);
1081
1082         return lookup->id;
1083 }
1084
1085 bool g_resolv_cancel_lookup(GResolv *resolv, guint id)
1086 {
1087         struct resolv_lookup *lookup;
1088         GList *list;
1089
1090         debug(resolv, "lookup id %d", id);
1091
1092         list = g_queue_find_custom(resolv->lookup_queue,
1093                                 GUINT_TO_POINTER(id), compare_lookup_id);
1094
1095         if (!list)
1096                 return false;
1097
1098         lookup = list->data;
1099
1100         debug(resolv, "lookup %p", lookup);
1101
1102         g_queue_remove(resolv->lookup_queue, lookup);
1103         destroy_lookup(lookup);
1104
1105         return true;
1106 }
1107
1108 bool g_resolv_set_address_family(GResolv *resolv, int family)
1109 {
1110         if (!resolv)
1111                 return false;
1112
1113         if (family != AF_UNSPEC && family != AF_INET && family != AF_INET6)
1114                 return false;
1115
1116         resolv->result_family = family;
1117
1118         return true;
1119 }