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