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