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