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