dnsproxy: Make sure "rr" is not NULL
[platform/upstream/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         if (rr == NULL)
583                 return -EINVAL;
584
585         *type = ntohs(rr->type);
586         *class = ntohs(rr->class);
587         *ttl = ntohl(rr->ttl);
588         *rdlen = ntohs(rr->rdlen);
589
590         if (*ttl < 0)
591                 return -EINVAL;
592
593         memcpy(response + offset, *end, sizeof(struct domain_rr));
594
595         offset += sizeof(struct domain_rr);
596         *end += sizeof(struct domain_rr);
597
598         if ((unsigned int) (offset + *rdlen) > *response_size)
599                 return -ENOBUFS;
600
601         memcpy(response + offset, *end, *rdlen);
602
603         *end += *rdlen;
604
605         *response_size = offset + *rdlen;
606
607         return 0;
608 }
609
610 static gboolean check_alias(GSList *aliases, char *name)
611 {
612         GSList *list;
613
614         if (aliases != NULL) {
615                 for (list = aliases; list; list = list->next) {
616                         int len = strlen((char *)list->data);
617                         if (strncmp((char *)list->data, name, len) == 0)
618                                 return TRUE;
619                 }
620         }
621
622         return FALSE;
623 }
624
625 static int parse_response(unsigned char *buf, int buflen,
626                         char *question, int qlen,
627                         uint16_t *type, uint16_t *class, int *ttl,
628                         unsigned char *response, unsigned int *response_len,
629                         uint16_t *answers)
630 {
631         struct domain_hdr *hdr = (void *) buf;
632         struct domain_question *q;
633         unsigned char *ptr;
634         uint16_t qdcount = ntohs(hdr->qdcount);
635         uint16_t ancount = ntohs(hdr->ancount);
636         int err, i;
637         uint16_t qtype, qclass;
638         unsigned char *next = NULL;
639         unsigned int maxlen = *response_len;
640         GSList *aliases = NULL, *list;
641         char name[NS_MAXDNAME + 1];
642
643         if (buflen < 12)
644                 return -EINVAL;
645
646         DBG("qr %d qdcount %d", hdr->qr, qdcount);
647
648         /* We currently only cache responses where question count is 1 */
649         if (hdr->qr != 1 || qdcount != 1)
650                 return -EINVAL;
651
652         ptr = buf + sizeof(struct domain_hdr);
653
654         strncpy(question, (char *) ptr, qlen);
655         qlen = strlen(question);
656         ptr += qlen + 1; /* skip \0 */
657
658         q = (void *) ptr;
659         qtype = ntohs(q->type);
660
661         /* We cache only A and AAAA records */
662         if (qtype != 1 && qtype != 28)
663                 return -ENOMSG;
664
665         qclass = ntohs(q->class);
666
667         ptr += 2 + 2; /* ptr points now to answers */
668
669         err = -ENOMSG;
670         *response_len = 0;
671         *answers = 0;
672
673         /*
674          * We have a bunch of answers (like A, AAAA, CNAME etc) to
675          * A or AAAA question. We traverse the answers and parse the
676          * resource records. Only A and AAAA records are cached, all
677          * the other records in answers are skipped.
678          */
679         for (i = 0; i < ancount; i++) {
680                 /*
681                  * Get one address at a time to this buffer.
682                  * The max size of the answer is
683                  *   2 (pointer) + 2 (type) + 2 (class) +
684                  *   4 (ttl) + 2 (rdlen) + addr (16 or 4) = 28
685                  * for A or AAAA record.
686                  * For CNAME the size can be bigger.
687                  */
688                 unsigned char rsp[NS_MAXCDNAME];
689                 unsigned int rsp_len = sizeof(rsp) - 1;
690                 int ret, rdlen;
691
692                 memset(rsp, 0, sizeof(rsp));
693
694                 ret = parse_rr(buf, ptr, buf + buflen, rsp, &rsp_len,
695                         type, class, ttl, &rdlen, &next, name);
696                 if (ret != 0) {
697                         err = ret;
698                         goto out;
699                 }
700
701                 /*
702                  * Now rsp contains compressed or uncompressed resource
703                  * record. Next we check if this record answers the question.
704                  * The name var contains the uncompressed label.
705                  * One tricky bit is the CNAME records as they alias
706                  * the name we might be interested in.
707                  */
708
709                 /*
710                  * Go to next answer if the class is not the one we are
711                  * looking for.
712                  */
713                 if (*class != qclass) {
714                         ptr = next;
715                         next = NULL;
716                         continue;
717                 }
718
719                 /*
720                  * Try to resolve aliases also, type is CNAME(5).
721                  * This is important as otherwise the aliased names would not
722                  * be cached at all as the cache would not contain the aliased
723                  * question.
724                  *
725                  * If any CNAME is found in DNS packet, then we cache the alias
726                  * IP address instead of the question (as the server
727                  * said that question has only an alias).
728                  * This means in practice that if e.g., ipv6.google.com is
729                  * queried, DNS server returns CNAME of that name which is
730                  * ipv6.l.google.com. We then cache the address of the CNAME
731                  * but return the question name to client. So the alias
732                  * status of the name is not saved in cache and thus not
733                  * returned to the client. We do not return DNS packets from
734                  * cache to client saying that ipv6.google.com is an alias to
735                  * ipv6.l.google.com but we return instead a DNS packet that
736                  * says ipv6.google.com has address xxx which is in fact the
737                  * address of ipv6.l.google.com. For caching purposes this
738                  * should not cause any issues.
739                  */
740                 if (*type == 5 && strncmp(question, name, qlen) == 0) {
741                         /*
742                          * So now the alias answered the question. This is
743                          * not very useful from caching point of view as
744                          * the following A or AAAA records will not match the
745                          * question. We need to find the real A/AAAA record
746                          * of the alias and cache that.
747                          */
748                         unsigned char *end = NULL;
749                         int name_len = 0, output_len;
750
751                         memset(rsp, 0, sizeof(rsp));
752                         rsp_len = sizeof(rsp) - 1;
753
754                         /*
755                          * Alias is in rdata part of the message,
756                          * and next-rdlen points to it. So we need to get
757                          * the real name of the alias.
758                          */
759                         ret = get_name(0, buf, next - rdlen, buf + buflen,
760                                         rsp, rsp_len, &output_len, &end,
761                                         name, &name_len);
762                         if (ret != 0) {
763                                 /* just ignore the error at this point */
764                                 ptr = next;
765                                 next = NULL;
766                                 continue;
767                         }
768
769                         /*
770                          * We should now have the alias of the entry we might
771                          * want to cache. Just remember it for a while.
772                          * We check the alias list when we have parsed the
773                          * A or AAAA record.
774                          */
775                         aliases = g_slist_prepend(aliases, g_strdup(name));
776
777                         ptr = next;
778                         next = NULL;
779                         continue;
780                 }
781
782                 if (*type == qtype) {
783                         /*
784                          * We found correct type (A or AAAA)
785                          */
786                         if (check_alias(aliases, name) == TRUE ||
787                                 (aliases == NULL && strncmp(question, name,
788                                                         qlen) == 0)) {
789                                 /*
790                                  * We found an alias or the name of the rr
791                                  * matches the question. If so, we append
792                                  * the compressed label to the cache.
793                                  * The end result is a response buffer that
794                                  * will contain one or more cached and
795                                  * compressed resource records.
796                                  */
797                                 if (*response_len + rsp_len > maxlen) {
798                                         err = -ENOBUFS;
799                                         goto out;
800                                 }
801                                 memcpy(response + *response_len, rsp, rsp_len);
802                                 *response_len += rsp_len;
803                                 (*answers)++;
804                                 err = 0;
805                         }
806                 }
807
808                 ptr = next;
809                 next = NULL;
810         }
811
812 out:
813         for (list = aliases; list; list = list->next)
814                 g_free(list->data);
815         g_slist_free(aliases);
816
817         return err;
818 }
819
820 struct cache_timeout {
821         time_t current_time;
822         int max_timeout;
823 };
824
825 static gboolean cache_check_entry(gpointer key, gpointer value,
826                                         gpointer user_data)
827 {
828         struct cache_timeout *data = user_data;
829         struct cache_entry *entry = value;
830         int max_timeout;
831
832         /*
833          * If either IPv4 or IPv6 cached entry has expired, we
834          * remove both from the cache.
835          */
836
837         if (entry->ipv4 != NULL && entry->ipv4->timeout > 0) {
838                 max_timeout = entry->ipv4->inserted + entry->ipv4->timeout;
839                 if (max_timeout > data->max_timeout)
840                         data->max_timeout = max_timeout;
841
842                 if (entry->ipv4->inserted + entry->ipv4->timeout
843                                                         < data->current_time)
844                         return TRUE;
845         }
846
847         if (entry->ipv6 != NULL && entry->ipv6->timeout > 0) {
848                 max_timeout = entry->ipv6->inserted + entry->ipv6->timeout;
849                 if (max_timeout > data->max_timeout)
850                         data->max_timeout = max_timeout;
851
852                 if (entry->ipv6->inserted + entry->ipv6->timeout
853                                                         < data->current_time)
854                         return TRUE;
855         }
856
857         return FALSE;
858 }
859
860 static void cache_cleanup(void)
861 {
862         static int max_timeout;
863         struct cache_timeout data;
864         int count;
865
866         data.current_time = time(0);
867         data.max_timeout = 0;
868
869         if (max_timeout > data.current_time) {
870                 DBG("waiting %ld secs before cleaning cache",
871                         max_timeout - data.current_time);
872                 return;
873         }
874
875         count = g_hash_table_foreach_remove(cache, cache_check_entry,
876                                                 &data);
877         DBG("removed %d", count);
878
879         if (count == 0)
880                 /*
881                  * If we could not remove anything, then remember
882                  * what is the max timeout and do nothing if we
883                  * have not yet reached it. This will prevent
884                  * constant traversal of the cache if it is full.
885                  */
886                 max_timeout = data.max_timeout;
887         else
888                 max_timeout = 0;
889 }
890
891 static int cache_update(struct server_data *srv, unsigned char *msg,
892                         unsigned int msg_len)
893 {
894         int offset = protocol_offset(srv->protocol);
895         int err, qlen, ttl = 0;
896         uint16_t answers, type = 0, class = 0;
897         struct domain_question *q;
898         struct cache_entry *entry;
899         struct cache_data *data;
900         char question[NS_MAXDNAME + 1];
901         unsigned char response[NS_MAXDNAME + 1];
902         unsigned char *ptr;
903         unsigned int rsplen;
904         gboolean new_entry = TRUE;
905         time_t current_time;
906
907         if (cache_size >= MAX_CACHE_SIZE) {
908                 cache_cleanup();
909                 if (cache_size >= MAX_CACHE_SIZE)
910                         return 0;
911         }
912
913         /* Continue only if response code is 0 (=ok) */
914         if (msg[3] & 0x0f)
915                 return 0;
916
917         if (offset < 0)
918                 return 0;
919
920         rsplen = sizeof(response) - 1;
921         question[sizeof(question) - 1] = '\0';
922
923         err = parse_response(msg + offset, msg_len - offset,
924                                 question, sizeof(question) - 1,
925                                 &type, &class, &ttl,
926                                 response, &rsplen, &answers);
927         if (err < 0 || ttl == 0)
928                 return 0;
929
930         qlen = strlen(question);
931         current_time = time(0);
932
933         /*
934          * If the cache contains already data, check if the
935          * type of the cached data is the same and do not add
936          * to cache if data is already there.
937          * This is needed so that we can cache both A and AAAA
938          * records for the same name.
939          */
940         entry = g_hash_table_lookup(cache, question);
941         if (entry == NULL) {
942                 entry = g_try_new(struct cache_entry, 1);
943                 if (entry == NULL)
944                         return -ENOMEM;
945
946                 data = g_try_new(struct cache_data, 1);
947                 if (data == NULL) {
948                         g_free(entry);
949                         return -ENOMEM;
950                 }
951
952                 entry->key = g_strdup(question);
953                 entry->ipv4 = entry->ipv6 = NULL;
954
955                 if (type == 1)
956                         entry->ipv4 = data;
957                 else
958                         entry->ipv6 = data;
959         } else {
960                 if (type == 1 && entry->ipv4 != NULL)
961                         return 0;
962
963                 if (type == 28 && entry->ipv6 != NULL)
964                         return 0;
965
966                 data = g_try_new(struct cache_data, 1);
967                 if (data == NULL)
968                         return -ENOMEM;
969
970                 if (type == 1)
971                         entry->ipv4 = data;
972                 else
973                         entry->ipv6 = data;
974
975                 new_entry = FALSE;
976         }
977
978         /*
979          * Restrict the cached DNS record TTL to some sane value
980          * in order to prevent data staying in the cache too long.
981          */
982         if (ttl > MAX_CACHE_TTL)
983                 ttl = MAX_CACHE_TTL;
984
985         data->inserted = current_time;
986         data->type = type;
987         data->answers = answers;
988         data->timeout = ttl;
989         data->data_len = 12 + qlen + 1 + 2 + 2 + rsplen;
990         data->data = ptr = g_malloc(data->data_len);
991         if (data->data == NULL) {
992                 g_free(entry->key);
993                 g_free(data);
994                 g_free(entry);
995                 return -ENOMEM;
996         }
997
998         memcpy(ptr, msg, 12);
999         memcpy(ptr + 12, question, qlen + 1); /* copy also the \0 */
1000
1001         q = (void *) (ptr + 12 + qlen + 1);
1002         q->type = htons(type);
1003         q->class = htons(class);
1004         memcpy(ptr + 12 + qlen + 1 + sizeof(struct domain_question),
1005                 response, rsplen);
1006
1007         if (new_entry == TRUE) {
1008                 g_hash_table_replace(cache, entry->key, entry);
1009                 cache_size++;
1010         }
1011
1012         DBG("cache %d %squestion \"%s\" type %d ttl %d size %zd",
1013                 cache_size, new_entry ? "new " : "old ",
1014                 question, type, ttl,
1015                 sizeof(*entry) + sizeof(*data) + data->data_len + qlen);
1016
1017         return 0;
1018 }
1019
1020 static int ns_resolv(struct server_data *server, struct request_data *req,
1021                                 gpointer request, gpointer name)
1022 {
1023         GList *list;
1024         int sk, err, type = 0;
1025         char *dot, *lookup = (char *) name;
1026         struct cache_entry *entry;
1027
1028         entry = cache_check(request, &type);
1029         if (entry != NULL) {
1030                 struct cache_data *data;
1031
1032                 DBG("cache hit %s type %s", lookup, type == 1 ? "A" : "AAAA");
1033                 if (type == 1)
1034                         data = entry->ipv4;
1035                 else
1036                         data = entry->ipv6;
1037
1038                 if (data != NULL && req->protocol == IPPROTO_TCP) {
1039                         send_cached_response(req->client_sk, data->data,
1040                                         data->data_len, NULL, 0, IPPROTO_TCP,
1041                                         req->srcid, data->answers);
1042                         return 1;
1043                 }
1044
1045                 if (data != NULL && req->protocol == IPPROTO_UDP) {
1046                         int sk;
1047                         sk = g_io_channel_unix_get_fd(
1048                                         req->ifdata->udp_listener_channel);
1049
1050                         send_cached_response(sk, data->data,
1051                                 data->data_len, &req->sa, req->sa_len,
1052                                 IPPROTO_UDP, req->srcid, data->answers);
1053                         return 1;
1054                 }
1055         }
1056
1057         sk = g_io_channel_unix_get_fd(server->channel);
1058
1059         err = send(sk, request, req->request_len, 0);
1060
1061         req->numserv++;
1062
1063         /* If we have more than one dot, we don't add domains */
1064         dot = strchr(lookup, '.');
1065         if (dot != NULL && dot != lookup + strlen(lookup) - 1)
1066                 return 0;
1067
1068         if (server->domains != NULL && server->domains->data != NULL)
1069                 req->append_domain = TRUE;
1070
1071         for (list = server->domains; list; list = list->next) {
1072                 char *domain;
1073                 unsigned char alt[1024];
1074                 struct domain_hdr *hdr = (void *) &alt;
1075                 int altlen, domlen, offset;
1076
1077                 domain = list->data;
1078
1079                 if (domain == NULL)
1080                         continue;
1081
1082                 offset = protocol_offset(server->protocol);
1083                 if (offset < 0)
1084                         return offset;
1085
1086                 domlen = strlen(domain) + 1;
1087                 if (domlen < 5)
1088                         return -EINVAL;
1089
1090                 alt[offset] = req->altid & 0xff;
1091                 alt[offset + 1] = req->altid >> 8;
1092
1093                 memcpy(alt + offset + 2, request + offset + 2, 10);
1094                 hdr->qdcount = htons(1);
1095
1096                 altlen = append_query(alt + offset + 12, sizeof(alt) - 12,
1097                                         name, domain);
1098                 if (altlen < 0)
1099                         return -EINVAL;
1100
1101                 altlen += 12;
1102
1103                 memcpy(alt + offset + altlen,
1104                         request + offset + altlen - domlen,
1105                                 req->request_len - altlen - offset + domlen);
1106
1107                 if (server->protocol == IPPROTO_TCP) {
1108                         int req_len = req->request_len + domlen - 2;
1109
1110                         alt[0] = (req_len >> 8) & 0xff;
1111                         alt[1] = req_len & 0xff;
1112                 }
1113
1114                 err = send(sk, alt, req->request_len + domlen, 0);
1115                 if (err < 0)
1116                         return -EIO;
1117
1118                 req->numserv++;
1119         }
1120
1121         return 0;
1122 }
1123
1124 static int forward_dns_reply(unsigned char *reply, int reply_len, int protocol,
1125                                 struct server_data *data)
1126 {
1127         struct domain_hdr *hdr;
1128         struct request_data *req;
1129         int dns_id, sk, err, offset = protocol_offset(protocol);
1130         struct listener_data *ifdata;
1131
1132         if (offset < 0)
1133                 return offset;
1134
1135         hdr = (void *)(reply + offset);
1136         dns_id = reply[offset] | reply[offset + 1] << 8;
1137
1138         DBG("Received %d bytes (id 0x%04x)", reply_len, dns_id);
1139
1140         req = find_request(dns_id);
1141         if (req == NULL)
1142                 return -EINVAL;
1143
1144         DBG("id 0x%04x rcode %d", hdr->id, hdr->rcode);
1145
1146         ifdata = req->ifdata;
1147
1148         reply[offset] = req->srcid & 0xff;
1149         reply[offset + 1] = req->srcid >> 8;
1150
1151         req->numresp++;
1152
1153         if (hdr->rcode == 0 || req->resp == NULL) {
1154
1155                 /*
1156                  * If the domain name was append
1157                  * remove it before forwarding the reply.
1158                  */
1159                 if (req->append_domain == TRUE) {
1160                         unsigned char *ptr;
1161                         uint8_t host_len;
1162                         unsigned int domain_len;
1163
1164                         /*
1165                          * ptr points to the first char of the hostname.
1166                          * ->hostname.domain.net
1167                          */
1168                         ptr = reply + offset + sizeof(struct domain_hdr);
1169                         host_len = *ptr;
1170                         domain_len = strlen((const char *)ptr) - host_len - 1;
1171
1172                         /*
1173                          * remove the domain name and replaced it by the end
1174                          * of reply.
1175                          */
1176                         memmove(ptr + host_len + 1,
1177                                 ptr + host_len + domain_len + 1,
1178                                 reply_len - (ptr - reply + domain_len));
1179
1180                         reply_len = reply_len - domain_len;
1181                 }
1182
1183                 g_free(req->resp);
1184                 req->resplen = 0;
1185
1186                 req->resp = g_try_malloc(reply_len);
1187                 if (req->resp == NULL)
1188                         return -ENOMEM;
1189
1190                 memcpy(req->resp, reply, reply_len);
1191                 req->resplen = reply_len;
1192
1193                 cache_update(data, reply, reply_len);
1194         }
1195
1196         if (hdr->rcode > 0 && req->numresp < req->numserv)
1197                 return -EINVAL;
1198
1199         if (req->timeout > 0)
1200                 g_source_remove(req->timeout);
1201
1202         request_list = g_slist_remove(request_list, req);
1203
1204         if (protocol == IPPROTO_UDP) {
1205                 sk = g_io_channel_unix_get_fd(ifdata->udp_listener_channel);
1206                 err = sendto(sk, req->resp, req->resplen, 0,
1207                              &req->sa, req->sa_len);
1208         } else {
1209                 sk = req->client_sk;
1210                 err = send(sk, req->resp, req->resplen, 0);
1211                 close(sk);
1212         }
1213
1214         g_free(req->resp);
1215         g_free(req);
1216
1217         return err;
1218 }
1219
1220 static void cache_element_destroy(gpointer value)
1221 {
1222         struct cache_entry *entry = value;
1223
1224         if (entry == NULL)
1225                 return;
1226
1227         if (entry->ipv4 != NULL) {
1228                 g_free(entry->ipv4->data);
1229                 g_free(entry->ipv4);
1230         }
1231
1232         if (entry->ipv6 != NULL) {
1233                 g_free(entry->ipv6->data);
1234                 g_free(entry->ipv6);
1235         }
1236
1237         g_free(entry->key);
1238         g_free(entry);
1239
1240         if (--cache_size < 0)
1241                 cache_size = 0;
1242 }
1243
1244 static void destroy_server(struct server_data *server)
1245 {
1246         GList *list;
1247
1248         DBG("interface %s server %s", server->interface, server->server);
1249
1250         server_list = g_slist_remove(server_list, server);
1251
1252         if (server->watch > 0)
1253                 g_source_remove(server->watch);
1254
1255         if (server->timeout > 0)
1256                 g_source_remove(server->timeout);
1257
1258         g_io_channel_unref(server->channel);
1259
1260         if (server->protocol == IPPROTO_UDP)
1261                 connman_info("Removing DNS server %s", server->server);
1262
1263         g_free(server->incoming_reply);
1264         g_free(server->server);
1265         for (list = server->domains; list; list = list->next) {
1266                 char *domain = list->data;
1267
1268                 server->domains = g_list_remove(server->domains, domain);
1269                 g_free(domain);
1270         }
1271         g_free(server->interface);
1272
1273         if (__sync_fetch_and_sub(&cache_refcount, 1) == 1)
1274                 g_hash_table_destroy(cache);
1275
1276         g_free(server);
1277 }
1278
1279 static gboolean udp_server_event(GIOChannel *channel, GIOCondition condition,
1280                                                         gpointer user_data)
1281 {
1282         unsigned char buf[4096];
1283         int sk, err, len;
1284         struct server_data *data = user_data;
1285
1286         if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
1287                 connman_error("Error with UDP server %s", data->server);
1288                 data->watch = 0;
1289                 return FALSE;
1290         }
1291
1292         sk = g_io_channel_unix_get_fd(channel);
1293
1294         len = recv(sk, buf, sizeof(buf), 0);
1295         if (len < 12)
1296                 return TRUE;
1297
1298         err = forward_dns_reply(buf, len, IPPROTO_UDP, data);
1299         if (err < 0)
1300                 return TRUE;
1301
1302         return TRUE;
1303 }
1304
1305 static gboolean tcp_server_event(GIOChannel *channel, GIOCondition condition,
1306                                                         gpointer user_data)
1307 {
1308         int sk;
1309         struct server_data *server = user_data;
1310
1311         sk = g_io_channel_unix_get_fd(channel);
1312         if (sk == 0)
1313                 return FALSE;
1314
1315         if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
1316                 GSList *list;
1317 hangup:
1318                 DBG("TCP server channel closed");
1319
1320                 /*
1321                  * Discard any partial response which is buffered; better
1322                  * to get a proper response from a working server.
1323                  */
1324                 g_free(server->incoming_reply);
1325                 server->incoming_reply = NULL;
1326
1327                 for (list = request_list; list; list = list->next) {
1328                         struct request_data *req = list->data;
1329                         struct domain_hdr *hdr;
1330
1331                         if (req->protocol == IPPROTO_UDP)
1332                                 continue;
1333
1334                         if (req->request == NULL)
1335                                 continue;
1336
1337                         /*
1338                          * If we're not waiting for any further response
1339                          * from another name server, then we send an error
1340                          * response to the client.
1341                          */
1342                         if (req->numserv && --(req->numserv))
1343                                 continue;
1344
1345                         hdr = (void *) (req->request + 2);
1346                         hdr->id = req->srcid;
1347                         send_response(req->client_sk, req->request,
1348                                 req->request_len, NULL, 0, IPPROTO_TCP);
1349
1350                         request_list = g_slist_remove(request_list, req);
1351                 }
1352
1353                 destroy_server(server);
1354
1355                 return FALSE;
1356         }
1357
1358         if ((condition & G_IO_OUT) && !server->connected) {
1359                 GSList *list;
1360                 GList *domains;
1361                 struct server_data *udp_server;
1362
1363                 udp_server = find_server(server->interface, server->server,
1364                                                                 IPPROTO_UDP);
1365                 if (udp_server != NULL) {
1366                         for (domains = udp_server->domains; domains;
1367                                                 domains = domains->next) {
1368                                 char *dom = domains->data;
1369
1370                                 DBG("Adding domain %s to %s",
1371                                                 dom, server->server);
1372
1373                                 server->domains = g_list_append(server->domains,
1374                                                                 g_strdup(dom));
1375                         }
1376                 }
1377
1378                 server->connected = TRUE;
1379                 server_list = g_slist_append(server_list, server);
1380
1381                 if (server->timeout > 0) {
1382                         g_source_remove(server->timeout);
1383                         server->timeout = 0;
1384                 }
1385
1386                 for (list = request_list; list; list = list->next) {
1387                         struct request_data *req = list->data;
1388
1389                         if (req->protocol == IPPROTO_UDP)
1390                                 continue;
1391
1392                         DBG("Sending req %s over TCP", (char *)req->name);
1393
1394                         if (req->timeout > 0)
1395                                 g_source_remove(req->timeout);
1396
1397                         req->timeout = g_timeout_add_seconds(30,
1398                                                 request_timeout, req);
1399                         if (ns_resolv(server, req, req->request,
1400                                         req->name) > 0) {
1401                                 /* We sent cached result so no need for timeout
1402                                  * handler.
1403                                  */
1404                                 if (req->timeout > 0) {
1405                                         g_source_remove(req->timeout);
1406                                         req->timeout = 0;
1407                                 }
1408                         }
1409                 }
1410
1411         } else if (condition & G_IO_IN) {
1412                 struct partial_reply *reply = server->incoming_reply;
1413                 int bytes_recv;
1414
1415                 if (!reply) {
1416                         unsigned char reply_len_buf[2];
1417                         uint16_t reply_len;
1418
1419                         bytes_recv = recv(sk, reply_len_buf, 2, MSG_PEEK);
1420                         if (!bytes_recv) {
1421                                 goto hangup;
1422                         } else if (bytes_recv < 0) {
1423                                 if (errno == EAGAIN || errno == EWOULDBLOCK)
1424                                         return TRUE;
1425
1426                                 connman_error("DNS proxy error %s",
1427                                                 strerror(errno));
1428                                 goto hangup;
1429                         } else if (bytes_recv < 2)
1430                                 return TRUE;
1431
1432                         reply_len = reply_len_buf[1] | reply_len_buf[0] << 8;
1433                         reply_len += 2;
1434
1435                         DBG("TCP reply %d bytes", reply_len);
1436
1437                         reply = g_try_malloc(sizeof(*reply) + reply_len + 2);
1438                         if (!reply)
1439                                 return TRUE;
1440
1441                         reply->len = reply_len;
1442                         reply->received = 0;
1443
1444                         server->incoming_reply = reply;
1445                 }
1446
1447                 while (reply->received < reply->len) {
1448                         bytes_recv = recv(sk, reply->buf + reply->received,
1449                                         reply->len - reply->received, 0);
1450                         if (!bytes_recv) {
1451                                 connman_error("DNS proxy TCP disconnect");
1452                                 break;
1453                         } else if (bytes_recv < 0) {
1454                                 if (errno == EAGAIN || errno == EWOULDBLOCK)
1455                                         return TRUE;
1456
1457                                 connman_error("DNS proxy error %s",
1458                                                 strerror(errno));
1459                                 break;
1460                         }
1461                         reply->received += bytes_recv;
1462                 }
1463
1464                 forward_dns_reply(reply->buf, reply->received, IPPROTO_TCP,
1465                                         server);
1466
1467                 g_free(reply);
1468                 server->incoming_reply = NULL;
1469
1470                 destroy_server(server);
1471
1472                 return FALSE;
1473         }
1474
1475         return TRUE;
1476 }
1477
1478 static gboolean tcp_idle_timeout(gpointer user_data)
1479 {
1480         struct server_data *server = user_data;
1481
1482         DBG("");
1483
1484         if (server == NULL)
1485                 return FALSE;
1486
1487         destroy_server(server);
1488
1489         return FALSE;
1490 }
1491
1492 static struct server_data *create_server(const char *interface,
1493                                         const char *domain, const char *server,
1494                                         int protocol)
1495 {
1496         struct addrinfo hints, *rp;
1497         struct server_data *data;
1498         int sk, ret;
1499
1500         DBG("interface %s server %s", interface, server);
1501
1502         memset(&hints, 0, sizeof(hints));
1503
1504         switch (protocol) {
1505         case IPPROTO_UDP:
1506                 hints.ai_socktype = SOCK_DGRAM;
1507                 break;
1508
1509         case IPPROTO_TCP:
1510                 hints.ai_socktype = SOCK_STREAM;
1511                 break;
1512
1513         default:
1514                 return NULL;
1515         }
1516         hints.ai_family = AF_UNSPEC;
1517         hints.ai_flags = AI_PASSIVE | AI_NUMERICSERV | AI_NUMERICHOST;
1518
1519         ret = getaddrinfo(server, "53", &hints, &rp);
1520         if (ret) {
1521                 connman_error("Failed to parse server %s address: %s\n",
1522                               server, gai_strerror(ret));
1523                 return NULL;
1524         }
1525         /* Do not blindly copy this code elsewhere; it doesn't loop over the
1526            results using ->ai_next as it should. That's OK in *this* case
1527            because it was a numeric lookup; we *know* there's only one. */
1528
1529         sk = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
1530         if (sk < 0) {
1531                 connman_error("Failed to create server %s socket", server);
1532                 freeaddrinfo(rp);
1533                 return NULL;
1534         }
1535
1536         if (interface != NULL) {
1537                 if (setsockopt(sk, SOL_SOCKET, SO_BINDTODEVICE,
1538                                 interface, strlen(interface) + 1) < 0) {
1539                         connman_error("Failed to bind server %s "
1540                                                 "to interface %s",
1541                                                         server, interface);
1542                         freeaddrinfo(rp);
1543                         close(sk);
1544                         return NULL;
1545                 }
1546         }
1547
1548         data = g_try_new0(struct server_data, 1);
1549         if (data == NULL) {
1550                 connman_error("Failed to allocate server %s data", server);
1551                 freeaddrinfo(rp);
1552                 close(sk);
1553                 return NULL;
1554         }
1555
1556         data->channel = g_io_channel_unix_new(sk);
1557         if (data->channel == NULL) {
1558                 connman_error("Failed to create server %s channel", server);
1559                 freeaddrinfo(rp);
1560                 close(sk);
1561                 g_free(data);
1562                 return NULL;
1563         }
1564
1565         g_io_channel_set_close_on_unref(data->channel, TRUE);
1566
1567         if (protocol == IPPROTO_TCP) {
1568                 g_io_channel_set_flags(data->channel, G_IO_FLAG_NONBLOCK, NULL);
1569                 data->watch = g_io_add_watch(data->channel,
1570                         G_IO_OUT | G_IO_IN | G_IO_HUP | G_IO_NVAL | G_IO_ERR,
1571                                                 tcp_server_event, data);
1572                 data->timeout = g_timeout_add_seconds(30, tcp_idle_timeout,
1573                                                                 data);
1574         } else
1575                 data->watch = g_io_add_watch(data->channel,
1576                         G_IO_IN | G_IO_NVAL | G_IO_ERR | G_IO_HUP,
1577                                                 udp_server_event, data);
1578
1579         data->interface = g_strdup(interface);
1580         if (domain)
1581                 data->domains = g_list_append(data->domains, g_strdup(domain));
1582         data->server = g_strdup(server);
1583         data->protocol = protocol;
1584
1585         ret = connect(sk, rp->ai_addr, rp->ai_addrlen);
1586         freeaddrinfo(rp);
1587         if (ret < 0) {
1588                 if ((protocol == IPPROTO_TCP && errno != EINPROGRESS) ||
1589                                 protocol == IPPROTO_UDP) {
1590                         GList *list;
1591
1592                         connman_error("Failed to connect to server %s", server);
1593                         if (data->watch > 0)
1594                                 g_source_remove(data->watch);
1595                         if (data->timeout > 0)
1596                                 g_source_remove(data->timeout);
1597
1598                         g_io_channel_unref(data->channel);
1599                         close(sk);
1600
1601                         g_free(data->server);
1602                         g_free(data->interface);
1603                         for (list = data->domains; list; list = list->next) {
1604                                 char *domain = list->data;
1605
1606                                 data->domains = g_list_remove(data->domains,
1607                                                                         domain);
1608                                 g_free(domain);
1609                         }
1610                         g_free(data);
1611                         return NULL;
1612                 }
1613         }
1614
1615         if (__sync_fetch_and_add(&cache_refcount, 1) == 0)
1616                 cache = g_hash_table_new_full(g_str_hash,
1617                                         g_str_equal,
1618                                         NULL,
1619                                         cache_element_destroy);
1620
1621         if (protocol == IPPROTO_UDP) {
1622                 /* Enable new servers by default */
1623                 data->enabled = TRUE;
1624                 connman_info("Adding DNS server %s", data->server);
1625
1626                 server_list = g_slist_append(server_list, data);
1627
1628                 return data;
1629         }
1630
1631         return NULL;
1632 }
1633
1634 static gboolean resolv(struct request_data *req,
1635                                 gpointer request, gpointer name)
1636 {
1637         GSList *list;
1638         int status;
1639
1640         for (list = server_list; list; list = list->next) {
1641                 struct server_data *data = list->data;
1642
1643                 DBG("server %s enabled %d", data->server, data->enabled);
1644
1645                 if (data->enabled == FALSE)
1646                         continue;
1647
1648                 if (data->watch == 0 && data->protocol == IPPROTO_UDP)
1649                         data->watch = g_io_add_watch(data->channel,
1650                                 G_IO_IN | G_IO_NVAL | G_IO_ERR | G_IO_HUP,
1651                                                 udp_server_event, data);
1652
1653                 status = ns_resolv(data, req, request, name);
1654                 if (status < 0)
1655                         continue;
1656
1657                 if (status > 0) {
1658                         if (req->timeout > 0) {
1659                                 g_source_remove(req->timeout);
1660                                 req->timeout = 0;
1661                         }
1662                 }
1663         }
1664
1665         return TRUE;
1666 }
1667
1668 static void append_domain(const char *interface, const char *domain)
1669 {
1670         GSList *list;
1671
1672         DBG("interface %s domain %s", interface, domain);
1673
1674         if (domain == NULL)
1675                 return;
1676
1677         for (list = server_list; list; list = list->next) {
1678                 struct server_data *data = list->data;
1679                 GList *dom_list;
1680                 char *dom;
1681                 gboolean dom_found = FALSE;
1682
1683                 if (data->interface == NULL)
1684                         continue;
1685
1686                 if (g_str_equal(data->interface, interface) == FALSE)
1687                         continue;
1688
1689                 for (dom_list = data->domains; dom_list;
1690                                 dom_list = dom_list->next) {
1691                         dom = dom_list->data;
1692
1693                         if (g_str_equal(dom, domain)) {
1694                                 dom_found = TRUE;
1695                                 break;
1696                         }
1697                 }
1698
1699                 if (dom_found == FALSE) {
1700                         data->domains =
1701                                 g_list_append(data->domains, g_strdup(domain));
1702                 }
1703         }
1704 }
1705
1706 int __connman_dnsproxy_append(const char *interface, const char *domain,
1707                                                         const char *server)
1708 {
1709         struct server_data *data;
1710
1711         DBG("interface %s server %s", interface, server);
1712
1713         if (server == NULL && domain == NULL)
1714                 return -EINVAL;
1715
1716         if (server == NULL) {
1717                 append_domain(interface, domain);
1718
1719                 return 0;
1720         }
1721
1722         if (g_str_equal(server, "127.0.0.1") == TRUE)
1723                 return -ENODEV;
1724
1725         data = find_server(interface, server, IPPROTO_UDP);
1726         if (data != NULL) {
1727                 append_domain(interface, domain);
1728                 return 0;
1729         }
1730
1731         data = create_server(interface, domain, server, IPPROTO_UDP);
1732         if (data == NULL)
1733                 return -EIO;
1734
1735         return 0;
1736 }
1737
1738 static void remove_server(const char *interface, const char *domain,
1739                         const char *server, int protocol)
1740 {
1741         struct server_data *data;
1742
1743         data = find_server(interface, server, protocol);
1744         if (data == NULL)
1745                 return;
1746
1747         destroy_server(data);
1748 }
1749
1750 int __connman_dnsproxy_remove(const char *interface, const char *domain,
1751                                                         const char *server)
1752 {
1753         DBG("interface %s server %s", interface, server);
1754
1755         if (server == NULL)
1756                 return -EINVAL;
1757
1758         if (g_str_equal(server, "127.0.0.1") == TRUE)
1759                 return -ENODEV;
1760
1761         remove_server(interface, domain, server, IPPROTO_UDP);
1762         remove_server(interface, domain, server, IPPROTO_TCP);
1763
1764         return 0;
1765 }
1766
1767 void __connman_dnsproxy_flush(void)
1768 {
1769         GSList *list;
1770
1771         list = request_pending_list;
1772         while (list) {
1773                 struct request_data *req = list->data;
1774
1775                 list = list->next;
1776
1777                 request_pending_list =
1778                                 g_slist_remove(request_pending_list, req);
1779                 resolv(req, req->request, req->name);
1780                 g_free(req->request);
1781                 g_free(req->name);
1782         }
1783 }
1784
1785 static void dnsproxy_offline_mode(connman_bool_t enabled)
1786 {
1787         GSList *list;
1788
1789         DBG("enabled %d", enabled);
1790
1791         for (list = server_list; list; list = list->next) {
1792                 struct server_data *data = list->data;
1793
1794                 if (enabled == FALSE) {
1795                         connman_info("Enabling DNS server %s", data->server);
1796                         data->enabled = TRUE;
1797                 } else {
1798                         connman_info("Disabling DNS server %s", data->server);
1799                         data->enabled = FALSE;
1800                 }
1801         }
1802 }
1803
1804 static void dnsproxy_default_changed(struct connman_service *service)
1805 {
1806         GSList *list;
1807         char *interface;
1808
1809         DBG("service %p", service);
1810
1811         if (service == NULL) {
1812                 /* When no services are active, then disable DNS proxying */
1813                 dnsproxy_offline_mode(TRUE);
1814                 return;
1815         }
1816
1817         interface = connman_service_get_interface(service);
1818         if (interface == NULL)
1819                 return;
1820
1821         for (list = server_list; list; list = list->next) {
1822                 struct server_data *data = list->data;
1823
1824                 if (g_strcmp0(data->interface, interface) == 0) {
1825                         connman_info("Enabling DNS server %s", data->server);
1826                         data->enabled = TRUE;
1827                 } else {
1828                         connman_info("Disabling DNS server %s", data->server);
1829                         data->enabled = FALSE;
1830                 }
1831         }
1832
1833         g_free(interface);
1834 }
1835
1836 static struct connman_notifier dnsproxy_notifier = {
1837         .name                   = "dnsproxy",
1838         .default_changed        = dnsproxy_default_changed,
1839         .offline_mode           = dnsproxy_offline_mode,
1840 };
1841
1842 static unsigned char opt_edns0_type[2] = { 0x00, 0x29 };
1843
1844 static int parse_request(unsigned char *buf, int len,
1845                                         char *name, unsigned int size)
1846 {
1847         struct domain_hdr *hdr = (void *) buf;
1848         uint16_t qdcount = ntohs(hdr->qdcount);
1849         uint16_t arcount = ntohs(hdr->arcount);
1850         unsigned char *ptr;
1851         char *last_label = NULL;
1852         unsigned int remain, used = 0;
1853
1854         if (len < 12)
1855                 return -EINVAL;
1856
1857         DBG("id 0x%04x qr %d opcode %d qdcount %d arcount %d",
1858                                         hdr->id, hdr->qr, hdr->opcode,
1859                                                         qdcount, arcount);
1860
1861         if (hdr->qr != 0 || qdcount != 1)
1862                 return -EINVAL;
1863
1864         memset(name, 0, size);
1865
1866         ptr = buf + sizeof(struct domain_hdr);
1867         remain = len - sizeof(struct domain_hdr);
1868
1869         while (remain > 0) {
1870                 uint8_t len = *ptr;
1871
1872                 if (len == 0x00) {
1873                         last_label = (char *) (ptr + 1);
1874                         break;
1875                 }
1876
1877                 if (used + len + 1 > size)
1878                         return -ENOBUFS;
1879
1880                 strncat(name, (char *) (ptr + 1), len);
1881                 strcat(name, ".");
1882
1883                 used += len + 1;
1884
1885                 ptr += len + 1;
1886                 remain -= len + 1;
1887         }
1888
1889         if (last_label && arcount && remain >= 9 && last_label[4] == 0 &&
1890                                 !memcmp(last_label + 5, opt_edns0_type, 2)) {
1891                 uint16_t edns0_bufsize;
1892
1893                 edns0_bufsize = last_label[7] << 8 | last_label[8];
1894
1895                 DBG("EDNS0 buffer size %u", edns0_bufsize);
1896
1897                 /* This is an evil hack until full TCP support has been
1898                  * implemented.
1899                  *
1900                  * Somtimes the EDNS0 request gets send with a too-small
1901                  * buffer size. Since glibc doesn't seem to crash when it
1902                  * gets a response biffer then it requested, just bump
1903                  * the buffer size up to 4KiB.
1904                  */
1905                 if (edns0_bufsize < 0x1000) {
1906                         last_label[7] = 0x10;
1907                         last_label[8] = 0x00;
1908                 }
1909         }
1910
1911         DBG("query %s", name);
1912
1913         return 0;
1914 }
1915
1916 static gboolean tcp_listener_event(GIOChannel *channel, GIOCondition condition,
1917                                                         gpointer user_data)
1918 {
1919         unsigned char buf[768];
1920         char query[512];
1921         struct request_data *req;
1922         struct server_data *server;
1923         int sk, client_sk, len, err;
1924         struct sockaddr_in6 client_addr;
1925         socklen_t client_addr_len = sizeof(client_addr);
1926         GSList *list;
1927         struct listener_data *ifdata = user_data;
1928
1929         DBG("condition 0x%x", condition);
1930
1931         if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
1932                 if (ifdata->tcp_listener_watch > 0)
1933                         g_source_remove(ifdata->tcp_listener_watch);
1934                 ifdata->tcp_listener_watch = 0;
1935
1936                 connman_error("Error with TCP listener channel");
1937
1938                 return FALSE;
1939         }
1940
1941         sk = g_io_channel_unix_get_fd(channel);
1942
1943         client_sk = accept(sk, (void *)&client_addr, &client_addr_len);
1944         if (client_sk < 0) {
1945                 connman_error("Accept failure on TCP listener");
1946                 ifdata->tcp_listener_watch = 0;
1947                 return FALSE;
1948         }
1949
1950         len = recv(client_sk, buf, sizeof(buf), 0);
1951         if (len < 2)
1952                 return TRUE;
1953
1954         DBG("Received %d bytes (id 0x%04x)", len, buf[2] | buf[3] << 8);
1955
1956         err = parse_request(buf + 2, len - 2, query, sizeof(query));
1957         if (err < 0 || (g_slist_length(server_list) == 0)) {
1958                 send_response(client_sk, buf, len, NULL, 0, IPPROTO_TCP);
1959                 return TRUE;
1960         }
1961
1962         req = g_try_new0(struct request_data, 1);
1963         if (req == NULL)
1964                 return TRUE;
1965
1966         memcpy(&req->sa, &client_addr, client_addr_len);
1967         req->sa_len = client_addr_len;
1968         req->client_sk = client_sk;
1969         req->protocol = IPPROTO_TCP;
1970
1971         request_id += 2;
1972         if (request_id == 0x0000 || request_id == 0xffff)
1973                 request_id += 2;
1974
1975         req->srcid = buf[2] | (buf[3] << 8);
1976         req->dstid = request_id;
1977         req->altid = request_id + 1;
1978         req->request_len = len;
1979
1980         buf[2] = req->dstid & 0xff;
1981         buf[3] = req->dstid >> 8;
1982
1983         req->numserv = 0;
1984         req->ifdata = (struct listener_data *) ifdata;
1985         req->append_domain = FALSE;
1986         request_list = g_slist_append(request_list, req);
1987
1988         for (list = server_list; list; list = list->next) {
1989                 struct server_data *data = list->data;
1990                 GList *domains;
1991
1992                 if (data->protocol != IPPROTO_UDP || data->enabled == FALSE)
1993                         continue;
1994
1995                 server = create_server(data->interface, NULL,
1996                                         data->server, IPPROTO_TCP);
1997
1998                 /*
1999                  * If server is NULL, we're not connected yet.
2000                  * Copy the relevant buffers and continue with
2001                  * the next nameserver.
2002                  * The request will actually be sent once we're
2003                  * properly connected over TCP to this nameserver.
2004                  */
2005                 if (server == NULL) {
2006                         req->request = g_try_malloc0(req->request_len);
2007                         if (req->request == NULL)
2008                                 return TRUE;
2009
2010                         memcpy(req->request, buf, req->request_len);
2011
2012                         req->name = g_try_malloc0(sizeof(query));
2013                         if (req->name == NULL) {
2014                                 g_free(req->request);
2015                                 return TRUE;
2016                         }
2017                         memcpy(req->name, query, sizeof(query));
2018
2019                         continue;
2020                 }
2021
2022                 if (req->timeout > 0)
2023                         g_source_remove(req->timeout);
2024
2025                 for (domains = data->domains; domains;
2026                                 domains = domains->next) {
2027                         char *dom = domains->data;
2028
2029                         DBG("Adding domain %s to %s", dom, server->server);
2030
2031                         server->domains = g_list_append(server->domains,
2032                                                 g_strdup(dom));
2033                 }
2034
2035                 req->timeout = g_timeout_add_seconds(30, request_timeout, req);
2036                 if (ns_resolv(server, req, buf, query) > 0) {
2037                         if (req->timeout > 0) {
2038                                 g_source_remove(req->timeout);
2039                                 req->timeout = 0;
2040                         }
2041                 }
2042         }
2043
2044         return TRUE;
2045 }
2046
2047 static gboolean udp_listener_event(GIOChannel *channel, GIOCondition condition,
2048                                                         gpointer user_data)
2049 {
2050         unsigned char buf[768];
2051         char query[512];
2052         struct request_data *req;
2053         struct sockaddr_in6 client_addr;
2054         socklen_t client_addr_len = sizeof(client_addr);
2055         int sk, err, len;
2056         struct listener_data *ifdata = user_data;
2057
2058         if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
2059                 connman_error("Error with UDP listener channel");
2060                 ifdata->udp_listener_watch = 0;
2061                 return FALSE;
2062         }
2063
2064         sk = g_io_channel_unix_get_fd(channel);
2065
2066         memset(&client_addr, 0, client_addr_len);
2067         len = recvfrom(sk, buf, sizeof(buf), 0, (void *)&client_addr,
2068                        &client_addr_len);
2069         if (len < 2)
2070                 return TRUE;
2071
2072         DBG("Received %d bytes (id 0x%04x)", len, buf[0] | buf[1] << 8);
2073
2074         err = parse_request(buf, len, query, sizeof(query));
2075         if (err < 0 || (g_slist_length(server_list) == 0)) {
2076                 send_response(sk, buf, len, (void *)&client_addr,
2077                                 client_addr_len, IPPROTO_UDP);
2078                 return TRUE;
2079         }
2080
2081         req = g_try_new0(struct request_data, 1);
2082         if (req == NULL)
2083                 return TRUE;
2084
2085         memcpy(&req->sa, &client_addr, client_addr_len);
2086         req->sa_len = client_addr_len;
2087         req->client_sk = 0;
2088         req->protocol = IPPROTO_UDP;
2089
2090         request_id += 2;
2091         if (request_id == 0x0000 || request_id == 0xffff)
2092                 request_id += 2;
2093
2094         req->srcid = buf[0] | (buf[1] << 8);
2095         req->dstid = request_id;
2096         req->altid = request_id + 1;
2097         req->request_len = len;
2098
2099         buf[0] = req->dstid & 0xff;
2100         buf[1] = req->dstid >> 8;
2101
2102         req->numserv = 0;
2103         req->ifdata = (struct listener_data *) ifdata;
2104         req->timeout = g_timeout_add_seconds(5, request_timeout, req);
2105         req->append_domain = FALSE;
2106         request_list = g_slist_append(request_list, req);
2107
2108         return resolv(req, buf, query);
2109 }
2110
2111 static int create_dns_listener(int protocol, struct listener_data *ifdata)
2112 {
2113         GIOChannel *channel;
2114         const char *proto;
2115         union {
2116                 struct sockaddr sa;
2117                 struct sockaddr_in6 sin6;
2118                 struct sockaddr_in sin;
2119         } s;
2120         socklen_t slen;
2121         int sk, type, v6only = 0;
2122         int family = AF_INET6;
2123
2124
2125         DBG("interface %s", ifdata->ifname);
2126
2127         switch (protocol) {
2128         case IPPROTO_UDP:
2129                 proto = "UDP";
2130                 type = SOCK_DGRAM | SOCK_CLOEXEC;
2131                 break;
2132
2133         case IPPROTO_TCP:
2134                 proto = "TCP";
2135                 type = SOCK_STREAM | SOCK_CLOEXEC;
2136                 break;
2137
2138         default:
2139                 return -EINVAL;
2140         }
2141
2142         sk = socket(family, type, protocol);
2143         if (sk < 0 && family == AF_INET6 && errno == EAFNOSUPPORT) {
2144                 connman_error("No IPv6 support; DNS proxy listening only on Legacy IP");
2145                 family = AF_INET;
2146                 sk = socket(family, type, protocol);
2147         }
2148         if (sk < 0) {
2149                 connman_error("Failed to create %s listener socket", proto);
2150                 return -EIO;
2151         }
2152
2153         if (setsockopt(sk, SOL_SOCKET, SO_BINDTODEVICE,
2154                                         ifdata->ifname,
2155                                         strlen(ifdata->ifname) + 1) < 0) {
2156                 connman_error("Failed to bind %s listener interface", proto);
2157                 close(sk);
2158                 return -EIO;
2159         }
2160         /* Ensure it accepts Legacy IP connections too */
2161         if (family == AF_INET6 &&
2162                         setsockopt(sk, SOL_IPV6, IPV6_V6ONLY,
2163                                         &v6only, sizeof(v6only)) < 0) {
2164                 connman_error("Failed to clear V6ONLY on %s listener socket",
2165                               proto);
2166                 close(sk);
2167                 return -EIO;
2168         }
2169
2170         if (family == AF_INET) {
2171                 memset(&s.sin, 0, sizeof(s.sin));
2172                 s.sin.sin_family = AF_INET;
2173                 s.sin.sin_port = htons(53);
2174                 s.sin.sin_addr.s_addr = htonl(INADDR_ANY);
2175                 slen = sizeof(s.sin);
2176         } else {
2177                 memset(&s.sin6, 0, sizeof(s.sin6));
2178                 s.sin6.sin6_family = AF_INET6;
2179                 s.sin6.sin6_port = htons(53);
2180                 s.sin6.sin6_addr = in6addr_any;
2181                 slen = sizeof(s.sin6);
2182         }
2183
2184         if (bind(sk, &s.sa, slen) < 0) {
2185                 connman_error("Failed to bind %s listener socket", proto);
2186                 close(sk);
2187                 return -EIO;
2188         }
2189
2190         if (protocol == IPPROTO_TCP && listen(sk, 10) < 0) {
2191                 connman_error("Failed to listen on TCP socket");
2192                 close(sk);
2193                 return -EIO;
2194         }
2195
2196         channel = g_io_channel_unix_new(sk);
2197         if (channel == NULL) {
2198                 connman_error("Failed to create %s listener channel", proto);
2199                 close(sk);
2200                 return -EIO;
2201         }
2202
2203         g_io_channel_set_close_on_unref(channel, TRUE);
2204
2205         if (protocol == IPPROTO_TCP) {
2206                 ifdata->tcp_listener_channel = channel;
2207                 ifdata->tcp_listener_watch = g_io_add_watch(channel,
2208                                 G_IO_IN, tcp_listener_event, (gpointer) ifdata);
2209         } else {
2210                 ifdata->udp_listener_channel = channel;
2211                 ifdata->udp_listener_watch = g_io_add_watch(channel,
2212                                 G_IO_IN, udp_listener_event, (gpointer) ifdata);
2213         }
2214
2215         return 0;
2216 }
2217
2218 static void destroy_udp_listener(struct listener_data *ifdata)
2219 {
2220         DBG("interface %s", ifdata->ifname);
2221
2222         if (ifdata->udp_listener_watch > 0)
2223                 g_source_remove(ifdata->udp_listener_watch);
2224
2225         g_io_channel_unref(ifdata->udp_listener_channel);
2226 }
2227
2228 static void destroy_tcp_listener(struct listener_data *ifdata)
2229 {
2230         DBG("interface %s", ifdata->ifname);
2231
2232         if (ifdata->tcp_listener_watch > 0)
2233                 g_source_remove(ifdata->tcp_listener_watch);
2234
2235         g_io_channel_unref(ifdata->tcp_listener_channel);
2236 }
2237
2238 static int create_listener(struct listener_data *ifdata)
2239 {
2240         int err;
2241
2242         err = create_dns_listener(IPPROTO_UDP, ifdata);
2243         if (err < 0)
2244                 return err;
2245
2246         err = create_dns_listener(IPPROTO_TCP, ifdata);
2247         if (err < 0) {
2248                 destroy_udp_listener(ifdata);
2249                 return err;
2250         }
2251
2252         if (g_strcmp0(ifdata->ifname, "lo") == 0)
2253                 __connman_resolvfile_append("lo", NULL, "127.0.0.1");
2254
2255         return 0;
2256 }
2257
2258 static void destroy_listener(struct listener_data *ifdata)
2259 {
2260         GSList *list;
2261
2262         if (g_strcmp0(ifdata->ifname, "lo") == 0)
2263                 __connman_resolvfile_remove("lo", NULL, "127.0.0.1");
2264
2265         for (list = request_pending_list; list; list = list->next) {
2266                 struct request_data *req = list->data;
2267
2268                 DBG("Dropping pending request (id 0x%04x -> 0x%04x)",
2269                                                 req->srcid, req->dstid);
2270
2271                 g_free(req->resp);
2272                 g_free(req->request);
2273                 g_free(req->name);
2274                 g_free(req);
2275                 list->data = NULL;
2276         }
2277
2278         g_slist_free(request_pending_list);
2279         request_pending_list = NULL;
2280
2281         for (list = request_list; list; list = list->next) {
2282                 struct request_data *req = list->data;
2283
2284                 DBG("Dropping request (id 0x%04x -> 0x%04x)",
2285                                                 req->srcid, req->dstid);
2286
2287                 g_free(req->resp);
2288                 g_free(req->request);
2289                 g_free(req->name);
2290                 g_free(req);
2291                 list->data = NULL;
2292         }
2293
2294         g_slist_free(request_list);
2295         request_list = NULL;
2296
2297         destroy_tcp_listener(ifdata);
2298         destroy_udp_listener(ifdata);
2299 }
2300
2301 int __connman_dnsproxy_add_listener(const char *interface)
2302 {
2303         struct listener_data *ifdata;
2304         int err;
2305
2306         DBG("interface %s", interface);
2307
2308         if (g_hash_table_lookup(listener_table, interface) != NULL)
2309                 return 0;
2310
2311         ifdata = g_try_new0(struct listener_data, 1);
2312         if (ifdata == NULL)
2313                 return -ENOMEM;
2314
2315         ifdata->ifname = g_strdup(interface);
2316         ifdata->udp_listener_channel = NULL;
2317         ifdata->udp_listener_watch = 0;
2318         ifdata->tcp_listener_channel = NULL;
2319         ifdata->tcp_listener_watch = 0;
2320
2321         err = create_listener(ifdata);
2322         if (err < 0) {
2323                 connman_error("Couldn't create listener for %s err %d",
2324                                 interface, err);
2325                 g_free(ifdata->ifname);
2326                 g_free(ifdata);
2327                 return err;
2328         }
2329         g_hash_table_insert(listener_table, ifdata->ifname, ifdata);
2330         return 0;
2331 }
2332
2333 void __connman_dnsproxy_remove_listener(const char *interface)
2334 {
2335         struct listener_data *ifdata;
2336
2337         DBG("interface %s", interface);
2338
2339         ifdata = g_hash_table_lookup(listener_table, interface);
2340         if (ifdata == NULL)
2341                 return;
2342
2343         destroy_listener(ifdata);
2344
2345         g_hash_table_remove(listener_table, interface);
2346 }
2347
2348 static void remove_listener(gpointer key, gpointer value, gpointer user_data)
2349 {
2350         __connman_dnsproxy_remove_listener(key);
2351 }
2352
2353 int __connman_dnsproxy_init(void)
2354 {
2355         int err;
2356
2357         DBG("");
2358
2359         listener_table = g_hash_table_new_full(g_str_hash, g_str_equal,
2360                                                         g_free, g_free);
2361         err = __connman_dnsproxy_add_listener("lo");
2362         if (err < 0)
2363                 return err;
2364
2365         err = connman_notifier_register(&dnsproxy_notifier);
2366         if (err < 0)
2367                 goto destroy;
2368
2369         return 0;
2370
2371 destroy:
2372         __connman_dnsproxy_remove_listener("lo");
2373         g_hash_table_destroy(listener_table);
2374
2375         return err;
2376 }
2377
2378 void __connman_dnsproxy_cleanup(void)
2379 {
2380         DBG("");
2381
2382         connman_notifier_unregister(&dnsproxy_notifier);
2383
2384         g_hash_table_foreach(listener_table, remove_listener, NULL);
2385
2386         g_hash_table_destroy(listener_table);
2387 }