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