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