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