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