Imported Upstream connman version 1.38
[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
1823         debug("count %d ptr %p end %p uptr %p", field_count, ptr, end, uptr);
1824
1825         while (field_count-- > 0 && ptr < end) {
1826                 int dlen;               /* data field length */
1827                 int ulen;               /* uncompress length */
1828                 int pos;                /* position in compressed string */
1829                 char name[NS_MAXLABEL]; /* tmp label */
1830                 uint16_t dns_type, dns_class;
1831                 int comp_pos;
1832
1833                 if (!convert_label(start, end, ptr, name, NS_MAXLABEL,
1834                                         &pos, &comp_pos))
1835                         goto out;
1836
1837                 /*
1838                  * Copy the uncompressed resource record, type, class and \0 to
1839                  * tmp buffer.
1840                  */
1841
1842                 ulen = strlen(name);
1843                 strncpy(uptr, name, uncomp_len - (uptr - uncompressed));
1844
1845                 debug("pos %d ulen %d left %d name %s", pos, ulen,
1846                         (int)(uncomp_len - (uptr - uncompressed)), uptr);
1847
1848                 uptr += ulen;
1849                 *uptr++ = '\0';
1850
1851                 ptr += pos;
1852
1853                 /*
1854                  * We copy also the fixed portion of the result (type, class,
1855                  * ttl, address length and the address)
1856                  */
1857                 memcpy(uptr, ptr, NS_RRFIXEDSZ);
1858
1859                 dns_type = uptr[0] << 8 | uptr[1];
1860                 dns_class = uptr[2] << 8 | uptr[3];
1861
1862                 if (dns_class != ns_c_in)
1863                         goto out;
1864
1865                 ptr += NS_RRFIXEDSZ;
1866                 uptr += NS_RRFIXEDSZ;
1867
1868                 /*
1869                  * Then the variable portion of the result (data length).
1870                  * Typically this portion is also compressed
1871                  * so we need to uncompress it also when necessary.
1872                  */
1873                 if (dns_type == ns_t_cname) {
1874                         if (!convert_label(start, end, ptr, uptr,
1875                                         uncomp_len - (uptr - uncompressed),
1876                                                 &pos, &comp_pos))
1877                                 goto out;
1878
1879                         uptr[-2] = comp_pos << 8;
1880                         uptr[-1] = comp_pos & 0xff;
1881
1882                         uptr += comp_pos;
1883                         ptr += pos;
1884
1885                 } else if (dns_type == ns_t_a || dns_type == ns_t_aaaa) {
1886                         dlen = uptr[-2] << 8 | uptr[-1];
1887
1888                         if (ptr + dlen > end) {
1889                                 debug("data len %d too long", dlen);
1890                                 goto out;
1891                         }
1892
1893                         memcpy(uptr, ptr, dlen);
1894                         uptr += dlen;
1895                         ptr += dlen;
1896
1897                 } else if (dns_type == ns_t_soa) {
1898                         int total_len = 0;
1899                         char *len_ptr;
1900
1901                         /* Primary name server expansion */
1902                         if (!convert_label(start, end, ptr, uptr,
1903                                         uncomp_len - (uptr - uncompressed),
1904                                                 &pos, &comp_pos))
1905                                 goto out;
1906
1907                         total_len += comp_pos;
1908                         len_ptr = &uptr[-2];
1909                         ptr += pos;
1910                         uptr += comp_pos;
1911
1912                         /* Responsible authority's mailbox */
1913                         if (!convert_label(start, end, ptr, uptr,
1914                                         uncomp_len - (uptr - uncompressed),
1915                                                 &pos, &comp_pos))
1916                                 goto out;
1917
1918                         total_len += comp_pos;
1919                         ptr += pos;
1920                         uptr += comp_pos;
1921
1922                         /*
1923                          * Copy rest of the soa fields (serial number,
1924                          * refresh interval, retry interval, expiration
1925                          * limit and minimum ttl). They are 20 bytes long.
1926                          */
1927                         memcpy(uptr, ptr, 20);
1928                         uptr += 20;
1929                         ptr += 20;
1930                         total_len += 20;
1931
1932                         /*
1933                          * Finally fix the length of the data part
1934                          */
1935                         len_ptr[0] = total_len << 8;
1936                         len_ptr[1] = total_len & 0xff;
1937                 }
1938
1939                 *uncompressed_ptr = uptr;
1940         }
1941
1942         return ptr;
1943
1944 out:
1945         return NULL;
1946 }
1947
1948 static int strip_domains(char *name, char *answers, int maxlen)
1949 {
1950         uint16_t data_len;
1951         int name_len = strlen(name);
1952         char *ptr, *start = answers, *end = answers + maxlen;
1953
1954         while (maxlen > 0) {
1955                 ptr = strstr(answers, name);
1956                 if (ptr) {
1957                         char *domain = ptr + name_len;
1958
1959                         if (*domain) {
1960                                 int domain_len = strlen(domain);
1961
1962                                 memmove(answers + name_len,
1963                                         domain + domain_len,
1964                                         end - (domain + domain_len));
1965
1966                                 end -= domain_len;
1967                                 maxlen -= domain_len;
1968                         }
1969                 }
1970
1971                 answers += strlen(answers) + 1;
1972                 answers += 2 + 2 + 4;  /* skip type, class and ttl fields */
1973
1974                 data_len = answers[0] << 8 | answers[1];
1975                 answers += 2; /* skip the length field */
1976
1977                 if (answers + data_len > end)
1978                         return -EINVAL;
1979
1980                 answers += data_len;
1981                 maxlen -= answers - ptr;
1982         }
1983
1984         return end - start;
1985 }
1986
1987 static int forward_dns_reply(unsigned char *reply, int reply_len, int protocol,
1988                                 struct server_data *data)
1989 {
1990         struct domain_hdr *hdr;
1991         struct request_data *req;
1992         int dns_id, sk, err, offset = protocol_offset(protocol);
1993
1994         if (offset < 0)
1995                 return offset;
1996
1997         hdr = (void *)(reply + offset);
1998         dns_id = reply[offset] | reply[offset + 1] << 8;
1999
2000         debug("Received %d bytes (id 0x%04x)", reply_len, dns_id);
2001
2002         req = find_request(dns_id);
2003         if (!req)
2004                 return -EINVAL;
2005
2006         debug("req %p dstid 0x%04x altid 0x%04x rcode %d",
2007                         req, req->dstid, req->altid, hdr->rcode);
2008
2009         reply[offset] = req->srcid & 0xff;
2010         reply[offset + 1] = req->srcid >> 8;
2011
2012         req->numresp++;
2013
2014         if (hdr->rcode == ns_r_noerror || !req->resp) {
2015                 unsigned char *new_reply = NULL;
2016
2017                 /*
2018                  * If the domain name was append
2019                  * remove it before forwarding the reply.
2020                  * If there were more than one question, then this
2021                  * domain name ripping can be hairy so avoid that
2022                  * and bail out in that that case.
2023                  *
2024                  * The reason we are doing this magic is that if the
2025                  * user's DNS client tries to resolv hostname without
2026                  * domain part, it also expects to get the result without
2027                  * a domain name part.
2028                  */
2029                 if (req->append_domain && ntohs(hdr->qdcount) == 1) {
2030                         uint16_t domain_len = 0;
2031                         uint16_t header_len;
2032                         uint16_t dns_type, dns_class;
2033                         uint8_t host_len, dns_type_pos;
2034                         char uncompressed[NS_MAXDNAME], *uptr;
2035                         char *ptr, *eom = (char *)reply + reply_len;
2036
2037                         /*
2038                          * ptr points to the first char of the hostname.
2039                          * ->hostname.domain.net
2040                          */
2041                         header_len = offset + sizeof(struct domain_hdr);
2042                         ptr = (char *)reply + header_len;
2043
2044                         host_len = *ptr;
2045                         if (host_len > 0)
2046                                 domain_len = strnlen(ptr + 1 + host_len,
2047                                                 reply_len - header_len);
2048
2049                         /*
2050                          * If the query type is anything other than A or AAAA,
2051                          * then bail out and pass the message as is.
2052                          * We only want to deal with IPv4 or IPv6 addresses.
2053                          */
2054                         dns_type_pos = host_len + 1 + domain_len + 1;
2055
2056                         dns_type = ptr[dns_type_pos] << 8 |
2057                                                         ptr[dns_type_pos + 1];
2058                         dns_class = ptr[dns_type_pos + 2] << 8 |
2059                                                         ptr[dns_type_pos + 3];
2060                         if (dns_type != ns_t_a && dns_type != ns_t_aaaa &&
2061                                         dns_class != ns_c_in) {
2062                                 debug("Pass msg dns type %d class %d",
2063                                         dns_type, dns_class);
2064                                 goto pass;
2065                         }
2066
2067                         /*
2068                          * Remove the domain name and replace it by the end
2069                          * of reply. Check if the domain is really there
2070                          * before trying to copy the data. We also need to
2071                          * uncompress the answers if necessary.
2072                          * The domain_len can be 0 because if the original
2073                          * query did not contain a domain name, then we are
2074                          * sending two packets, first without the domain name
2075                          * and the second packet with domain name.
2076                          * The append_domain is set to true even if we sent
2077                          * the first packet without domain name. In this
2078                          * case we end up in this branch.
2079                          */
2080                         if (domain_len > 0) {
2081                                 int len = host_len + 1;
2082                                 int new_len, fixed_len;
2083                                 char *answers;
2084
2085                                 /*
2086                                  * First copy host (without domain name) into
2087                                  * tmp buffer.
2088                                  */
2089                                 uptr = &uncompressed[0];
2090                                 memcpy(uptr, ptr, len);
2091
2092                                 uptr[len] = '\0'; /* host termination */
2093                                 uptr += len + 1;
2094
2095                                 /*
2096                                  * Copy type and class fields of the question.
2097                                  */
2098                                 ptr += len + domain_len + 1;
2099                                 memcpy(uptr, ptr, NS_QFIXEDSZ);
2100
2101                                 /*
2102                                  * ptr points to answers after this
2103                                  */
2104                                 ptr += NS_QFIXEDSZ;
2105                                 uptr += NS_QFIXEDSZ;
2106                                 answers = uptr;
2107                                 fixed_len = answers - uncompressed;
2108
2109                                 /*
2110                                  * We then uncompress the result to buffer
2111                                  * so that we can rip off the domain name
2112                                  * part from the question. First answers,
2113                                  * then name server (authority) information,
2114                                  * and finally additional record info.
2115                                  */
2116
2117                                 ptr = uncompress(ntohs(hdr->ancount),
2118                                                 (char *)reply + offset, eom,
2119                                                 ptr, uncompressed, NS_MAXDNAME,
2120                                                 &uptr);
2121                                 if (!ptr)
2122                                         goto out;
2123
2124                                 ptr = uncompress(ntohs(hdr->nscount),
2125                                                 (char *)reply + offset, eom,
2126                                                 ptr, uncompressed, NS_MAXDNAME,
2127                                                 &uptr);
2128                                 if (!ptr)
2129                                         goto out;
2130
2131                                 ptr = uncompress(ntohs(hdr->arcount),
2132                                                 (char *)reply + offset, eom,
2133                                                 ptr, uncompressed, NS_MAXDNAME,
2134                                                 &uptr);
2135                                 if (!ptr)
2136                                         goto out;
2137
2138                                 /*
2139                                  * The uncompressed buffer now contains almost
2140                                  * valid response. Final step is to get rid of
2141                                  * the domain name because at least glibc
2142                                  * gethostbyname() implementation does extra
2143                                  * checks and expects to find an answer without
2144                                  * domain name if we asked a query without
2145                                  * domain part. Note that glibc getaddrinfo()
2146                                  * works differently and accepts FQDN in answer
2147                                  */
2148                                 new_len = strip_domains(uncompressed, answers,
2149                                                         uptr - answers);
2150                                 if (new_len < 0) {
2151                                         debug("Corrupted packet");
2152                                         return -EINVAL;
2153                                 }
2154
2155                                 /*
2156                                  * Because we have now uncompressed the answers
2157                                  * we might have to create a bigger buffer to
2158                                  * hold all that data.
2159                                  */
2160
2161                                 reply_len = header_len + new_len + fixed_len;
2162
2163                                 new_reply = g_try_malloc(reply_len);
2164                                 if (!new_reply)
2165                                         return -ENOMEM;
2166
2167                                 memcpy(new_reply, reply, header_len);
2168                                 memcpy(new_reply + header_len, uncompressed,
2169                                         new_len + fixed_len);
2170
2171                                 reply = new_reply;
2172                         }
2173                 }
2174
2175         pass:
2176                 g_free(req->resp);
2177                 req->resplen = 0;
2178
2179                 req->resp = g_try_malloc(reply_len);
2180 #if defined TIZEN_EXT
2181                 if (!req->resp) {
2182                         g_free(new_reply);
2183                         return -ENOMEM;
2184                 }
2185 #else
2186                 if (!req->resp)
2187                         return -ENOMEM;
2188 #endif
2189
2190                 memcpy(req->resp, reply, reply_len);
2191                 req->resplen = reply_len;
2192
2193                 cache_update(data, reply, reply_len);
2194
2195                 g_free(new_reply);
2196         }
2197
2198 out:
2199         if (req->numresp < req->numserv) {
2200                 if (hdr->rcode > ns_r_noerror) {
2201                         return -EINVAL;
2202                 } else if (hdr->ancount == 0 && req->append_domain) {
2203                         return -EINVAL;
2204                 }
2205         }
2206
2207         request_list = g_slist_remove(request_list, req);
2208
2209         if (protocol == IPPROTO_UDP) {
2210                 sk = get_req_udp_socket(req);
2211                 if (sk < 0) {
2212                         errno = -EIO;
2213                         err = -EIO;
2214                 } else
2215                         err = sendto(sk, req->resp, req->resplen, 0,
2216                                 &req->sa, req->sa_len);
2217         } else {
2218                 sk = req->client_sk;
2219                 err = send(sk, req->resp, req->resplen, MSG_NOSIGNAL);
2220         }
2221
2222         if (err < 0)
2223                 debug("Cannot send msg, sk %d proto %d errno %d/%s", sk,
2224                         protocol, errno, strerror(errno));
2225         else
2226                 debug("proto %d sent %d bytes to %d", protocol, err, sk);
2227
2228         destroy_request_data(req);
2229
2230         return err;
2231 }
2232
2233 static void server_destroy_socket(struct server_data *data)
2234 {
2235         debug("index %d server %s proto %d", data->index,
2236                                         data->server, data->protocol);
2237
2238         if (data->watch > 0) {
2239                 g_source_remove(data->watch);
2240                 data->watch = 0;
2241         }
2242
2243         if (data->timeout > 0) {
2244                 g_source_remove(data->timeout);
2245                 data->timeout = 0;
2246         }
2247
2248         if (data->channel) {
2249                 g_io_channel_shutdown(data->channel, TRUE, NULL);
2250                 g_io_channel_unref(data->channel);
2251                 data->channel = NULL;
2252         }
2253
2254         g_free(data->incoming_reply);
2255         data->incoming_reply = NULL;
2256 }
2257
2258 static void destroy_server(struct server_data *server)
2259 {
2260         debug("index %d server %s sock %d", server->index, server->server,
2261                         server->channel ?
2262                         g_io_channel_unix_get_fd(server->channel): -1);
2263
2264         server_list = g_slist_remove(server_list, server);
2265         server_destroy_socket(server);
2266
2267         if (server->protocol == IPPROTO_UDP && server->enabled)
2268                 debug("Removing DNS server %s", server->server);
2269
2270         g_free(server->server);
2271         g_list_free_full(server->domains, g_free);
2272         g_free(server->server_addr);
2273
2274         /*
2275          * We do not remove cache right away but delay it few seconds.
2276          * The idea is that when IPv6 DNS server is added via RDNSS, it has a
2277          * lifetime. When the lifetime expires we decrease the refcount so it
2278          * is possible that the cache is then removed. Because a new DNS server
2279          * is usually created almost immediately we would then loose the cache
2280          * without any good reason. The small delay allows the new RDNSS to
2281          * create a new DNS server instance and the refcount does not go to 0.
2282          */
2283         if (cache && !cache_timer)
2284                 cache_timer = g_timeout_add_seconds(3, try_remove_cache, NULL);
2285
2286         g_free(server);
2287 }
2288
2289 static gboolean udp_server_event(GIOChannel *channel, GIOCondition condition,
2290                                                         gpointer user_data)
2291 {
2292         unsigned char buf[4096];
2293         int sk, len;
2294         struct server_data *data = user_data;
2295
2296         if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
2297                 connman_error("Error with UDP server %s", data->server);
2298                 server_destroy_socket(data);
2299                 return FALSE;
2300         }
2301
2302         sk = g_io_channel_unix_get_fd(channel);
2303
2304         len = recv(sk, buf, sizeof(buf), 0);
2305
2306         if (len >= 12)
2307                 forward_dns_reply(buf, len, IPPROTO_UDP, data);
2308
2309 #if defined TIZEN_EXT
2310         GSList *list;
2311
2312         for (list = server_list_sec; list; list = list->next) {
2313                 struct server_data *new_data = list->data;
2314
2315                 if (new_data == data) {
2316                         destroy_server_sec(data);
2317                         return TRUE;
2318                 }
2319         }
2320 #endif
2321
2322         return TRUE;
2323 }
2324
2325 static gboolean tcp_server_event(GIOChannel *channel, GIOCondition condition,
2326                                                         gpointer user_data)
2327 {
2328         int sk;
2329         struct server_data *server = user_data;
2330
2331         sk = g_io_channel_unix_get_fd(channel);
2332         if (sk == 0)
2333                 return FALSE;
2334
2335         if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
2336                 GSList *list;
2337 hangup:
2338                 debug("TCP server channel closed, sk %d", sk);
2339
2340                 /*
2341                  * Discard any partial response which is buffered; better
2342                  * to get a proper response from a working server.
2343                  */
2344                 g_free(server->incoming_reply);
2345                 server->incoming_reply = NULL;
2346
2347                 list = request_list;
2348                 while (list) {
2349                         struct request_data *req = list->data;
2350                         struct domain_hdr *hdr;
2351                         list = list->next;
2352
2353                         if (req->protocol == IPPROTO_UDP)
2354                                 continue;
2355
2356                         if (!req->request)
2357                                 continue;
2358
2359                         /*
2360                          * If we're not waiting for any further response
2361                          * from another name server, then we send an error
2362                          * response to the client.
2363                          */
2364                         if (req->numserv && --(req->numserv))
2365                                 continue;
2366
2367                         hdr = (void *) (req->request + 2);
2368                         hdr->id = req->srcid;
2369                         send_response(req->client_sk, req->request,
2370                                 req->request_len, NULL, 0, IPPROTO_TCP);
2371
2372                         request_list = g_slist_remove(request_list, req);
2373                 }
2374
2375                 destroy_server(server);
2376
2377                 return FALSE;
2378         }
2379
2380         if ((condition & G_IO_OUT) && !server->connected) {
2381                 GSList *list;
2382                 GList *domains;
2383                 bool no_request_sent = true;
2384                 struct server_data *udp_server;
2385
2386                 udp_server = find_server(server->index, server->server,
2387                                                                 IPPROTO_UDP);
2388                 if (udp_server) {
2389                         for (domains = udp_server->domains; domains;
2390                                                 domains = domains->next) {
2391                                 char *dom = domains->data;
2392
2393                                 debug("Adding domain %s to %s",
2394                                                 dom, server->server);
2395
2396                                 server->domains = g_list_append(server->domains,
2397                                                                 g_strdup(dom));
2398                         }
2399                 }
2400
2401                 server->connected = true;
2402                 server_list = g_slist_append(server_list, server);
2403
2404                 if (server->timeout > 0) {
2405                         g_source_remove(server->timeout);
2406                         server->timeout = 0;
2407                 }
2408
2409                 for (list = request_list; list; ) {
2410                         struct request_data *req = list->data;
2411                         int status;
2412
2413                         if (req->protocol == IPPROTO_UDP) {
2414                                 list = list->next;
2415                                 continue;
2416                         }
2417
2418                         debug("Sending req %s over TCP", (char *)req->name);
2419
2420                         status = ns_resolv(server, req,
2421                                                 req->request, req->name);
2422                         if (status > 0) {
2423                                 /*
2424                                  * A cached result was sent,
2425                                  * so the request can be released
2426                                  */
2427                                 list = list->next;
2428                                 request_list = g_slist_remove(request_list, req);
2429                                 destroy_request_data(req);
2430                                 continue;
2431                         }
2432
2433                         if (status < 0) {
2434                                 list = list->next;
2435                                 continue;
2436                         }
2437
2438                         no_request_sent = false;
2439
2440                         if (req->timeout > 0)
2441                                 g_source_remove(req->timeout);
2442
2443                         req->timeout = g_timeout_add_seconds(30,
2444                                                 request_timeout, req);
2445                         list = list->next;
2446                 }
2447
2448                 if (no_request_sent) {
2449                         destroy_server(server);
2450                         return FALSE;
2451                 }
2452
2453         } else if (condition & G_IO_IN) {
2454                 struct partial_reply *reply = server->incoming_reply;
2455                 int bytes_recv;
2456
2457                 if (!reply) {
2458                         unsigned char reply_len_buf[2];
2459                         uint16_t reply_len;
2460
2461                         bytes_recv = recv(sk, reply_len_buf, 2, MSG_PEEK);
2462                         if (!bytes_recv) {
2463                                 goto hangup;
2464                         } else if (bytes_recv < 0) {
2465                                 if (errno == EAGAIN || errno == EWOULDBLOCK)
2466                                         return TRUE;
2467
2468                                 connman_error("DNS proxy error %s",
2469                                                 strerror(errno));
2470                                 goto hangup;
2471                         } else if (bytes_recv < 2)
2472                                 return TRUE;
2473
2474                         reply_len = reply_len_buf[1] | reply_len_buf[0] << 8;
2475                         reply_len += 2;
2476
2477                         debug("TCP reply %d bytes from %d", reply_len, sk);
2478
2479                         reply = g_try_malloc(sizeof(*reply) + reply_len + 2);
2480                         if (!reply)
2481                                 return TRUE;
2482
2483                         reply->len = reply_len;
2484                         reply->received = 0;
2485
2486                         server->incoming_reply = reply;
2487                 }
2488
2489                 while (reply->received < reply->len) {
2490                         bytes_recv = recv(sk, reply->buf + reply->received,
2491                                         reply->len - reply->received, 0);
2492                         if (!bytes_recv) {
2493                                 connman_error("DNS proxy TCP disconnect");
2494                                 break;
2495                         } else if (bytes_recv < 0) {
2496                                 if (errno == EAGAIN || errno == EWOULDBLOCK)
2497                                         return TRUE;
2498
2499                                 connman_error("DNS proxy error %s",
2500                                                 strerror(errno));
2501                                 break;
2502                         }
2503                         reply->received += bytes_recv;
2504                 }
2505
2506                 forward_dns_reply(reply->buf, reply->received, IPPROTO_TCP,
2507                                         server);
2508
2509                 g_free(reply);
2510                 server->incoming_reply = NULL;
2511
2512                 destroy_server(server);
2513
2514                 return FALSE;
2515         }
2516
2517         return TRUE;
2518 }
2519
2520 static gboolean tcp_idle_timeout(gpointer user_data)
2521 {
2522         struct server_data *server = user_data;
2523
2524         debug("");
2525
2526         if (!server)
2527                 return FALSE;
2528
2529         destroy_server(server);
2530
2531         return FALSE;
2532 }
2533
2534 static int server_create_socket(struct server_data *data)
2535 {
2536         int sk, err;
2537         char *interface;
2538
2539         debug("index %d server %s proto %d", data->index,
2540                                         data->server, data->protocol);
2541
2542         sk = socket(data->server_addr->sa_family,
2543                 data->protocol == IPPROTO_TCP ? SOCK_STREAM : SOCK_DGRAM,
2544                 data->protocol);
2545         if (sk < 0) {
2546                 err = errno;
2547                 connman_error("Failed to create server %s socket",
2548                                                         data->server);
2549                 server_destroy_socket(data);
2550                 return -err;
2551         }
2552
2553         debug("sk %d", sk);
2554
2555         interface = connman_inet_ifname(data->index);
2556         if (interface) {
2557                 if (setsockopt(sk, SOL_SOCKET, SO_BINDTODEVICE,
2558                                         interface,
2559                                         strlen(interface) + 1) < 0) {
2560                         err = errno;
2561                         connman_error("Failed to bind server %s "
2562                                                 "to interface %s",
2563                                                 data->server, interface);
2564                         close(sk);
2565                         server_destroy_socket(data);
2566                         g_free(interface);
2567                         return -err;
2568                 }
2569                 g_free(interface);
2570         }
2571
2572         data->channel = g_io_channel_unix_new(sk);
2573         if (!data->channel) {
2574                 connman_error("Failed to create server %s channel",
2575                                                         data->server);
2576                 close(sk);
2577                 server_destroy_socket(data);
2578                 return -ENOMEM;
2579         }
2580
2581         g_io_channel_set_close_on_unref(data->channel, TRUE);
2582
2583         if (data->protocol == IPPROTO_TCP) {
2584                 g_io_channel_set_flags(data->channel, G_IO_FLAG_NONBLOCK, NULL);
2585                 data->watch = g_io_add_watch(data->channel,
2586                         G_IO_OUT | G_IO_IN | G_IO_HUP | G_IO_NVAL | G_IO_ERR,
2587                                                 tcp_server_event, data);
2588                 data->timeout = g_timeout_add_seconds(30, tcp_idle_timeout,
2589                                                                 data);
2590         } else
2591                 data->watch = g_io_add_watch(data->channel,
2592                         G_IO_IN | G_IO_NVAL | G_IO_ERR | G_IO_HUP,
2593                                                 udp_server_event, data);
2594
2595         if (connect(sk, data->server_addr, data->server_addr_len) < 0) {
2596                 err = errno;
2597
2598                 if ((data->protocol == IPPROTO_TCP && errno != EINPROGRESS) ||
2599                                 data->protocol == IPPROTO_UDP) {
2600
2601                         connman_error("Failed to connect to server %s",
2602                                                                 data->server);
2603                         server_destroy_socket(data);
2604                         return -err;
2605                 }
2606         }
2607
2608         create_cache();
2609
2610         return 0;
2611 }
2612
2613 static void enable_fallback(bool enable)
2614 {
2615         GSList *list;
2616
2617         for (list = server_list; list; list = list->next) {
2618                 struct server_data *data = list->data;
2619
2620                 if (data->index != -1)
2621                         continue;
2622
2623                 if (enable)
2624                         DBG("Enabling fallback DNS server %s", data->server);
2625                 else
2626                         DBG("Disabling fallback DNS server %s", data->server);
2627
2628                 data->enabled = enable;
2629         }
2630 }
2631
2632 #if defined TIZEN_EXT
2633
2634 static void destroy_server_sec(struct server_data *server)
2635 {
2636         GList *list;
2637         int fd;
2638
2639         if (server->channel)
2640                 fd = g_io_channel_unix_get_fd(server->channel);
2641         else
2642                 fd = -1;
2643
2644         DBG("index %d server %s sock %d", server->index, server->server, fd);
2645
2646         server_list_sec = g_slist_remove(server_list_sec, server);
2647
2648         if (fd > 0)
2649                 close(fd);
2650
2651         server_destroy_socket(server);
2652
2653         if (server->protocol == IPPROTO_UDP && server->enabled)
2654                 DBG("Removing DNS server %s", server->server);
2655
2656         g_free(server->server);
2657         for (list = server->domains; list; list = list->next) {
2658                 char *domain = list->data;
2659
2660                 server->domains = g_list_remove(server->domains, domain);
2661                 g_free(domain);
2662         }
2663         g_free(server->server_addr);
2664
2665         /*
2666          * We do not remove cache right away but delay it few seconds.
2667          * The idea is that when IPv6 DNS server is added via RDNSS, it has a
2668          * lifetime. When the lifetime expires we decrease the refcount so it
2669          * is possible that the cache is then removed. Because a new DNS server
2670          * is usually created almost immediately we would then loose the cache
2671          * without any good reason. The small delay allows the new RDNSS to
2672          * create a new DNS server instance and the refcount does not go to 0.
2673          */
2674         /* TODO: Need to check this */
2675         /* g_timeout_add_seconds(3, try_remove_cache, NULL); */
2676
2677         g_free(server);
2678 }
2679
2680 static void destroy_all_server_sec()
2681 {
2682         GSList *list;
2683
2684         DBG("remove all dns server");
2685
2686         for (list = server_list_sec; list; list = list->next) {
2687                 struct server_data *server = list->data;
2688                 destroy_server_sec(server);
2689         }
2690         server_list_sec = NULL;
2691 }
2692
2693 static gboolean sec_udp_idle_timeout(gpointer user_data)
2694 {
2695         struct server_data *server = user_data;
2696
2697         DBG("");
2698
2699         if (server == NULL)
2700                 return FALSE;
2701
2702         destroy_server_sec(server);
2703
2704         return FALSE;
2705 }
2706
2707 static struct server_data *create_server_sec(int index,
2708                                         const char *domain, const char *server,
2709                                         int protocol)
2710 {
2711         struct server_data *data;
2712         struct addrinfo hints, *rp;
2713         int ret;
2714
2715         DBG("index %d server %s", index, server);
2716
2717         data = g_try_new0(struct server_data, 1);
2718         if (data == NULL) {
2719                 connman_error("Failed to allocate server %s data", server);
2720                 return NULL;
2721         }
2722
2723         data->index = index;
2724         if (domain)
2725                 data->domains = g_list_append(data->domains, g_strdup(domain));
2726         data->server = g_strdup(server);
2727         data->protocol = protocol;
2728
2729         memset(&hints, 0, sizeof(hints));
2730
2731         switch (protocol) {
2732         case IPPROTO_UDP:
2733                 hints.ai_socktype = SOCK_DGRAM;
2734                 break;
2735
2736         case IPPROTO_TCP:
2737                 hints.ai_socktype = SOCK_STREAM;
2738                 break;
2739
2740         default:
2741                 destroy_server_sec(data);
2742                 return NULL;
2743         }
2744         hints.ai_family = AF_UNSPEC;
2745         hints.ai_flags = AI_NUMERICSERV | AI_NUMERICHOST;
2746
2747         ret = getaddrinfo(data->server, "53", &hints, &rp);
2748         if (ret) {
2749                 connman_error("Failed to parse server %s address: %s\n",
2750                                 data->server, gai_strerror(ret));
2751                 freeaddrinfo(rp);
2752                 destroy_server_sec(data);
2753                 return NULL;
2754         }
2755
2756         /* Do not blindly copy this code elsewhere; it doesn't loop over the
2757            results using ->ai_next as it should. That's OK in *this* case
2758            because it was a numeric lookup; we *know* there's only one. */
2759
2760         data->server_addr_len = rp->ai_addrlen;
2761
2762         switch (rp->ai_family) {
2763         case AF_INET:
2764                 data->server_addr = (struct sockaddr *)
2765                                         g_try_new0(struct sockaddr_in, 1);
2766                 break;
2767         case AF_INET6:
2768                 data->server_addr = (struct sockaddr *)
2769                                         g_try_new0(struct sockaddr_in6, 1);
2770                 break;
2771         default:
2772                 connman_error("Wrong address family %d", rp->ai_family);
2773                 break;
2774         }
2775         if (data->server_addr == NULL) {
2776                 freeaddrinfo(rp);
2777                 destroy_server_sec(data);
2778                 return NULL;
2779         }
2780         memcpy(data->server_addr, rp->ai_addr, rp->ai_addrlen);
2781         freeaddrinfo(rp);
2782
2783         if (server_create_socket(data) != 0) {
2784                 destroy_server_sec(data);
2785                 return NULL;
2786         }
2787
2788         if (protocol == IPPROTO_UDP) {
2789                 /* Enable new servers by default */
2790                 data->enabled = TRUE;
2791                 DBG("Adding DNS server %s", data->server);
2792
2793                 data->timeout = g_timeout_add_seconds(30, sec_udp_idle_timeout,
2794                                                                 data);
2795
2796                 server_list_sec = g_slist_append(server_list_sec, data);
2797         }
2798
2799         return data;
2800 }
2801 #endif
2802
2803 static struct server_data *create_server(int index,
2804                                         const char *domain, const char *server,
2805                                         int protocol)
2806 {
2807         struct server_data *data;
2808         struct addrinfo hints, *rp;
2809         int ret;
2810
2811         DBG("index %d server %s", index, server);
2812
2813         data = g_try_new0(struct server_data, 1);
2814         if (!data) {
2815                 connman_error("Failed to allocate server %s data", server);
2816                 return NULL;
2817         }
2818
2819         data->index = index;
2820         if (domain)
2821                 data->domains = g_list_append(data->domains, g_strdup(domain));
2822         data->server = g_strdup(server);
2823         data->protocol = protocol;
2824
2825         memset(&hints, 0, sizeof(hints));
2826
2827         switch (protocol) {
2828         case IPPROTO_UDP:
2829                 hints.ai_socktype = SOCK_DGRAM;
2830                 break;
2831
2832         case IPPROTO_TCP:
2833                 hints.ai_socktype = SOCK_STREAM;
2834                 break;
2835
2836         default:
2837                 destroy_server(data);
2838                 return NULL;
2839         }
2840         hints.ai_family = AF_UNSPEC;
2841         hints.ai_flags = AI_NUMERICSERV | AI_NUMERICHOST;
2842
2843         ret = getaddrinfo(data->server, "53", &hints, &rp);
2844         if (ret) {
2845                 connman_error("Failed to parse server %s address: %s\n",
2846                               data->server, gai_strerror(ret));
2847                 destroy_server(data);
2848                 return NULL;
2849         }
2850
2851         /* Do not blindly copy this code elsewhere; it doesn't loop over the
2852            results using ->ai_next as it should. That's OK in *this* case
2853            because it was a numeric lookup; we *know* there's only one. */
2854
2855         data->server_addr_len = rp->ai_addrlen;
2856
2857         switch (rp->ai_family) {
2858         case AF_INET:
2859                 data->server_addr = (struct sockaddr *)
2860                                         g_try_new0(struct sockaddr_in, 1);
2861                 break;
2862         case AF_INET6:
2863                 data->server_addr = (struct sockaddr *)
2864                                         g_try_new0(struct sockaddr_in6, 1);
2865                 break;
2866         default:
2867                 connman_error("Wrong address family %d", rp->ai_family);
2868                 break;
2869         }
2870         if (!data->server_addr) {
2871                 freeaddrinfo(rp);
2872                 destroy_server(data);
2873                 return NULL;
2874         }
2875         memcpy(data->server_addr, rp->ai_addr, rp->ai_addrlen);
2876         freeaddrinfo(rp);
2877
2878         if (server_create_socket(data) != 0) {
2879                 destroy_server(data);
2880                 return NULL;
2881         }
2882
2883         if (protocol == IPPROTO_UDP) {
2884                 if (__connman_service_index_is_default(data->index) ||
2885                                 __connman_service_index_is_split_routing(
2886                                                                 data->index)) {
2887                         data->enabled = true;
2888                         DBG("Adding DNS server %s", data->server);
2889
2890                         enable_fallback(false);
2891                 }
2892
2893                 server_list = g_slist_append(server_list, data);
2894         }
2895
2896         return data;
2897 }
2898
2899 static bool resolv(struct request_data *req,
2900                                 gpointer request, gpointer name)
2901 {
2902         GSList *list;
2903
2904         for (list = server_list; list; list = list->next) {
2905                 struct server_data *data = list->data;
2906
2907                 if (data->protocol == IPPROTO_TCP) {
2908                         DBG("server %s ignored proto TCP", data->server);
2909                         continue;
2910                 }
2911
2912                 debug("server %s enabled %d", data->server, data->enabled);
2913
2914                 if (!data->enabled)
2915                         continue;
2916
2917                 if (!data->channel && data->protocol == IPPROTO_UDP) {
2918                         if (server_create_socket(data) < 0) {
2919                                 DBG("socket creation failed while resolving");
2920                                 continue;
2921                         }
2922                 }
2923
2924                 if (ns_resolv(data, req, request, name) > 0)
2925                         return true;
2926         }
2927
2928         return false;
2929 }
2930
2931 static void update_domain(int index, const char *domain, bool append)
2932 {
2933         GSList *list;
2934
2935         DBG("index %d domain %s", index, domain);
2936
2937         if (!domain)
2938                 return;
2939
2940         for (list = server_list; list; list = list->next) {
2941                 struct server_data *data = list->data;
2942                 GList *dom_list;
2943                 char *dom;
2944                 bool dom_found = false;
2945
2946                 if (data->index < 0)
2947                         continue;
2948
2949                 if (data->index != index)
2950                         continue;
2951
2952                 for (dom_list = data->domains; dom_list;
2953                                 dom_list = dom_list->next) {
2954                         dom = dom_list->data;
2955
2956                         if (g_str_equal(dom, domain)) {
2957                                 dom_found = true;
2958                                 break;
2959                         }
2960                 }
2961
2962                 if (!dom_found && append) {
2963                         data->domains =
2964                                 g_list_append(data->domains, g_strdup(domain));
2965                 } else if (dom_found && !append) {
2966                         data->domains =
2967                                 g_list_remove(data->domains, dom);
2968                         g_free(dom);
2969                 }
2970         }
2971 }
2972
2973 static void append_domain(int index, const char *domain)
2974 {
2975         update_domain(index, domain, true);
2976 }
2977
2978 static void remove_domain(int index, const char *domain)
2979 {
2980         update_domain(index, domain, false);
2981 }
2982
2983 static void flush_requests(struct server_data *server)
2984 {
2985         GSList *list;
2986
2987         list = request_list;
2988         while (list) {
2989                 struct request_data *req = list->data;
2990
2991                 list = list->next;
2992
2993                 if (ns_resolv(server, req, req->request, req->name)) {
2994                         /*
2995                          * A cached result was sent,
2996                          * so the request can be released
2997                          */
2998                         request_list =
2999                                 g_slist_remove(request_list, req);
3000                         destroy_request_data(req);
3001                         continue;
3002                 }
3003
3004                 if (req->timeout > 0)
3005                         g_source_remove(req->timeout);
3006
3007                 req->timeout = g_timeout_add_seconds(5, request_timeout, req);
3008         }
3009 }
3010
3011 int __connman_dnsproxy_append(int index, const char *domain,
3012                                                         const char *server)
3013 {
3014         struct server_data *data;
3015
3016         DBG("index %d server %s", index, server);
3017
3018         if (!server && !domain)
3019                 return -EINVAL;
3020
3021         if (!server) {
3022                 append_domain(index, domain);
3023
3024                 return 0;
3025         }
3026
3027         if (g_str_equal(server, "127.0.0.1"))
3028                 return -ENODEV;
3029
3030         if (g_str_equal(server, "::1"))
3031                 return -ENODEV;
3032
3033         data = find_server(index, server, IPPROTO_UDP);
3034         if (data) {
3035                 append_domain(index, domain);
3036                 return 0;
3037         }
3038
3039         data = create_server(index, domain, server, IPPROTO_UDP);
3040         if (!data)
3041                 return -EIO;
3042
3043         flush_requests(data);
3044
3045         return 0;
3046 }
3047
3048 static void remove_server(int index, const char *domain,
3049                         const char *server, int protocol)
3050 {
3051         struct server_data *data;
3052         GSList *list;
3053
3054         data = find_server(index, server, protocol);
3055         if (!data)
3056                 return;
3057
3058         destroy_server(data);
3059
3060         for (list = server_list; list; list = list->next) {
3061                 struct server_data *data = list->data;
3062
3063                 if (data->index != -1 && data->enabled == true)
3064                         return;
3065         }
3066
3067         enable_fallback(true);
3068 }
3069
3070 int __connman_dnsproxy_remove(int index, const char *domain,
3071                                                         const char *server)
3072 {
3073         DBG("index %d server %s", index, server);
3074
3075         if (!server && !domain)
3076                 return -EINVAL;
3077
3078         if (!server) {
3079                 remove_domain(index, domain);
3080
3081                 return 0;
3082         }
3083
3084         if (g_str_equal(server, "127.0.0.1"))
3085                 return -ENODEV;
3086
3087         if (g_str_equal(server, "::1"))
3088                 return -ENODEV;
3089
3090         remove_server(index, domain, server, IPPROTO_UDP);
3091         remove_server(index, domain, server, IPPROTO_TCP);
3092
3093 #if defined TIZEN_EXT
3094         destroy_all_server_sec();
3095 #endif
3096
3097         return 0;
3098 }
3099
3100 static void dnsproxy_offline_mode(bool enabled)
3101 {
3102         GSList *list;
3103
3104         DBG("enabled %d", enabled);
3105
3106         for (list = server_list; list; list = list->next) {
3107                 struct server_data *data = list->data;
3108
3109                 if (!enabled) {
3110                         DBG("Enabling DNS server %s", data->server);
3111                         data->enabled = true;
3112                         cache_invalidate();
3113                         cache_refresh();
3114                 } else {
3115                         DBG("Disabling DNS server %s", data->server);
3116                         data->enabled = false;
3117                         cache_invalidate();
3118                 }
3119         }
3120 }
3121
3122 static void dnsproxy_default_changed(struct connman_service *service)
3123 {
3124         bool server_enabled = false;
3125         GSList *list;
3126         int index;
3127
3128         DBG("service %p", service);
3129
3130         /* DNS has changed, invalidate the cache */
3131         cache_invalidate();
3132
3133         if (!service) {
3134                 /* When no services are active, then disable DNS proxying */
3135                 dnsproxy_offline_mode(true);
3136                 return;
3137         }
3138
3139         index = __connman_service_get_index(service);
3140         if (index < 0)
3141                 return;
3142
3143         for (list = server_list; list; list = list->next) {
3144                 struct server_data *data = list->data;
3145
3146                 if (data->index == index) {
3147                         DBG("Enabling DNS server %s", data->server);
3148                         data->enabled = true;
3149                         server_enabled = true;
3150                 } else {
3151                         DBG("Disabling DNS server %s", data->server);
3152                         data->enabled = false;
3153                 }
3154         }
3155
3156         if (!server_enabled)
3157                 enable_fallback(true);
3158
3159         cache_refresh();
3160 }
3161
3162 static void dnsproxy_service_state_changed(struct connman_service *service,
3163                         enum connman_service_state state)
3164 {
3165         GSList *list;
3166         int index;
3167
3168         switch (state) {
3169         case CONNMAN_SERVICE_STATE_DISCONNECT:
3170         case CONNMAN_SERVICE_STATE_IDLE:
3171                 break;
3172         case CONNMAN_SERVICE_STATE_ASSOCIATION:
3173         case CONNMAN_SERVICE_STATE_CONFIGURATION:
3174         case CONNMAN_SERVICE_STATE_FAILURE:
3175         case CONNMAN_SERVICE_STATE_ONLINE:
3176         case CONNMAN_SERVICE_STATE_READY:
3177         case CONNMAN_SERVICE_STATE_UNKNOWN:
3178                 return;
3179         }
3180
3181         index = __connman_service_get_index(service);
3182         list = server_list;
3183
3184         while (list) {
3185                 struct server_data *data = list->data;
3186
3187                 /* Get next before the list is changed by destroy_server() */
3188                 list = list->next;
3189
3190                 if (data->index == index) {
3191                         DBG("removing server data of index %d", index);
3192                         destroy_server(data);
3193                 }
3194         }
3195 }
3196
3197 static const struct connman_notifier dnsproxy_notifier = {
3198         .name                   = "dnsproxy",
3199         .default_changed        = dnsproxy_default_changed,
3200         .offline_mode           = dnsproxy_offline_mode,
3201         .service_state_changed  = dnsproxy_service_state_changed,
3202 };
3203
3204 static const unsigned char opt_edns0_type[2] = { 0x00, 0x29 };
3205
3206 static int parse_request(unsigned char *buf, size_t len,
3207                                         char *name, unsigned int size)
3208 {
3209         struct domain_hdr *hdr = (void *) buf;
3210         uint16_t qdcount = ntohs(hdr->qdcount);
3211         uint16_t ancount = ntohs(hdr->ancount);
3212         uint16_t nscount = ntohs(hdr->nscount);
3213         uint16_t arcount = ntohs(hdr->arcount);
3214         unsigned char *ptr;
3215         unsigned int remain, used = 0;
3216
3217         if (len < sizeof(*hdr) + sizeof(struct qtype_qclass) ||
3218                         hdr->qr || qdcount != 1 || ancount || nscount) {
3219                 DBG("Dropped DNS request qr %d with len %zd qdcount %d "
3220                         "ancount %d nscount %d", hdr->qr, len, qdcount, ancount,
3221                         nscount);
3222
3223                 return -EINVAL;
3224         }
3225
3226         if (!name || !size)
3227                 return -EINVAL;
3228
3229         debug("id 0x%04x qr %d opcode %d qdcount %d arcount %d",
3230                                         hdr->id, hdr->qr, hdr->opcode,
3231                                                         qdcount, arcount);
3232
3233         name[0] = '\0';
3234
3235         ptr = buf + sizeof(struct domain_hdr);
3236         remain = len - sizeof(struct domain_hdr);
3237
3238         while (remain > 0) {
3239                 uint8_t label_len = *ptr;
3240
3241                 if (label_len == 0x00) {
3242                         uint8_t class;
3243                         struct qtype_qclass *q =
3244                                 (struct qtype_qclass *)(ptr + 1);
3245
3246                         if (remain < sizeof(*q)) {
3247                                 DBG("Dropped malformed DNS query");
3248                                 return -EINVAL;
3249                         }
3250
3251                         class = ntohs(q->qclass);
3252                         if (class != 1 && class != 255) {
3253                                 DBG("Dropped non-IN DNS class %d", class);
3254                                 return -EINVAL;
3255                         }
3256
3257                         ptr += sizeof(*q) + 1;
3258                         remain -= (sizeof(*q) + 1);
3259                         break;
3260                 }
3261
3262                 if (used + label_len + 1 > size)
3263                         return -ENOBUFS;
3264
3265                 strncat(name, (char *) (ptr + 1), label_len);
3266                 strcat(name, ".");
3267
3268                 used += label_len + 1;
3269
3270                 ptr += label_len + 1;
3271                 remain -= label_len + 1;
3272         }
3273
3274         if (arcount && remain >= sizeof(struct domain_rr) + 1 && !ptr[0] &&
3275                 ptr[1] == opt_edns0_type[0] && ptr[2] == opt_edns0_type[1]) {
3276                 struct domain_rr *edns0 = (struct domain_rr *)(ptr + 1);
3277
3278                 DBG("EDNS0 buffer size %u", ntohs(edns0->class));
3279         } else if (!arcount && remain) {
3280                 DBG("DNS request with %d garbage bytes", remain);
3281         }
3282
3283         debug("query %s", name);
3284
3285         return 0;
3286 }
3287
3288 static void client_reset(struct tcp_partial_client_data *client)
3289 {
3290         if (!client)
3291                 return;
3292
3293         if (client->channel) {
3294                 debug("client %d closing",
3295                         g_io_channel_unix_get_fd(client->channel));
3296
3297                 g_io_channel_unref(client->channel);
3298                 client->channel = NULL;
3299         }
3300
3301         if (client->watch > 0) {
3302                 g_source_remove(client->watch);
3303                 client->watch = 0;
3304         }
3305
3306         if (client->timeout > 0) {
3307                 g_source_remove(client->timeout);
3308                 client->timeout = 0;
3309         }
3310
3311         g_free(client->buf);
3312         client->buf = NULL;
3313
3314         client->buf_end = 0;
3315 }
3316
3317 static unsigned int get_msg_len(unsigned char *buf)
3318 {
3319         return buf[0]<<8 | buf[1];
3320 }
3321
3322 static bool read_tcp_data(struct tcp_partial_client_data *client,
3323                                 void *client_addr, socklen_t client_addr_len,
3324                                 int read_len)
3325 {
3326         char query[TCP_MAX_BUF_LEN];
3327         struct request_data *req;
3328         int client_sk, err;
3329         unsigned int msg_len;
3330         GSList *list;
3331         bool waiting_for_connect = false;
3332         int qtype = 0;
3333         struct cache_entry *entry;
3334
3335         client_sk = g_io_channel_unix_get_fd(client->channel);
3336
3337         if (read_len == 0) {
3338                 debug("client %d closed, pending %d bytes",
3339                         client_sk, client->buf_end);
3340                 g_hash_table_remove(partial_tcp_req_table,
3341                                         GINT_TO_POINTER(client_sk));
3342                 return false;
3343         }
3344
3345         debug("client %d received %d bytes", client_sk, read_len);
3346
3347         client->buf_end += read_len;
3348
3349         if (client->buf_end < 2)
3350                 return true;
3351
3352         msg_len = get_msg_len(client->buf);
3353         if (msg_len > TCP_MAX_BUF_LEN) {
3354                 debug("client %d sent too much data %d", client_sk, msg_len);
3355                 g_hash_table_remove(partial_tcp_req_table,
3356                                         GINT_TO_POINTER(client_sk));
3357                 return false;
3358         }
3359
3360 read_another:
3361         debug("client %d msg len %d end %d past end %d", client_sk, msg_len,
3362                 client->buf_end, client->buf_end - (msg_len + 2));
3363
3364         if (client->buf_end < (msg_len + 2)) {
3365                 debug("client %d still missing %d bytes",
3366                         client_sk,
3367                         msg_len + 2 - client->buf_end);
3368                 return true;
3369         }
3370
3371         debug("client %d all data %d received", client_sk, msg_len);
3372
3373         err = parse_request(client->buf + 2, msg_len,
3374                         query, sizeof(query));
3375         if (err < 0 || (g_slist_length(server_list) == 0)) {
3376                 send_response(client_sk, client->buf, msg_len + 2,
3377                         NULL, 0, IPPROTO_TCP);
3378                 return true;
3379         }
3380
3381         req = g_try_new0(struct request_data, 1);
3382         if (!req)
3383                 return true;
3384
3385         memcpy(&req->sa, client_addr, client_addr_len);
3386         req->sa_len = client_addr_len;
3387         req->client_sk = client_sk;
3388         req->protocol = IPPROTO_TCP;
3389         req->family = client->family;
3390
3391         req->srcid = client->buf[2] | (client->buf[3] << 8);
3392         req->dstid = get_id();
3393         req->altid = get_id();
3394         req->request_len = msg_len + 2;
3395
3396         client->buf[2] = req->dstid & 0xff;
3397         client->buf[3] = req->dstid >> 8;
3398
3399         req->numserv = 0;
3400         req->ifdata = client->ifdata;
3401         req->append_domain = false;
3402
3403         /*
3404          * Check if the answer is found in the cache before
3405          * creating sockets to the server.
3406          */
3407         entry = cache_check(client->buf, &qtype, IPPROTO_TCP);
3408         if (entry) {
3409                 int ttl_left = 0;
3410                 struct cache_data *data;
3411
3412                 debug("cache hit %s type %s", query, qtype == 1 ? "A" : "AAAA");
3413                 if (qtype == 1)
3414                         data = entry->ipv4;
3415                 else
3416                         data = entry->ipv6;
3417
3418                 if (data) {
3419                         ttl_left = data->valid_until - time(NULL);
3420                         entry->hits++;
3421
3422                         send_cached_response(client_sk, data->data,
3423                                         data->data_len, NULL, 0, IPPROTO_TCP,
3424                                         req->srcid, data->answers, ttl_left);
3425
3426                         g_free(req);
3427                         goto out;
3428                 } else
3429                         debug("data missing, ignoring cache for this query");
3430         }
3431
3432         for (list = server_list; list; list = list->next) {
3433                 struct server_data *data = list->data;
3434
3435                 if (data->protocol != IPPROTO_UDP || !data->enabled)
3436                         continue;
3437
3438                 if (!create_server(data->index, NULL, data->server,
3439                                         IPPROTO_TCP))
3440                         continue;
3441
3442                 waiting_for_connect = true;
3443         }
3444
3445         if (!waiting_for_connect) {
3446                 /* No server is waiting for connect */
3447                 send_response(client_sk, client->buf,
3448                         req->request_len, NULL, 0, IPPROTO_TCP);
3449                 g_free(req);
3450                 return true;
3451         }
3452
3453         /*
3454          * The server is not connected yet.
3455          * Copy the relevant buffers.
3456          * The request will actually be sent once we're
3457          * properly connected over TCP to the nameserver.
3458          */
3459         req->request = g_try_malloc0(req->request_len);
3460         if (!req->request) {
3461                 send_response(client_sk, client->buf,
3462                         req->request_len, NULL, 0, IPPROTO_TCP);
3463                 g_free(req);
3464                 goto out;
3465         }
3466         memcpy(req->request, client->buf, req->request_len);
3467
3468         req->name = g_try_malloc0(sizeof(query));
3469         if (!req->name) {
3470                 send_response(client_sk, client->buf,
3471                         req->request_len, NULL, 0, IPPROTO_TCP);
3472                 g_free(req->request);
3473                 g_free(req);
3474                 goto out;
3475         }
3476         memcpy(req->name, query, sizeof(query));
3477
3478         req->timeout = g_timeout_add_seconds(30, request_timeout, req);
3479
3480         request_list = g_slist_append(request_list, req);
3481
3482 out:
3483         if (client->buf_end > (msg_len + 2)) {
3484                 debug("client %d buf %p -> %p end %d len %d new %d",
3485                         client_sk,
3486                         client->buf + msg_len + 2,
3487                         client->buf, client->buf_end,
3488                         TCP_MAX_BUF_LEN - client->buf_end,
3489                         client->buf_end - (msg_len + 2));
3490                 memmove(client->buf, client->buf + msg_len + 2,
3491                         TCP_MAX_BUF_LEN - client->buf_end);
3492                 client->buf_end = client->buf_end - (msg_len + 2);
3493
3494                 /*
3495                  * If we have a full message waiting, just read it
3496                  * immediately.
3497                  */
3498                 msg_len = get_msg_len(client->buf);
3499                 if ((msg_len + 2) == client->buf_end) {
3500                         debug("client %d reading another %d bytes", client_sk,
3501                                                                 msg_len + 2);
3502                         goto read_another;
3503                 }
3504         } else {
3505                 debug("client %d clearing reading buffer", client_sk);
3506
3507                 client->buf_end = 0;
3508                 memset(client->buf, 0, TCP_MAX_BUF_LEN);
3509
3510                 /*
3511                  * We received all the packets from client so we must also
3512                  * remove the timeout handler here otherwise we might get
3513                  * timeout while waiting the results from server.
3514                  */
3515                 g_source_remove(client->timeout);
3516                 client->timeout = 0;
3517         }
3518
3519         return true;
3520 }
3521
3522 static gboolean tcp_client_event(GIOChannel *channel, GIOCondition condition,
3523                                 gpointer user_data)
3524 {
3525         struct tcp_partial_client_data *client = user_data;
3526         struct sockaddr_in6 client_addr6;
3527         socklen_t client_addr6_len = sizeof(client_addr6);
3528         struct sockaddr_in client_addr4;
3529         socklen_t client_addr4_len = sizeof(client_addr4);
3530         void *client_addr;
3531         socklen_t *client_addr_len;
3532         int len, client_sk;
3533
3534         client_sk = g_io_channel_unix_get_fd(channel);
3535
3536         if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
3537                 g_hash_table_remove(partial_tcp_req_table,
3538                                         GINT_TO_POINTER(client_sk));
3539
3540                 connman_error("Error with TCP client %d channel", client_sk);
3541                 return FALSE;
3542         }
3543
3544         switch (client->family) {
3545         case AF_INET:
3546                 client_addr = &client_addr4;
3547                 client_addr_len = &client_addr4_len;
3548                 break;
3549         case AF_INET6:
3550                 client_addr = &client_addr6;
3551                 client_addr_len = &client_addr6_len;
3552                 break;
3553         default:
3554                 g_hash_table_remove(partial_tcp_req_table,
3555                                         GINT_TO_POINTER(client_sk));
3556                 connman_error("client %p corrupted", client);
3557                 return FALSE;
3558         }
3559
3560         len = recvfrom(client_sk, client->buf + client->buf_end,
3561                         TCP_MAX_BUF_LEN - client->buf_end, 0,
3562                         client_addr, client_addr_len);
3563         if (len < 0) {
3564                 if (errno == EAGAIN || errno == EWOULDBLOCK)
3565                         return TRUE;
3566
3567                 debug("client %d cannot read errno %d/%s", client_sk, -errno,
3568                         strerror(errno));
3569                 g_hash_table_remove(partial_tcp_req_table,
3570                                         GINT_TO_POINTER(client_sk));
3571                 return FALSE;
3572         }
3573
3574         return read_tcp_data(client, client_addr, *client_addr_len, len);
3575 }
3576
3577 static gboolean client_timeout(gpointer user_data)
3578 {
3579         struct tcp_partial_client_data *client = user_data;
3580         int sock;
3581
3582         sock = g_io_channel_unix_get_fd(client->channel);
3583
3584         debug("client %d timeout pending %d bytes", sock, client->buf_end);
3585
3586         g_hash_table_remove(partial_tcp_req_table, GINT_TO_POINTER(sock));
3587
3588         return FALSE;
3589 }
3590
3591 #if defined TIZEN_EXT
3592 static void recover_listener(GIOChannel *channel, struct listener_data *ifdata)
3593 {
3594         int sk, index;
3595
3596         index = ifdata->index;
3597
3598         sk = g_io_channel_unix_get_fd(channel);
3599         close(sk);
3600
3601         __connman_dnsproxy_remove_listener(index);
3602
3603         if (__connman_dnsproxy_add_listener(index) == 0)
3604                 DBG("listener %d successfully recovered", index);
3605 }
3606 #endif
3607
3608 static bool tcp_listener_event(GIOChannel *channel, GIOCondition condition,
3609                                 struct listener_data *ifdata, int family,
3610                                 guint *listener_watch)
3611 {
3612         int sk, client_sk, len;
3613         unsigned int msg_len;
3614         struct tcp_partial_client_data *client;
3615         struct sockaddr_in6 client_addr6;
3616         socklen_t client_addr6_len = sizeof(client_addr6);
3617         struct sockaddr_in client_addr4;
3618         socklen_t client_addr4_len = sizeof(client_addr4);
3619         void *client_addr;
3620         socklen_t *client_addr_len;
3621         struct timeval tv;
3622         fd_set readfds;
3623
3624         debug("condition 0x%02x channel %p ifdata %p family %d",
3625                 condition, channel, ifdata, family);
3626
3627         if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
3628 #if defined TIZEN_EXT
3629                 connman_error("Error %d with TCP listener channel", condition);
3630
3631                 recover_listener(channel, ifdata);
3632 #else
3633                 if (*listener_watch > 0)
3634                         g_source_remove(*listener_watch);
3635                 *listener_watch = 0;
3636
3637                 connman_error("Error with TCP listener channel");
3638 #endif
3639
3640                 return false;
3641         }
3642
3643         sk = g_io_channel_unix_get_fd(channel);
3644
3645         if (family == AF_INET) {
3646                 client_addr = &client_addr4;
3647                 client_addr_len = &client_addr4_len;
3648         } else {
3649                 client_addr = &client_addr6;
3650                 client_addr_len = &client_addr6_len;
3651         }
3652
3653         tv.tv_sec = tv.tv_usec = 0;
3654         FD_ZERO(&readfds);
3655         FD_SET(sk, &readfds);
3656
3657         select(sk + 1, &readfds, NULL, NULL, &tv);
3658         if (FD_ISSET(sk, &readfds)) {
3659                 client_sk = accept(sk, client_addr, client_addr_len);
3660                 debug("client %d accepted", client_sk);
3661         } else {
3662                 debug("No data to read from master %d, waiting.", sk);
3663                 return true;
3664         }
3665
3666         if (client_sk < 0) {
3667                 connman_error("Accept failure on TCP listener");
3668                 *listener_watch = 0;
3669                 return false;
3670         }
3671
3672         fcntl(client_sk, F_SETFL, O_NONBLOCK);
3673
3674         client = g_hash_table_lookup(partial_tcp_req_table,
3675                                         GINT_TO_POINTER(client_sk));
3676         if (!client) {
3677                 client = g_try_new0(struct tcp_partial_client_data, 1);
3678                 if (!client) {
3679                         close(client_sk);
3680                         return false;
3681                 }
3682
3683                 g_hash_table_insert(partial_tcp_req_table,
3684                                         GINT_TO_POINTER(client_sk),
3685                                         client);
3686
3687                 client->channel = g_io_channel_unix_new(client_sk);
3688                 g_io_channel_set_close_on_unref(client->channel, TRUE);
3689
3690                 client->watch = g_io_add_watch(client->channel,
3691                                                 G_IO_IN, tcp_client_event,
3692                                                 (gpointer)client);
3693
3694                 client->ifdata = ifdata;
3695
3696                 debug("client %d created %p", client_sk, client);
3697         } else {
3698                 debug("client %d already exists %p", client_sk, client);
3699         }
3700
3701         if (!client->buf) {
3702                 client->buf = g_try_malloc(TCP_MAX_BUF_LEN);
3703                 if (!client->buf)
3704                         return false;
3705         }
3706         memset(client->buf, 0, TCP_MAX_BUF_LEN);
3707         client->buf_end = 0;
3708         client->family = family;
3709
3710         if (client->timeout == 0)
3711                 client->timeout = g_timeout_add_seconds(2, client_timeout,
3712                                                         client);
3713
3714         /*
3715          * Check how much data there is. If all is there, then we can
3716          * proceed normally, otherwise read the bits until everything
3717          * is received or timeout occurs.
3718          */
3719         len = recv(client_sk, client->buf, TCP_MAX_BUF_LEN, 0);
3720         if (len < 0) {
3721                 if (errno == EAGAIN || errno == EWOULDBLOCK) {
3722                         debug("client %d no data to read, waiting", client_sk);
3723                         return true;
3724                 }
3725
3726                 debug("client %d cannot read errno %d/%s", client_sk, -errno,
3727                         strerror(errno));
3728                 g_hash_table_remove(partial_tcp_req_table,
3729                                         GINT_TO_POINTER(client_sk));
3730                 return true;
3731         }
3732
3733         if (len < 2) {
3734                 debug("client %d not enough data to read, waiting", client_sk);
3735                 client->buf_end += len;
3736                 return true;
3737         }
3738
3739         msg_len = get_msg_len(client->buf);
3740         if (msg_len > TCP_MAX_BUF_LEN) {
3741                 debug("client %d invalid message length %u ignoring packet",
3742                         client_sk, msg_len);
3743                 g_hash_table_remove(partial_tcp_req_table,
3744                                         GINT_TO_POINTER(client_sk));
3745                 return true;
3746         }
3747
3748         /*
3749          * The packet length bytes do not contain the total message length,
3750          * that is the reason to -2 below.
3751          */
3752 #if defined TIZEN_EXT
3753         if (msg_len > (unsigned int)(len - 2)) {
3754 #else
3755         if (msg_len != (unsigned int)(len - 2)) {
3756 #endif
3757                 debug("client %d sent %d bytes but expecting %u pending %d",
3758                         client_sk, len, msg_len + 2, msg_len + 2 - len);
3759
3760                 client->buf_end += len;
3761                 return true;
3762         }
3763
3764         return read_tcp_data(client, client_addr, *client_addr_len, len);
3765 }
3766
3767 static gboolean tcp4_listener_event(GIOChannel *channel, GIOCondition condition,
3768                                 gpointer user_data)
3769 {
3770         struct listener_data *ifdata = user_data;
3771
3772         return tcp_listener_event(channel, condition, ifdata, AF_INET,
3773                                 &ifdata->tcp4_listener_watch);
3774 }
3775
3776 static gboolean tcp6_listener_event(GIOChannel *channel, GIOCondition condition,
3777                                 gpointer user_data)
3778 {
3779         struct listener_data *ifdata = user_data;
3780
3781         return tcp_listener_event(channel, condition, user_data, AF_INET6,
3782                                 &ifdata->tcp6_listener_watch);
3783 }
3784
3785 static bool udp_listener_event(GIOChannel *channel, GIOCondition condition,
3786                                 struct listener_data *ifdata, int family,
3787                                 guint *listener_watch)
3788 {
3789         unsigned char buf[768];
3790         char query[512];
3791         struct request_data *req;
3792         struct sockaddr_in6 client_addr6;
3793         socklen_t client_addr6_len = sizeof(client_addr6);
3794         struct sockaddr_in client_addr4;
3795         socklen_t client_addr4_len = sizeof(client_addr4);
3796         void *client_addr;
3797         socklen_t *client_addr_len;
3798         int sk, err, len;
3799
3800         if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
3801 #if defined TIZEN_EXT
3802                 connman_error("Error %d with UDP listener channel", condition);
3803
3804                 recover_listener(channel, ifdata);
3805 #else
3806                 connman_error("Error with UDP listener channel");
3807                 *listener_watch = 0;
3808 #endif
3809                 return false;
3810         }
3811
3812         sk = g_io_channel_unix_get_fd(channel);
3813
3814         if (family == AF_INET) {
3815                 client_addr = &client_addr4;
3816                 client_addr_len = &client_addr4_len;
3817         } else {
3818                 client_addr = &client_addr6;
3819                 client_addr_len = &client_addr6_len;
3820         }
3821
3822         memset(client_addr, 0, *client_addr_len);
3823         len = recvfrom(sk, buf, sizeof(buf), 0, client_addr, client_addr_len);
3824         if (len < 2)
3825                 return true;
3826
3827         debug("Received %d bytes (id 0x%04x)", len, buf[0] | buf[1] << 8);
3828
3829         err = parse_request(buf, len, query, sizeof(query));
3830         if (err < 0 || (g_slist_length(server_list) == 0)) {
3831                 send_response(sk, buf, len, client_addr,
3832                                 *client_addr_len, IPPROTO_UDP);
3833                 return true;
3834         }
3835
3836         req = g_try_new0(struct request_data, 1);
3837         if (!req)
3838                 return true;
3839
3840         memcpy(&req->sa, client_addr, *client_addr_len);
3841         req->sa_len = *client_addr_len;
3842         req->client_sk = 0;
3843         req->protocol = IPPROTO_UDP;
3844         req->family = family;
3845
3846         req->srcid = buf[0] | (buf[1] << 8);
3847         req->dstid = get_id();
3848         req->altid = get_id();
3849         req->request_len = len;
3850
3851         buf[0] = req->dstid & 0xff;
3852         buf[1] = req->dstid >> 8;
3853
3854         req->numserv = 0;
3855         req->ifdata = ifdata;
3856         req->append_domain = false;
3857
3858         if (resolv(req, buf, query)) {
3859                 /* a cached result was sent, so the request can be released */
3860                 g_free(req);
3861                 return true;
3862         }
3863
3864         req->name = g_strdup(query);
3865         req->request = g_malloc(len);
3866         memcpy(req->request, buf, len);
3867 #if defined TIZEN_EXT
3868         DBG("req %p dstid 0x%04x altid 0x%04x", req, req->dstid, req->altid);
3869         req->timeout = g_timeout_add_seconds(30, request_timeout, req);
3870 #else
3871         req->timeout = g_timeout_add_seconds(5, request_timeout, req);
3872 #endif
3873         request_list = g_slist_append(request_list, req);
3874
3875         return true;
3876 }
3877
3878 static gboolean udp4_listener_event(GIOChannel *channel, GIOCondition condition,
3879                                 gpointer user_data)
3880 {
3881         struct listener_data *ifdata = user_data;
3882
3883         return udp_listener_event(channel, condition, ifdata, AF_INET,
3884                                 &ifdata->udp4_listener_watch);
3885 }
3886
3887 static gboolean udp6_listener_event(GIOChannel *channel, GIOCondition condition,
3888                                 gpointer user_data)
3889 {
3890         struct listener_data *ifdata = user_data;
3891
3892         return udp_listener_event(channel, condition, user_data, AF_INET6,
3893                                 &ifdata->udp6_listener_watch);
3894 }
3895
3896 static GIOChannel *get_listener(int family, int protocol, int index)
3897 {
3898         GIOChannel *channel;
3899         const char *proto;
3900 #if !defined TIZEN_EXT
3901         union {
3902                 struct sockaddr sa;
3903                 struct sockaddr_in6 sin6;
3904                 struct sockaddr_in sin;
3905         } s;
3906         socklen_t slen;
3907 #endif
3908         int sk, type;
3909 #if !defined TIZEN_EXT
3910         char *interface;
3911 #endif
3912 #if defined TIZEN_EXT
3913         int option;
3914         int sd_num = 0;
3915         int rv;
3916         int is_socket_inet = 0;
3917 #endif
3918
3919         debug("family %d protocol %d index %d", family, protocol, index);
3920
3921         switch (protocol) {
3922         case IPPROTO_UDP:
3923                 proto = "UDP";
3924                 type = SOCK_DGRAM | SOCK_CLOEXEC;
3925                 break;
3926
3927         case IPPROTO_TCP:
3928                 proto = "TCP";
3929                 type = SOCK_STREAM | SOCK_CLOEXEC;
3930                 break;
3931
3932         default:
3933                 return NULL;
3934         }
3935 #if defined TIZEN_EXT
3936         sd_num = sd_listen_fds(0);
3937         DBG("socket type(%s) systemd number of fds(%d)", proto, sd_num);
3938         if(sd_num < 1){
3939                 DBG("fail to get the fd from systemd");
3940                 return NULL;
3941         }
3942
3943         if(protocol == IPPROTO_TCP)
3944                 type = SOCK_STREAM;
3945         else
3946                 type = SOCK_DGRAM;
3947
3948         for(sk = SD_LISTEN_FDS_START; sk < SD_LISTEN_FDS_START+sd_num; ++sk){
3949                 rv = sd_is_socket_inet(sk, family, type, -1, 53);
3950                 if(rv > 0){
3951                         DBG("socket fd (%d) is passed by systemd", sk);
3952                         is_socket_inet = 1;
3953                         break;
3954                 }
3955         }
3956
3957         if (!is_socket_inet) {
3958                 DBG("socket fd is not matched what connman requests");
3959                 return NULL;
3960         }
3961 #else
3962         sk = socket(family, type, protocol);
3963         if (sk < 0 && family == AF_INET6 && errno == EAFNOSUPPORT) {
3964                 connman_error("No IPv6 support");
3965                 return NULL;
3966         }
3967
3968         if (sk < 0) {
3969                 connman_error("Failed to create %s listener socket", proto);
3970                 return NULL;
3971         }
3972
3973         interface = connman_inet_ifname(index);
3974         if (!interface || setsockopt(sk, SOL_SOCKET, SO_BINDTODEVICE,
3975                                         interface,
3976                                         strlen(interface) + 1) < 0) {
3977                 connman_error("Failed to bind %s listener interface "
3978                         "for %s (%d/%s)",
3979                         proto, family == AF_INET ? "IPv4" : "IPv6",
3980                         -errno, strerror(errno));
3981                 close(sk);
3982                 g_free(interface);
3983                 return NULL;
3984         }
3985         g_free(interface);
3986
3987         if (family == AF_INET6) {
3988                 memset(&s.sin6, 0, sizeof(s.sin6));
3989                 s.sin6.sin6_family = AF_INET6;
3990                 s.sin6.sin6_port = htons(53);
3991                 slen = sizeof(s.sin6);
3992
3993                 if (__connman_inet_get_interface_address(index,
3994                                                 AF_INET6,
3995                                                 &s.sin6.sin6_addr) < 0) {
3996                         /* So we could not find suitable IPv6 address for
3997                          * the interface. This could happen if we have
3998                          * disabled IPv6 for the interface.
3999                          */
4000                         close(sk);
4001                         return NULL;
4002                 }
4003
4004         } else if (family == AF_INET) {
4005                 memset(&s.sin, 0, sizeof(s.sin));
4006                 s.sin.sin_family = AF_INET;
4007                 s.sin.sin_port = htons(53);
4008                 slen = sizeof(s.sin);
4009
4010                 if (__connman_inet_get_interface_address(index,
4011                                                 AF_INET,
4012                                                 &s.sin.sin_addr) < 0) {
4013                         close(sk);
4014                         return NULL;
4015                 }
4016         } else {
4017                 close(sk);
4018                 return NULL;
4019         }
4020 #endif
4021
4022 #if defined TIZEN_EXT
4023         /* When ConnMan crashed,
4024          * probably DNS listener cannot bind existing address */
4025         option = 1;
4026         if (setsockopt(sk, SOL_SOCKET, SO_REUSEADDR, &option, sizeof(option)) < 0) {
4027                 connman_error("Failed to set socket option SO_REUSEADDR");
4028                 close(sk);
4029                 return NULL;
4030         }
4031 #endif
4032 #if !defined TIZEN_EXT
4033         if (bind(sk, &s.sa, slen) < 0) {
4034                 connman_error("Failed to bind %s listener socket", proto);
4035                 close(sk);
4036                 return NULL;
4037         }
4038 #endif
4039
4040         if (protocol == IPPROTO_TCP) {
4041
4042 #if !defined TIZEN_EXT
4043                 if (listen(sk, 10) < 0) {
4044                         connman_error("Failed to listen on TCP socket %d/%s",
4045                                 -errno, strerror(errno));
4046                         close(sk);
4047                         return NULL;
4048                 }
4049
4050 #endif
4051                 fcntl(sk, F_SETFL, O_NONBLOCK);
4052         }
4053
4054         channel = g_io_channel_unix_new(sk);
4055         if (!channel) {
4056                 connman_error("Failed to create %s listener channel", proto);
4057                 close(sk);
4058                 return NULL;
4059         }
4060
4061         g_io_channel_set_close_on_unref(channel, TRUE);
4062
4063         return channel;
4064 }
4065
4066 #define UDP_IPv4_FAILED 0x01
4067 #define TCP_IPv4_FAILED 0x02
4068 #define UDP_IPv6_FAILED 0x04
4069 #define TCP_IPv6_FAILED 0x08
4070 #define UDP_FAILED (UDP_IPv4_FAILED | UDP_IPv6_FAILED)
4071 #define TCP_FAILED (TCP_IPv4_FAILED | TCP_IPv6_FAILED)
4072 #define IPv6_FAILED (UDP_IPv6_FAILED | TCP_IPv6_FAILED)
4073 #define IPv4_FAILED (UDP_IPv4_FAILED | TCP_IPv4_FAILED)
4074
4075 static int create_dns_listener(int protocol, struct listener_data *ifdata)
4076 {
4077         int ret = 0;
4078
4079         if (protocol == IPPROTO_TCP) {
4080                 ifdata->tcp4_listener_channel = get_listener(AF_INET, protocol,
4081                                                         ifdata->index);
4082                 if (ifdata->tcp4_listener_channel)
4083 #if defined TIZEN_EXT
4084                         ifdata->tcp4_listener_watch =
4085                                 g_io_add_watch(ifdata->tcp4_listener_channel,
4086                                         G_IO_IN | G_IO_ERR | G_IO_HUP | G_IO_NVAL,
4087                                         tcp4_listener_event, (gpointer)ifdata);
4088 #else
4089                         ifdata->tcp4_listener_watch =
4090                                 g_io_add_watch(ifdata->tcp4_listener_channel,
4091                                         G_IO_IN, tcp4_listener_event,
4092                                         (gpointer)ifdata);
4093 #endif
4094                 else
4095                         ret |= TCP_IPv4_FAILED;
4096
4097                 ifdata->tcp6_listener_channel = get_listener(AF_INET6, protocol,
4098                                                         ifdata->index);
4099                 if (ifdata->tcp6_listener_channel)
4100 #if defined TIZEN_EXT
4101                         ifdata->tcp6_listener_watch =
4102                                 g_io_add_watch(ifdata->tcp6_listener_channel,
4103                                         G_IO_IN | G_IO_ERR | G_IO_HUP | G_IO_NVAL,
4104                                         tcp6_listener_event, (gpointer)ifdata);
4105 #else
4106                         ifdata->tcp6_listener_watch =
4107                                 g_io_add_watch(ifdata->tcp6_listener_channel,
4108                                         G_IO_IN, tcp6_listener_event,
4109                                         (gpointer)ifdata);
4110 #endif
4111                 else
4112                         ret |= TCP_IPv6_FAILED;
4113         } else {
4114                 ifdata->udp4_listener_channel = get_listener(AF_INET, protocol,
4115                                                         ifdata->index);
4116                 if (ifdata->udp4_listener_channel)
4117 #if defined TIZEN_EXT
4118                         ifdata->udp4_listener_watch =
4119                                 g_io_add_watch(ifdata->udp4_listener_channel,
4120                                         G_IO_IN | G_IO_ERR | G_IO_HUP | G_IO_NVAL,
4121                                         udp4_listener_event, (gpointer)ifdata);
4122 #else
4123                         ifdata->udp4_listener_watch =
4124                                 g_io_add_watch(ifdata->udp4_listener_channel,
4125                                         G_IO_IN, udp4_listener_event,
4126                                         (gpointer)ifdata);
4127 #endif
4128                 else
4129                         ret |= UDP_IPv4_FAILED;
4130
4131                 ifdata->udp6_listener_channel = get_listener(AF_INET6, protocol,
4132                                                         ifdata->index);
4133                 if (ifdata->udp6_listener_channel)
4134 #if defined TIZEN_EXT
4135                         ifdata->udp6_listener_watch =
4136                                 g_io_add_watch(ifdata->udp6_listener_channel,
4137                                         G_IO_IN | G_IO_ERR | G_IO_HUP | G_IO_NVAL,
4138                                         udp6_listener_event, (gpointer)ifdata);
4139 #else
4140                         ifdata->udp6_listener_watch =
4141                                 g_io_add_watch(ifdata->udp6_listener_channel,
4142                                         G_IO_IN, udp6_listener_event,
4143                                         (gpointer)ifdata);
4144 #endif
4145                 else
4146                         ret |= UDP_IPv6_FAILED;
4147         }
4148
4149         return ret;
4150 }
4151
4152 static void destroy_udp_listener(struct listener_data *ifdata)
4153 {
4154         DBG("index %d", ifdata->index);
4155
4156         if (ifdata->udp4_listener_watch > 0)
4157                 g_source_remove(ifdata->udp4_listener_watch);
4158
4159         if (ifdata->udp6_listener_watch > 0)
4160                 g_source_remove(ifdata->udp6_listener_watch);
4161
4162         if (ifdata->udp4_listener_channel)
4163                 g_io_channel_unref(ifdata->udp4_listener_channel);
4164         if (ifdata->udp6_listener_channel)
4165                 g_io_channel_unref(ifdata->udp6_listener_channel);
4166 }
4167
4168 static void destroy_tcp_listener(struct listener_data *ifdata)
4169 {
4170         DBG("index %d", ifdata->index);
4171
4172         if (ifdata->tcp4_listener_watch > 0)
4173                 g_source_remove(ifdata->tcp4_listener_watch);
4174         if (ifdata->tcp6_listener_watch > 0)
4175                 g_source_remove(ifdata->tcp6_listener_watch);
4176
4177         if (ifdata->tcp4_listener_channel)
4178                 g_io_channel_unref(ifdata->tcp4_listener_channel);
4179         if (ifdata->tcp6_listener_channel)
4180                 g_io_channel_unref(ifdata->tcp6_listener_channel);
4181 }
4182
4183 static int create_listener(struct listener_data *ifdata)
4184 {
4185         int err, index;
4186
4187         err = create_dns_listener(IPPROTO_UDP, ifdata);
4188         if ((err & UDP_FAILED) == UDP_FAILED)
4189                 return -EIO;
4190
4191         err |= create_dns_listener(IPPROTO_TCP, ifdata);
4192         if ((err & TCP_FAILED) == TCP_FAILED) {
4193                 destroy_udp_listener(ifdata);
4194                 return -EIO;
4195         }
4196
4197         index = connman_inet_ifindex("lo");
4198         if (ifdata->index == index) {
4199                 if ((err & IPv6_FAILED) != IPv6_FAILED)
4200                         __connman_resolvfile_append(index, NULL, "::1");
4201
4202                 if ((err & IPv4_FAILED) != IPv4_FAILED)
4203                         __connman_resolvfile_append(index, NULL, "127.0.0.1");
4204         }
4205
4206         return 0;
4207 }
4208
4209 static void destroy_listener(struct listener_data *ifdata)
4210 {
4211         int index;
4212         GSList *list;
4213
4214         index = connman_inet_ifindex("lo");
4215         if (ifdata->index == index) {
4216                 __connman_resolvfile_remove(index, NULL, "127.0.0.1");
4217                 __connman_resolvfile_remove(index, NULL, "::1");
4218         }
4219
4220         for (list = request_list; list; list = list->next) {
4221                 struct request_data *req = list->data;
4222
4223                 debug("Dropping request (id 0x%04x -> 0x%04x)",
4224                                                 req->srcid, req->dstid);
4225                 destroy_request_data(req);
4226                 list->data = NULL;
4227         }
4228
4229         g_slist_free(request_list);
4230         request_list = NULL;
4231
4232         destroy_tcp_listener(ifdata);
4233         destroy_udp_listener(ifdata);
4234 }
4235
4236 int __connman_dnsproxy_add_listener(int index)
4237 {
4238         struct listener_data *ifdata;
4239         int err;
4240
4241         DBG("index %d", index);
4242
4243         if (index < 0)
4244                 return -EINVAL;
4245
4246         if (!listener_table)
4247                 return -ENOENT;
4248
4249         if (g_hash_table_lookup(listener_table, GINT_TO_POINTER(index)))
4250                 return 0;
4251
4252         ifdata = g_try_new0(struct listener_data, 1);
4253         if (!ifdata)
4254                 return -ENOMEM;
4255
4256         ifdata->index = index;
4257         ifdata->udp4_listener_channel = NULL;
4258         ifdata->udp4_listener_watch = 0;
4259         ifdata->tcp4_listener_channel = NULL;
4260         ifdata->tcp4_listener_watch = 0;
4261         ifdata->udp6_listener_channel = NULL;
4262         ifdata->udp6_listener_watch = 0;
4263         ifdata->tcp6_listener_channel = NULL;
4264         ifdata->tcp6_listener_watch = 0;
4265
4266         err = create_listener(ifdata);
4267         if (err < 0) {
4268                 connman_error("Couldn't create listener for index %d err %d",
4269                                 index, err);
4270                 g_free(ifdata);
4271                 return err;
4272         }
4273         g_hash_table_insert(listener_table, GINT_TO_POINTER(ifdata->index),
4274                         ifdata);
4275         return 0;
4276 }
4277
4278 void __connman_dnsproxy_remove_listener(int index)
4279 {
4280         struct listener_data *ifdata;
4281
4282         DBG("index %d", index);
4283
4284         if (!listener_table)
4285                 return;
4286
4287         ifdata = g_hash_table_lookup(listener_table, GINT_TO_POINTER(index));
4288         if (!ifdata)
4289                 return;
4290
4291         destroy_listener(ifdata);
4292
4293         g_hash_table_remove(listener_table, GINT_TO_POINTER(index));
4294 }
4295
4296 static void remove_listener(gpointer key, gpointer value, gpointer user_data)
4297 {
4298         int index = GPOINTER_TO_INT(key);
4299         struct listener_data *ifdata = value;
4300
4301         DBG("index %d", index);
4302
4303         destroy_listener(ifdata);
4304 }
4305
4306 static void free_partial_reqs(gpointer value)
4307 {
4308         struct tcp_partial_client_data *data = value;
4309
4310         client_reset(data);
4311         g_free(data);
4312 }
4313
4314 int __connman_dnsproxy_init(void)
4315 {
4316         int err, index;
4317
4318         DBG("");
4319
4320         listener_table = g_hash_table_new_full(g_direct_hash, g_direct_equal,
4321                                                         NULL, g_free);
4322
4323         partial_tcp_req_table = g_hash_table_new_full(g_direct_hash,
4324                                                         g_direct_equal,
4325                                                         NULL,
4326                                                         free_partial_reqs);
4327
4328         index = connman_inet_ifindex("lo");
4329         err = __connman_dnsproxy_add_listener(index);
4330         if (err < 0)
4331                 return err;
4332
4333         err = connman_notifier_register(&dnsproxy_notifier);
4334         if (err < 0)
4335                 goto destroy;
4336
4337         return 0;
4338
4339 destroy:
4340         __connman_dnsproxy_remove_listener(index);
4341         g_hash_table_destroy(listener_table);
4342         g_hash_table_destroy(partial_tcp_req_table);
4343
4344         return err;
4345 }
4346
4347 int __connman_dnsproxy_set_mdns(int index, bool enabled)
4348 {
4349         return -ENOTSUP;
4350 }
4351
4352 void __connman_dnsproxy_cleanup(void)
4353 {
4354         DBG("");
4355
4356         if (cache_timer) {
4357                 g_source_remove(cache_timer);
4358                 cache_timer = 0;
4359         }
4360
4361         if (cache) {
4362                 g_hash_table_destroy(cache);
4363                 cache = NULL;
4364         }
4365
4366         connman_notifier_unregister(&dnsproxy_notifier);
4367
4368         g_hash_table_foreach(listener_table, remove_listener, NULL);
4369
4370         g_hash_table_destroy(listener_table);
4371
4372         g_hash_table_destroy(partial_tcp_req_table);
4373
4374         if (ipv4_resolve)
4375                 g_resolv_unref(ipv4_resolve);
4376         if (ipv6_resolve)
4377                 g_resolv_unref(ipv6_resolve);
4378 }