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