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