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