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