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