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