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