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