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