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