dnsproxy: Check compress flag properly.
[framework/connectivity/connman.git] / src / dnsproxy.c
1 /*
2  *
3  *  Connection Manager
4  *
5  *  Copyright (C) 2007-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 <string.h>
29 #include <stdint.h>
30 #include <arpa/inet.h>
31 #include <netinet/in.h>
32 #include <sys/types.h>
33 #include <sys/socket.h>
34 #include <netdb.h>
35 #include <resolv.h>
36
37 #include <glib.h>
38
39 #include "connman.h"
40
41 #if __BYTE_ORDER == __LITTLE_ENDIAN
42 struct domain_hdr {
43         uint16_t id;
44         uint8_t rd:1;
45         uint8_t tc:1;
46         uint8_t aa:1;
47         uint8_t opcode:4;
48         uint8_t qr:1;
49         uint8_t rcode:4;
50         uint8_t z:3;
51         uint8_t ra:1;
52         uint16_t qdcount;
53         uint16_t ancount;
54         uint16_t nscount;
55         uint16_t arcount;
56 } __attribute__ ((packed));
57 #elif __BYTE_ORDER == __BIG_ENDIAN
58 struct domain_hdr {
59         uint16_t id;
60         uint8_t qr:1;
61         uint8_t opcode:4;
62         uint8_t aa:1;
63         uint8_t tc:1;
64         uint8_t rd:1;
65         uint8_t ra:1;
66         uint8_t z:3;
67         uint8_t rcode:4;
68         uint16_t qdcount;
69         uint16_t ancount;
70         uint16_t nscount;
71         uint16_t arcount;
72 } __attribute__ ((packed));
73 #else
74 #error "Unknown byte order"
75 #endif
76
77 struct partial_reply {
78         uint16_t len;
79         uint16_t received;
80         unsigned char buf[];
81 };
82
83 struct server_data {
84         char *interface;
85         GList *domains;
86         char *server;
87         int protocol;
88         GIOChannel *channel;
89         guint watch;
90         guint timeout;
91         gboolean enabled;
92         gboolean connected;
93         struct partial_reply *incoming_reply;
94 };
95
96 struct request_data {
97         union {
98                 struct sockaddr_in6 __sin6; /* Only for the length */
99                 struct sockaddr sa;
100         };
101         socklen_t sa_len;
102         int client_sk;
103         int protocol;
104         guint16 srcid;
105         guint16 dstid;
106         guint16 altid;
107         guint timeout;
108         guint watch;
109         guint numserv;
110         guint numresp;
111         gpointer request;
112         gsize request_len;
113         gpointer name;
114         gpointer resp;
115         gsize resplen;
116         struct listener_data *ifdata;
117         gboolean append_domain;
118 };
119
120 struct listener_data {
121         char *ifname;
122         GIOChannel *udp_listener_channel;
123         guint udp_listener_watch;
124         GIOChannel *tcp_listener_channel;
125         guint tcp_listener_watch;
126 };
127
128 struct cache_data {
129         time_t inserted;
130         int timeout;
131         uint16_t type;
132         uint16_t answers;
133         unsigned int data_len;
134         unsigned char *data; /* contains DNS header + body */
135 };
136
137 struct cache_entry {
138         char *key;
139         struct cache_data *ipv4;
140         struct cache_data *ipv6;
141 };
142
143 struct domain_question {
144         uint16_t type;
145         uint16_t class;
146 } __attribute__ ((packed));
147
148 struct domain_rr {
149         uint16_t type;
150         uint16_t class;
151         uint32_t ttl;
152         uint16_t rdlen;
153 } __attribute__ ((packed));
154
155 /*
156  * We limit how long the cached DNS entry stays in the cache.
157  * By default the TTL (time-to-live) of the DNS response is used
158  * when setting the cache entry life time. The value is in seconds.
159  */
160 #define MAX_CACHE_TTL (60 * 30)
161
162 /*
163  * We limit the cache size to some sane value so that cached data does
164  * not occupy too much memory. Each cached entry occupies on average
165  * about 100 bytes memory (depending on DNS name length).
166  * Example: caching www.connman.net uses 97 bytes memory.
167  * The value is the max amount of cached DNS responses (count).
168  */
169 #define MAX_CACHE_SIZE 256
170
171 static int cache_size;
172 static GHashTable *cache;
173 static int cache_refcount;
174 static GSList *server_list = NULL;
175 static GSList *request_list = NULL;
176 static GSList *request_pending_list = NULL;
177 static guint16 request_id = 0x0000;
178 static GHashTable *listener_table = NULL;
179
180 static int protocol_offset(int protocol)
181 {
182         switch (protocol) {
183         case IPPROTO_UDP:
184                 return 0;
185
186         case IPPROTO_TCP:
187                 return 2;
188
189         default:
190                 return -EINVAL;
191         }
192
193 }
194
195 static struct request_data *find_request(guint16 id)
196 {
197         GSList *list;
198
199         for (list = request_list; list; list = list->next) {
200                 struct request_data *req = list->data;
201
202                 if (req->dstid == id || req->altid == id)
203                         return req;
204         }
205
206         return NULL;
207 }
208
209 static struct server_data *find_server(const char *interface,
210                                         const char *server,
211                                                 int protocol)
212 {
213         GSList *list;
214
215         DBG("interface %s server %s", interface, server);
216
217         for (list = server_list; list; list = list->next) {
218                 struct server_data *data = list->data;
219
220                 if (interface == NULL && data->interface == NULL &&
221                                 g_str_equal(data->server, server) == TRUE &&
222                                 data->protocol == protocol)
223                         return data;
224
225                 if (interface == NULL ||
226                                 data->interface == NULL || data->server == NULL)
227                         continue;
228
229                 if (g_str_equal(data->interface, interface) == TRUE &&
230                                 g_str_equal(data->server, server) == TRUE &&
231                                 data->protocol == protocol)
232                         return data;
233         }
234
235         return NULL;
236 }
237
238 static void send_cached_response(int sk, unsigned char *buf, int len,
239                                 const struct sockaddr *to, socklen_t tolen,
240                                 int protocol, int id, uint16_t answers)
241 {
242         struct domain_hdr *hdr;
243         int err, offset = protocol_offset(protocol);
244
245         if (offset < 0)
246                 return;
247
248         if (len < 12)
249                 return;
250
251         hdr = (void *) (buf + offset);
252
253         hdr->id = id;
254         hdr->qr = 1;
255         hdr->rcode = 0;
256         hdr->ancount = htons(answers);
257         hdr->nscount = 0;
258         hdr->arcount = 0;
259
260         DBG("id 0x%04x answers %d", hdr->id, answers);
261
262         err = sendto(sk, buf, len, 0, to, tolen);
263         if (err < 0) {
264                 connman_error("Cannot send cached DNS response: %s",
265                                 strerror(errno));
266                 return;
267         }
268 }
269
270 static void send_response(int sk, unsigned char *buf, int len,
271                                 const struct sockaddr *to, socklen_t tolen,
272                                 int protocol)
273 {
274         struct domain_hdr *hdr;
275         int err, offset = protocol_offset(protocol);
276
277         DBG("");
278
279         if (offset < 0)
280                 return;
281
282         if (len < 12)
283                 return;
284
285         hdr = (void *) (buf + offset);
286
287         DBG("id 0x%04x qr %d opcode %d", hdr->id, hdr->qr, hdr->opcode);
288
289         hdr->qr = 1;
290         hdr->rcode = 2;
291
292         hdr->ancount = 0;
293         hdr->nscount = 0;
294         hdr->arcount = 0;
295
296         err = sendto(sk, buf, len, 0, to, tolen);
297         if (err < 0) {
298                 connman_error("Failed to send DNS response: %s",
299                                 strerror(errno));
300                 return;
301         }
302 }
303
304 static gboolean request_timeout(gpointer user_data)
305 {
306         struct request_data *req = user_data;
307         struct listener_data *ifdata;
308
309         DBG("id 0x%04x", req->srcid);
310
311         if (req == NULL)
312                 return FALSE;
313
314         ifdata = req->ifdata;
315
316         request_list = g_slist_remove(request_list, req);
317         req->numserv--;
318
319         if (req->resplen > 0 && req->resp != NULL) {
320                 int sk, err;
321
322                 sk = g_io_channel_unix_get_fd(ifdata->udp_listener_channel);
323
324                 err = sendto(sk, req->resp, req->resplen, 0,
325                                                 &req->sa, req->sa_len);
326                 if (err < 0)
327                         return FALSE;
328         } else if (req->request && req->numserv == 0) {
329                 struct domain_hdr *hdr;
330
331                 if (req->protocol == IPPROTO_TCP) {
332                         hdr = (void *) (req->request + 2);
333                         hdr->id = req->srcid;
334                         send_response(req->client_sk, req->request,
335                                 req->request_len, NULL, 0, IPPROTO_TCP);
336
337                 } else if (req->protocol == IPPROTO_UDP) {
338                         int sk;
339
340                         hdr = (void *) (req->request);
341                         hdr->id = req->srcid;
342                         sk = g_io_channel_unix_get_fd(
343                                                 ifdata->udp_listener_channel);
344                         send_response(sk, req->request, req->request_len,
345                                         &req->sa, req->sa_len, IPPROTO_UDP);
346                 }
347         }
348
349         g_free(req->resp);
350         g_free(req);
351
352         return FALSE;
353 }
354
355 static int append_query(unsigned char *buf, unsigned int size,
356                                 const char *query, const char *domain)
357 {
358         unsigned char *ptr = buf;
359         char *offset;
360         int len;
361
362         DBG("query %s domain %s", query, domain);
363
364         offset = (char *) query;
365         while (offset != NULL) {
366                 char *tmp;
367
368                 tmp = strchr(offset, '.');
369                 if (tmp == NULL) {
370                         len = strlen(offset);
371                         if (len == 0)
372                                 break;
373                         *ptr = len;
374                         memcpy(ptr + 1, offset, len);
375                         ptr += len + 1;
376                         break;
377                 }
378
379                 *ptr = tmp - offset;
380                 memcpy(ptr + 1, offset, tmp - offset);
381                 ptr += tmp - offset + 1;
382
383                 offset = tmp + 1;
384         }
385
386         offset = (char *) domain;
387         while (offset != NULL) {
388                 char *tmp;
389
390                 tmp = strchr(offset, '.');
391                 if (tmp == NULL) {
392                         len = strlen(offset);
393                         if (len == 0)
394                                 break;
395                         *ptr = len;
396                         memcpy(ptr + 1, offset, len);
397                         ptr += len + 1;
398                         break;
399                 }
400
401                 *ptr = tmp - offset;
402                 memcpy(ptr + 1, offset, tmp - offset);
403                 ptr += tmp - offset + 1;
404
405                 offset = tmp + 1;
406         }
407
408         *ptr++ = 0x00;
409
410         return ptr - buf;
411 }
412
413 static gboolean cache_check_is_valid(struct cache_data *data,
414                                 time_t current_time)
415 {
416         if (data == NULL)
417                 return FALSE;
418
419         if (data->inserted + data->timeout < current_time)
420                 return FALSE;
421
422         return TRUE;
423 }
424
425 static uint16_t cache_check_validity(char *question, uint16_t type,
426                                 struct cache_data *ipv4,
427                                 struct cache_data *ipv6)
428 {
429         time_t current_time = time(0);
430
431         switch (type) {
432         case 1:         /* IPv4 */
433                 if (cache_check_is_valid(ipv4, current_time) == FALSE) {
434                         DBG("cache %s \"%s\" type A",
435                                 ipv4 ? "timeout" : "entry missing", question);
436
437                         /*
438                          * We do not remove cache entry if there is still
439                          * valid IPv6 entry found in the cache.
440                          */
441                         if (cache_check_is_valid(ipv6, current_time) == FALSE)
442                                 g_hash_table_remove(cache, question);
443
444                         type = 0;
445                 }
446                 break;
447
448         case 28:        /* IPv6 */
449                 if (cache_check_is_valid(ipv6, current_time) == FALSE) {
450                         DBG("cache %s \"%s\" type AAAA",
451                                 ipv6 ? "timeout" : "entry missing", question);
452
453                         if (cache_check_is_valid(ipv4, current_time) == FALSE)
454                                 g_hash_table_remove(cache, question);
455
456                         type = 0;
457                 }
458                 break;
459         }
460
461         return type;
462 }
463
464 static struct cache_entry *cache_check(gpointer request, int *qtype)
465 {
466         char *question = request + 12;
467         struct cache_entry *entry;
468         struct domain_question *q;
469         uint16_t type;
470         int offset;
471
472         offset = strlen(question) + 1;
473         q = (void *) (question + offset);
474         type = ntohs(q->type);
475
476         /* We only cache either A (1) or AAAA (28) requests */
477         if (type != 1 && type != 28)
478                 return NULL;
479
480         entry = g_hash_table_lookup(cache, question);
481         if (entry == NULL)
482                 return NULL;
483
484         type = cache_check_validity(question, type, entry->ipv4, entry->ipv6);
485         if (type == 0)
486                 return NULL;
487
488         *qtype = type;
489         return entry;
490 }
491
492 /*
493  * Get a label/name from DNS resource record. The function decompresses the
494  * label if necessary. The function does not convert the name to presentation
495  * form. This means that the result string will contain label lengths instead
496  * of dots between labels. We intentionally do not want to convert to dotted
497  * format so that we can cache the wire format string directly.
498  */
499 static int get_name(int counter,
500                 unsigned char *pkt, unsigned char *start, unsigned char *max,
501                 unsigned char *output, int output_max, int *output_len,
502                 unsigned char **end, char *name, int *name_len)
503 {
504         unsigned char *p;
505
506         /* Limit recursion to 10 (this means up to 10 labels in domain name) */
507         if (counter > 10)
508                 return -EINVAL;
509
510         p = start;
511         while (*p) {
512                 if ((*p & NS_CMPRSFLGS) == NS_CMPRSFLGS) {
513                         uint16_t offset = (*p & 0x3F) * 256 + *(p + 1);
514
515                         if (offset >= max - pkt)
516                                 return -ENOBUFS;
517
518                         if (*end == NULL)
519                                 *end = p + 2;
520
521                         return get_name(counter + 1, pkt, pkt + offset, max,
522                                         output, output_max, output_len, end,
523                                         name, name_len);
524                 } else {
525                         unsigned label_len = *p;
526
527                         if (pkt + label_len > max)
528                                 return -ENOBUFS;
529
530                         if (*output_len > output_max)
531                                 return -ENOBUFS;
532
533                         /*
534                          * We need the original name in order to check
535                          * if this answer is the correct one.
536                          */
537                         name[(*name_len)++] = label_len;
538                         memcpy(name + *name_len, p + 1, label_len + 1);
539                         *name_len += label_len;
540
541                         /* We compress the result */
542                         output[0] = NS_CMPRSFLGS;
543                         output[1] = 0x0C;
544                         *output_len = 2;
545
546                         p += label_len + 1;
547
548                         if (*end == NULL)
549                                 *end = p;
550
551                         if (p >= max)
552                                 return -ENOBUFS;
553                 }
554         }
555
556         return 0;
557 }
558
559 static int parse_rr(unsigned char *buf, unsigned char *start,
560                         unsigned char *max,
561                         unsigned char *response, unsigned int *response_size,
562                         uint16_t *type, uint16_t *class, int *ttl, int *rdlen,
563                         unsigned char **end,
564                         char *name)
565 {
566         struct domain_rr *rr;
567         int err, offset;
568         int name_len = 0, output_len = 0, max_rsp = *response_size;
569
570         err = get_name(0, buf, start, max, response, max_rsp,
571                 &output_len, end, name, &name_len);
572         if (err < 0)
573                 return err;
574
575         offset = output_len;
576
577         if ((unsigned int) offset > *response_size)
578                 return -ENOBUFS;
579
580         rr = (void *) (*end);
581
582         *type = ntohs(rr->type);
583         *class = ntohs(rr->class);
584         *ttl = ntohl(rr->ttl);
585         *rdlen = ntohs(rr->rdlen);
586
587         if (*ttl < 0)
588                 return -EINVAL;
589
590         memcpy(response + offset, *end, sizeof(struct domain_rr));
591
592         offset += sizeof(struct domain_rr);
593         *end += sizeof(struct domain_rr);
594
595         if ((unsigned int) (offset + *rdlen) > *response_size)
596                 return -ENOBUFS;
597
598         memcpy(response + offset, *end, *rdlen);
599
600         *end += *rdlen;
601
602         *response_size = offset + *rdlen;
603
604         return 0;
605 }
606
607 static gboolean check_alias(GSList *aliases, char *name)
608 {
609         GSList *list;
610
611         if (aliases != NULL) {
612                 for (list = aliases; list; list = list->next) {
613                         int len = strlen((char *)list->data);
614                         if (strncmp((char *)list->data, name, len) == 0)
615                                 return TRUE;
616                 }
617         }
618
619         return FALSE;
620 }
621
622 static int parse_response(unsigned char *buf, int buflen,
623                         char *question, int qlen,
624                         uint16_t *type, uint16_t *class, int *ttl,
625                         unsigned char *response, unsigned int *response_len,
626                         uint16_t *answers)
627 {
628         struct domain_hdr *hdr = (void *) buf;
629         struct domain_question *q;
630         unsigned char *ptr;
631         uint16_t qdcount = ntohs(hdr->qdcount);
632         uint16_t ancount = ntohs(hdr->ancount);
633         int err, i;
634         uint16_t qtype, qclass;
635         unsigned char *next = NULL;
636         unsigned int maxlen = *response_len;
637         GSList *aliases = NULL, *list;
638         char name[NS_MAXDNAME + 1];
639
640         if (buflen < 12)
641                 return -EINVAL;
642
643         DBG("qr %d qdcount %d", hdr->qr, qdcount);
644
645         /* We currently only cache responses where question count is 1 */
646         if (hdr->qr != 1 || qdcount != 1)
647                 return -EINVAL;
648
649         ptr = buf + sizeof(struct domain_hdr);
650
651         strncpy(question, (char *) ptr, qlen);
652         qlen = strlen(question);
653         ptr += qlen + 1; /* skip \0 */
654
655         q = (void *) ptr;
656         qtype = ntohs(q->type);
657
658         /* We cache only A and AAAA records */
659         if (qtype != 1 && qtype != 28)
660                 return -ENOMSG;
661
662         qclass = ntohs(q->class);
663
664         ptr += 2 + 2; /* ptr points now to answers */
665
666         err = -ENOMSG;
667         *response_len = 0;
668         *answers = 0;
669
670         /*
671          * We have a bunch of answers (like A, AAAA, CNAME etc) to
672          * A or AAAA question. We traverse the answers and parse the
673          * resource records. Only A and AAAA records are cached, all
674          * the other records in answers are skipped.
675          */
676         for (i = 0; i < ancount; i++) {
677                 /*
678                  * Get one address at a time to this buffer.
679                  * The max size of the answer is
680                  *   2 (pointer) + 2 (type) + 2 (class) +
681                  *   4 (ttl) + 2 (rdlen) + addr (16 or 4) = 28
682                  * for A or AAAA record.
683                  * For CNAME the size can be bigger.
684                  */
685                 unsigned char rsp[NS_MAXCDNAME];
686                 unsigned int rsp_len = sizeof(rsp) - 1;
687                 int ret, rdlen;
688
689                 memset(rsp, 0, sizeof(rsp));
690
691                 ret = parse_rr(buf, ptr, buf + buflen, rsp, &rsp_len,
692                         type, class, ttl, &rdlen, &next, name);
693                 if (ret != 0) {
694                         err = ret;
695                         goto out;
696                 }
697
698                 /*
699                  * Now rsp contains compressed or uncompressed resource
700                  * record. Next we check if this record answers the question.
701                  * The name var contains the uncompressed label.
702                  * One tricky bit is the CNAME records as they alias
703                  * the name we might be interested in.
704                  */
705
706                 /*
707                  * Go to next answer if the class is not the one we are
708                  * looking for.
709                  */
710                 if (*class != qclass) {
711                         ptr = next;
712                         next = NULL;
713                         continue;
714                 }
715
716                 /*
717                  * Try to resolve aliases also, type is CNAME(5).
718                  * This is important as otherwise the aliased names would not
719                  * be cached at all as the cache would not contain the aliased
720                  * question.
721                  *
722                  * If any CNAME is found in DNS packet, then we cache the alias
723                  * IP address instead of the question (as the server
724                  * said that question has only an alias).
725                  * This means in practice that if e.g., ipv6.google.com is
726                  * queried, DNS server returns CNAME of that name which is
727                  * ipv6.l.google.com. We then cache the address of the CNAME
728                  * but return the question name to client. So the alias
729                  * status of the name is not saved in cache and thus not
730                  * returned to the client. We do not return DNS packets from
731                  * cache to client saying that ipv6.google.com is an alias to
732                  * ipv6.l.google.com but we return instead a DNS packet that
733                  * says ipv6.google.com has address xxx which is in fact the
734                  * address of ipv6.l.google.com. For caching purposes this
735                  * should not cause any issues.
736                  */
737                 if (*type == 5 && strncmp(question, name, qlen) == 0) {
738                         /*
739                          * So now the alias answered the question. This is
740                          * not very useful from caching point of view as
741                          * the following A or AAAA records will not match the
742                          * question. We need to find the real A/AAAA record
743                          * of the alias and cache that.
744                          */
745                         unsigned char *end = NULL;
746                         int name_len = 0, output_len;
747
748                         memset(rsp, 0, sizeof(rsp));
749                         rsp_len = sizeof(rsp) - 1;
750
751                         /*
752                          * Alias is in rdata part of the message,
753                          * and next-rdlen points to it. So we need to get
754                          * the real name of the alias.
755                          */
756                         ret = get_name(0, buf, next - rdlen, buf + buflen,
757                                         rsp, rsp_len, &output_len, &end,
758                                         name, &name_len);
759                         if (ret != 0) {
760                                 /* just ignore the error at this point */
761                                 ptr = next;
762                                 next = NULL;
763                                 continue;
764                         }
765
766                         /*
767                          * We should now have the alias of the entry we might
768                          * want to cache. Just remember it for a while.
769                          * We check the alias list when we have parsed the
770                          * A or AAAA record.
771                          */
772                         aliases = g_slist_prepend(aliases, g_strdup(name));
773
774                         ptr = next;
775                         next = NULL;
776                         continue;
777                 }
778
779                 if (*type == qtype) {
780                         /*
781                          * We found correct type (A or AAAA)
782                          */
783                         if (check_alias(aliases, name) == TRUE ||
784                                 (aliases == NULL && strncmp(question, name,
785                                                         qlen) == 0)) {
786                                 /*
787                                  * We found an alias or the name of the rr
788                                  * matches the question. If so, we append
789                                  * the compressed label to the cache.
790                                  * The end result is a response buffer that
791                                  * will contain one or more cached and
792                                  * compressed resource records.
793                                  */
794                                 if (*response_len + rsp_len > maxlen) {
795                                         err = -ENOBUFS;
796                                         goto out;
797                                 }
798                                 memcpy(response + *response_len, rsp, rsp_len);
799                                 *response_len += rsp_len;
800                                 (*answers)++;
801                                 err = 0;
802                         }
803                 }
804
805                 ptr = next;
806                 next = NULL;
807         }
808
809 out:
810         for (list = aliases; list; list = list->next)
811                 g_free(list->data);
812         g_slist_free(aliases);
813
814         return err;
815 }
816
817 struct cache_timeout {
818         time_t current_time;
819         int max_timeout;
820 };
821
822 static gboolean cache_check_entry(gpointer key, gpointer value,
823                                         gpointer user_data)
824 {
825         struct cache_timeout *data = user_data;
826         struct cache_entry *entry = value;
827         int max_timeout;
828
829         /*
830          * If either IPv4 or IPv6 cached entry has expired, we
831          * remove both from the cache.
832          */
833
834         if (entry->ipv4 != NULL && entry->ipv4->timeout > 0) {
835                 max_timeout = entry->ipv4->inserted + entry->ipv4->timeout;
836                 if (max_timeout > data->max_timeout)
837                         data->max_timeout = max_timeout;
838
839                 if (entry->ipv4->inserted + entry->ipv4->timeout
840                                                         < data->current_time)
841                         return TRUE;
842         }
843
844         if (entry->ipv6 != NULL && entry->ipv6->timeout > 0) {
845                 max_timeout = entry->ipv6->inserted + entry->ipv6->timeout;
846                 if (max_timeout > data->max_timeout)
847                         data->max_timeout = max_timeout;
848
849                 if (entry->ipv6->inserted + entry->ipv6->timeout
850                                                         < data->current_time)
851                         return TRUE;
852         }
853
854         return FALSE;
855 }
856
857 static void cache_cleanup(void)
858 {
859         static int max_timeout;
860         struct cache_timeout data;
861         int count;
862
863         data.current_time = time(0);
864         data.max_timeout = 0;
865
866         if (max_timeout > data.current_time) {
867                 DBG("waiting %ld secs before cleaning cache",
868                         max_timeout - data.current_time);
869                 return;
870         }
871
872         count = g_hash_table_foreach_remove(cache, cache_check_entry,
873                                                 &data);
874         DBG("removed %d", count);
875
876         if (count == 0)
877                 /*
878                  * If we could not remove anything, then remember
879                  * what is the max timeout and do nothing if we
880                  * have not yet reached it. This will prevent
881                  * constant traversal of the cache if it is full.
882                  */
883                 max_timeout = data.max_timeout;
884         else
885                 max_timeout = 0;
886 }
887
888 static int cache_update(struct server_data *srv, unsigned char *msg,
889                         unsigned int msg_len)
890 {
891         int offset = protocol_offset(srv->protocol);
892         int err, qlen, ttl = 0;
893         uint16_t answers, type = 0, class = 0;
894         struct domain_question *q;
895         struct cache_entry *entry;
896         struct cache_data *data;
897         char question[NS_MAXDNAME + 1];
898         unsigned char response[NS_MAXDNAME + 1];
899         unsigned char *ptr;
900         unsigned int rsplen;
901         gboolean new_entry = TRUE;
902         time_t current_time;
903
904         if (cache_size >= MAX_CACHE_SIZE) {
905                 cache_cleanup();
906                 if (cache_size >= MAX_CACHE_SIZE)
907                         return 0;
908         }
909
910         /* Continue only if response code is 0 (=ok) */
911         if (msg[3] & 0x0f)
912                 return 0;
913
914         if (offset < 0)
915                 return 0;
916
917         rsplen = sizeof(response) - 1;
918         question[sizeof(question) - 1] = '\0';
919
920         err = parse_response(msg + offset, msg_len - offset,
921                                 question, sizeof(question) - 1,
922                                 &type, &class, &ttl,
923                                 response, &rsplen, &answers);
924         if (err < 0 || ttl == 0)
925                 return 0;
926
927         qlen = strlen(question);
928         current_time = time(0);
929
930         /*
931          * If the cache contains already data, check if the
932          * type of the cached data is the same and do not add
933          * to cache if data is already there.
934          * This is needed so that we can cache both A and AAAA
935          * records for the same name.
936          */
937         entry = g_hash_table_lookup(cache, question);
938         if (entry == NULL) {
939                 entry = g_try_new(struct cache_entry, 1);
940                 if (entry == NULL)
941                         return -ENOMEM;
942
943                 data = g_try_new(struct cache_data, 1);
944                 if (data == NULL) {
945                         g_free(entry);
946                         return -ENOMEM;
947                 }
948
949                 entry->key = g_strdup(question);
950                 entry->ipv4 = entry->ipv6 = NULL;
951
952                 if (type == 1)
953                         entry->ipv4 = data;
954                 else
955                         entry->ipv6 = data;
956         } else {
957                 if (type == 1 && entry->ipv4 != NULL)
958                         return 0;
959
960                 if (type == 28 && entry->ipv6 != NULL)
961                         return 0;
962
963                 data = g_try_new(struct cache_data, 1);
964                 if (data == NULL)
965                         return -ENOMEM;
966
967                 if (type == 1)
968                         entry->ipv4 = data;
969                 else
970                         entry->ipv6 = data;
971
972                 new_entry = FALSE;
973         }
974
975         /*
976          * Restrict the cached DNS record TTL to some sane value
977          * in order to prevent data staying in the cache too long.
978          */
979         if (ttl > MAX_CACHE_TTL)
980                 ttl = MAX_CACHE_TTL;
981
982         data->inserted = current_time;
983         data->type = type;
984         data->answers = answers;
985         data->timeout = ttl;
986         data->data_len = 12 + qlen + 1 + 2 + 2 + rsplen;
987         data->data = ptr = g_malloc(data->data_len);
988         if (data->data == NULL) {
989                 g_free(entry->key);
990                 g_free(data);
991                 g_free(entry);
992                 return -ENOMEM;
993         }
994
995         memcpy(ptr, msg, 12);
996         memcpy(ptr + 12, question, qlen + 1); /* copy also the \0 */
997
998         q = (void *) (ptr + 12 + qlen + 1);
999         q->type = htons(type);
1000         q->class = htons(class);
1001         memcpy(ptr + 12 + qlen + 1 + sizeof(struct domain_question),
1002                 response, rsplen);
1003
1004         if (new_entry == TRUE) {
1005                 g_hash_table_replace(cache, entry->key, entry);
1006                 cache_size++;
1007         }
1008
1009         DBG("cache %d %squestion \"%s\" type %d ttl %d size %zd",
1010                 cache_size, new_entry ? "new " : "old ",
1011                 question, type, ttl,
1012                 sizeof(*entry) + sizeof(*data) + data->data_len + qlen);
1013
1014         return 0;
1015 }
1016
1017 static int ns_resolv(struct server_data *server, struct request_data *req,
1018                                 gpointer request, gpointer name)
1019 {
1020         GList *list;
1021         int sk, err, type = 0;
1022         char *dot, *lookup = (char *) name;
1023         struct cache_entry *entry;
1024
1025         entry = cache_check(request, &type);
1026         if (entry != NULL) {
1027                 struct cache_data *data;
1028
1029                 DBG("cache hit %s type %s", lookup, type == 1 ? "A" : "AAAA");
1030                 if (type == 1)
1031                         data = entry->ipv4;
1032                 else
1033                         data = entry->ipv6;
1034
1035                 if (data != NULL && req->protocol == IPPROTO_TCP) {
1036                         send_cached_response(req->client_sk, data->data,
1037                                         data->data_len, NULL, 0, IPPROTO_TCP,
1038                                         req->srcid, data->answers);
1039                         return 1;
1040                 }
1041
1042                 if (data != NULL && req->protocol == IPPROTO_UDP) {
1043                         int sk;
1044                         sk = g_io_channel_unix_get_fd(
1045                                         req->ifdata->udp_listener_channel);
1046
1047                         send_cached_response(sk, data->data,
1048                                 data->data_len, &req->sa, req->sa_len,
1049                                 IPPROTO_UDP, req->srcid, data->answers);
1050                         return 1;
1051                 }
1052         }
1053
1054         sk = g_io_channel_unix_get_fd(server->channel);
1055
1056         err = send(sk, request, req->request_len, 0);
1057
1058         req->numserv++;
1059
1060         /* If we have more than one dot, we don't add domains */
1061         dot = strchr(lookup, '.');
1062         if (dot != NULL && dot != lookup + strlen(lookup) - 1)
1063                 return 0;
1064
1065         if (server->domains != NULL && server->domains->data != NULL)
1066                 req->append_domain = TRUE;
1067
1068         for (list = server->domains; list; list = list->next) {
1069                 char *domain;
1070                 unsigned char alt[1024];
1071                 struct domain_hdr *hdr = (void *) &alt;
1072                 int altlen, domlen, offset;
1073
1074                 domain = list->data;
1075
1076                 if (domain == NULL)
1077                         continue;
1078
1079                 offset = protocol_offset(server->protocol);
1080                 if (offset < 0)
1081                         return offset;
1082
1083                 domlen = strlen(domain) + 1;
1084                 if (domlen < 5)
1085                         return -EINVAL;
1086
1087                 alt[offset] = req->altid & 0xff;
1088                 alt[offset + 1] = req->altid >> 8;
1089
1090                 memcpy(alt + offset + 2, request + offset + 2, 10);
1091                 hdr->qdcount = htons(1);
1092
1093                 altlen = append_query(alt + offset + 12, sizeof(alt) - 12,
1094                                         name, domain);
1095                 if (altlen < 0)
1096                         return -EINVAL;
1097
1098                 altlen += 12;
1099
1100                 memcpy(alt + offset + altlen,
1101                         request + offset + altlen - domlen,
1102                                 req->request_len - altlen - offset + domlen);
1103
1104                 if (server->protocol == IPPROTO_TCP) {
1105                         int req_len = req->request_len + domlen - 2;
1106
1107                         alt[0] = (req_len >> 8) & 0xff;
1108                         alt[1] = req_len & 0xff;
1109                 }
1110
1111                 err = send(sk, alt, req->request_len + domlen, 0);
1112                 if (err < 0)
1113                         return -EIO;
1114
1115                 req->numserv++;
1116         }
1117
1118         return 0;
1119 }
1120
1121 static int forward_dns_reply(unsigned char *reply, int reply_len, int protocol,
1122                                 struct server_data *data)
1123 {
1124         struct domain_hdr *hdr;
1125         struct request_data *req;
1126         int dns_id, sk, err, offset = protocol_offset(protocol);
1127         struct listener_data *ifdata;
1128
1129         if (offset < 0)
1130                 return offset;
1131
1132         hdr = (void *)(reply + offset);
1133         dns_id = reply[offset] | reply[offset + 1] << 8;
1134
1135         DBG("Received %d bytes (id 0x%04x)", reply_len, dns_id);
1136
1137         req = find_request(dns_id);
1138         if (req == NULL)
1139                 return -EINVAL;
1140
1141         DBG("id 0x%04x rcode %d", hdr->id, hdr->rcode);
1142
1143         ifdata = req->ifdata;
1144
1145         reply[offset] = req->srcid & 0xff;
1146         reply[offset + 1] = req->srcid >> 8;
1147
1148         req->numresp++;
1149
1150         if (hdr->rcode == 0 || req->resp == NULL) {
1151
1152                 /*
1153                  * If the domain name was append
1154                  * remove it before forwarding the reply.
1155                  */
1156                 if (req->append_domain == TRUE) {
1157                         unsigned char *ptr;
1158                         uint8_t host_len;
1159                         unsigned int domain_len;
1160
1161                         /*
1162                          * ptr points to the first char of the hostname.
1163                          * ->hostname.domain.net
1164                          */
1165                         ptr = reply + offset + sizeof(struct domain_hdr);
1166                         host_len = *ptr;
1167                         domain_len = strlen((const char *)ptr) - host_len - 1;
1168
1169                         /*
1170                          * remove the domain name and replaced it by the end
1171                          * of reply.
1172                          */
1173                         memmove(ptr + host_len + 1,
1174                                 ptr + host_len + domain_len + 1,
1175                                 reply_len - (ptr - reply + domain_len));
1176
1177                         reply_len = reply_len - domain_len;
1178                 }
1179
1180                 g_free(req->resp);
1181                 req->resplen = 0;
1182
1183                 req->resp = g_try_malloc(reply_len);
1184                 if (req->resp == NULL)
1185                         return -ENOMEM;
1186
1187                 memcpy(req->resp, reply, reply_len);
1188                 req->resplen = reply_len;
1189
1190                 cache_update(data, reply, reply_len);
1191         }
1192
1193         if (hdr->rcode > 0 && req->numresp < req->numserv)
1194                 return -EINVAL;
1195
1196         if (req->timeout > 0)
1197                 g_source_remove(req->timeout);
1198
1199         request_list = g_slist_remove(request_list, req);
1200
1201         if (protocol == IPPROTO_UDP) {
1202                 sk = g_io_channel_unix_get_fd(ifdata->udp_listener_channel);
1203                 err = sendto(sk, req->resp, req->resplen, 0,
1204                              &req->sa, req->sa_len);
1205         } else {
1206                 sk = req->client_sk;
1207                 err = send(sk, req->resp, req->resplen, 0);
1208                 close(sk);
1209         }
1210
1211         g_free(req->resp);
1212         g_free(req);
1213
1214         return err;
1215 }
1216
1217 static void cache_element_destroy(gpointer value)
1218 {
1219         struct cache_entry *entry = value;
1220
1221         if (entry == NULL)
1222                 return;
1223
1224         if (entry->ipv4 != NULL) {
1225                 g_free(entry->ipv4->data);
1226                 g_free(entry->ipv4);
1227         }
1228
1229         if (entry->ipv6 != NULL) {
1230                 g_free(entry->ipv6->data);
1231                 g_free(entry->ipv6);
1232         }
1233
1234         g_free(entry->key);
1235         g_free(entry);
1236
1237         if (--cache_size < 0)
1238                 cache_size = 0;
1239 }
1240
1241 static void destroy_server(struct server_data *server)
1242 {
1243         GList *list;
1244
1245         DBG("interface %s server %s", server->interface, server->server);
1246
1247         server_list = g_slist_remove(server_list, server);
1248
1249         if (server->watch > 0)
1250                 g_source_remove(server->watch);
1251
1252         if (server->timeout > 0)
1253                 g_source_remove(server->timeout);
1254
1255         g_io_channel_unref(server->channel);
1256
1257         if (server->protocol == IPPROTO_UDP)
1258                 connman_info("Removing DNS server %s", server->server);
1259
1260         g_free(server->incoming_reply);
1261         g_free(server->server);
1262         for (list = server->domains; list; list = list->next) {
1263                 char *domain = list->data;
1264
1265                 server->domains = g_list_remove(server->domains, domain);
1266                 g_free(domain);
1267         }
1268         g_free(server->interface);
1269
1270         if (__sync_fetch_and_sub(&cache_refcount, 1) == 1)
1271                 g_hash_table_destroy(cache);
1272
1273         g_free(server);
1274 }
1275
1276 static gboolean udp_server_event(GIOChannel *channel, GIOCondition condition,
1277                                                         gpointer user_data)
1278 {
1279         unsigned char buf[4096];
1280         int sk, err, len;
1281         struct server_data *data = user_data;
1282
1283         if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
1284                 connman_error("Error with UDP server %s", data->server);
1285                 data->watch = 0;
1286                 return FALSE;
1287         }
1288
1289         sk = g_io_channel_unix_get_fd(channel);
1290
1291         len = recv(sk, buf, sizeof(buf), 0);
1292         if (len < 12)
1293                 return TRUE;
1294
1295         err = forward_dns_reply(buf, len, IPPROTO_UDP, data);
1296         if (err < 0)
1297                 return TRUE;
1298
1299         return TRUE;
1300 }
1301
1302 static gboolean tcp_server_event(GIOChannel *channel, GIOCondition condition,
1303                                                         gpointer user_data)
1304 {
1305         int sk;
1306         struct server_data *server = user_data;
1307
1308         sk = g_io_channel_unix_get_fd(channel);
1309         if (sk == 0)
1310                 return FALSE;
1311
1312         if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
1313                 GSList *list;
1314 hangup:
1315                 DBG("TCP server channel closed");
1316
1317                 /*
1318                  * Discard any partial response which is buffered; better
1319                  * to get a proper response from a working server.
1320                  */
1321                 g_free(server->incoming_reply);
1322                 server->incoming_reply = NULL;
1323
1324                 for (list = request_list; list; list = list->next) {
1325                         struct request_data *req = list->data;
1326                         struct domain_hdr *hdr;
1327
1328                         if (req->protocol == IPPROTO_UDP)
1329                                 continue;
1330
1331                         if (req->request == NULL)
1332                                 continue;
1333
1334                         /*
1335                          * If we're not waiting for any further response
1336                          * from another name server, then we send an error
1337                          * response to the client.
1338                          */
1339                         if (req->numserv && --(req->numserv))
1340                                 continue;
1341
1342                         hdr = (void *) (req->request + 2);
1343                         hdr->id = req->srcid;
1344                         send_response(req->client_sk, req->request,
1345                                 req->request_len, NULL, 0, IPPROTO_TCP);
1346
1347                         request_list = g_slist_remove(request_list, req);
1348                 }
1349
1350                 destroy_server(server);
1351
1352                 return FALSE;
1353         }
1354
1355         if ((condition & G_IO_OUT) && !server->connected) {
1356                 GSList *list;
1357                 GList *domains;
1358                 struct server_data *udp_server;
1359
1360                 udp_server = find_server(server->interface, server->server,
1361                                                                 IPPROTO_UDP);
1362                 if (udp_server != NULL) {
1363                         for (domains = udp_server->domains; domains;
1364                                                 domains = domains->next) {
1365                                 char *dom = domains->data;
1366
1367                                 DBG("Adding domain %s to %s",
1368                                                 dom, server->server);
1369
1370                                 server->domains = g_list_append(server->domains,
1371                                                                 g_strdup(dom));
1372                         }
1373                 }
1374
1375                 server->connected = TRUE;
1376                 server_list = g_slist_append(server_list, server);
1377
1378                 if (server->timeout > 0) {
1379                         g_source_remove(server->timeout);
1380                         server->timeout = 0;
1381                 }
1382
1383                 for (list = request_list; list; list = list->next) {
1384                         struct request_data *req = list->data;
1385
1386                         if (req->protocol == IPPROTO_UDP)
1387                                 continue;
1388
1389                         DBG("Sending req %s over TCP", (char *)req->name);
1390
1391                         if (req->timeout > 0)
1392                                 g_source_remove(req->timeout);
1393
1394                         req->timeout = g_timeout_add_seconds(30,
1395                                                 request_timeout, req);
1396                         if (ns_resolv(server, req, req->request,
1397                                         req->name) > 0) {
1398                                 /* We sent cached result so no need for timeout
1399                                  * handler.
1400                                  */
1401                                 if (req->timeout > 0) {
1402                                         g_source_remove(req->timeout);
1403                                         req->timeout = 0;
1404                                 }
1405                         }
1406                 }
1407
1408         } else if (condition & G_IO_IN) {
1409                 struct partial_reply *reply = server->incoming_reply;
1410                 int bytes_recv;
1411
1412                 if (!reply) {
1413                         unsigned char reply_len_buf[2];
1414                         uint16_t reply_len;
1415
1416                         bytes_recv = recv(sk, reply_len_buf, 2, MSG_PEEK);
1417                         if (!bytes_recv) {
1418                                 goto hangup;
1419                         } else if (bytes_recv < 0) {
1420                                 if (errno == EAGAIN || errno == EWOULDBLOCK)
1421                                         return TRUE;
1422
1423                                 connman_error("DNS proxy error %s",
1424                                                 strerror(errno));
1425                                 goto hangup;
1426                         } else if (bytes_recv < 2)
1427                                 return TRUE;
1428
1429                         reply_len = reply_len_buf[1] | reply_len_buf[0] << 8;
1430                         reply_len += 2;
1431
1432                         DBG("TCP reply %d bytes", reply_len);
1433
1434                         reply = g_try_malloc(sizeof(*reply) + reply_len + 2);
1435                         if (!reply)
1436                                 return TRUE;
1437
1438                         reply->len = reply_len;
1439                         reply->received = 0;
1440
1441                         server->incoming_reply = reply;
1442                 }
1443
1444                 while (reply->received < reply->len) {
1445                         bytes_recv = recv(sk, reply->buf + reply->received,
1446                                         reply->len - reply->received, 0);
1447                         if (!bytes_recv) {
1448                                 connman_error("DNS proxy TCP disconnect");
1449                                 break;
1450                         } else if (bytes_recv < 0) {
1451                                 if (errno == EAGAIN || errno == EWOULDBLOCK)
1452                                         return TRUE;
1453
1454                                 connman_error("DNS proxy error %s",
1455                                                 strerror(errno));
1456                                 break;
1457                         }
1458                         reply->received += bytes_recv;
1459                 }
1460
1461                 forward_dns_reply(reply->buf, reply->received, IPPROTO_TCP,
1462                                         server);
1463
1464                 g_free(reply);
1465                 server->incoming_reply = NULL;
1466
1467                 destroy_server(server);
1468
1469                 return FALSE;
1470         }
1471
1472         return TRUE;
1473 }
1474
1475 static gboolean tcp_idle_timeout(gpointer user_data)
1476 {
1477         struct server_data *server = user_data;
1478
1479         DBG("");
1480
1481         if (server == NULL)
1482                 return FALSE;
1483
1484         destroy_server(server);
1485
1486         return FALSE;
1487 }
1488
1489 static struct server_data *create_server(const char *interface,
1490                                         const char *domain, const char *server,
1491                                         int protocol)
1492 {
1493         struct addrinfo hints, *rp;
1494         struct server_data *data;
1495         int sk, ret;
1496
1497         DBG("interface %s server %s", interface, server);
1498
1499         memset(&hints, 0, sizeof(hints));
1500
1501         switch (protocol) {
1502         case IPPROTO_UDP:
1503                 hints.ai_socktype = SOCK_DGRAM;
1504                 break;
1505
1506         case IPPROTO_TCP:
1507                 hints.ai_socktype = SOCK_STREAM;
1508                 break;
1509
1510         default:
1511                 return NULL;
1512         }
1513         hints.ai_family = AF_UNSPEC;
1514         hints.ai_flags = AI_PASSIVE | AI_NUMERICSERV | AI_NUMERICHOST;
1515
1516         ret = getaddrinfo(server, "53", &hints, &rp);
1517         if (ret) {
1518                 connman_error("Failed to parse server %s address: %s\n",
1519                               server, gai_strerror(ret));
1520                 return NULL;
1521         }
1522         /* Do not blindly copy this code elsewhere; it doesn't loop over the
1523            results using ->ai_next as it should. That's OK in *this* case
1524            because it was a numeric lookup; we *know* there's only one. */
1525
1526         sk = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
1527         if (sk < 0) {
1528                 connman_error("Failed to create server %s socket", server);
1529                 freeaddrinfo(rp);
1530                 return NULL;
1531         }
1532
1533         if (interface != NULL) {
1534                 if (setsockopt(sk, SOL_SOCKET, SO_BINDTODEVICE,
1535                                 interface, strlen(interface) + 1) < 0) {
1536                         connman_error("Failed to bind server %s "
1537                                                 "to interface %s",
1538                                                         server, interface);
1539                         freeaddrinfo(rp);
1540                         close(sk);
1541                         return NULL;
1542                 }
1543         }
1544
1545         data = g_try_new0(struct server_data, 1);
1546         if (data == NULL) {
1547                 connman_error("Failed to allocate server %s data", server);
1548                 freeaddrinfo(rp);
1549                 close(sk);
1550                 return NULL;
1551         }
1552
1553         data->channel = g_io_channel_unix_new(sk);
1554         if (data->channel == NULL) {
1555                 connman_error("Failed to create server %s channel", server);
1556                 freeaddrinfo(rp);
1557                 close(sk);
1558                 g_free(data);
1559                 return NULL;
1560         }
1561
1562         g_io_channel_set_close_on_unref(data->channel, TRUE);
1563
1564         if (protocol == IPPROTO_TCP) {
1565                 g_io_channel_set_flags(data->channel, G_IO_FLAG_NONBLOCK, NULL);
1566                 data->watch = g_io_add_watch(data->channel,
1567                         G_IO_OUT | G_IO_IN | G_IO_HUP | G_IO_NVAL | G_IO_ERR,
1568                                                 tcp_server_event, data);
1569                 data->timeout = g_timeout_add_seconds(30, tcp_idle_timeout,
1570                                                                 data);
1571         } else
1572                 data->watch = g_io_add_watch(data->channel,
1573                         G_IO_IN | G_IO_NVAL | G_IO_ERR | G_IO_HUP,
1574                                                 udp_server_event, data);
1575
1576         data->interface = g_strdup(interface);
1577         if (domain)
1578                 data->domains = g_list_append(data->domains, g_strdup(domain));
1579         data->server = g_strdup(server);
1580         data->protocol = protocol;
1581
1582         ret = connect(sk, rp->ai_addr, rp->ai_addrlen);
1583         freeaddrinfo(rp);
1584         if (ret < 0) {
1585                 if ((protocol == IPPROTO_TCP && errno != EINPROGRESS) ||
1586                                 protocol == IPPROTO_UDP) {
1587                         GList *list;
1588
1589                         connman_error("Failed to connect to server %s", server);
1590                         if (data->watch > 0)
1591                                 g_source_remove(data->watch);
1592                         if (data->timeout > 0)
1593                                 g_source_remove(data->timeout);
1594
1595                         g_io_channel_unref(data->channel);
1596                         close(sk);
1597
1598                         g_free(data->server);
1599                         g_free(data->interface);
1600                         for (list = data->domains; list; list = list->next) {
1601                                 char *domain = list->data;
1602
1603                                 data->domains = g_list_remove(data->domains,
1604                                                                         domain);
1605                                 g_free(domain);
1606                         }
1607                         g_free(data);
1608                         return NULL;
1609                 }
1610         }
1611
1612         if (__sync_fetch_and_add(&cache_refcount, 1) == 0)
1613                 cache = g_hash_table_new_full(g_str_hash,
1614                                         g_str_equal,
1615                                         NULL,
1616                                         cache_element_destroy);
1617
1618         if (protocol == IPPROTO_UDP) {
1619                 /* Enable new servers by default */
1620                 data->enabled = TRUE;
1621                 connman_info("Adding DNS server %s", data->server);
1622
1623                 server_list = g_slist_append(server_list, data);
1624
1625                 return data;
1626         }
1627
1628         return NULL;
1629 }
1630
1631 static gboolean resolv(struct request_data *req,
1632                                 gpointer request, gpointer name)
1633 {
1634         GSList *list;
1635         int status;
1636
1637         for (list = server_list; list; list = list->next) {
1638                 struct server_data *data = list->data;
1639
1640                 DBG("server %s enabled %d", data->server, data->enabled);
1641
1642                 if (data->enabled == FALSE)
1643                         continue;
1644
1645                 if (data->watch == 0 && data->protocol == IPPROTO_UDP)
1646                         data->watch = g_io_add_watch(data->channel,
1647                                 G_IO_IN | G_IO_NVAL | G_IO_ERR | G_IO_HUP,
1648                                                 udp_server_event, data);
1649
1650                 status = ns_resolv(data, req, request, name);
1651                 if (status < 0)
1652                         continue;
1653
1654                 if (status > 0) {
1655                         if (req->timeout > 0) {
1656                                 g_source_remove(req->timeout);
1657                                 req->timeout = 0;
1658                         }
1659                 }
1660         }
1661
1662         return TRUE;
1663 }
1664
1665 static void append_domain(const char *interface, const char *domain)
1666 {
1667         GSList *list;
1668
1669         DBG("interface %s domain %s", interface, domain);
1670
1671         if (domain == NULL)
1672                 return;
1673
1674         for (list = server_list; list; list = list->next) {
1675                 struct server_data *data = list->data;
1676                 GList *dom_list;
1677                 char *dom;
1678                 gboolean dom_found = FALSE;
1679
1680                 if (data->interface == NULL)
1681                         continue;
1682
1683                 if (g_str_equal(data->interface, interface) == FALSE)
1684                         continue;
1685
1686                 for (dom_list = data->domains; dom_list;
1687                                 dom_list = dom_list->next) {
1688                         dom = dom_list->data;
1689
1690                         if (g_str_equal(dom, domain)) {
1691                                 dom_found = TRUE;
1692                                 break;
1693                         }
1694                 }
1695
1696                 if (dom_found == FALSE) {
1697                         data->domains =
1698                                 g_list_append(data->domains, g_strdup(domain));
1699                 }
1700         }
1701 }
1702
1703 int __connman_dnsproxy_append(const char *interface, const char *domain,
1704                                                         const char *server)
1705 {
1706         struct server_data *data;
1707
1708         DBG("interface %s server %s", interface, server);
1709
1710         if (server == NULL && domain == NULL)
1711                 return -EINVAL;
1712
1713         if (server == NULL) {
1714                 append_domain(interface, domain);
1715
1716                 return 0;
1717         }
1718
1719         if (g_str_equal(server, "127.0.0.1") == TRUE)
1720                 return -ENODEV;
1721
1722         data = find_server(interface, server, IPPROTO_UDP);
1723         if (data != NULL) {
1724                 append_domain(interface, domain);
1725                 return 0;
1726         }
1727
1728         data = create_server(interface, domain, server, IPPROTO_UDP);
1729         if (data == NULL)
1730                 return -EIO;
1731
1732         return 0;
1733 }
1734
1735 static void remove_server(const char *interface, const char *domain,
1736                         const char *server, int protocol)
1737 {
1738         struct server_data *data;
1739
1740         data = find_server(interface, server, protocol);
1741         if (data == NULL)
1742                 return;
1743
1744         destroy_server(data);
1745 }
1746
1747 int __connman_dnsproxy_remove(const char *interface, const char *domain,
1748                                                         const char *server)
1749 {
1750         DBG("interface %s server %s", interface, server);
1751
1752         if (server == NULL)
1753                 return -EINVAL;
1754
1755         if (g_str_equal(server, "127.0.0.1") == TRUE)
1756                 return -ENODEV;
1757
1758         remove_server(interface, domain, server, IPPROTO_UDP);
1759         remove_server(interface, domain, server, IPPROTO_TCP);
1760
1761         return 0;
1762 }
1763
1764 void __connman_dnsproxy_flush(void)
1765 {
1766         GSList *list;
1767
1768         list = request_pending_list;
1769         while (list) {
1770                 struct request_data *req = list->data;
1771
1772                 list = list->next;
1773
1774                 request_pending_list =
1775                                 g_slist_remove(request_pending_list, req);
1776                 resolv(req, req->request, req->name);
1777                 g_free(req->request);
1778                 g_free(req->name);
1779         }
1780 }
1781
1782 static void dnsproxy_offline_mode(connman_bool_t enabled)
1783 {
1784         GSList *list;
1785
1786         DBG("enabled %d", enabled);
1787
1788         for (list = server_list; list; list = list->next) {
1789                 struct server_data *data = list->data;
1790
1791                 if (enabled == FALSE) {
1792                         connman_info("Enabling DNS server %s", data->server);
1793                         data->enabled = TRUE;
1794                 } else {
1795                         connman_info("Disabling DNS server %s", data->server);
1796                         data->enabled = FALSE;
1797                 }
1798         }
1799 }
1800
1801 static void dnsproxy_default_changed(struct connman_service *service)
1802 {
1803         GSList *list;
1804         char *interface;
1805
1806         DBG("service %p", service);
1807
1808         if (service == NULL) {
1809                 /* When no services are active, then disable DNS proxying */
1810                 dnsproxy_offline_mode(TRUE);
1811                 return;
1812         }
1813
1814         interface = connman_service_get_interface(service);
1815         if (interface == NULL)
1816                 return;
1817
1818         for (list = server_list; list; list = list->next) {
1819                 struct server_data *data = list->data;
1820
1821                 if (g_strcmp0(data->interface, interface) == 0) {
1822                         connman_info("Enabling DNS server %s", data->server);
1823                         data->enabled = TRUE;
1824                 } else {
1825                         connman_info("Disabling DNS server %s", data->server);
1826                         data->enabled = FALSE;
1827                 }
1828         }
1829
1830         g_free(interface);
1831 }
1832
1833 static struct connman_notifier dnsproxy_notifier = {
1834         .name                   = "dnsproxy",
1835         .default_changed        = dnsproxy_default_changed,
1836         .offline_mode           = dnsproxy_offline_mode,
1837 };
1838
1839 static unsigned char opt_edns0_type[2] = { 0x00, 0x29 };
1840
1841 static int parse_request(unsigned char *buf, int len,
1842                                         char *name, unsigned int size)
1843 {
1844         struct domain_hdr *hdr = (void *) buf;
1845         uint16_t qdcount = ntohs(hdr->qdcount);
1846         uint16_t arcount = ntohs(hdr->arcount);
1847         unsigned char *ptr;
1848         char *last_label = NULL;
1849         unsigned int remain, used = 0;
1850
1851         if (len < 12)
1852                 return -EINVAL;
1853
1854         DBG("id 0x%04x qr %d opcode %d qdcount %d arcount %d",
1855                                         hdr->id, hdr->qr, hdr->opcode,
1856                                                         qdcount, arcount);
1857
1858         if (hdr->qr != 0 || qdcount != 1)
1859                 return -EINVAL;
1860
1861         memset(name, 0, size);
1862
1863         ptr = buf + sizeof(struct domain_hdr);
1864         remain = len - sizeof(struct domain_hdr);
1865
1866         while (remain > 0) {
1867                 uint8_t len = *ptr;
1868
1869                 if (len == 0x00) {
1870                         last_label = (char *) (ptr + 1);
1871                         break;
1872                 }
1873
1874                 if (used + len + 1 > size)
1875                         return -ENOBUFS;
1876
1877                 strncat(name, (char *) (ptr + 1), len);
1878                 strcat(name, ".");
1879
1880                 used += len + 1;
1881
1882                 ptr += len + 1;
1883                 remain -= len + 1;
1884         }
1885
1886         if (last_label && arcount && remain >= 9 && last_label[4] == 0 &&
1887                                 !memcmp(last_label + 5, opt_edns0_type, 2)) {
1888                 uint16_t edns0_bufsize;
1889
1890                 edns0_bufsize = last_label[7] << 8 | last_label[8];
1891
1892                 DBG("EDNS0 buffer size %u", edns0_bufsize);
1893
1894                 /* This is an evil hack until full TCP support has been
1895                  * implemented.
1896                  *
1897                  * Somtimes the EDNS0 request gets send with a too-small
1898                  * buffer size. Since glibc doesn't seem to crash when it
1899                  * gets a response biffer then it requested, just bump
1900                  * the buffer size up to 4KiB.
1901                  */
1902                 if (edns0_bufsize < 0x1000) {
1903                         last_label[7] = 0x10;
1904                         last_label[8] = 0x00;
1905                 }
1906         }
1907
1908         DBG("query %s", name);
1909
1910         return 0;
1911 }
1912
1913 static gboolean tcp_listener_event(GIOChannel *channel, GIOCondition condition,
1914                                                         gpointer user_data)
1915 {
1916         unsigned char buf[768];
1917         char query[512];
1918         struct request_data *req;
1919         struct server_data *server;
1920         int sk, client_sk, len, err;
1921         struct sockaddr_in6 client_addr;
1922         socklen_t client_addr_len = sizeof(client_addr);
1923         GSList *list;
1924         struct listener_data *ifdata = user_data;
1925
1926         DBG("condition 0x%x", condition);
1927
1928         if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
1929                 if (ifdata->tcp_listener_watch > 0)
1930                         g_source_remove(ifdata->tcp_listener_watch);
1931                 ifdata->tcp_listener_watch = 0;
1932
1933                 connman_error("Error with TCP listener channel");
1934
1935                 return FALSE;
1936         }
1937
1938         sk = g_io_channel_unix_get_fd(channel);
1939
1940         client_sk = accept(sk, (void *)&client_addr, &client_addr_len);
1941         if (client_sk < 0) {
1942                 connman_error("Accept failure on TCP listener");
1943                 ifdata->tcp_listener_watch = 0;
1944                 return FALSE;
1945         }
1946
1947         len = recv(client_sk, buf, sizeof(buf), 0);
1948         if (len < 2)
1949                 return TRUE;
1950
1951         DBG("Received %d bytes (id 0x%04x)", len, buf[2] | buf[3] << 8);
1952
1953         err = parse_request(buf + 2, len - 2, query, sizeof(query));
1954         if (err < 0 || (g_slist_length(server_list) == 0)) {
1955                 send_response(client_sk, buf, len, NULL, 0, IPPROTO_TCP);
1956                 return TRUE;
1957         }
1958
1959         req = g_try_new0(struct request_data, 1);
1960         if (req == NULL)
1961                 return TRUE;
1962
1963         memcpy(&req->sa, &client_addr, client_addr_len);
1964         req->sa_len = client_addr_len;
1965         req->client_sk = client_sk;
1966         req->protocol = IPPROTO_TCP;
1967
1968         request_id += 2;
1969         if (request_id == 0x0000 || request_id == 0xffff)
1970                 request_id += 2;
1971
1972         req->srcid = buf[2] | (buf[3] << 8);
1973         req->dstid = request_id;
1974         req->altid = request_id + 1;
1975         req->request_len = len;
1976
1977         buf[2] = req->dstid & 0xff;
1978         buf[3] = req->dstid >> 8;
1979
1980         req->numserv = 0;
1981         req->ifdata = (struct listener_data *) ifdata;
1982         req->append_domain = FALSE;
1983         request_list = g_slist_append(request_list, req);
1984
1985         for (list = server_list; list; list = list->next) {
1986                 struct server_data *data = list->data;
1987                 GList *domains;
1988
1989                 if (data->protocol != IPPROTO_UDP || data->enabled == FALSE)
1990                         continue;
1991
1992                 server = create_server(data->interface, NULL,
1993                                         data->server, IPPROTO_TCP);
1994
1995                 /*
1996                  * If server is NULL, we're not connected yet.
1997                  * Copy the relevant buffers and continue with
1998                  * the next nameserver.
1999                  * The request will actually be sent once we're
2000                  * properly connected over TCP to this nameserver.
2001                  */
2002                 if (server == NULL) {
2003                         req->request = g_try_malloc0(req->request_len);
2004                         if (req->request == NULL)
2005                                 return TRUE;
2006
2007                         memcpy(req->request, buf, req->request_len);
2008
2009                         req->name = g_try_malloc0(sizeof(query));
2010                         if (req->name == NULL) {
2011                                 g_free(req->request);
2012                                 return TRUE;
2013                         }
2014                         memcpy(req->name, query, sizeof(query));
2015
2016                         continue;
2017                 }
2018
2019                 if (req->timeout > 0)
2020                         g_source_remove(req->timeout);
2021
2022                 for (domains = data->domains; domains;
2023                                 domains = domains->next) {
2024                         char *dom = domains->data;
2025
2026                         DBG("Adding domain %s to %s", dom, server->server);
2027
2028                         server->domains = g_list_append(server->domains,
2029                                                 g_strdup(dom));
2030                 }
2031
2032                 req->timeout = g_timeout_add_seconds(30, request_timeout, req);
2033                 if (ns_resolv(server, req, buf, query) > 0) {
2034                         if (req->timeout > 0) {
2035                                 g_source_remove(req->timeout);
2036                                 req->timeout = 0;
2037                         }
2038                 }
2039         }
2040
2041         return TRUE;
2042 }
2043
2044 static gboolean udp_listener_event(GIOChannel *channel, GIOCondition condition,
2045                                                         gpointer user_data)
2046 {
2047         unsigned char buf[768];
2048         char query[512];
2049         struct request_data *req;
2050         struct sockaddr_in6 client_addr;
2051         socklen_t client_addr_len = sizeof(client_addr);
2052         int sk, err, len;
2053         struct listener_data *ifdata = user_data;
2054
2055         if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
2056                 connman_error("Error with UDP listener channel");
2057                 ifdata->udp_listener_watch = 0;
2058                 return FALSE;
2059         }
2060
2061         sk = g_io_channel_unix_get_fd(channel);
2062
2063         memset(&client_addr, 0, client_addr_len);
2064         len = recvfrom(sk, buf, sizeof(buf), 0, (void *)&client_addr,
2065                        &client_addr_len);
2066         if (len < 2)
2067                 return TRUE;
2068
2069         DBG("Received %d bytes (id 0x%04x)", len, buf[0] | buf[1] << 8);
2070
2071         err = parse_request(buf, len, query, sizeof(query));
2072         if (err < 0 || (g_slist_length(server_list) == 0)) {
2073                 send_response(sk, buf, len, (void *)&client_addr,
2074                                 client_addr_len, IPPROTO_UDP);
2075                 return TRUE;
2076         }
2077
2078         req = g_try_new0(struct request_data, 1);
2079         if (req == NULL)
2080                 return TRUE;
2081
2082         memcpy(&req->sa, &client_addr, client_addr_len);
2083         req->sa_len = client_addr_len;
2084         req->client_sk = 0;
2085         req->protocol = IPPROTO_UDP;
2086
2087         request_id += 2;
2088         if (request_id == 0x0000 || request_id == 0xffff)
2089                 request_id += 2;
2090
2091         req->srcid = buf[0] | (buf[1] << 8);
2092         req->dstid = request_id;
2093         req->altid = request_id + 1;
2094         req->request_len = len;
2095
2096         buf[0] = req->dstid & 0xff;
2097         buf[1] = req->dstid >> 8;
2098
2099         req->numserv = 0;
2100         req->ifdata = (struct listener_data *) ifdata;
2101         req->timeout = g_timeout_add_seconds(5, request_timeout, req);
2102         req->append_domain = FALSE;
2103         request_list = g_slist_append(request_list, req);
2104
2105         return resolv(req, buf, query);
2106 }
2107
2108 static int create_dns_listener(int protocol, struct listener_data *ifdata)
2109 {
2110         GIOChannel *channel;
2111         const char *proto;
2112         union {
2113                 struct sockaddr sa;
2114                 struct sockaddr_in6 sin6;
2115                 struct sockaddr_in sin;
2116         } s;
2117         socklen_t slen;
2118         int sk, type, v6only = 0;
2119         int family = AF_INET6;
2120
2121
2122         DBG("interface %s", ifdata->ifname);
2123
2124         switch (protocol) {
2125         case IPPROTO_UDP:
2126                 proto = "UDP";
2127                 type = SOCK_DGRAM | SOCK_CLOEXEC;
2128                 break;
2129
2130         case IPPROTO_TCP:
2131                 proto = "TCP";
2132                 type = SOCK_STREAM | SOCK_CLOEXEC;
2133                 break;
2134
2135         default:
2136                 return -EINVAL;
2137         }
2138
2139         sk = socket(family, type, protocol);
2140         if (sk < 0 && family == AF_INET6 && errno == EAFNOSUPPORT) {
2141                 connman_error("No IPv6 support; DNS proxy listening only on Legacy IP");
2142                 family = AF_INET;
2143                 sk = socket(family, type, protocol);
2144         }
2145         if (sk < 0) {
2146                 connman_error("Failed to create %s listener socket", proto);
2147                 return -EIO;
2148         }
2149
2150         if (setsockopt(sk, SOL_SOCKET, SO_BINDTODEVICE,
2151                                         ifdata->ifname,
2152                                         strlen(ifdata->ifname) + 1) < 0) {
2153                 connman_error("Failed to bind %s listener interface", proto);
2154                 close(sk);
2155                 return -EIO;
2156         }
2157         /* Ensure it accepts Legacy IP connections too */
2158         if (family == AF_INET6 &&
2159                         setsockopt(sk, SOL_IPV6, IPV6_V6ONLY,
2160                                         &v6only, sizeof(v6only)) < 0) {
2161                 connman_error("Failed to clear V6ONLY on %s listener socket",
2162                               proto);
2163                 close(sk);
2164                 return -EIO;
2165         }
2166
2167         if (family == AF_INET) {
2168                 memset(&s.sin, 0, sizeof(s.sin));
2169                 s.sin.sin_family = AF_INET;
2170                 s.sin.sin_port = htons(53);
2171                 s.sin.sin_addr.s_addr = htonl(INADDR_ANY);
2172                 slen = sizeof(s.sin);
2173         } else {
2174                 memset(&s.sin6, 0, sizeof(s.sin6));
2175                 s.sin6.sin6_family = AF_INET6;
2176                 s.sin6.sin6_port = htons(53);
2177                 s.sin6.sin6_addr = in6addr_any;
2178                 slen = sizeof(s.sin6);
2179         }
2180
2181         if (bind(sk, &s.sa, slen) < 0) {
2182                 connman_error("Failed to bind %s listener socket", proto);
2183                 close(sk);
2184                 return -EIO;
2185         }
2186
2187         if (protocol == IPPROTO_TCP && listen(sk, 10) < 0) {
2188                 connman_error("Failed to listen on TCP socket");
2189                 close(sk);
2190                 return -EIO;
2191         }
2192
2193         channel = g_io_channel_unix_new(sk);
2194         if (channel == NULL) {
2195                 connman_error("Failed to create %s listener channel", proto);
2196                 close(sk);
2197                 return -EIO;
2198         }
2199
2200         g_io_channel_set_close_on_unref(channel, TRUE);
2201
2202         if (protocol == IPPROTO_TCP) {
2203                 ifdata->tcp_listener_channel = channel;
2204                 ifdata->tcp_listener_watch = g_io_add_watch(channel,
2205                                 G_IO_IN, tcp_listener_event, (gpointer) ifdata);
2206         } else {
2207                 ifdata->udp_listener_channel = channel;
2208                 ifdata->udp_listener_watch = g_io_add_watch(channel,
2209                                 G_IO_IN, udp_listener_event, (gpointer) ifdata);
2210         }
2211
2212         return 0;
2213 }
2214
2215 static void destroy_udp_listener(struct listener_data *ifdata)
2216 {
2217         DBG("interface %s", ifdata->ifname);
2218
2219         if (ifdata->udp_listener_watch > 0)
2220                 g_source_remove(ifdata->udp_listener_watch);
2221
2222         g_io_channel_unref(ifdata->udp_listener_channel);
2223 }
2224
2225 static void destroy_tcp_listener(struct listener_data *ifdata)
2226 {
2227         DBG("interface %s", ifdata->ifname);
2228
2229         if (ifdata->tcp_listener_watch > 0)
2230                 g_source_remove(ifdata->tcp_listener_watch);
2231
2232         g_io_channel_unref(ifdata->tcp_listener_channel);
2233 }
2234
2235 static int create_listener(struct listener_data *ifdata)
2236 {
2237         int err;
2238
2239         err = create_dns_listener(IPPROTO_UDP, ifdata);
2240         if (err < 0)
2241                 return err;
2242
2243         err = create_dns_listener(IPPROTO_TCP, ifdata);
2244         if (err < 0) {
2245                 destroy_udp_listener(ifdata);
2246                 return err;
2247         }
2248
2249         if (g_strcmp0(ifdata->ifname, "lo") == 0)
2250                 __connman_resolvfile_append("lo", NULL, "127.0.0.1");
2251
2252         return 0;
2253 }
2254
2255 static void destroy_listener(struct listener_data *ifdata)
2256 {
2257         GSList *list;
2258
2259         if (g_strcmp0(ifdata->ifname, "lo") == 0)
2260                 __connman_resolvfile_remove("lo", NULL, "127.0.0.1");
2261
2262         for (list = request_pending_list; list; list = list->next) {
2263                 struct request_data *req = list->data;
2264
2265                 DBG("Dropping pending request (id 0x%04x -> 0x%04x)",
2266                                                 req->srcid, req->dstid);
2267
2268                 g_free(req->resp);
2269                 g_free(req->request);
2270                 g_free(req->name);
2271                 g_free(req);
2272                 list->data = NULL;
2273         }
2274
2275         g_slist_free(request_pending_list);
2276         request_pending_list = NULL;
2277
2278         for (list = request_list; list; list = list->next) {
2279                 struct request_data *req = list->data;
2280
2281                 DBG("Dropping request (id 0x%04x -> 0x%04x)",
2282                                                 req->srcid, req->dstid);
2283
2284                 g_free(req->resp);
2285                 g_free(req->request);
2286                 g_free(req->name);
2287                 g_free(req);
2288                 list->data = NULL;
2289         }
2290
2291         g_slist_free(request_list);
2292         request_list = NULL;
2293
2294         destroy_tcp_listener(ifdata);
2295         destroy_udp_listener(ifdata);
2296 }
2297
2298 int __connman_dnsproxy_add_listener(const char *interface)
2299 {
2300         struct listener_data *ifdata;
2301         int err;
2302
2303         DBG("interface %s", interface);
2304
2305         if (g_hash_table_lookup(listener_table, interface) != NULL)
2306                 return 0;
2307
2308         ifdata = g_try_new0(struct listener_data, 1);
2309         if (ifdata == NULL)
2310                 return -ENOMEM;
2311
2312         ifdata->ifname = g_strdup(interface);
2313         ifdata->udp_listener_channel = NULL;
2314         ifdata->udp_listener_watch = 0;
2315         ifdata->tcp_listener_channel = NULL;
2316         ifdata->tcp_listener_watch = 0;
2317
2318         err = create_listener(ifdata);
2319         if (err < 0) {
2320                 connman_error("Couldn't create listener for %s err %d",
2321                                 interface, err);
2322                 g_free(ifdata->ifname);
2323                 g_free(ifdata);
2324                 return err;
2325         }
2326         g_hash_table_insert(listener_table, ifdata->ifname, ifdata);
2327         return 0;
2328 }
2329
2330 void __connman_dnsproxy_remove_listener(const char *interface)
2331 {
2332         struct listener_data *ifdata;
2333
2334         DBG("interface %s", interface);
2335
2336         ifdata = g_hash_table_lookup(listener_table, interface);
2337         if (ifdata == NULL)
2338                 return;
2339
2340         destroy_listener(ifdata);
2341
2342         g_hash_table_remove(listener_table, interface);
2343 }
2344
2345 static void remove_listener(gpointer key, gpointer value, gpointer user_data)
2346 {
2347         __connman_dnsproxy_remove_listener(key);
2348 }
2349
2350 int __connman_dnsproxy_init(void)
2351 {
2352         int err;
2353
2354         DBG("");
2355
2356         listener_table = g_hash_table_new_full(g_str_hash, g_str_equal,
2357                                                         g_free, g_free);
2358         err = __connman_dnsproxy_add_listener("lo");
2359         if (err < 0)
2360                 return err;
2361
2362         err = connman_notifier_register(&dnsproxy_notifier);
2363         if (err < 0)
2364                 goto destroy;
2365
2366         return 0;
2367
2368 destroy:
2369         __connman_dnsproxy_remove_listener("lo");
2370         g_hash_table_destroy(listener_table);
2371
2372         return err;
2373 }
2374
2375 void __connman_dnsproxy_cleanup(void)
2376 {
2377         DBG("");
2378
2379         connman_notifier_unregister(&dnsproxy_notifier);
2380
2381         g_hash_table_foreach(listener_table, remove_listener, NULL);
2382
2383         g_hash_table_destroy(listener_table);
2384 }