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