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