gresolv: Queries address family scope restriction
[platform/upstream/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[100];
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         rfc3484_sort_results(lookup);
465
466         for (i = 0; i < lookup->nr_results; i++) {
467                 if (lookup->results[i].dst.sa.sa_family == AF_INET) {
468                         if (inet_ntop(AF_INET,
469                                         &lookup->results[i].dst.sin.sin_addr,
470                                         buf, sizeof(buf)) == NULL)
471                                 continue;
472                 } else if (lookup->results[i].dst.sa.sa_family == AF_INET6) {
473                         if (inet_ntop(AF_INET6,
474                                         &lookup->results[i].dst.sin6.sin6_addr,
475                                         buf, sizeof(buf)) == NULL)
476                                 continue;
477                 } else
478                         continue;
479
480                 results[n++] = strdup(buf);
481         }
482
483         results[n++] = NULL;
484
485         status = lookup->ipv4_status;
486
487         if (status == G_RESOLV_RESULT_STATUS_SUCCESS)
488                 status = lookup->ipv6_status;
489
490         lookup->result_func(status, results, lookup->result_data);
491
492         g_strfreev(results);
493         g_queue_remove(lookup->resolv->lookup_queue, lookup);
494         destroy_lookup(lookup);
495 }
496
497 static gboolean query_timeout(gpointer user_data)
498 {
499         struct resolv_query *query = user_data;
500         struct resolv_lookup *lookup = query->lookup;
501         GResolv *resolv = query->resolv;
502
503         query->timeout = 0;
504
505         if (query == lookup->ipv4_query) {
506                 lookup->ipv4_status = G_RESOLV_RESULT_STATUS_NO_RESPONSE;
507                 lookup->ipv4_query = NULL;
508         } else if (query == lookup->ipv6_query) {
509                 lookup->ipv6_status = G_RESOLV_RESULT_STATUS_NO_RESPONSE;
510                 lookup->ipv6_query = NULL;
511         }
512
513         if (lookup->ipv4_query == NULL && lookup->ipv4_query == NULL)
514                 sort_and_return_results(lookup);
515
516         destroy_query(query);
517         g_queue_remove(resolv->query_queue, query);
518
519         return FALSE;
520 }
521
522 static void free_nameserver(struct resolv_nameserver *nameserver)
523 {
524         if (nameserver == NULL)
525                 return;
526
527         if (nameserver->udp_watch > 0)
528                 g_source_remove(nameserver->udp_watch);
529
530         if (nameserver->udp_channel != NULL)
531                 g_io_channel_unref(nameserver->udp_channel);
532
533         g_free(nameserver->address);
534         g_free(nameserver);
535 }
536
537 static void flush_nameservers(GResolv *resolv)
538 {
539         GList *list;
540
541         for (list = g_list_first(resolv->nameserver_list);
542                                         list; list = g_list_next(list))
543                 free_nameserver(list->data);
544
545         g_list_free(resolv->nameserver_list);
546         resolv->nameserver_list = NULL;
547 }
548
549 static int send_query(GResolv *resolv, const unsigned char *buf, int len)
550 {
551         GList *list;
552
553         if (resolv->nameserver_list == NULL)
554                 return -ENOENT;
555
556         for (list = g_list_first(resolv->nameserver_list);
557                                         list; list = g_list_next(list)) {
558                 struct resolv_nameserver *nameserver = list->data;
559                 int sk, sent;
560
561                 if (nameserver->udp_channel == NULL)
562                         continue;
563
564                 sk = g_io_channel_unix_get_fd(nameserver->udp_channel);
565
566                 sent = send(sk, buf, len, 0);
567                 if (sent < 0)
568                         continue;
569         }
570
571         return 0;
572 }
573
574 static gint compare_lookup_id(gconstpointer a, gconstpointer b)
575 {
576         const struct resolv_lookup *lookup = a;
577         guint id = GPOINTER_TO_UINT(b);
578
579         if (lookup->id < id)
580                 return -1;
581
582         if (lookup->id > id)
583                 return 1;
584
585         return 0;
586 }
587
588 static gint compare_query_msgid(gconstpointer a, gconstpointer b)
589 {
590         const struct resolv_query *query = a;
591         uint16_t msgid = GPOINTER_TO_UINT(b);
592
593         if (query->msgid < msgid)
594                 return -1;
595
596         if (query->msgid > msgid)
597                 return 1;
598
599         return 0;
600 }
601
602 static void add_result(struct resolv_lookup *lookup, int family,
603                                                         const void *data)
604 {
605         int n = lookup->nr_results++;
606         lookup->results = g_realloc(lookup->results,
607                                         sizeof(struct sort_result) * (n + 1));
608
609         memset(&lookup->results[n], 0, sizeof(struct sort_result));
610
611         lookup->results[n].dst.sa.sa_family = family;
612         if (family == AF_INET)
613                 memcpy(&lookup->results[n].dst.sin.sin_addr,
614                                                 data, NS_INADDRSZ);
615         else
616                 memcpy(&lookup->results[n].dst.sin6.sin6_addr,
617                                                 data, NS_IN6ADDRSZ);
618 }
619
620 static void parse_response(struct resolv_nameserver *nameserver,
621                                         const unsigned char *buf, int len)
622 {
623         GResolv *resolv = nameserver->resolv;
624         GResolvResultStatus status;
625         struct resolv_query *query;
626         struct resolv_lookup *lookup;
627         GList *list;
628         ns_msg msg;
629         ns_rr rr;
630         int i, rcode, count;
631
632         debug(resolv, "response from %s", nameserver->address);
633
634         ns_initparse(buf, len, &msg);
635
636         rcode = ns_msg_getflag(msg, ns_f_rcode);
637         count = ns_msg_count(msg, ns_s_an);
638
639         debug(resolv, "msg id: 0x%04x rcode: %d count: %d",
640                                         ns_msg_id(msg), rcode, count);
641
642         switch (rcode) {
643         case 0:
644                 status = G_RESOLV_RESULT_STATUS_SUCCESS;
645                 break;
646         case 1:
647                 status = G_RESOLV_RESULT_STATUS_FORMAT_ERROR;
648                 break;
649         case 2:
650                 status = G_RESOLV_RESULT_STATUS_SERVER_FAILURE;
651                 break;
652         case 3:
653                 status = G_RESOLV_RESULT_STATUS_NAME_ERROR;
654                 break;
655         case 4:
656                 status = G_RESOLV_RESULT_STATUS_NOT_IMPLEMENTED;
657                 break;
658         case 5:
659                 status = G_RESOLV_RESULT_STATUS_REFUSED;
660                 break;
661         default:
662                 status = G_RESOLV_RESULT_STATUS_ERROR;
663                 break;
664         }
665
666         list = g_queue_find_custom(resolv->query_queue,
667                         GUINT_TO_POINTER(ns_msg_id(msg)), compare_query_msgid);
668         if (!list)
669                 return;
670
671         query = list->data;
672         lookup = query->lookup;
673
674         if (query == lookup->ipv6_query) {
675                 lookup->ipv6_status = status;
676                 lookup->ipv6_query = NULL;
677         } else if (query == lookup->ipv4_query) {
678                 lookup->ipv4_status = status;
679                 lookup->ipv4_query = NULL;
680         }
681
682         for (i = 0; i < count; i++) {
683                 ns_parserr(&msg, ns_s_an, i, &rr);
684
685                 if (ns_rr_class(rr) != ns_c_in)
686                         continue;
687
688                 g_assert(offsetof(struct sockaddr_in, sin_addr) ==
689                                 offsetof(struct sockaddr_in6, sin6_flowinfo));
690
691                 if (ns_rr_type(rr) == ns_t_a &&
692                                         ns_rr_rdlen(rr) == NS_INADDRSZ) {
693                         add_result(lookup, AF_INET, ns_rr_rdata(rr));
694                 } else if (ns_rr_type(rr) == ns_t_aaaa &&
695                                         ns_rr_rdlen(rr) == NS_IN6ADDRSZ) {
696                         add_result(lookup, AF_INET6, ns_rr_rdata(rr));
697                 }
698         }
699
700         if (lookup->ipv4_query == NULL && lookup->ipv6_query == NULL)
701                 sort_and_return_results(lookup);
702
703         destroy_query(query);
704         g_queue_remove(resolv->query_queue, query);
705 }
706
707 static gboolean received_udp_data(GIOChannel *channel, GIOCondition cond,
708                                                         gpointer user_data)
709 {
710         struct resolv_nameserver *nameserver = user_data;
711         unsigned char buf[4096];
712         int sk, len;
713
714         if (cond & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
715                 nameserver->udp_watch = 0;
716                 return FALSE;
717         }
718
719         sk = g_io_channel_unix_get_fd(nameserver->udp_channel);
720
721         len = recv(sk, buf, sizeof(buf), 0);
722         if (len < 12)
723                 return TRUE;
724
725         parse_response(nameserver, buf, len);
726
727         return TRUE;
728 }
729
730 static int connect_udp_channel(struct resolv_nameserver *nameserver)
731 {
732         struct addrinfo hints, *rp;
733         char portnr[6];
734         int err, sk;
735
736         memset(&hints, 0, sizeof(hints));
737         hints.ai_family = AF_UNSPEC;
738         hints.ai_socktype = SOCK_DGRAM;
739         hints.ai_flags = AI_PASSIVE | AI_NUMERICSERV | AI_NUMERICHOST;
740
741         sprintf(portnr, "%d", nameserver->port);
742         err = getaddrinfo(nameserver->address, portnr, &hints, &rp);
743         if (err)
744                 return -EINVAL;
745
746         /*
747          * Do not blindly copy this code elsewhere; it doesn't loop over the
748          * results using ->ai_next as it should. That's OK in *this* case
749          * because it was a numeric lookup; we *know* there's only one.
750          */
751         if (!rp)
752                 return -EINVAL;
753
754         sk = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
755         if (sk < 0) {
756                 freeaddrinfo(rp);
757                 return -EIO;
758         }
759
760         if (connect(sk, rp->ai_addr, rp->ai_addrlen) < 0) {
761                 close(sk);
762                 freeaddrinfo(rp);
763                 return -EIO;
764         }
765
766         freeaddrinfo(rp);
767
768         nameserver->udp_channel = g_io_channel_unix_new(sk);
769         if (nameserver->udp_channel == NULL) {
770                 close(sk);
771                 return -ENOMEM;
772         }
773
774         g_io_channel_set_close_on_unref(nameserver->udp_channel, TRUE);
775
776         nameserver->udp_watch = g_io_add_watch(nameserver->udp_channel,
777                                 G_IO_IN | G_IO_NVAL | G_IO_ERR | G_IO_HUP,
778                                 received_udp_data, nameserver);
779
780         return 0;
781 }
782
783 GResolv *g_resolv_new(int index)
784 {
785         GResolv *resolv;
786
787         if (index < 0)
788                 return NULL;
789
790         resolv = g_try_new0(GResolv, 1);
791         if (resolv == NULL)
792                 return NULL;
793
794         resolv->ref_count = 1;
795
796         resolv->result_family = AF_UNSPEC;
797
798         resolv->next_lookup_id = 1;
799
800         resolv->query_queue = g_queue_new();
801         if (resolv->query_queue == NULL) {
802                 g_free(resolv);
803                 return NULL;
804         }
805
806         resolv->lookup_queue = g_queue_new();
807         if (resolv->lookup_queue == NULL) {
808                 g_queue_free(resolv->query_queue);
809                 g_free(resolv);
810                 return NULL;
811         }
812
813         resolv->index = index;
814         resolv->nameserver_list = NULL;
815
816         res_ninit(&resolv->res);
817
818         return resolv;
819 }
820
821 GResolv *g_resolv_ref(GResolv *resolv)
822 {
823         if (resolv == NULL)
824                 return NULL;
825
826         g_atomic_int_inc(&resolv->ref_count);
827
828         return resolv;
829 }
830
831 void g_resolv_unref(GResolv *resolv)
832 {
833         struct resolv_query *query;
834
835         if (resolv == NULL)
836                 return;
837
838         if (g_atomic_int_dec_and_test(&resolv->ref_count) == FALSE)
839                 return;
840
841         while ((query = g_queue_pop_head(resolv->query_queue)))
842                 destroy_query(query);
843
844         g_queue_free(resolv->query_queue);
845         g_queue_free(resolv->lookup_queue);
846
847         flush_nameservers(resolv);
848
849         res_nclose(&resolv->res);
850
851         g_free(resolv);
852 }
853
854 void g_resolv_set_debug(GResolv *resolv, GResolvDebugFunc func,
855                                                 gpointer user_data)
856 {
857         if (resolv == NULL)
858                 return;
859
860         resolv->debug_func = func;
861         resolv->debug_data = user_data;
862 }
863
864 gboolean g_resolv_add_nameserver(GResolv *resolv, const char *address,
865                                         uint16_t port, unsigned long flags)
866 {
867         struct resolv_nameserver *nameserver;
868
869         if (resolv == NULL)
870                 return FALSE;
871
872         nameserver = g_try_new0(struct resolv_nameserver, 1);
873         if (nameserver == NULL)
874                 return FALSE;
875
876         nameserver->address = g_strdup(address);
877         nameserver->port = port;
878         nameserver->flags = flags;
879
880         if (connect_udp_channel(nameserver) < 0) {
881                 free_nameserver(nameserver);
882                 return FALSE;
883         }
884
885         nameserver->resolv = resolv;
886
887         resolv->nameserver_list = g_list_append(resolv->nameserver_list,
888                                                                 nameserver);
889
890         debug(resolv, "setting nameserver %s", address);
891
892         return TRUE;
893 }
894
895 void g_resolv_flush_nameservers(GResolv *resolv)
896 {
897         if (resolv == NULL)
898                 return;
899
900         flush_nameservers(resolv);
901 }
902
903 static gint add_query(struct resolv_lookup *lookup, const char *hostname, int type)
904 {
905         struct resolv_query *query = g_try_new0(struct resolv_query, 1);
906         unsigned char buf[4096];
907         int len;
908
909         if (query == NULL)
910                 return -ENOMEM;
911
912         len = res_mkquery(ns_o_query, hostname, ns_c_in, type,
913                                         NULL, 0, NULL, buf, sizeof(buf));
914
915         query->msgid = buf[0] << 8 | buf[1];
916
917         if (send_query(lookup->resolv, buf, len) < 0) {
918                 g_free(query);
919                 return -EIO;
920         }
921
922         query->resolv = lookup->resolv;
923         query->lookup = lookup;
924
925         g_queue_push_tail(lookup->resolv->query_queue, query);
926
927         query->timeout = g_timeout_add_seconds(5, query_timeout, query);
928
929         if (type == ns_t_aaaa)
930                 lookup->ipv6_query = query;
931         else
932                 lookup->ipv4_query = query;
933
934         return 0;
935 }
936
937 guint g_resolv_lookup_hostname(GResolv *resolv, const char *hostname,
938                                 GResolvResultFunc func, gpointer user_data)
939 {
940         struct resolv_lookup *lookup;
941
942         debug(resolv, "lookup hostname %s", hostname);
943
944         if (resolv == NULL)
945                 return 0;
946
947         if (resolv->nameserver_list == NULL) {
948                 int i;
949
950                 for (i = 0; i < resolv->res.nscount; i++) {
951                         char buf[100];
952                         int family = resolv->res.nsaddr_list[i].sin_family;
953                         void *sa_addr = &resolv->res.nsaddr_list[i].sin_addr;
954
955                         if (family != AF_INET &&
956                                         resolv->res._u._ext.nsaddrs[i]) {
957                                 family = AF_INET6;
958                                 sa_addr = &resolv->res._u._ext.nsaddrs[i]->sin6_addr;
959                         }
960
961                         if (family != AF_INET && family != AF_INET6)
962                                 continue;
963
964                         if (inet_ntop(family, sa_addr, buf, sizeof(buf)))
965                                 g_resolv_add_nameserver(resolv, buf, 53, 0);
966                 }
967
968                 if (resolv->nameserver_list == NULL)
969                         g_resolv_add_nameserver(resolv, "127.0.0.1", 53, 0);
970         }
971
972         lookup = g_try_new0(struct resolv_lookup, 1);
973         if (lookup == NULL)
974                 return 0;
975
976         lookup->resolv = resolv;
977         lookup->result_func = func;
978         lookup->result_data = user_data;
979         lookup->id = resolv->next_lookup_id++;
980
981         if (resolv->result_family != AF_INET6) {
982                 if (add_query(lookup, hostname, ns_t_a)) {
983                         g_free(lookup);
984                         return -EIO;
985                 }
986         }
987
988         if (resolv->result_family != AF_INET) {
989                 if (add_query(lookup, hostname, ns_t_aaaa)) {
990                         if (resolv->result_family != AF_INET6) {
991                                 destroy_query(lookup->ipv4_query);
992                                 g_queue_remove(resolv->query_queue,
993                                                 lookup->ipv4_query);
994                         }
995
996                         g_free(lookup);
997                         return -EIO;
998                 }
999         }
1000
1001         g_queue_push_tail(resolv->lookup_queue, lookup);
1002         return lookup->id;
1003 }
1004
1005 gboolean g_resolv_cancel_lookup(GResolv *resolv, guint id)
1006 {
1007         GList *list;
1008
1009         list = g_queue_find_custom(resolv->lookup_queue,
1010                                 GUINT_TO_POINTER(id), compare_lookup_id);
1011
1012         if (list == NULL)
1013                 return FALSE;
1014
1015         destroy_lookup(list->data);
1016         g_queue_remove(resolv->query_queue, list->data);
1017
1018         return TRUE;
1019 }
1020
1021 gboolean g_resolv_set_address_family(GResolv *resolv, int family)
1022 {
1023         if (resolv == NULL)
1024                 return FALSE;
1025
1026         if (family != AF_UNSPEC && family != AF_INET && family != AF_INET6)
1027                 return FALSE;
1028
1029         resolv->result_family = family;
1030
1031         return TRUE;
1032 }