f5ec50210345aec6659188fbcb4f65e0566e73cd
[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         if(fd > 0)
2598                 close(fd);
2599         server_destroy_socket(server);
2600
2601         if (server->protocol == IPPROTO_UDP && server->enabled)
2602                 DBG("Removing DNS server %s", server->server);
2603
2604         g_free(server->server);
2605         for (list = server->domains; list; list = list->next) {
2606                 char *domain = list->data;
2607
2608                 server->domains = g_list_remove(server->domains, domain);
2609                 g_free(domain);
2610         }
2611         g_free(server->server_addr);
2612
2613         /*
2614          * We do not remove cache right away but delay it few seconds.
2615          * The idea is that when IPv6 DNS server is added via RDNSS, it has a
2616          * lifetime. When the lifetime expires we decrease the refcount so it
2617          * is possible that the cache is then removed. Because a new DNS server
2618          * is usually created almost immediately we would then loose the cache
2619          * without any good reason. The small delay allows the new RDNSS to
2620          * create a new DNS server instance and the refcount does not go to 0.
2621          */
2622         /* TODO: Need to check this */
2623         /* g_timeout_add_seconds(3, try_remove_cache, NULL); */
2624
2625         g_free(server);
2626 }
2627
2628 static void destroy_all_server_sec()
2629 {
2630         GSList *list;
2631
2632         DBG("remove all dns server");
2633
2634         for (list = server_list_sec; list; list = list->next) {
2635                 struct server_data *server = list->data;
2636                 destroy_server_sec(server);
2637         }
2638         server_list_sec = NULL;
2639 }
2640
2641 static gboolean sec_udp_idle_timeout(gpointer user_data)
2642 {
2643         struct server_data *server = user_data;
2644
2645         DBG("");
2646
2647         if (server == NULL)
2648                 return FALSE;
2649
2650         destroy_server_sec(server);
2651
2652         return FALSE;
2653 }
2654
2655 static struct server_data *create_server_sec(int index,
2656                                         const char *domain, const char *server,
2657                                         int protocol)
2658 {
2659         struct server_data *data;
2660         struct addrinfo hints, *rp;
2661         int ret;
2662
2663         DBG("index %d server %s", index, server);
2664
2665         data = g_try_new0(struct server_data, 1);
2666         if (data == NULL) {
2667                 connman_error("Failed to allocate server %s data", server);
2668                 return NULL;
2669         }
2670
2671         data->index = index;
2672         if (domain)
2673                 data->domains = g_list_append(data->domains, g_strdup(domain));
2674         data->server = g_strdup(server);
2675         data->protocol = protocol;
2676
2677         memset(&hints, 0, sizeof(hints));
2678
2679         switch (protocol) {
2680         case IPPROTO_UDP:
2681                 hints.ai_socktype = SOCK_DGRAM;
2682                 break;
2683
2684         case IPPROTO_TCP:
2685                 hints.ai_socktype = SOCK_STREAM;
2686                 break;
2687
2688         default:
2689                 destroy_server_sec(data);
2690                 return NULL;
2691         }
2692         hints.ai_family = AF_UNSPEC;
2693         hints.ai_flags = AI_NUMERICSERV | AI_NUMERICHOST;
2694
2695         ret = getaddrinfo(data->server, "53", &hints, &rp);
2696         if (ret) {
2697                 connman_error("Failed to parse server %s address: %s\n",
2698                                 data->server, gai_strerror(ret));
2699                 destroy_server_sec(data);
2700                 return NULL;
2701         }
2702
2703         /* Do not blindly copy this code elsewhere; it doesn't loop over the
2704            results using ->ai_next as it should. That's OK in *this* case
2705            because it was a numeric lookup; we *know* there's only one. */
2706
2707         data->server_addr_len = rp->ai_addrlen;
2708
2709         switch (rp->ai_family) {
2710         case AF_INET:
2711                 data->server_addr = (struct sockaddr *)
2712                                         g_try_new0(struct sockaddr_in, 1);
2713                 break;
2714         case AF_INET6:
2715                 data->server_addr = (struct sockaddr *)
2716                                         g_try_new0(struct sockaddr_in6, 1);
2717                 break;
2718         default:
2719                 connman_error("Wrong address family %d", rp->ai_family);
2720                 break;
2721         }
2722         if (data->server_addr == NULL) {
2723                 freeaddrinfo(rp);
2724                 destroy_server_sec(data);
2725                 return NULL;
2726         }
2727         memcpy(data->server_addr, rp->ai_addr, rp->ai_addrlen);
2728         freeaddrinfo(rp);
2729
2730         if (server_create_socket(data) != 0) {
2731                 destroy_server_sec(data);
2732                 return NULL;
2733         }
2734
2735         if (protocol == IPPROTO_UDP) {
2736                 /* Enable new servers by default */
2737                 data->enabled = TRUE;
2738                 DBG("Adding DNS server %s", data->server);
2739
2740                 data->timeout = g_timeout_add_seconds(30, sec_udp_idle_timeout,
2741                                                                 data);
2742
2743                 server_list_sec = g_slist_append(server_list_sec, data);
2744         }
2745
2746         return data;
2747 }
2748 #endif
2749
2750 static struct server_data *create_server(int index,
2751                                         const char *domain, const char *server,
2752                                         int protocol)
2753 {
2754         struct server_data *data;
2755         struct addrinfo hints, *rp;
2756         int ret;
2757
2758         DBG("index %d server %s", index, server);
2759
2760         data = g_try_new0(struct server_data, 1);
2761         if (!data) {
2762                 connman_error("Failed to allocate server %s data", server);
2763                 return NULL;
2764         }
2765
2766         data->index = index;
2767         if (domain)
2768                 data->domains = g_list_append(data->domains, g_strdup(domain));
2769         data->server = g_strdup(server);
2770         data->protocol = protocol;
2771
2772         memset(&hints, 0, sizeof(hints));
2773
2774         switch (protocol) {
2775         case IPPROTO_UDP:
2776                 hints.ai_socktype = SOCK_DGRAM;
2777                 break;
2778
2779         case IPPROTO_TCP:
2780                 hints.ai_socktype = SOCK_STREAM;
2781                 break;
2782
2783         default:
2784                 destroy_server(data);
2785                 return NULL;
2786         }
2787         hints.ai_family = AF_UNSPEC;
2788         hints.ai_flags = AI_NUMERICSERV | AI_NUMERICHOST;
2789
2790         ret = getaddrinfo(data->server, "53", &hints, &rp);
2791         if (ret) {
2792                 connman_error("Failed to parse server %s address: %s\n",
2793                               data->server, gai_strerror(ret));
2794                 destroy_server(data);
2795                 return NULL;
2796         }
2797
2798         /* Do not blindly copy this code elsewhere; it doesn't loop over the
2799            results using ->ai_next as it should. That's OK in *this* case
2800            because it was a numeric lookup; we *know* there's only one. */
2801
2802         data->server_addr_len = rp->ai_addrlen;
2803
2804         switch (rp->ai_family) {
2805         case AF_INET:
2806                 data->server_addr = (struct sockaddr *)
2807                                         g_try_new0(struct sockaddr_in, 1);
2808                 break;
2809         case AF_INET6:
2810                 data->server_addr = (struct sockaddr *)
2811                                         g_try_new0(struct sockaddr_in6, 1);
2812                 break;
2813         default:
2814                 connman_error("Wrong address family %d", rp->ai_family);
2815                 break;
2816         }
2817         if (!data->server_addr) {
2818                 freeaddrinfo(rp);
2819                 destroy_server(data);
2820                 return NULL;
2821         }
2822         memcpy(data->server_addr, rp->ai_addr, rp->ai_addrlen);
2823         freeaddrinfo(rp);
2824
2825         if (server_create_socket(data) != 0) {
2826                 destroy_server(data);
2827                 return NULL;
2828         }
2829
2830         if (protocol == IPPROTO_UDP) {
2831                 if (__connman_service_index_is_default(data->index) ||
2832                                 __connman_service_index_is_split_routing(
2833                                                                 data->index)) {
2834                         data->enabled = true;
2835                         DBG("Adding DNS server %s", data->server);
2836                 }
2837
2838                 server_list = g_slist_append(server_list, data);
2839         }
2840
2841         return data;
2842 }
2843
2844 static bool resolv(struct request_data *req,
2845                                 gpointer request, gpointer name)
2846 {
2847         GSList *list;
2848
2849         for (list = server_list; list; list = list->next) {
2850                 struct server_data *data = list->data;
2851
2852                 if (data->protocol == IPPROTO_TCP) {
2853                         DBG("server %s ignored proto TCP", data->server);
2854                         continue;
2855                 }
2856
2857                 DBG("server %s enabled %d", data->server, data->enabled);
2858
2859                 if (!data->enabled)
2860                         continue;
2861
2862                 if (!data->channel && data->protocol == IPPROTO_UDP) {
2863                         if (server_create_socket(data) < 0) {
2864                                 DBG("socket creation failed while resolving");
2865                                 continue;
2866                         }
2867                 }
2868
2869                 if (ns_resolv(data, req, request, name) > 0)
2870                         return true;
2871         }
2872
2873         return false;
2874 }
2875
2876 static void append_domain(int index, const char *domain)
2877 {
2878         GSList *list;
2879
2880         DBG("index %d domain %s", index, domain);
2881
2882         if (!domain)
2883                 return;
2884
2885         for (list = server_list; list; list = list->next) {
2886                 struct server_data *data = list->data;
2887                 GList *dom_list;
2888                 char *dom;
2889                 bool dom_found = false;
2890
2891                 if (data->index < 0)
2892                         continue;
2893
2894                 if (data->index != index)
2895                         continue;
2896
2897                 for (dom_list = data->domains; dom_list;
2898                                 dom_list = dom_list->next) {
2899                         dom = dom_list->data;
2900
2901                         if (g_str_equal(dom, domain)) {
2902                                 dom_found = true;
2903                                 break;
2904                         }
2905                 }
2906
2907                 if (!dom_found) {
2908                         data->domains =
2909                                 g_list_append(data->domains, g_strdup(domain));
2910                 }
2911         }
2912 }
2913
2914 static void flush_requests(struct server_data *server)
2915 {
2916         GSList *list;
2917
2918         list = request_list;
2919         while (list) {
2920                 struct request_data *req = list->data;
2921
2922                 list = list->next;
2923
2924                 if (ns_resolv(server, req, req->request, req->name)) {
2925                         /*
2926                          * A cached result was sent,
2927                          * so the request can be released
2928                          */
2929                         request_list =
2930                                 g_slist_remove(request_list, req);
2931                         destroy_request_data(req);
2932                         continue;
2933                 }
2934
2935                 if (req->timeout > 0)
2936                         g_source_remove(req->timeout);
2937
2938                 req->timeout = g_timeout_add_seconds(5, request_timeout, req);
2939         }
2940 }
2941
2942 int __connman_dnsproxy_append(int index, const char *domain,
2943                                                         const char *server)
2944 {
2945         struct server_data *data;
2946
2947         DBG("index %d server %s", index, server);
2948
2949         if (!server && !domain)
2950                 return -EINVAL;
2951
2952         if (!server) {
2953                 append_domain(index, domain);
2954
2955                 return 0;
2956         }
2957
2958         if (g_str_equal(server, "127.0.0.1"))
2959                 return -ENODEV;
2960
2961         if (g_str_equal(server, "::1"))
2962                 return -ENODEV;
2963
2964         data = find_server(index, server, IPPROTO_UDP);
2965         if (data) {
2966                 append_domain(index, domain);
2967                 return 0;
2968         }
2969
2970         data = create_server(index, domain, server, IPPROTO_UDP);
2971         if (!data)
2972                 return -EIO;
2973
2974         flush_requests(data);
2975
2976         return 0;
2977 }
2978
2979 static void remove_server(int index, const char *domain,
2980                         const char *server, int protocol)
2981 {
2982         struct server_data *data;
2983
2984         data = find_server(index, server, protocol);
2985         if (!data)
2986                 return;
2987
2988         destroy_server(data);
2989 }
2990
2991 int __connman_dnsproxy_remove(int index, const char *domain,
2992                                                         const char *server)
2993 {
2994         DBG("index %d server %s", index, server);
2995
2996         if (!server)
2997                 return -EINVAL;
2998
2999         if (g_str_equal(server, "127.0.0.1"))
3000                 return -ENODEV;
3001
3002         if (g_str_equal(server, "::1"))
3003                 return -ENODEV;
3004
3005         remove_server(index, domain, server, IPPROTO_UDP);
3006         remove_server(index, domain, server, IPPROTO_TCP);
3007
3008 #if defined TIZEN_EXT
3009         destroy_all_server_sec();
3010 #endif
3011
3012         return 0;
3013 }
3014
3015 static void dnsproxy_offline_mode(bool enabled)
3016 {
3017         GSList *list;
3018
3019         DBG("enabled %d", enabled);
3020
3021         for (list = server_list; list; list = list->next) {
3022                 struct server_data *data = list->data;
3023
3024                 if (!enabled) {
3025                         DBG("Enabling DNS server %s", data->server);
3026                         data->enabled = true;
3027                         cache_invalidate();
3028                         cache_refresh();
3029                 } else {
3030                         DBG("Disabling DNS server %s", data->server);
3031                         data->enabled = false;
3032                         cache_invalidate();
3033                 }
3034         }
3035 }
3036
3037 static void dnsproxy_default_changed(struct connman_service *service)
3038 {
3039         GSList *list;
3040         int index;
3041
3042         DBG("service %p", service);
3043
3044         /* DNS has changed, invalidate the cache */
3045         cache_invalidate();
3046
3047         if (!service) {
3048                 /* When no services are active, then disable DNS proxying */
3049                 dnsproxy_offline_mode(true);
3050                 return;
3051         }
3052
3053         index = __connman_service_get_index(service);
3054         if (index < 0)
3055                 return;
3056
3057         for (list = server_list; list; list = list->next) {
3058                 struct server_data *data = list->data;
3059
3060                 if (data->index == index) {
3061                         DBG("Enabling DNS server %s", data->server);
3062                         data->enabled = true;
3063                 } else {
3064                         DBG("Disabling DNS server %s", data->server);
3065                         data->enabled = false;
3066                 }
3067         }
3068
3069         cache_refresh();
3070 }
3071
3072 static struct connman_notifier dnsproxy_notifier = {
3073         .name                   = "dnsproxy",
3074         .default_changed        = dnsproxy_default_changed,
3075         .offline_mode           = dnsproxy_offline_mode,
3076 };
3077
3078 static unsigned char opt_edns0_type[2] = { 0x00, 0x29 };
3079
3080 static int parse_request(unsigned char *buf, int len,
3081                                         char *name, unsigned int size)
3082 {
3083         struct domain_hdr *hdr = (void *) buf;
3084         uint16_t qdcount = ntohs(hdr->qdcount);
3085         uint16_t arcount = ntohs(hdr->arcount);
3086         unsigned char *ptr;
3087         char *last_label = NULL;
3088         unsigned int remain, used = 0;
3089
3090         if (len < 12)
3091                 return -EINVAL;
3092
3093         DBG("id 0x%04x qr %d opcode %d qdcount %d arcount %d",
3094                                         hdr->id, hdr->qr, hdr->opcode,
3095                                                         qdcount, arcount);
3096
3097         if (hdr->qr != 0 || qdcount != 1)
3098                 return -EINVAL;
3099
3100         name[0] = '\0';
3101
3102         ptr = buf + sizeof(struct domain_hdr);
3103         remain = len - sizeof(struct domain_hdr);
3104
3105         while (remain > 0) {
3106                 uint8_t label_len = *ptr;
3107
3108                 if (label_len == 0x00) {
3109                         last_label = (char *) (ptr + 1);
3110                         break;
3111                 }
3112
3113                 if (used + label_len + 1 > size)
3114                         return -ENOBUFS;
3115
3116                 strncat(name, (char *) (ptr + 1), label_len);
3117                 strcat(name, ".");
3118
3119                 used += label_len + 1;
3120
3121                 ptr += label_len + 1;
3122                 remain -= label_len + 1;
3123         }
3124
3125 #if defined TIZEN_EXT
3126         /* parse DNS query type either A or AAAA
3127          * enforce to drop AAAA temporarily (IPv6 not supported)
3128          */
3129         if (last_label != NULL) {
3130                 uint16_t *type_p = (uint16_t *)last_label;
3131                 uint16_t type = ntohs(*type_p);
3132
3133                 if (type == 0x1c) {
3134                         DBG("query %s is type AAAA(0x%x)", name, type);
3135                         return -ENOENT;
3136                 }
3137         }
3138 #endif
3139
3140         if (last_label && arcount && remain >= 9 && last_label[4] == 0 &&
3141                                 !memcmp(last_label + 5, opt_edns0_type, 2)) {
3142                 uint16_t edns0_bufsize;
3143
3144                 edns0_bufsize = last_label[7] << 8 | last_label[8];
3145
3146                 DBG("EDNS0 buffer size %u", edns0_bufsize);
3147
3148                 /* This is an evil hack until full TCP support has been
3149                  * implemented.
3150                  *
3151                  * Somtimes the EDNS0 request gets send with a too-small
3152                  * buffer size. Since glibc doesn't seem to crash when it
3153                  * gets a response biffer then it requested, just bump
3154                  * the buffer size up to 4KiB.
3155                  */
3156                 if (edns0_bufsize < 0x1000) {
3157                         last_label[7] = 0x10;
3158                         last_label[8] = 0x00;
3159                 }
3160         }
3161
3162         DBG("query %s", name);
3163
3164         return 0;
3165 }
3166
3167 static void client_reset(struct tcp_partial_client_data *client)
3168 {
3169         if (!client)
3170                 return;
3171
3172         if (client->channel) {
3173                 DBG("client %d closing",
3174                         g_io_channel_unix_get_fd(client->channel));
3175
3176                 g_io_channel_unref(client->channel);
3177                 client->channel = NULL;
3178         }
3179
3180         if (client->watch > 0) {
3181                 g_source_remove(client->watch);
3182                 client->watch = 0;
3183         }
3184
3185         if (client->timeout > 0) {
3186                 g_source_remove(client->timeout);
3187                 client->timeout = 0;
3188         }
3189
3190         g_free(client->buf);
3191         client->buf = NULL;
3192
3193         client->buf_end = 0;
3194 }
3195
3196 static unsigned int get_msg_len(unsigned char *buf)
3197 {
3198         return buf[0]<<8 | buf[1];
3199 }
3200
3201 static bool read_tcp_data(struct tcp_partial_client_data *client,
3202                                 void *client_addr, socklen_t client_addr_len,
3203                                 int read_len)
3204 {
3205         char query[TCP_MAX_BUF_LEN];
3206         struct request_data *req;
3207         int client_sk, err;
3208         unsigned int msg_len;
3209         GSList *list;
3210         bool waiting_for_connect = false;
3211         int qtype = 0;
3212         struct cache_entry *entry;
3213
3214         client_sk = g_io_channel_unix_get_fd(client->channel);
3215
3216         if (read_len == 0) {
3217                 DBG("client %d closed, pending %d bytes",
3218                         client_sk, client->buf_end);
3219                 g_hash_table_remove(partial_tcp_req_table,
3220                                         GINT_TO_POINTER(client_sk));
3221                 return false;
3222         }
3223
3224         DBG("client %d received %d bytes", client_sk, read_len);
3225
3226         client->buf_end += read_len;
3227
3228         if (client->buf_end < 2)
3229                 return true;
3230
3231         msg_len = get_msg_len(client->buf);
3232         if (msg_len > TCP_MAX_BUF_LEN) {
3233                 DBG("client %d sent too much data %d", client_sk, msg_len);
3234                 g_hash_table_remove(partial_tcp_req_table,
3235                                         GINT_TO_POINTER(client_sk));
3236                 return false;
3237         }
3238
3239 read_another:
3240         DBG("client %d msg len %d end %d past end %d", client_sk, msg_len,
3241                 client->buf_end, client->buf_end - (msg_len + 2));
3242
3243         if (client->buf_end < (msg_len + 2)) {
3244                 DBG("client %d still missing %d bytes",
3245                         client_sk,
3246                         msg_len + 2 - client->buf_end);
3247                 return true;
3248         }
3249
3250         DBG("client %d all data %d received", client_sk, msg_len);
3251
3252         err = parse_request(client->buf + 2, msg_len,
3253                         query, sizeof(query));
3254         if (err < 0 || (g_slist_length(server_list) == 0)) {
3255                 send_response(client_sk, client->buf, msg_len + 2,
3256                         NULL, 0, IPPROTO_TCP);
3257                 return true;
3258         }
3259
3260         req = g_try_new0(struct request_data, 1);
3261         if (!req)
3262                 return true;
3263
3264         memcpy(&req->sa, client_addr, client_addr_len);
3265         req->sa_len = client_addr_len;
3266         req->client_sk = client_sk;
3267         req->protocol = IPPROTO_TCP;
3268         req->family = client->family;
3269
3270         req->srcid = client->buf[2] | (client->buf[3] << 8);
3271         req->dstid = get_id();
3272         req->altid = get_id();
3273         req->request_len = msg_len + 2;
3274
3275         client->buf[2] = req->dstid & 0xff;
3276         client->buf[3] = req->dstid >> 8;
3277
3278         req->numserv = 0;
3279         req->ifdata = client->ifdata;
3280         req->append_domain = false;
3281
3282         /*
3283          * Check if the answer is found in the cache before
3284          * creating sockets to the server.
3285          */
3286         entry = cache_check(client->buf, &qtype, IPPROTO_TCP);
3287         if (entry) {
3288                 int ttl_left = 0;
3289                 struct cache_data *data;
3290
3291                 DBG("cache hit %s type %s", query, qtype == 1 ? "A" : "AAAA");
3292                 if (qtype == 1)
3293                         data = entry->ipv4;
3294                 else
3295                         data = entry->ipv6;
3296
3297                 if (data) {
3298                         ttl_left = data->valid_until - time(NULL);
3299                         entry->hits++;
3300
3301                         send_cached_response(client_sk, data->data,
3302                                         data->data_len, NULL, 0, IPPROTO_TCP,
3303                                         req->srcid, data->answers, ttl_left);
3304
3305                         g_free(req);
3306                         goto out;
3307                 } else
3308                         DBG("data missing, ignoring cache for this query");
3309         }
3310
3311         for (list = server_list; list; list = list->next) {
3312                 struct server_data *data = list->data;
3313
3314                 if (data->protocol != IPPROTO_UDP || !data->enabled)
3315                         continue;
3316
3317                 if (!create_server(data->index, NULL, data->server,
3318                                         IPPROTO_TCP))
3319                         continue;
3320
3321                 waiting_for_connect = true;
3322         }
3323
3324         if (!waiting_for_connect) {
3325                 /* No server is waiting for connect */
3326                 send_response(client_sk, client->buf,
3327                         req->request_len, NULL, 0, IPPROTO_TCP);
3328                 g_free(req);
3329                 return true;
3330         }
3331
3332         /*
3333          * The server is not connected yet.
3334          * Copy the relevant buffers.
3335          * The request will actually be sent once we're
3336          * properly connected over TCP to the nameserver.
3337          */
3338         req->request = g_try_malloc0(req->request_len);
3339         if (!req->request) {
3340                 send_response(client_sk, client->buf,
3341                         req->request_len, NULL, 0, IPPROTO_TCP);
3342                 g_free(req);
3343                 goto out;
3344         }
3345         memcpy(req->request, client->buf, req->request_len);
3346
3347         req->name = g_try_malloc0(sizeof(query));
3348         if (!req->name) {
3349                 send_response(client_sk, client->buf,
3350                         req->request_len, NULL, 0, IPPROTO_TCP);
3351                 g_free(req->request);
3352                 g_free(req);
3353                 goto out;
3354         }
3355         memcpy(req->name, query, sizeof(query));
3356
3357         req->timeout = g_timeout_add_seconds(30, request_timeout, req);
3358
3359         request_list = g_slist_append(request_list, req);
3360
3361 out:
3362         if (client->buf_end > (msg_len + 2)) {
3363                 DBG("client %d buf %p -> %p end %d len %d new %d",
3364                         client_sk,
3365                         client->buf + msg_len + 2,
3366                         client->buf, client->buf_end,
3367                         TCP_MAX_BUF_LEN - client->buf_end,
3368                         client->buf_end - (msg_len + 2));
3369                 memmove(client->buf, client->buf + msg_len + 2,
3370                         TCP_MAX_BUF_LEN - client->buf_end);
3371                 client->buf_end = client->buf_end - (msg_len + 2);
3372
3373                 /*
3374                  * If we have a full message waiting, just read it
3375                  * immediately.
3376                  */
3377                 msg_len = get_msg_len(client->buf);
3378                 if ((msg_len + 2) == client->buf_end) {
3379                         DBG("client %d reading another %d bytes", client_sk,
3380                                                                 msg_len + 2);
3381                         goto read_another;
3382                 }
3383         } else {
3384                 DBG("client %d clearing reading buffer", client_sk);
3385
3386                 client->buf_end = 0;
3387                 memset(client->buf, 0, TCP_MAX_BUF_LEN);
3388
3389                 /*
3390                  * We received all the packets from client so we must also
3391                  * remove the timeout handler here otherwise we might get
3392                  * timeout while waiting the results from server.
3393                  */
3394                 g_source_remove(client->timeout);
3395                 client->timeout = 0;
3396         }
3397
3398         return true;
3399 }
3400
3401 static gboolean tcp_client_event(GIOChannel *channel, GIOCondition condition,
3402                                 gpointer user_data)
3403 {
3404         struct tcp_partial_client_data *client = user_data;
3405         struct sockaddr_in6 client_addr6;
3406         socklen_t client_addr6_len = sizeof(client_addr6);
3407         struct sockaddr_in client_addr4;
3408         socklen_t client_addr4_len = sizeof(client_addr4);
3409         void *client_addr;
3410         socklen_t *client_addr_len;
3411         int len, client_sk;
3412
3413         client_sk = g_io_channel_unix_get_fd(channel);
3414
3415         if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
3416                 g_hash_table_remove(partial_tcp_req_table,
3417                                         GINT_TO_POINTER(client_sk));
3418
3419                 connman_error("Error with TCP client %d channel", client_sk);
3420                 return FALSE;
3421         }
3422
3423         switch (client->family) {
3424         case AF_INET:
3425                 client_addr = &client_addr4;
3426                 client_addr_len = &client_addr4_len;
3427                 break;
3428         case AF_INET6:
3429                 client_addr = &client_addr6;
3430                 client_addr_len = &client_addr6_len;
3431                 break;
3432         default:
3433                 g_hash_table_remove(partial_tcp_req_table,
3434                                         GINT_TO_POINTER(client_sk));
3435                 connman_error("client %p corrupted", client);
3436                 return FALSE;
3437         }
3438
3439         len = recvfrom(client_sk, client->buf + client->buf_end,
3440                         TCP_MAX_BUF_LEN - client->buf_end, 0,
3441                         client_addr, client_addr_len);
3442         if (len < 0) {
3443                 if (errno == EAGAIN || errno == EWOULDBLOCK)
3444                         return TRUE;
3445
3446                 DBG("client %d cannot read errno %d/%s", client_sk, -errno,
3447                         strerror(errno));
3448                 g_hash_table_remove(partial_tcp_req_table,
3449                                         GINT_TO_POINTER(client_sk));
3450                 return FALSE;
3451         }
3452
3453         return read_tcp_data(client, client_addr, *client_addr_len, len);
3454 }
3455
3456 static gboolean client_timeout(gpointer user_data)
3457 {
3458         struct tcp_partial_client_data *client = user_data;
3459         int sock;
3460
3461         sock = g_io_channel_unix_get_fd(client->channel);
3462
3463         DBG("client %d timeout pending %d bytes", sock, client->buf_end);
3464
3465         g_hash_table_remove(partial_tcp_req_table, GINT_TO_POINTER(sock));
3466
3467         return FALSE;
3468 }
3469
3470 #if defined TIZEN_EXT
3471 static void recover_listener(GIOChannel *channel, struct listener_data *ifdata)
3472 {
3473         int sk, index;
3474
3475         index = ifdata->index;
3476
3477         sk = g_io_channel_unix_get_fd(channel);
3478         close(sk);
3479
3480         __connman_dnsproxy_remove_listener(index);
3481
3482         if (__connman_dnsproxy_add_listener(index) == 0)
3483                 DBG("listener %d successfully recovered", index);
3484 }
3485 #endif
3486
3487 static bool tcp_listener_event(GIOChannel *channel, GIOCondition condition,
3488                                 struct listener_data *ifdata, int family,
3489                                 guint *listener_watch)
3490 {
3491         int sk, client_sk, len;
3492         unsigned int msg_len;
3493         struct tcp_partial_client_data *client;
3494         struct sockaddr_in6 client_addr6;
3495         socklen_t client_addr6_len = sizeof(client_addr6);
3496         struct sockaddr_in client_addr4;
3497         socklen_t client_addr4_len = sizeof(client_addr4);
3498         void *client_addr;
3499         socklen_t *client_addr_len;
3500         struct timeval tv;
3501         fd_set readfds;
3502
3503         DBG("condition 0x%02x channel %p ifdata %p family %d",
3504                 condition, channel, ifdata, family);
3505
3506         if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
3507 #if defined TIZEN_EXT
3508                 connman_error("Error %d with TCP listener channel", condition);
3509
3510                 recover_listener(channel, ifdata);
3511 #else
3512                 if (*listener_watch > 0)
3513                         g_source_remove(*listener_watch);
3514                 *listener_watch = 0;
3515
3516                 connman_error("Error with TCP listener channel");
3517 #endif
3518
3519                 return false;
3520         }
3521
3522         sk = g_io_channel_unix_get_fd(channel);
3523
3524         if (family == AF_INET) {
3525                 client_addr = &client_addr4;
3526                 client_addr_len = &client_addr4_len;
3527         } else {
3528                 client_addr = &client_addr6;
3529                 client_addr_len = &client_addr6_len;
3530         }
3531
3532         tv.tv_sec = tv.tv_usec = 0;
3533         FD_ZERO(&readfds);
3534         FD_SET(sk, &readfds);
3535
3536         select(sk + 1, &readfds, NULL, NULL, &tv);
3537         if (FD_ISSET(sk, &readfds)) {
3538                 client_sk = accept(sk, client_addr, client_addr_len);
3539                 DBG("client %d accepted", client_sk);
3540         } else {
3541                 DBG("No data to read from master %d, waiting.", sk);
3542                 return true;
3543         }
3544
3545         if (client_sk < 0) {
3546                 connman_error("Accept failure on TCP listener");
3547                 *listener_watch = 0;
3548                 return false;
3549         }
3550
3551         fcntl(client_sk, F_SETFL, O_NONBLOCK);
3552
3553         client = g_hash_table_lookup(partial_tcp_req_table,
3554                                         GINT_TO_POINTER(client_sk));
3555         if (!client) {
3556                 client = g_try_new0(struct tcp_partial_client_data, 1);
3557                 if (!client) {
3558                         close(client_sk);
3559                         return false;
3560                 }
3561
3562                 g_hash_table_insert(partial_tcp_req_table,
3563                                         GINT_TO_POINTER(client_sk),
3564                                         client);
3565
3566                 client->channel = g_io_channel_unix_new(client_sk);
3567                 g_io_channel_set_close_on_unref(client->channel, TRUE);
3568
3569                 client->watch = g_io_add_watch(client->channel,
3570                                                 G_IO_IN, tcp_client_event,
3571                                                 (gpointer)client);
3572
3573                 client->ifdata = ifdata;
3574
3575                 DBG("client %d created %p", client_sk, client);
3576         } else {
3577                 DBG("client %d already exists %p", client_sk, client);
3578         }
3579
3580         if (!client->buf) {
3581                 client->buf = g_try_malloc(TCP_MAX_BUF_LEN);
3582                 if (!client->buf)
3583                         return false;
3584         }
3585         memset(client->buf, 0, TCP_MAX_BUF_LEN);
3586         client->buf_end = 0;
3587         client->family = family;
3588
3589         if (client->timeout == 0)
3590                 client->timeout = g_timeout_add_seconds(2, client_timeout,
3591                                                         client);
3592
3593         /*
3594          * Check how much data there is. If all is there, then we can
3595          * proceed normally, otherwise read the bits until everything
3596          * is received or timeout occurs.
3597          */
3598         len = recv(client_sk, client->buf, TCP_MAX_BUF_LEN, 0);
3599         if (len < 0) {
3600                 if (errno == EAGAIN || errno == EWOULDBLOCK) {
3601                         DBG("client %d no data to read, waiting", client_sk);
3602                         return true;
3603                 }
3604
3605                 DBG("client %d cannot read errno %d/%s", client_sk, -errno,
3606                         strerror(errno));
3607                 g_hash_table_remove(partial_tcp_req_table,
3608                                         GINT_TO_POINTER(client_sk));
3609                 return true;
3610         }
3611
3612         if (len < 2) {
3613                 DBG("client %d not enough data to read, waiting", client_sk);
3614                 client->buf_end += len;
3615                 return true;
3616         }
3617
3618         msg_len = get_msg_len(client->buf);
3619         if (msg_len > TCP_MAX_BUF_LEN) {
3620                 DBG("client %d invalid message length %u ignoring packet",
3621                         client_sk, msg_len);
3622                 g_hash_table_remove(partial_tcp_req_table,
3623                                         GINT_TO_POINTER(client_sk));
3624                 return true;
3625         }
3626
3627         /*
3628          * The packet length bytes do not contain the total message length,
3629          * that is the reason to -2 below.
3630          */
3631 #if defined TIZEN_EXT
3632         if (msg_len > (unsigned int)(len - 2)) {
3633 #else
3634         if (msg_len != (unsigned int)(len - 2)) {
3635 #endif
3636                 DBG("client %d sent %d bytes but expecting %u pending %d",
3637                         client_sk, len, msg_len + 2, msg_len + 2 - len);
3638
3639                 client->buf_end += len;
3640                 return true;
3641         }
3642
3643         return read_tcp_data(client, client_addr, *client_addr_len, len);
3644 }
3645
3646 static gboolean tcp4_listener_event(GIOChannel *channel, GIOCondition condition,
3647                                 gpointer user_data)
3648 {
3649         struct listener_data *ifdata = user_data;
3650
3651         return tcp_listener_event(channel, condition, ifdata, AF_INET,
3652                                 &ifdata->tcp4_listener_watch);
3653 }
3654
3655 static gboolean tcp6_listener_event(GIOChannel *channel, GIOCondition condition,
3656                                 gpointer user_data)
3657 {
3658         struct listener_data *ifdata = user_data;
3659
3660         return tcp_listener_event(channel, condition, user_data, AF_INET6,
3661                                 &ifdata->tcp6_listener_watch);
3662 }
3663
3664 #if defined TIZEN_EXT
3665 /* Temporarily disable AAAA type to enhance performance (IPv6 not supported) */
3666 static void __send_response_not_implemented(int sk, unsigned char *buf, int len,
3667                                 const struct sockaddr *to, socklen_t tolen,
3668                                 int protocol)
3669 {
3670         struct domain_hdr *hdr;
3671         int err, offset = protocol_offset(protocol);
3672
3673         DBG("sk %d", sk);
3674
3675         if (offset < 0)
3676                 return;
3677
3678         if (len < 12)
3679                 return;
3680
3681         hdr = (void *) (buf + offset);
3682
3683         DBG("id 0x%04x qr %d opcode %d", hdr->id, hdr->qr, hdr->opcode);
3684
3685         hdr->qr = 1;
3686         hdr->rcode = 4;
3687
3688         hdr->ancount = 0;
3689         hdr->nscount = 0;
3690         hdr->arcount = 0;
3691
3692         err = sendto(sk, buf, len, MSG_NOSIGNAL, to, tolen);
3693         if (err < 0)
3694                 connman_error("Failed to send DNS response to %d: %s",
3695                                 sk, strerror(errno));
3696 }
3697 #endif
3698
3699 static bool udp_listener_event(GIOChannel *channel, GIOCondition condition,
3700                                 struct listener_data *ifdata, int family,
3701                                 guint *listener_watch)
3702 {
3703         unsigned char buf[768];
3704         char query[512];
3705         struct request_data *req;
3706         struct sockaddr_in6 client_addr6;
3707         socklen_t client_addr6_len = sizeof(client_addr6);
3708         struct sockaddr_in client_addr4;
3709         socklen_t client_addr4_len = sizeof(client_addr4);
3710         void *client_addr;
3711         socklen_t *client_addr_len;
3712         int sk, err, len;
3713
3714         if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
3715 #if defined TIZEN_EXT
3716                 connman_error("Error %d with UDP listener channel", condition);
3717
3718                 recover_listener(channel, ifdata);
3719 #else
3720                 connman_error("Error with UDP listener channel");
3721                 *listener_watch = 0;
3722 #endif
3723                 return false;
3724         }
3725
3726         sk = g_io_channel_unix_get_fd(channel);
3727
3728         if (family == AF_INET) {
3729                 client_addr = &client_addr4;
3730                 client_addr_len = &client_addr4_len;
3731         } else {
3732                 client_addr = &client_addr6;
3733                 client_addr_len = &client_addr6_len;
3734         }
3735
3736         memset(client_addr, 0, *client_addr_len);
3737         len = recvfrom(sk, buf, sizeof(buf), 0, client_addr, client_addr_len);
3738         if (len < 2)
3739                 return true;
3740
3741         DBG("Received %d bytes (id 0x%04x)", len, buf[0] | buf[1] << 8);
3742
3743         err = parse_request(buf, len, query, sizeof(query));
3744         if (err < 0 || (g_slist_length(server_list) == 0)) {
3745 #if defined TIZEN_EXT
3746                 if (err == -ENOENT) {
3747                         /* Temporarily disable AAAA type to enhance performance
3748                          * (IPv6 not supported)
3749                          */
3750                         __send_response_not_implemented(sk, buf, len, client_addr,
3751                                                                         *client_addr_len, IPPROTO_UDP);
3752                         return TRUE;
3753                 }
3754 #endif
3755                 send_response(sk, buf, len, client_addr,
3756                                 *client_addr_len, IPPROTO_UDP);
3757                 return true;
3758         }
3759
3760         req = g_try_new0(struct request_data, 1);
3761         if (!req)
3762                 return true;
3763
3764         memcpy(&req->sa, client_addr, *client_addr_len);
3765         req->sa_len = *client_addr_len;
3766         req->client_sk = 0;
3767         req->protocol = IPPROTO_UDP;
3768         req->family = family;
3769
3770         req->srcid = buf[0] | (buf[1] << 8);
3771         req->dstid = get_id();
3772         req->altid = get_id();
3773         req->request_len = len;
3774
3775         buf[0] = req->dstid & 0xff;
3776         buf[1] = req->dstid >> 8;
3777
3778         req->numserv = 0;
3779         req->ifdata = ifdata;
3780         req->append_domain = false;
3781
3782         if (resolv(req, buf, query)) {
3783                 /* a cached result was sent, so the request can be released */
3784                 g_free(req);
3785                 return true;
3786         }
3787
3788         req->name = g_strdup(query);
3789         req->request = g_malloc(len);
3790         memcpy(req->request, buf, len);
3791 #if defined TIZEN_EXT
3792         DBG("req %p dstid 0x%04x altid 0x%04x", req, req->dstid, req->altid);
3793         req->timeout = g_timeout_add_seconds(30, request_timeout, req);
3794 #else
3795         req->timeout = g_timeout_add_seconds(5, request_timeout, req);
3796 #endif
3797         request_list = g_slist_append(request_list, req);
3798
3799         return true;
3800 }
3801
3802 static gboolean udp4_listener_event(GIOChannel *channel, GIOCondition condition,
3803                                 gpointer user_data)
3804 {
3805         struct listener_data *ifdata = user_data;
3806
3807         return udp_listener_event(channel, condition, ifdata, AF_INET,
3808                                 &ifdata->udp4_listener_watch);
3809 }
3810
3811 static gboolean udp6_listener_event(GIOChannel *channel, GIOCondition condition,
3812                                 gpointer user_data)
3813 {
3814         struct listener_data *ifdata = user_data;
3815
3816         return udp_listener_event(channel, condition, user_data, AF_INET6,
3817                                 &ifdata->udp6_listener_watch);
3818 }
3819
3820 static GIOChannel *get_listener(int family, int protocol, int index)
3821 {
3822         GIOChannel *channel;
3823         const char *proto;
3824         union {
3825                 struct sockaddr sa;
3826                 struct sockaddr_in6 sin6;
3827                 struct sockaddr_in sin;
3828         } s;
3829         socklen_t slen;
3830         int sk, type;
3831 #if !defined TIZEN_EXT
3832         char *interface;
3833 #endif
3834 #if defined TIZEN_EXT
3835         int option;
3836 #endif
3837
3838         DBG("family %d protocol %d index %d", family, protocol, index);
3839
3840         switch (protocol) {
3841         case IPPROTO_UDP:
3842                 proto = "UDP";
3843                 type = SOCK_DGRAM | SOCK_CLOEXEC;
3844                 break;
3845
3846         case IPPROTO_TCP:
3847                 proto = "TCP";
3848                 type = SOCK_STREAM | SOCK_CLOEXEC;
3849                 break;
3850
3851         default:
3852                 return NULL;
3853         }
3854
3855         sk = socket(family, type, protocol);
3856         if (sk < 0 && family == AF_INET6 && errno == EAFNOSUPPORT) {
3857                 connman_error("No IPv6 support");
3858                 return NULL;
3859         }
3860
3861         if (sk < 0) {
3862                 connman_error("Failed to create %s listener socket", proto);
3863                 return NULL;
3864         }
3865
3866 #if !defined TIZEN_EXT
3867         /* ConnMan listens DNS from multiple interfaces
3868          * E.g. various technology based and tethering interfaces
3869          */
3870         interface = connman_inet_ifname(index);
3871         if (!interface || setsockopt(sk, SOL_SOCKET, SO_BINDTODEVICE,
3872                                         interface,
3873                                         strlen(interface) + 1) < 0) {
3874                 connman_error("Failed to bind %s listener interface "
3875                         "for %s (%d/%s)",
3876                         proto, family == AF_INET ? "IPv4" : "IPv6",
3877                         -errno, strerror(errno));
3878                 close(sk);
3879                 g_free(interface);
3880                 return NULL;
3881         }
3882         g_free(interface);
3883 #endif
3884
3885         if (family == AF_INET6) {
3886                 memset(&s.sin6, 0, sizeof(s.sin6));
3887                 s.sin6.sin6_family = AF_INET6;
3888                 s.sin6.sin6_port = htons(53);
3889                 slen = sizeof(s.sin6);
3890 #if defined TIZEN_EXT
3891                 s.sin6.sin6_addr = in6addr_any;
3892 #else
3893                 if (__connman_inet_get_interface_address(index,
3894                                                 AF_INET6,
3895                                                 &s.sin6.sin6_addr) < 0) {
3896                         /* So we could not find suitable IPv6 address for
3897                          * the interface. This could happen if we have
3898                          * disabled IPv6 for the interface.
3899                          */
3900                         close(sk);
3901                         return NULL;
3902                 }
3903 #endif
3904
3905         } else if (family == AF_INET) {
3906                 memset(&s.sin, 0, sizeof(s.sin));
3907                 s.sin.sin_family = AF_INET;
3908                 s.sin.sin_port = htons(53);
3909                 slen = sizeof(s.sin);
3910 #if defined TIZEN_EXT
3911                 s.sin.sin_addr.s_addr = htonl(INADDR_ANY);
3912 #else
3913                 if (__connman_inet_get_interface_address(index,
3914                                                 AF_INET,
3915                                                 &s.sin.sin_addr) < 0) {
3916                         close(sk);
3917                         return NULL;
3918                 }
3919 #endif
3920         } else {
3921                 close(sk);
3922                 return NULL;
3923         }
3924
3925 #if defined TIZEN_EXT
3926         /* When ConnMan crashed,
3927          * probably DNS listener cannot bind existing address */
3928         option = 1;
3929         setsockopt(sk, SOL_SOCKET, SO_REUSEADDR, &option, sizeof(option));
3930 #endif
3931         if (bind(sk, &s.sa, slen) < 0) {
3932                 connman_error("Failed to bind %s listener socket", proto);
3933                 close(sk);
3934                 return NULL;
3935         }
3936
3937         if (protocol == IPPROTO_TCP) {
3938
3939                 if (listen(sk, 10) < 0) {
3940                         connman_error("Failed to listen on TCP socket %d/%s",
3941                                 -errno, strerror(errno));
3942                         close(sk);
3943                         return NULL;
3944                 }
3945
3946                 fcntl(sk, F_SETFL, O_NONBLOCK);
3947         }
3948
3949         channel = g_io_channel_unix_new(sk);
3950         if (!channel) {
3951                 connman_error("Failed to create %s listener channel", proto);
3952                 close(sk);
3953                 return NULL;
3954         }
3955
3956         g_io_channel_set_close_on_unref(channel, TRUE);
3957
3958         return channel;
3959 }
3960
3961 #define UDP_IPv4_FAILED 0x01
3962 #define TCP_IPv4_FAILED 0x02
3963 #define UDP_IPv6_FAILED 0x04
3964 #define TCP_IPv6_FAILED 0x08
3965 #define UDP_FAILED (UDP_IPv4_FAILED | UDP_IPv6_FAILED)
3966 #define TCP_FAILED (TCP_IPv4_FAILED | TCP_IPv6_FAILED)
3967 #define IPv6_FAILED (UDP_IPv6_FAILED | TCP_IPv6_FAILED)
3968 #define IPv4_FAILED (UDP_IPv4_FAILED | TCP_IPv4_FAILED)
3969
3970 static int create_dns_listener(int protocol, struct listener_data *ifdata)
3971 {
3972         int ret = 0;
3973
3974         if (protocol == IPPROTO_TCP) {
3975                 ifdata->tcp4_listener_channel = get_listener(AF_INET, protocol,
3976                                                         ifdata->index);
3977                 if (ifdata->tcp4_listener_channel)
3978 #if defined TIZEN_EXT
3979                         ifdata->tcp4_listener_watch =
3980                                 g_io_add_watch(ifdata->tcp4_listener_channel,
3981                                         G_IO_IN | G_IO_ERR | G_IO_HUP | G_IO_NVAL,
3982                                         tcp4_listener_event, (gpointer)ifdata);
3983 #else
3984                         ifdata->tcp4_listener_watch =
3985                                 g_io_add_watch(ifdata->tcp4_listener_channel,
3986                                         G_IO_IN, tcp4_listener_event,
3987                                         (gpointer)ifdata);
3988 #endif
3989                 else
3990                         ret |= TCP_IPv4_FAILED;
3991
3992                 ifdata->tcp6_listener_channel = get_listener(AF_INET6, protocol,
3993                                                         ifdata->index);
3994                 if (ifdata->tcp6_listener_channel)
3995 #if defined TIZEN_EXT
3996                         ifdata->tcp6_listener_watch =
3997                                 g_io_add_watch(ifdata->tcp6_listener_channel,
3998                                         G_IO_IN | G_IO_ERR | G_IO_HUP | G_IO_NVAL,
3999                                         tcp6_listener_event, (gpointer)ifdata);
4000 #else
4001                         ifdata->tcp6_listener_watch =
4002                                 g_io_add_watch(ifdata->tcp6_listener_channel,
4003                                         G_IO_IN, tcp6_listener_event,
4004                                         (gpointer)ifdata);
4005 #endif
4006                 else
4007                         ret |= TCP_IPv6_FAILED;
4008         } else {
4009                 ifdata->udp4_listener_channel = get_listener(AF_INET, protocol,
4010                                                         ifdata->index);
4011                 if (ifdata->udp4_listener_channel)
4012 #if defined TIZEN_EXT
4013                         ifdata->udp4_listener_watch =
4014                                 g_io_add_watch(ifdata->udp4_listener_channel,
4015                                         G_IO_IN | G_IO_ERR | G_IO_HUP | G_IO_NVAL,
4016                                         udp4_listener_event, (gpointer)ifdata);
4017 #else
4018                         ifdata->udp4_listener_watch =
4019                                 g_io_add_watch(ifdata->udp4_listener_channel,
4020                                         G_IO_IN, udp4_listener_event,
4021                                         (gpointer)ifdata);
4022 #endif
4023                 else
4024                         ret |= UDP_IPv4_FAILED;
4025
4026                 ifdata->udp6_listener_channel = get_listener(AF_INET6, protocol,
4027                                                         ifdata->index);
4028                 if (ifdata->udp6_listener_channel)
4029 #if defined TIZEN_EXT
4030                         ifdata->udp6_listener_watch =
4031                                 g_io_add_watch(ifdata->udp6_listener_channel,
4032                                         G_IO_IN | G_IO_ERR | G_IO_HUP | G_IO_NVAL,
4033                                         udp6_listener_event, (gpointer)ifdata);
4034 #else
4035                         ifdata->udp6_listener_watch =
4036                                 g_io_add_watch(ifdata->udp6_listener_channel,
4037                                         G_IO_IN, udp6_listener_event,
4038                                         (gpointer)ifdata);
4039 #endif
4040                 else
4041                         ret |= UDP_IPv6_FAILED;
4042         }
4043
4044         return ret;
4045 }
4046
4047 static void destroy_udp_listener(struct listener_data *ifdata)
4048 {
4049         DBG("index %d", ifdata->index);
4050
4051         if (ifdata->udp4_listener_watch > 0)
4052                 g_source_remove(ifdata->udp4_listener_watch);
4053
4054         if (ifdata->udp6_listener_watch > 0)
4055                 g_source_remove(ifdata->udp6_listener_watch);
4056
4057         if (ifdata->udp4_listener_channel)
4058                 g_io_channel_unref(ifdata->udp4_listener_channel);
4059         if (ifdata->udp6_listener_channel)
4060                 g_io_channel_unref(ifdata->udp6_listener_channel);
4061 }
4062
4063 static void destroy_tcp_listener(struct listener_data *ifdata)
4064 {
4065         DBG("index %d", ifdata->index);
4066
4067         if (ifdata->tcp4_listener_watch > 0)
4068                 g_source_remove(ifdata->tcp4_listener_watch);
4069         if (ifdata->tcp6_listener_watch > 0)
4070                 g_source_remove(ifdata->tcp6_listener_watch);
4071
4072         if (ifdata->tcp4_listener_channel)
4073                 g_io_channel_unref(ifdata->tcp4_listener_channel);
4074         if (ifdata->tcp6_listener_channel)
4075                 g_io_channel_unref(ifdata->tcp6_listener_channel);
4076 }
4077
4078 static int create_listener(struct listener_data *ifdata)
4079 {
4080         int err, index;
4081
4082         err = create_dns_listener(IPPROTO_UDP, ifdata);
4083         if ((err & UDP_FAILED) == UDP_FAILED)
4084                 return -EIO;
4085
4086         err |= create_dns_listener(IPPROTO_TCP, ifdata);
4087         if ((err & TCP_FAILED) == TCP_FAILED) {
4088                 destroy_udp_listener(ifdata);
4089                 return -EIO;
4090         }
4091
4092         index = connman_inet_ifindex("lo");
4093         if (ifdata->index == index) {
4094                 if ((err & IPv6_FAILED) != IPv6_FAILED)
4095                         __connman_resolvfile_append(index, NULL, "::1");
4096
4097                 if ((err & IPv4_FAILED) != IPv4_FAILED)
4098                         __connman_resolvfile_append(index, NULL, "127.0.0.1");
4099         }
4100
4101         return 0;
4102 }
4103
4104 static void destroy_listener(struct listener_data *ifdata)
4105 {
4106         int index;
4107         GSList *list;
4108
4109         index = connman_inet_ifindex("lo");
4110         if (ifdata->index == index) {
4111                 __connman_resolvfile_remove(index, NULL, "127.0.0.1");
4112                 __connman_resolvfile_remove(index, NULL, "::1");
4113         }
4114
4115         for (list = request_list; list; list = list->next) {
4116                 struct request_data *req = list->data;
4117
4118                 DBG("Dropping request (id 0x%04x -> 0x%04x)",
4119                                                 req->srcid, req->dstid);
4120                 destroy_request_data(req);
4121                 list->data = NULL;
4122         }
4123
4124         g_slist_free(request_list);
4125         request_list = NULL;
4126
4127         destroy_tcp_listener(ifdata);
4128         destroy_udp_listener(ifdata);
4129 }
4130
4131 int __connman_dnsproxy_add_listener(int index)
4132 {
4133         struct listener_data *ifdata;
4134         int err;
4135
4136         DBG("index %d", index);
4137
4138         if (index < 0)
4139                 return -EINVAL;
4140
4141         if (!listener_table)
4142                 return -ENOENT;
4143
4144         if (g_hash_table_lookup(listener_table, GINT_TO_POINTER(index)))
4145                 return 0;
4146
4147         ifdata = g_try_new0(struct listener_data, 1);
4148         if (!ifdata)
4149                 return -ENOMEM;
4150
4151         ifdata->index = index;
4152         ifdata->udp4_listener_channel = NULL;
4153         ifdata->udp4_listener_watch = 0;
4154         ifdata->tcp4_listener_channel = NULL;
4155         ifdata->tcp4_listener_watch = 0;
4156         ifdata->udp6_listener_channel = NULL;
4157         ifdata->udp6_listener_watch = 0;
4158         ifdata->tcp6_listener_channel = NULL;
4159         ifdata->tcp6_listener_watch = 0;
4160
4161         err = create_listener(ifdata);
4162         if (err < 0) {
4163                 connman_error("Couldn't create listener for index %d err %d",
4164                                 index, err);
4165                 g_free(ifdata);
4166                 return err;
4167         }
4168         g_hash_table_insert(listener_table, GINT_TO_POINTER(ifdata->index),
4169                         ifdata);
4170         return 0;
4171 }
4172
4173 void __connman_dnsproxy_remove_listener(int index)
4174 {
4175         struct listener_data *ifdata;
4176
4177         DBG("index %d", index);
4178
4179         if (!listener_table)
4180                 return;
4181
4182         ifdata = g_hash_table_lookup(listener_table, GINT_TO_POINTER(index));
4183         if (!ifdata)
4184                 return;
4185
4186         destroy_listener(ifdata);
4187
4188         g_hash_table_remove(listener_table, GINT_TO_POINTER(index));
4189 }
4190
4191 static void remove_listener(gpointer key, gpointer value, gpointer user_data)
4192 {
4193         int index = GPOINTER_TO_INT(key);
4194         struct listener_data *ifdata = value;
4195
4196         DBG("index %d", index);
4197
4198         destroy_listener(ifdata);
4199 }
4200
4201 static void free_partial_reqs(gpointer value)
4202 {
4203         struct tcp_partial_client_data *data = value;
4204
4205         client_reset(data);
4206         g_free(data);
4207 }
4208
4209 int __connman_dnsproxy_init(void)
4210 {
4211         int err, index;
4212
4213         DBG("");
4214
4215         listener_table = g_hash_table_new_full(g_direct_hash, g_direct_equal,
4216                                                         NULL, g_free);
4217
4218         partial_tcp_req_table = g_hash_table_new_full(g_direct_hash,
4219                                                         g_direct_equal,
4220                                                         NULL,
4221                                                         free_partial_reqs);
4222
4223         index = connman_inet_ifindex("lo");
4224         err = __connman_dnsproxy_add_listener(index);
4225         if (err < 0)
4226                 return err;
4227
4228         err = connman_notifier_register(&dnsproxy_notifier);
4229         if (err < 0)
4230                 goto destroy;
4231
4232         return 0;
4233
4234 destroy:
4235         __connman_dnsproxy_remove_listener(index);
4236         g_hash_table_destroy(listener_table);
4237         g_hash_table_destroy(partial_tcp_req_table);
4238
4239         return err;
4240 }
4241
4242 void __connman_dnsproxy_cleanup(void)
4243 {
4244         DBG("");
4245
4246         if (cache_timer) {
4247                 g_source_remove(cache_timer);
4248                 cache_timer = 0;
4249         }
4250
4251         if (cache) {
4252                 g_hash_table_destroy(cache);
4253                 cache = NULL;
4254         }
4255
4256         connman_notifier_unregister(&dnsproxy_notifier);
4257
4258         g_hash_table_foreach(listener_table, remove_listener, NULL);
4259
4260         g_hash_table_destroy(listener_table);
4261
4262         g_hash_table_destroy(partial_tcp_req_table);
4263 }