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