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