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