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