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