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