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