dnsproxy: Return error if initial send fails
[framework/connectivity/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 <unistd.h>
28 #include <string.h>
29 #include <stdint.h>
30 #include <arpa/inet.h>
31 #include <netinet/in.h>
32 #include <sys/types.h>
33 #include <sys/socket.h>
34 #include <netdb.h>
35 #include <resolv.h>
36 #include <gweb/gresolv.h>
37
38 #include <glib.h>
39
40 #include "connman.h"
41
42 #if __BYTE_ORDER == __LITTLE_ENDIAN
43 struct domain_hdr {
44         uint16_t id;
45         uint8_t rd:1;
46         uint8_t tc:1;
47         uint8_t aa:1;
48         uint8_t opcode:4;
49         uint8_t qr:1;
50         uint8_t rcode:4;
51         uint8_t z:3;
52         uint8_t ra:1;
53         uint16_t qdcount;
54         uint16_t ancount;
55         uint16_t nscount;
56         uint16_t arcount;
57 } __attribute__ ((packed));
58 #elif __BYTE_ORDER == __BIG_ENDIAN
59 struct domain_hdr {
60         uint16_t id;
61         uint8_t qr:1;
62         uint8_t opcode:4;
63         uint8_t aa:1;
64         uint8_t tc:1;
65         uint8_t rd:1;
66         uint8_t ra:1;
67         uint8_t z:3;
68         uint8_t rcode:4;
69         uint16_t qdcount;
70         uint16_t ancount;
71         uint16_t nscount;
72         uint16_t arcount;
73 } __attribute__ ((packed));
74 #else
75 #error "Unknown byte order"
76 #endif
77
78 struct partial_reply {
79         uint16_t len;
80         uint16_t received;
81         unsigned char buf[];
82 };
83
84 struct server_data {
85         char *interface;
86         GList *domains;
87         char *server;
88         int protocol;
89         GIOChannel *channel;
90         guint watch;
91         guint timeout;
92         gboolean enabled;
93         gboolean connected;
94         struct partial_reply *incoming_reply;
95 };
96
97 struct request_data {
98         union {
99                 struct sockaddr_in6 __sin6; /* Only for the length */
100                 struct sockaddr sa;
101         };
102         socklen_t sa_len;
103         int client_sk;
104         int protocol;
105         guint16 srcid;
106         guint16 dstid;
107         guint16 altid;
108         guint timeout;
109         guint watch;
110         guint numserv;
111         guint numresp;
112         gpointer request;
113         gsize request_len;
114         gpointer name;
115         gpointer resp;
116         gsize resplen;
117         struct listener_data *ifdata;
118         gboolean append_domain;
119 };
120
121 struct listener_data {
122         char *ifname;
123         GIOChannel *udp_listener_channel;
124         guint udp_listener_watch;
125         GIOChannel *tcp_listener_channel;
126         guint tcp_listener_watch;
127 };
128
129 struct cache_data {
130         time_t inserted;
131         time_t valid_until;
132         time_t cache_until;
133         int timeout;
134         uint16_t type;
135         uint16_t answers;
136         unsigned int data_len;
137         unsigned char *data; /* contains DNS header + body */
138 };
139
140 struct cache_entry {
141         char *key;
142         int want_refresh;
143         int hits;
144         struct cache_data *ipv4;
145         struct cache_data *ipv6;
146 };
147
148 struct domain_question {
149         uint16_t type;
150         uint16_t class;
151 } __attribute__ ((packed));
152
153 struct domain_rr {
154         uint16_t type;
155         uint16_t class;
156         uint32_t ttl;
157         uint16_t rdlen;
158 } __attribute__ ((packed));
159
160 /*
161  * We limit how long the cached DNS entry stays in the cache.
162  * By default the TTL (time-to-live) of the DNS response is used
163  * when setting the cache entry life time. The value is in seconds.
164  */
165 #define MAX_CACHE_TTL (60 * 30)
166 /*
167  * Also limit the other end, cache at least for 30 seconds.
168  */
169 #define MIN_CACHE_TTL (30)
170
171 /*
172  * We limit the cache size to some sane value so that cached data does
173  * not occupy too much memory. Each cached entry occupies on average
174  * about 100 bytes memory (depending on DNS name length).
175  * Example: caching www.connman.net uses 97 bytes memory.
176  * The value is the max amount of cached DNS responses (count).
177  */
178 #define MAX_CACHE_SIZE 256
179
180 static int cache_size;
181 static GHashTable *cache;
182 static int cache_refcount;
183 static GSList *server_list = NULL;
184 static GSList *request_list = NULL;
185 static GSList *request_pending_list = NULL;
186 static guint16 request_id = 0x0000;
187 static GHashTable *listener_table = NULL;
188 static time_t next_refresh;
189
190 static int protocol_offset(int protocol)
191 {
192         switch (protocol) {
193         case IPPROTO_UDP:
194                 return 0;
195
196         case IPPROTO_TCP:
197                 return 2;
198
199         default:
200                 return -EINVAL;
201         }
202
203 }
204
205 /*
206  * There is a power and efficiency benefit to have entries
207  * in our cache expire at the same time. To this extend,
208  * we round down the cache valid time to common boundaries.
209  */
210 static time_t round_down_ttl(time_t end_time, int ttl)
211 {
212         if (ttl < 15)
213                 return end_time;
214
215         /* Less than 5 minutes, round to 10 second boundary */
216         if (ttl < 300) {
217                 end_time = end_time / 10;
218                 end_time = end_time * 10;
219         } else { /* 5 or more minutes, round to 30 seconds */
220                 end_time = end_time / 30;
221                 end_time = end_time * 30;
222         }
223         return end_time;
224 }
225
226 static struct request_data *find_request(guint16 id)
227 {
228         GSList *list;
229
230         for (list = request_list; list; list = list->next) {
231                 struct request_data *req = list->data;
232
233                 if (req->dstid == id || req->altid == id)
234                         return req;
235         }
236
237         return NULL;
238 }
239
240 static struct server_data *find_server(const char *interface,
241                                         const char *server,
242                                                 int protocol)
243 {
244         GSList *list;
245
246         DBG("interface %s server %s", interface, server);
247
248         for (list = server_list; list; list = list->next) {
249                 struct server_data *data = list->data;
250
251                 if (interface == NULL && data->interface == NULL &&
252                                 g_str_equal(data->server, server) == TRUE &&
253                                 data->protocol == protocol)
254                         return data;
255
256                 if (interface == NULL ||
257                                 data->interface == NULL || data->server == NULL)
258                         continue;
259
260                 if (g_str_equal(data->interface, interface) == TRUE &&
261                                 g_str_equal(data->server, server) == TRUE &&
262                                 data->protocol == protocol)
263                         return data;
264         }
265
266         return NULL;
267 }
268
269 /* we can keep using the same resolve's */
270 static GResolv *ipv4_resolve;
271 static GResolv *ipv6_resolve;
272
273 static void dummy_resolve_func(GResolvResultStatus status,
274                                         char **results, gpointer user_data)
275 {
276 }
277
278 /*
279  * Refresh a DNS entry, but also age the hit count a bit */
280 static void refresh_dns_entry(struct cache_entry *entry, char *name)
281 {
282         int age = 1;
283
284         if (ipv4_resolve == NULL) {
285                 ipv4_resolve = g_resolv_new(0);
286                 g_resolv_set_address_family(ipv4_resolve, AF_INET);
287                 g_resolv_add_nameserver(ipv4_resolve, "127.0.0.1", 53, 0);
288         }
289
290         if (ipv6_resolve == NULL) {
291                 ipv6_resolve = g_resolv_new(0);
292                 g_resolv_set_address_family(ipv6_resolve, AF_INET6);
293                 g_resolv_add_nameserver(ipv6_resolve, "127.0.0.1", 53, 0);
294         }
295
296         if (entry->ipv4 == NULL) {
297                 DBG("Refresing A record for %s", name);
298                 g_resolv_lookup_hostname(ipv4_resolve, name,
299                                         dummy_resolve_func, NULL);
300                 age = 4;
301         }
302
303         if (entry->ipv6 == NULL) {
304                 DBG("Refresing AAAA record for %s", name);
305                 g_resolv_lookup_hostname(ipv6_resolve, name,
306                                         dummy_resolve_func, NULL);
307                 age = 4;
308         }
309
310         entry->hits -= age;
311         if (entry->hits < 0)
312                 entry->hits = 0;
313 }
314
315 static int dns_name_length(unsigned char *buf)
316 {
317         if ((buf[0] & NS_CMPRSFLGS) == NS_CMPRSFLGS) /* compressed name */
318                 return 2;
319         return strlen((char *)buf);
320 }
321
322 static void update_cached_ttl(unsigned char *buf, int len, int new_ttl)
323 {
324         unsigned char *c;
325         uint32_t *i;
326         uint16_t *w;
327         int l;
328
329         /* skip the header */
330         c = buf + 12;
331         len -= 12;
332
333         /* skip the query, which is a name and 2 16 bit words */
334         l = dns_name_length(c);
335         c += l;
336         len -= l;
337         c += 4;
338         len -= 4;
339
340         /* now we get the answer records */
341
342         while (len > 0) {
343                 /* first a name */
344                 l = dns_name_length(c);
345                 c += l;
346                 len -= l;
347                 if (len < 0)
348                         break;
349                 /* then type + class, 2 bytes each */
350                 c += 4;
351                 len -= 4;
352                 if (len < 0)
353                         break;
354
355                 /* now the 4 byte TTL field */
356                 i = (uint32_t *)c;
357                 *i = htonl(new_ttl);
358                 c += 4;
359                 len -= 4;
360                 if (len < 0)
361                         break;
362
363                 /* now the 2 byte rdlen field */
364                 w = (uint16_t *)c;
365                 c += ntohs(*w) + 2;
366                 len -= ntohs(*w) + 2;
367         }
368 }
369
370 static void send_cached_response(int sk, unsigned char *buf, int len,
371                                 const struct sockaddr *to, socklen_t tolen,
372                                 int protocol, int id, uint16_t answers, int ttl)
373 {
374         struct domain_hdr *hdr;
375         int err, offset = protocol_offset(protocol);
376
377         if (offset < 0)
378                 return;
379
380         if (len < 12)
381                 return;
382
383         hdr = (void *) (buf + offset);
384
385         hdr->id = id;
386         hdr->qr = 1;
387         hdr->rcode = 0;
388         hdr->ancount = htons(answers);
389         hdr->nscount = 0;
390         hdr->arcount = 0;
391
392         /* if this is a negative reply, we are authorative */
393         if (answers == 0)
394                 hdr->aa = 1;
395         else
396                 update_cached_ttl(buf, len, ttl);
397
398         DBG("id 0x%04x answers %d", hdr->id, answers);
399
400         err = sendto(sk, buf, len, 0, to, tolen);
401         if (err < 0) {
402                 connman_error("Cannot send cached DNS response: %s",
403                                 strerror(errno));
404                 return;
405         }
406 }
407
408 static void send_response(int sk, unsigned char *buf, int len,
409                                 const struct sockaddr *to, socklen_t tolen,
410                                 int protocol)
411 {
412         struct domain_hdr *hdr;
413         int err, offset = protocol_offset(protocol);
414
415         DBG("");
416
417         if (offset < 0)
418                 return;
419
420         if (len < 12)
421                 return;
422
423         hdr = (void *) (buf + offset);
424
425         DBG("id 0x%04x qr %d opcode %d", hdr->id, hdr->qr, hdr->opcode);
426
427         hdr->qr = 1;
428         hdr->rcode = 2;
429
430         hdr->ancount = 0;
431         hdr->nscount = 0;
432         hdr->arcount = 0;
433
434         err = sendto(sk, buf, len, 0, to, tolen);
435         if (err < 0) {
436                 connman_error("Failed to send DNS response: %s",
437                                 strerror(errno));
438                 return;
439         }
440 }
441
442 static gboolean request_timeout(gpointer user_data)
443 {
444         struct request_data *req = user_data;
445         struct listener_data *ifdata;
446
447         DBG("id 0x%04x", req->srcid);
448
449         if (req == NULL)
450                 return FALSE;
451
452         ifdata = req->ifdata;
453
454         request_list = g_slist_remove(request_list, req);
455         req->numserv--;
456
457         if (req->resplen > 0 && req->resp != NULL) {
458                 int sk, err;
459
460                 sk = g_io_channel_unix_get_fd(ifdata->udp_listener_channel);
461
462                 err = sendto(sk, req->resp, req->resplen, 0,
463                                                 &req->sa, req->sa_len);
464                 if (err < 0)
465                         return FALSE;
466         } else if (req->request && req->numserv == 0) {
467                 struct domain_hdr *hdr;
468
469                 if (req->protocol == IPPROTO_TCP) {
470                         hdr = (void *) (req->request + 2);
471                         hdr->id = req->srcid;
472                         send_response(req->client_sk, req->request,
473                                 req->request_len, NULL, 0, IPPROTO_TCP);
474
475                 } else if (req->protocol == IPPROTO_UDP) {
476                         int sk;
477
478                         hdr = (void *) (req->request);
479                         hdr->id = req->srcid;
480                         sk = g_io_channel_unix_get_fd(
481                                                 ifdata->udp_listener_channel);
482                         send_response(sk, req->request, req->request_len,
483                                         &req->sa, req->sa_len, IPPROTO_UDP);
484                 }
485         }
486
487         g_free(req->resp);
488         g_free(req);
489
490         return FALSE;
491 }
492
493 static int append_query(unsigned char *buf, unsigned int size,
494                                 const char *query, const char *domain)
495 {
496         unsigned char *ptr = buf;
497         char *offset;
498         int len;
499
500         DBG("query %s domain %s", query, domain);
501
502         offset = (char *) query;
503         while (offset != NULL) {
504                 char *tmp;
505
506                 tmp = strchr(offset, '.');
507                 if (tmp == NULL) {
508                         len = strlen(offset);
509                         if (len == 0)
510                                 break;
511                         *ptr = len;
512                         memcpy(ptr + 1, offset, len);
513                         ptr += len + 1;
514                         break;
515                 }
516
517                 *ptr = tmp - offset;
518                 memcpy(ptr + 1, offset, tmp - offset);
519                 ptr += tmp - offset + 1;
520
521                 offset = tmp + 1;
522         }
523
524         offset = (char *) domain;
525         while (offset != NULL) {
526                 char *tmp;
527
528                 tmp = strchr(offset, '.');
529                 if (tmp == NULL) {
530                         len = strlen(offset);
531                         if (len == 0)
532                                 break;
533                         *ptr = len;
534                         memcpy(ptr + 1, offset, len);
535                         ptr += len + 1;
536                         break;
537                 }
538
539                 *ptr = tmp - offset;
540                 memcpy(ptr + 1, offset, tmp - offset);
541                 ptr += tmp - offset + 1;
542
543                 offset = tmp + 1;
544         }
545
546         *ptr++ = 0x00;
547
548         return ptr - buf;
549 }
550
551 static gboolean cache_check_is_valid(struct cache_data *data,
552                                 time_t current_time)
553 {
554         if (data == NULL)
555                 return FALSE;
556
557         if (data->cache_until < current_time)
558                 return FALSE;
559
560         return TRUE;
561 }
562
563 /*
564  * remove stale cached entries so that they can be refreshed
565  */
566 static void cache_enforce_validity(struct cache_entry *entry)
567 {
568         time_t current_time = time(NULL);
569
570         if (cache_check_is_valid(entry->ipv4, current_time) == FALSE
571                                                         && entry->ipv4) {
572                 DBG("cache timeout \"%s\" type A", entry->key);
573                 g_free(entry->ipv4->data);
574                 g_free(entry->ipv4);
575                 entry->ipv4 = NULL;
576
577         }
578
579         if (cache_check_is_valid(entry->ipv6, current_time) == FALSE
580                                                         && entry->ipv6) {
581                 DBG("cache timeout \"%s\" type AAAA", entry->key);
582                 g_free(entry->ipv6->data);
583                 g_free(entry->ipv6);
584                 entry->ipv6 = NULL;
585         }
586 }
587
588 static uint16_t cache_check_validity(char *question, uint16_t type,
589                                 struct cache_entry *entry)
590 {
591         time_t current_time = time(NULL);
592         int want_refresh = 0;
593
594         /*
595          * if we have a popular entry, we want a refresh instead of
596          * total destruction of the entry.
597          */
598         if (entry->hits > 2)
599                 want_refresh = 1;
600
601         cache_enforce_validity(entry);
602
603         switch (type) {
604         case 1:         /* IPv4 */
605                 if (cache_check_is_valid(entry->ipv4, current_time) == FALSE) {
606                         DBG("cache %s \"%s\" type A", entry->ipv4 ?
607                                         "timeout" : "entry missing", question);
608
609                         if (want_refresh)
610                                 entry->want_refresh = 1;
611
612                         /*
613                          * We do not remove cache entry if there is still
614                          * valid IPv6 entry found in the cache.
615                          */
616                         if (cache_check_is_valid(entry->ipv6, current_time)
617                                         == FALSE && want_refresh == FALSE) {
618                                 g_hash_table_remove(cache, question);
619                                 type = 0;
620                         }
621                 }
622                 break;
623
624         case 28:        /* IPv6 */
625                 if (cache_check_is_valid(entry->ipv6, current_time) == FALSE) {
626                         DBG("cache %s \"%s\" type AAAA", entry->ipv6 ?
627                                         "timeout" : "entry missing", question);
628
629                         if (want_refresh)
630                                 entry->want_refresh = 1;
631
632                         if (cache_check_is_valid(entry->ipv4, current_time)
633                                         == FALSE && want_refresh == FALSE) {
634                                 g_hash_table_remove(cache, question);
635                                 type = 0;
636                         }
637                 }
638                 break;
639         }
640
641         return type;
642 }
643
644 static struct cache_entry *cache_check(gpointer request, int *qtype)
645 {
646         char *question = request + 12;
647         struct cache_entry *entry;
648         struct domain_question *q;
649         uint16_t type;
650         int offset;
651
652         offset = strlen(question) + 1;
653         q = (void *) (question + offset);
654         type = ntohs(q->type);
655
656         /* We only cache either A (1) or AAAA (28) requests */
657         if (type != 1 && type != 28)
658                 return NULL;
659
660         entry = g_hash_table_lookup(cache, question);
661         if (entry == NULL)
662                 return NULL;
663
664         type = cache_check_validity(question, type, entry);
665         if (type == 0)
666                 return NULL;
667
668         *qtype = type;
669         return entry;
670 }
671
672 /*
673  * Get a label/name from DNS resource record. The function decompresses the
674  * label if necessary. The function does not convert the name to presentation
675  * form. This means that the result string will contain label lengths instead
676  * of dots between labels. We intentionally do not want to convert to dotted
677  * format so that we can cache the wire format string directly.
678  */
679 static int get_name(int counter,
680                 unsigned char *pkt, unsigned char *start, unsigned char *max,
681                 unsigned char *output, int output_max, int *output_len,
682                 unsigned char **end, char *name, int *name_len)
683 {
684         unsigned char *p;
685
686         /* Limit recursion to 10 (this means up to 10 labels in domain name) */
687         if (counter > 10)
688                 return -EINVAL;
689
690         p = start;
691         while (*p) {
692                 if ((*p & NS_CMPRSFLGS) == NS_CMPRSFLGS) {
693                         uint16_t offset = (*p & 0x3F) * 256 + *(p + 1);
694
695                         if (offset >= max - pkt)
696                                 return -ENOBUFS;
697
698                         if (*end == NULL)
699                                 *end = p + 2;
700
701                         return get_name(counter + 1, pkt, pkt + offset, max,
702                                         output, output_max, output_len, end,
703                                         name, name_len);
704                 } else {
705                         unsigned label_len = *p;
706
707                         if (pkt + label_len > max)
708                                 return -ENOBUFS;
709
710                         if (*output_len > output_max)
711                                 return -ENOBUFS;
712
713                         /*
714                          * We need the original name in order to check
715                          * if this answer is the correct one.
716                          */
717                         name[(*name_len)++] = label_len;
718                         memcpy(name + *name_len, p + 1, label_len + 1);
719                         *name_len += label_len;
720
721                         /* We compress the result */
722                         output[0] = NS_CMPRSFLGS;
723                         output[1] = 0x0C;
724                         *output_len = 2;
725
726                         p += label_len + 1;
727
728                         if (*end == NULL)
729                                 *end = p;
730
731                         if (p >= max)
732                                 return -ENOBUFS;
733                 }
734         }
735
736         return 0;
737 }
738
739 static int parse_rr(unsigned char *buf, unsigned char *start,
740                         unsigned char *max,
741                         unsigned char *response, unsigned int *response_size,
742                         uint16_t *type, uint16_t *class, int *ttl, int *rdlen,
743                         unsigned char **end,
744                         char *name)
745 {
746         struct domain_rr *rr;
747         int err, offset;
748         int name_len = 0, output_len = 0, max_rsp = *response_size;
749
750         err = get_name(0, buf, start, max, response, max_rsp,
751                 &output_len, end, name, &name_len);
752         if (err < 0)
753                 return err;
754
755         offset = output_len;
756
757         if ((unsigned int) offset > *response_size)
758                 return -ENOBUFS;
759
760         rr = (void *) (*end);
761
762         if (rr == NULL)
763                 return -EINVAL;
764
765         *type = ntohs(rr->type);
766         *class = ntohs(rr->class);
767         *ttl = ntohl(rr->ttl);
768         *rdlen = ntohs(rr->rdlen);
769
770         if (*ttl < 0)
771                 return -EINVAL;
772
773         memcpy(response + offset, *end, sizeof(struct domain_rr));
774
775         offset += sizeof(struct domain_rr);
776         *end += sizeof(struct domain_rr);
777
778         if ((unsigned int) (offset + *rdlen) > *response_size)
779                 return -ENOBUFS;
780
781         memcpy(response + offset, *end, *rdlen);
782
783         *end += *rdlen;
784
785         *response_size = offset + *rdlen;
786
787         return 0;
788 }
789
790 static gboolean check_alias(GSList *aliases, char *name)
791 {
792         GSList *list;
793
794         if (aliases != NULL) {
795                 for (list = aliases; list; list = list->next) {
796                         int len = strlen((char *)list->data);
797                         if (strncmp((char *)list->data, name, len) == 0)
798                                 return TRUE;
799                 }
800         }
801
802         return FALSE;
803 }
804
805 static int parse_response(unsigned char *buf, int buflen,
806                         char *question, int qlen,
807                         uint16_t *type, uint16_t *class, int *ttl,
808                         unsigned char *response, unsigned int *response_len,
809                         uint16_t *answers)
810 {
811         struct domain_hdr *hdr = (void *) buf;
812         struct domain_question *q;
813         unsigned char *ptr;
814         uint16_t qdcount = ntohs(hdr->qdcount);
815         uint16_t ancount = ntohs(hdr->ancount);
816         int err, i;
817         uint16_t qtype, qclass;
818         unsigned char *next = NULL;
819         unsigned int maxlen = *response_len;
820         GSList *aliases = NULL, *list;
821         char name[NS_MAXDNAME + 1];
822
823         if (buflen < 12)
824                 return -EINVAL;
825
826         DBG("qr %d qdcount %d", hdr->qr, qdcount);
827
828         /* We currently only cache responses where question count is 1 */
829         if (hdr->qr != 1 || qdcount != 1)
830                 return -EINVAL;
831
832         ptr = buf + sizeof(struct domain_hdr);
833
834         strncpy(question, (char *) ptr, qlen);
835         qlen = strlen(question);
836         ptr += qlen + 1; /* skip \0 */
837
838         q = (void *) ptr;
839         qtype = ntohs(q->type);
840
841         /* We cache only A and AAAA records */
842         if (qtype != 1 && qtype != 28)
843                 return -ENOMSG;
844
845         qclass = ntohs(q->class);
846
847         ptr += 2 + 2; /* ptr points now to answers */
848
849         err = -ENOMSG;
850         *response_len = 0;
851         *answers = 0;
852
853         /*
854          * We have a bunch of answers (like A, AAAA, CNAME etc) to
855          * A or AAAA question. We traverse the answers and parse the
856          * resource records. Only A and AAAA records are cached, all
857          * the other records in answers are skipped.
858          */
859         for (i = 0; i < ancount; i++) {
860                 /*
861                  * Get one address at a time to this buffer.
862                  * The max size of the answer is
863                  *   2 (pointer) + 2 (type) + 2 (class) +
864                  *   4 (ttl) + 2 (rdlen) + addr (16 or 4) = 28
865                  * for A or AAAA record.
866                  * For CNAME the size can be bigger.
867                  */
868                 unsigned char rsp[NS_MAXCDNAME];
869                 unsigned int rsp_len = sizeof(rsp) - 1;
870                 int ret, rdlen;
871
872                 memset(rsp, 0, sizeof(rsp));
873
874                 ret = parse_rr(buf, ptr, buf + buflen, rsp, &rsp_len,
875                         type, class, ttl, &rdlen, &next, name);
876                 if (ret != 0) {
877                         err = ret;
878                         goto out;
879                 }
880
881                 /*
882                  * Now rsp contains compressed or uncompressed resource
883                  * record. Next we check if this record answers the question.
884                  * The name var contains the uncompressed label.
885                  * One tricky bit is the CNAME records as they alias
886                  * the name we might be interested in.
887                  */
888
889                 /*
890                  * Go to next answer if the class is not the one we are
891                  * looking for.
892                  */
893                 if (*class != qclass) {
894                         ptr = next;
895                         next = NULL;
896                         continue;
897                 }
898
899                 /*
900                  * Try to resolve aliases also, type is CNAME(5).
901                  * This is important as otherwise the aliased names would not
902                  * be cached at all as the cache would not contain the aliased
903                  * question.
904                  *
905                  * If any CNAME is found in DNS packet, then we cache the alias
906                  * IP address instead of the question (as the server
907                  * said that question has only an alias).
908                  * This means in practice that if e.g., ipv6.google.com is
909                  * queried, DNS server returns CNAME of that name which is
910                  * ipv6.l.google.com. We then cache the address of the CNAME
911                  * but return the question name to client. So the alias
912                  * status of the name is not saved in cache and thus not
913                  * returned to the client. We do not return DNS packets from
914                  * cache to client saying that ipv6.google.com is an alias to
915                  * ipv6.l.google.com but we return instead a DNS packet that
916                  * says ipv6.google.com has address xxx which is in fact the
917                  * address of ipv6.l.google.com. For caching purposes this
918                  * should not cause any issues.
919                  */
920                 if (*type == 5 && strncmp(question, name, qlen) == 0) {
921                         /*
922                          * So now the alias answered the question. This is
923                          * not very useful from caching point of view as
924                          * the following A or AAAA records will not match the
925                          * question. We need to find the real A/AAAA record
926                          * of the alias and cache that.
927                          */
928                         unsigned char *end = NULL;
929                         int name_len = 0, output_len;
930
931                         memset(rsp, 0, sizeof(rsp));
932                         rsp_len = sizeof(rsp) - 1;
933
934                         /*
935                          * Alias is in rdata part of the message,
936                          * and next-rdlen points to it. So we need to get
937                          * the real name of the alias.
938                          */
939                         ret = get_name(0, buf, next - rdlen, buf + buflen,
940                                         rsp, rsp_len, &output_len, &end,
941                                         name, &name_len);
942                         if (ret != 0) {
943                                 /* just ignore the error at this point */
944                                 ptr = next;
945                                 next = NULL;
946                                 continue;
947                         }
948
949                         /*
950                          * We should now have the alias of the entry we might
951                          * want to cache. Just remember it for a while.
952                          * We check the alias list when we have parsed the
953                          * A or AAAA record.
954                          */
955                         aliases = g_slist_prepend(aliases, g_strdup(name));
956
957                         ptr = next;
958                         next = NULL;
959                         continue;
960                 }
961
962                 if (*type == qtype) {
963                         /*
964                          * We found correct type (A or AAAA)
965                          */
966                         if (check_alias(aliases, name) == TRUE ||
967                                 (aliases == NULL && strncmp(question, name,
968                                                         qlen) == 0)) {
969                                 /*
970                                  * We found an alias or the name of the rr
971                                  * matches the question. If so, we append
972                                  * the compressed label to the cache.
973                                  * The end result is a response buffer that
974                                  * will contain one or more cached and
975                                  * compressed resource records.
976                                  */
977                                 if (*response_len + rsp_len > maxlen) {
978                                         err = -ENOBUFS;
979                                         goto out;
980                                 }
981                                 memcpy(response + *response_len, rsp, rsp_len);
982                                 *response_len += rsp_len;
983                                 (*answers)++;
984                                 err = 0;
985                         }
986                 }
987
988                 ptr = next;
989                 next = NULL;
990         }
991
992 out:
993         for (list = aliases; list; list = list->next)
994                 g_free(list->data);
995         g_slist_free(aliases);
996
997         return err;
998 }
999
1000 struct cache_timeout {
1001         time_t current_time;
1002         int max_timeout;
1003         int try_harder;
1004 };
1005
1006 static gboolean cache_check_entry(gpointer key, gpointer value,
1007                                         gpointer user_data)
1008 {
1009         struct cache_timeout *data = user_data;
1010         struct cache_entry *entry = value;
1011         int max_timeout;
1012
1013         /* Scale the number of hits by half as part of cache aging */
1014
1015         entry->hits /= 2;
1016
1017         /*
1018          * If either IPv4 or IPv6 cached entry has expired, we
1019          * remove both from the cache.
1020          */
1021
1022         if (entry->ipv4 != NULL && entry->ipv4->timeout > 0) {
1023                 max_timeout = entry->ipv4->cache_until;
1024                 if (max_timeout > data->max_timeout)
1025                         data->max_timeout = max_timeout;
1026
1027                 if (entry->ipv4->cache_until < data->current_time)
1028                         return TRUE;
1029         }
1030
1031         if (entry->ipv6 != NULL && entry->ipv6->timeout > 0) {
1032                 max_timeout = entry->ipv6->cache_until;
1033                 if (max_timeout > data->max_timeout)
1034                         data->max_timeout = max_timeout;
1035
1036                 if (entry->ipv6->cache_until < data->current_time)
1037                         return TRUE;
1038         }
1039
1040         /*
1041          * if we're asked to try harder, also remove entries that have
1042          * few hits
1043          */
1044         if (data->try_harder && entry->hits < 4)
1045                 return TRUE;
1046
1047         return FALSE;
1048 }
1049
1050 static void cache_cleanup(void)
1051 {
1052         static int max_timeout;
1053         struct cache_timeout data;
1054         int count = 0;
1055
1056         data.current_time = time(NULL);
1057         data.max_timeout = 0;
1058         data.try_harder = 0;
1059
1060         /*
1061          * In the first pass, we only remove entries that have timed out.
1062          * We use a cache of the first time to expire to do this only
1063          * when it makes sense.
1064          */
1065         if (max_timeout <= data.current_time) {
1066                 count = g_hash_table_foreach_remove(cache, cache_check_entry,
1067                                                 &data);
1068         }
1069         DBG("removed %d in the first pass", count);
1070
1071         /*
1072          * In the second pass, if the first pass turned up blank,
1073          * we also expire entries with a low hit count,
1074          * while aging the hit count at the same time.
1075          */
1076         data.try_harder = 1;
1077         if (count == 0)
1078                 count = g_hash_table_foreach_remove(cache, cache_check_entry,
1079                                                 &data);
1080
1081         if (count == 0)
1082                 /*
1083                  * If we could not remove anything, then remember
1084                  * what is the max timeout and do nothing if we
1085                  * have not yet reached it. This will prevent
1086                  * constant traversal of the cache if it is full.
1087                  */
1088                 max_timeout = data.max_timeout;
1089         else
1090                 max_timeout = 0;
1091 }
1092
1093 static gboolean cache_invalidate_entry(gpointer key, gpointer value,
1094                                         gpointer user_data)
1095 {
1096         struct cache_entry *entry = value;
1097
1098         /* first, delete any expired elements */
1099         cache_enforce_validity(entry);
1100
1101         /* if anything is not expired, mark the entry for refresh */
1102         if (entry->hits > 0 && (entry->ipv4 || entry->ipv6))
1103                 entry->want_refresh = 1;
1104
1105         /* delete the cached data */
1106         if (entry->ipv4) {
1107                 g_free(entry->ipv4->data);
1108                 g_free(entry->ipv4);
1109                 entry->ipv4 = NULL;
1110         }
1111
1112         if (entry->ipv6) {
1113                 g_free(entry->ipv6->data);
1114                 g_free(entry->ipv6);
1115                 entry->ipv6 = NULL;
1116         }
1117
1118         /* keep the entry if we want it refreshed, delete it otherwise */
1119         if (entry->want_refresh)
1120                 return FALSE;
1121         else
1122                 return TRUE;
1123 }
1124
1125 /*
1126  * cache_invalidate is called from places where the DNS landscape
1127  * has changed, say because connections are added or we entered a VPN.
1128  * The logic is to wipe all cache data, but mark all non-expired
1129  * parts of the cache for refresh rather than deleting the whole cache.
1130  */
1131 static void cache_invalidate(void)
1132 {
1133         DBG("Invalidating the DNS cache %p", cache);
1134
1135         if (cache == NULL)
1136                 return;
1137
1138         g_hash_table_foreach_remove(cache, cache_invalidate_entry, NULL);
1139 }
1140
1141 static void cache_refresh_entry(struct cache_entry *entry)
1142 {
1143
1144         cache_enforce_validity(entry);
1145
1146         if (entry->hits > 2 && entry->ipv4 == NULL)
1147                 entry->want_refresh = 1;
1148         if (entry->hits > 2 && entry->ipv6 == NULL)
1149                 entry->want_refresh = 1;
1150
1151         if (entry->want_refresh) {
1152                 char *c;
1153                 char dns_name[NS_MAXDNAME + 1];
1154                 entry->want_refresh = 0;
1155
1156                 /* turn a DNS name into a hostname with dots */
1157                 strncpy(dns_name, entry->key, NS_MAXDNAME);
1158                 c = dns_name;
1159                 while (c && *c) {
1160                         int jump;
1161                         jump = *c;
1162                         *c = '.';
1163                         c += jump + 1;
1164                 }
1165                 DBG("Refreshing %s\n", dns_name);
1166                 /* then refresh the hostname */
1167                 refresh_dns_entry(entry, &dns_name[1]);
1168         }
1169 }
1170
1171 static void cache_refresh_iterator(gpointer key, gpointer value,
1172                                         gpointer user_data)
1173 {
1174         struct cache_entry *entry = value;
1175
1176         cache_refresh_entry(entry);
1177 }
1178
1179 static void cache_refresh(void)
1180 {
1181         if (cache == NULL)
1182                 return;
1183
1184         g_hash_table_foreach(cache, cache_refresh_iterator, NULL);
1185 }
1186
1187 static int reply_query_type(unsigned char *msg, int len)
1188 {
1189         unsigned char *c;
1190         uint16_t *w;
1191         int l;
1192         int type;
1193
1194         /* skip the header */
1195         c = msg + sizeof(struct domain_hdr);
1196         len -= sizeof(struct domain_hdr);
1197
1198         if (len < 0)
1199                 return 0;
1200
1201         /* now the query, which is a name and 2 16 bit words */
1202         l = dns_name_length(c) + 1;
1203         c += l;
1204         len -= l;
1205         w = (uint16_t *) c;
1206         type = ntohs(*w);
1207
1208         return type;
1209 }
1210
1211 static int cache_update(struct server_data *srv, unsigned char *msg,
1212                         unsigned int msg_len)
1213 {
1214         int offset = protocol_offset(srv->protocol);
1215         int err, qlen, ttl = 0;
1216         uint16_t answers = 0, type = 0, class = 0;
1217         struct domain_question *q;
1218         struct cache_entry *entry;
1219         struct cache_data *data;
1220         char question[NS_MAXDNAME + 1];
1221         unsigned char response[NS_MAXDNAME + 1];
1222         unsigned char *ptr;
1223         unsigned int rsplen;
1224         gboolean new_entry = TRUE;
1225         time_t current_time;
1226
1227         if (cache_size >= MAX_CACHE_SIZE) {
1228                 cache_cleanup();
1229                 if (cache_size >= MAX_CACHE_SIZE)
1230                         return 0;
1231         }
1232
1233         current_time = time(NULL);
1234
1235         /* don't do a cache refresh more than twice a minute */
1236         if (next_refresh < current_time) {
1237                 cache_refresh();
1238                 next_refresh = current_time + 30;
1239         }
1240
1241
1242         /* Continue only if response code is 0 (=ok) */
1243         if (msg[3] & 0x0f)
1244                 return 0;
1245
1246         if (offset < 0)
1247                 return 0;
1248
1249         rsplen = sizeof(response) - 1;
1250         question[sizeof(question) - 1] = '\0';
1251
1252         err = parse_response(msg + offset, msg_len - offset,
1253                                 question, sizeof(question) - 1,
1254                                 &type, &class, &ttl,
1255                                 response, &rsplen, &answers);
1256
1257         /*
1258          * special case: if we do a ipv6 lookup and get no result
1259          * for a record that's already in our ipv4 cache.. we want
1260          * to cache the negative response.
1261          */
1262         if ((err == -ENOMSG || err == -ENOBUFS) &&
1263                         reply_query_type(msg, msg_len) == 28) {
1264                 entry = g_hash_table_lookup(cache, question);
1265                 if (entry && entry->ipv4 && entry->ipv6 == NULL) {
1266                         data = g_try_new(struct cache_data, 1);
1267                         if (data == NULL)
1268                                 return -ENOMEM;
1269                         data->inserted = entry->ipv4->inserted;
1270                         data->type = type;
1271                         data->answers = msg[5];
1272                         data->timeout = entry->ipv4->timeout;
1273                         data->data_len = msg_len;
1274                         data->data = ptr = g_malloc(msg_len);
1275                         data->valid_until = entry->ipv4->valid_until;
1276                         data->cache_until = entry->ipv4->cache_until;
1277                         memcpy(data->data, msg, msg_len);
1278                         entry->ipv6 = data;
1279                         /*
1280                          * we will get a "hit" when we serve the response
1281                          * out of the cache
1282                          */
1283                         entry->hits--;
1284                         if (entry->hits < 0)
1285                                 entry->hits = 0;
1286                         return 0;
1287                 }
1288         }
1289
1290         if (err < 0 || ttl == 0)
1291                 return 0;
1292
1293         qlen = strlen(question);
1294
1295         /*
1296          * If the cache contains already data, check if the
1297          * type of the cached data is the same and do not add
1298          * to cache if data is already there.
1299          * This is needed so that we can cache both A and AAAA
1300          * records for the same name.
1301          */
1302         entry = g_hash_table_lookup(cache, question);
1303         if (entry == NULL) {
1304                 entry = g_try_new(struct cache_entry, 1);
1305                 if (entry == NULL)
1306                         return -ENOMEM;
1307
1308                 data = g_try_new(struct cache_data, 1);
1309                 if (data == NULL) {
1310                         g_free(entry);
1311                         return -ENOMEM;
1312                 }
1313
1314                 entry->key = g_strdup(question);
1315                 entry->ipv4 = entry->ipv6 = NULL;
1316                 entry->want_refresh = 0;
1317                 entry->hits = 0;
1318
1319                 if (type == 1)
1320                         entry->ipv4 = data;
1321                 else
1322                         entry->ipv6 = data;
1323         } else {
1324                 if (type == 1 && entry->ipv4 != NULL)
1325                         return 0;
1326
1327                 if (type == 28 && entry->ipv6 != NULL)
1328                         return 0;
1329
1330                 data = g_try_new(struct cache_data, 1);
1331                 if (data == NULL)
1332                         return -ENOMEM;
1333
1334                 if (type == 1)
1335                         entry->ipv4 = data;
1336                 else
1337                         entry->ipv6 = data;
1338
1339                 /*
1340                  * compensate for the hit we'll get for serving
1341                  * the response out of the cache
1342                  */
1343                 entry->hits--;
1344                 if (entry->hits < 0)
1345                         entry->hits = 0;
1346
1347                 new_entry = FALSE;
1348         }
1349
1350         if (ttl < MIN_CACHE_TTL)
1351                 ttl = MIN_CACHE_TTL;
1352
1353         data->inserted = current_time;
1354         data->type = type;
1355         data->answers = answers;
1356         data->timeout = ttl;
1357         data->data_len = 12 + qlen + 1 + 2 + 2 + rsplen;
1358         data->data = ptr = g_malloc(data->data_len);
1359         data->valid_until = current_time + ttl;
1360
1361         /*
1362          * Restrict the cached DNS record TTL to some sane value
1363          * in order to prevent data staying in the cache too long.
1364          */
1365         if (ttl > MAX_CACHE_TTL)
1366                 ttl = MAX_CACHE_TTL;
1367
1368         data->cache_until = round_down_ttl(current_time + ttl, ttl);
1369
1370         if (data->data == NULL) {
1371                 g_free(entry->key);
1372                 g_free(data);
1373                 g_free(entry);
1374                 return -ENOMEM;
1375         }
1376
1377         memcpy(ptr, msg, 12);
1378         memcpy(ptr + 12, question, qlen + 1); /* copy also the \0 */
1379
1380         q = (void *) (ptr + 12 + qlen + 1);
1381         q->type = htons(type);
1382         q->class = htons(class);
1383         memcpy(ptr + 12 + qlen + 1 + sizeof(struct domain_question),
1384                 response, rsplen);
1385
1386         if (new_entry == TRUE) {
1387                 g_hash_table_replace(cache, entry->key, entry);
1388                 cache_size++;
1389         }
1390
1391         DBG("cache %d %squestion \"%s\" type %d ttl %d size %zd",
1392                 cache_size, new_entry ? "new " : "old ",
1393                 question, type, ttl,
1394                 sizeof(*entry) + sizeof(*data) + data->data_len + qlen);
1395
1396         return 0;
1397 }
1398
1399 static int ns_resolv(struct server_data *server, struct request_data *req,
1400                                 gpointer request, gpointer name)
1401 {
1402         GList *list;
1403         int sk, err, type = 0;
1404         char *dot, *lookup = (char *) name;
1405         struct cache_entry *entry;
1406
1407         entry = cache_check(request, &type);
1408         if (entry != NULL) {
1409                 int ttl_left = 0;
1410                 struct cache_data *data;
1411
1412                 DBG("cache hit %s type %s", lookup, type == 1 ? "A" : "AAAA");
1413                 if (type == 1)
1414                         data = entry->ipv4;
1415                 else
1416                         data = entry->ipv6;
1417
1418                 if (data) {
1419                         ttl_left = data->valid_until - time(NULL);
1420                         entry->hits++;
1421                 }
1422
1423                 if (data != NULL && req->protocol == IPPROTO_TCP) {
1424                         send_cached_response(req->client_sk, data->data,
1425                                         data->data_len, NULL, 0, IPPROTO_TCP,
1426                                         req->srcid, data->answers, ttl_left);
1427                         return 1;
1428                 }
1429
1430                 if (data != NULL && req->protocol == IPPROTO_UDP) {
1431                         int sk;
1432                         sk = g_io_channel_unix_get_fd(
1433                                         req->ifdata->udp_listener_channel);
1434
1435                         send_cached_response(sk, data->data,
1436                                 data->data_len, &req->sa, req->sa_len,
1437                                 IPPROTO_UDP, req->srcid, data->answers,
1438                                 ttl_left);
1439                         return 1;
1440                 }
1441         }
1442
1443         sk = g_io_channel_unix_get_fd(server->channel);
1444
1445         err = send(sk, request, req->request_len, 0);
1446         if (err < 0)
1447                 return -EIO;
1448
1449         req->numserv++;
1450
1451         /* If we have more than one dot, we don't add domains */
1452         dot = strchr(lookup, '.');
1453         if (dot != NULL && dot != lookup + strlen(lookup) - 1)
1454                 return 0;
1455
1456         if (server->domains != NULL && server->domains->data != NULL)
1457                 req->append_domain = TRUE;
1458
1459         for (list = server->domains; list; list = list->next) {
1460                 char *domain;
1461                 unsigned char alt[1024];
1462                 struct domain_hdr *hdr = (void *) &alt;
1463                 int altlen, domlen, offset;
1464
1465                 domain = list->data;
1466
1467                 if (domain == NULL)
1468                         continue;
1469
1470                 offset = protocol_offset(server->protocol);
1471                 if (offset < 0)
1472                         return offset;
1473
1474                 domlen = strlen(domain) + 1;
1475                 if (domlen < 5)
1476                         return -EINVAL;
1477
1478                 alt[offset] = req->altid & 0xff;
1479                 alt[offset + 1] = req->altid >> 8;
1480
1481                 memcpy(alt + offset + 2, request + offset + 2, 10);
1482                 hdr->qdcount = htons(1);
1483
1484                 altlen = append_query(alt + offset + 12, sizeof(alt) - 12,
1485                                         name, domain);
1486                 if (altlen < 0)
1487                         return -EINVAL;
1488
1489                 altlen += 12;
1490
1491                 memcpy(alt + offset + altlen,
1492                         request + offset + altlen - domlen,
1493                                 req->request_len - altlen - offset + domlen);
1494
1495                 if (server->protocol == IPPROTO_TCP) {
1496                         int req_len = req->request_len + domlen - 2;
1497
1498                         alt[0] = (req_len >> 8) & 0xff;
1499                         alt[1] = req_len & 0xff;
1500                 }
1501
1502                 err = send(sk, alt, req->request_len + domlen, 0);
1503                 if (err < 0)
1504                         return -EIO;
1505
1506                 req->numserv++;
1507         }
1508
1509         return 0;
1510 }
1511
1512 static int forward_dns_reply(unsigned char *reply, int reply_len, int protocol,
1513                                 struct server_data *data)
1514 {
1515         struct domain_hdr *hdr;
1516         struct request_data *req;
1517         int dns_id, sk, err, offset = protocol_offset(protocol);
1518         struct listener_data *ifdata;
1519
1520         if (offset < 0)
1521                 return offset;
1522
1523         hdr = (void *)(reply + offset);
1524         dns_id = reply[offset] | reply[offset + 1] << 8;
1525
1526         DBG("Received %d bytes (id 0x%04x)", reply_len, dns_id);
1527
1528         req = find_request(dns_id);
1529         if (req == NULL)
1530                 return -EINVAL;
1531
1532         DBG("id 0x%04x rcode %d", hdr->id, hdr->rcode);
1533
1534         ifdata = req->ifdata;
1535
1536         reply[offset] = req->srcid & 0xff;
1537         reply[offset + 1] = req->srcid >> 8;
1538
1539         req->numresp++;
1540
1541         if (hdr->rcode == 0 || req->resp == NULL) {
1542
1543                 /*
1544                  * If the domain name was append
1545                  * remove it before forwarding the reply.
1546                  */
1547                 if (req->append_domain == TRUE) {
1548                         unsigned char *ptr;
1549                         uint8_t host_len;
1550                         unsigned int domain_len;
1551
1552                         /*
1553                          * ptr points to the first char of the hostname.
1554                          * ->hostname.domain.net
1555                          */
1556                         ptr = reply + offset + sizeof(struct domain_hdr);
1557                         host_len = *ptr;
1558                         domain_len = strlen((const char *)ptr) - host_len - 1;
1559
1560                         /*
1561                          * remove the domain name and replaced it by the end
1562                          * of reply.
1563                          */
1564                         memmove(ptr + host_len + 1,
1565                                 ptr + host_len + domain_len + 1,
1566                                 reply_len - (ptr - reply + domain_len));
1567
1568                         reply_len = reply_len - domain_len;
1569                 }
1570
1571                 g_free(req->resp);
1572                 req->resplen = 0;
1573
1574                 req->resp = g_try_malloc(reply_len);
1575                 if (req->resp == NULL)
1576                         return -ENOMEM;
1577
1578                 memcpy(req->resp, reply, reply_len);
1579                 req->resplen = reply_len;
1580
1581                 cache_update(data, reply, reply_len);
1582         }
1583
1584         if (hdr->rcode > 0 && req->numresp < req->numserv)
1585                 return -EINVAL;
1586
1587         if (req->timeout > 0)
1588                 g_source_remove(req->timeout);
1589
1590         request_list = g_slist_remove(request_list, req);
1591
1592         if (protocol == IPPROTO_UDP) {
1593                 sk = g_io_channel_unix_get_fd(ifdata->udp_listener_channel);
1594                 err = sendto(sk, req->resp, req->resplen, 0,
1595                              &req->sa, req->sa_len);
1596         } else {
1597                 sk = req->client_sk;
1598                 err = send(sk, req->resp, req->resplen, 0);
1599                 close(sk);
1600         }
1601
1602         g_free(req->resp);
1603         g_free(req);
1604
1605         return err;
1606 }
1607
1608 static void cache_element_destroy(gpointer value)
1609 {
1610         struct cache_entry *entry = value;
1611
1612         if (entry == NULL)
1613                 return;
1614
1615         if (entry->ipv4 != NULL) {
1616                 g_free(entry->ipv4->data);
1617                 g_free(entry->ipv4);
1618         }
1619
1620         if (entry->ipv6 != NULL) {
1621                 g_free(entry->ipv6->data);
1622                 g_free(entry->ipv6);
1623         }
1624
1625         g_free(entry->key);
1626         g_free(entry);
1627
1628         if (--cache_size < 0)
1629                 cache_size = 0;
1630 }
1631
1632 static gboolean try_remove_cache(gpointer user_data)
1633 {
1634         if (__sync_fetch_and_sub(&cache_refcount, 1) == 1) {
1635                 DBG("No cache users, removing it.");
1636
1637                 g_hash_table_destroy(cache);
1638                 cache = NULL;
1639         }
1640
1641         return FALSE;
1642 }
1643
1644 static void destroy_server(struct server_data *server)
1645 {
1646         GList *list;
1647
1648         DBG("interface %s server %s", server->interface, server->server);
1649
1650         server_list = g_slist_remove(server_list, server);
1651
1652         if (server->watch > 0)
1653                 g_source_remove(server->watch);
1654
1655         if (server->timeout > 0)
1656                 g_source_remove(server->timeout);
1657
1658         g_io_channel_unref(server->channel);
1659
1660         if (server->protocol == IPPROTO_UDP)
1661                 connman_info("Removing DNS server %s", server->server);
1662
1663         g_free(server->incoming_reply);
1664         g_free(server->server);
1665         for (list = server->domains; list; list = list->next) {
1666                 char *domain = list->data;
1667
1668                 server->domains = g_list_remove(server->domains, domain);
1669                 g_free(domain);
1670         }
1671         g_free(server->interface);
1672
1673         /*
1674          * We do not remove cache right away but delay it few seconds.
1675          * The idea is that when IPv6 DNS server is added via RDNSS, it has a
1676          * lifetime. When the lifetime expires we decrease the refcount so it
1677          * is possible that the cache is then removed. Because a new DNS server
1678          * is usually created almost immediately we would then loose the cache
1679          * without any good reason. The small delay allows the new RDNSS to
1680          * create a new DNS server instance and the refcount does not go to 0.
1681          */
1682         g_timeout_add_seconds(3, try_remove_cache, NULL);
1683
1684         g_free(server);
1685 }
1686
1687 static gboolean udp_server_event(GIOChannel *channel, GIOCondition condition,
1688                                                         gpointer user_data)
1689 {
1690         unsigned char buf[4096];
1691         int sk, err, len;
1692         struct server_data *data = user_data;
1693
1694         if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
1695                 connman_error("Error with UDP server %s", data->server);
1696                 data->watch = 0;
1697                 return FALSE;
1698         }
1699
1700         sk = g_io_channel_unix_get_fd(channel);
1701
1702         len = recv(sk, buf, sizeof(buf), 0);
1703         if (len < 12)
1704                 return TRUE;
1705
1706         err = forward_dns_reply(buf, len, IPPROTO_UDP, data);
1707         if (err < 0)
1708                 return TRUE;
1709
1710         return TRUE;
1711 }
1712
1713 static gboolean tcp_server_event(GIOChannel *channel, GIOCondition condition,
1714                                                         gpointer user_data)
1715 {
1716         int sk;
1717         struct server_data *server = user_data;
1718
1719         sk = g_io_channel_unix_get_fd(channel);
1720         if (sk == 0)
1721                 return FALSE;
1722
1723         if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
1724                 GSList *list;
1725 hangup:
1726                 DBG("TCP server channel closed");
1727
1728                 /*
1729                  * Discard any partial response which is buffered; better
1730                  * to get a proper response from a working server.
1731                  */
1732                 g_free(server->incoming_reply);
1733                 server->incoming_reply = NULL;
1734
1735                 for (list = request_list; list; list = list->next) {
1736                         struct request_data *req = list->data;
1737                         struct domain_hdr *hdr;
1738
1739                         if (req->protocol == IPPROTO_UDP)
1740                                 continue;
1741
1742                         if (req->request == NULL)
1743                                 continue;
1744
1745                         /*
1746                          * If we're not waiting for any further response
1747                          * from another name server, then we send an error
1748                          * response to the client.
1749                          */
1750                         if (req->numserv && --(req->numserv))
1751                                 continue;
1752
1753                         hdr = (void *) (req->request + 2);
1754                         hdr->id = req->srcid;
1755                         send_response(req->client_sk, req->request,
1756                                 req->request_len, NULL, 0, IPPROTO_TCP);
1757
1758                         request_list = g_slist_remove(request_list, req);
1759                 }
1760
1761                 destroy_server(server);
1762
1763                 return FALSE;
1764         }
1765
1766         if ((condition & G_IO_OUT) && !server->connected) {
1767                 GSList *list;
1768                 GList *domains;
1769                 struct server_data *udp_server;
1770
1771                 udp_server = find_server(server->interface, server->server,
1772                                                                 IPPROTO_UDP);
1773                 if (udp_server != NULL) {
1774                         for (domains = udp_server->domains; domains;
1775                                                 domains = domains->next) {
1776                                 char *dom = domains->data;
1777
1778                                 DBG("Adding domain %s to %s",
1779                                                 dom, server->server);
1780
1781                                 server->domains = g_list_append(server->domains,
1782                                                                 g_strdup(dom));
1783                         }
1784                 }
1785
1786                 server->connected = TRUE;
1787                 server_list = g_slist_append(server_list, server);
1788
1789                 if (server->timeout > 0) {
1790                         g_source_remove(server->timeout);
1791                         server->timeout = 0;
1792                 }
1793
1794                 for (list = request_list; list; list = list->next) {
1795                         struct request_data *req = list->data;
1796
1797                         if (req->protocol == IPPROTO_UDP)
1798                                 continue;
1799
1800                         DBG("Sending req %s over TCP", (char *)req->name);
1801
1802                         if (req->timeout > 0)
1803                                 g_source_remove(req->timeout);
1804
1805                         req->timeout = g_timeout_add_seconds(30,
1806                                                 request_timeout, req);
1807                         if (ns_resolv(server, req, req->request,
1808                                         req->name) > 0) {
1809                                 /* We sent cached result so no need for timeout
1810                                  * handler.
1811                                  */
1812                                 if (req->timeout > 0) {
1813                                         g_source_remove(req->timeout);
1814                                         req->timeout = 0;
1815                                 }
1816                         }
1817                 }
1818
1819         } else if (condition & G_IO_IN) {
1820                 struct partial_reply *reply = server->incoming_reply;
1821                 int bytes_recv;
1822
1823                 if (!reply) {
1824                         unsigned char reply_len_buf[2];
1825                         uint16_t reply_len;
1826
1827                         bytes_recv = recv(sk, reply_len_buf, 2, MSG_PEEK);
1828                         if (!bytes_recv) {
1829                                 goto hangup;
1830                         } else if (bytes_recv < 0) {
1831                                 if (errno == EAGAIN || errno == EWOULDBLOCK)
1832                                         return TRUE;
1833
1834                                 connman_error("DNS proxy error %s",
1835                                                 strerror(errno));
1836                                 goto hangup;
1837                         } else if (bytes_recv < 2)
1838                                 return TRUE;
1839
1840                         reply_len = reply_len_buf[1] | reply_len_buf[0] << 8;
1841                         reply_len += 2;
1842
1843                         DBG("TCP reply %d bytes", reply_len);
1844
1845                         reply = g_try_malloc(sizeof(*reply) + reply_len + 2);
1846                         if (!reply)
1847                                 return TRUE;
1848
1849                         reply->len = reply_len;
1850                         reply->received = 0;
1851
1852                         server->incoming_reply = reply;
1853                 }
1854
1855                 while (reply->received < reply->len) {
1856                         bytes_recv = recv(sk, reply->buf + reply->received,
1857                                         reply->len - reply->received, 0);
1858                         if (!bytes_recv) {
1859                                 connman_error("DNS proxy TCP disconnect");
1860                                 break;
1861                         } else if (bytes_recv < 0) {
1862                                 if (errno == EAGAIN || errno == EWOULDBLOCK)
1863                                         return TRUE;
1864
1865                                 connman_error("DNS proxy error %s",
1866                                                 strerror(errno));
1867                                 break;
1868                         }
1869                         reply->received += bytes_recv;
1870                 }
1871
1872                 forward_dns_reply(reply->buf, reply->received, IPPROTO_TCP,
1873                                         server);
1874
1875                 g_free(reply);
1876                 server->incoming_reply = NULL;
1877
1878                 destroy_server(server);
1879
1880                 return FALSE;
1881         }
1882
1883         return TRUE;
1884 }
1885
1886 static gboolean tcp_idle_timeout(gpointer user_data)
1887 {
1888         struct server_data *server = user_data;
1889
1890         DBG("");
1891
1892         if (server == NULL)
1893                 return FALSE;
1894
1895         destroy_server(server);
1896
1897         return FALSE;
1898 }
1899
1900 static struct server_data *create_server(const char *interface,
1901                                         const char *domain, const char *server,
1902                                         int protocol)
1903 {
1904         struct addrinfo hints, *rp;
1905         struct server_data *data;
1906         int sk, ret;
1907
1908         DBG("interface %s server %s", interface, server);
1909
1910         memset(&hints, 0, sizeof(hints));
1911
1912         switch (protocol) {
1913         case IPPROTO_UDP:
1914                 hints.ai_socktype = SOCK_DGRAM;
1915                 break;
1916
1917         case IPPROTO_TCP:
1918                 hints.ai_socktype = SOCK_STREAM;
1919                 break;
1920
1921         default:
1922                 return NULL;
1923         }
1924         hints.ai_family = AF_UNSPEC;
1925         hints.ai_flags = AI_PASSIVE | AI_NUMERICSERV | AI_NUMERICHOST;
1926
1927         ret = getaddrinfo(server, "53", &hints, &rp);
1928         if (ret) {
1929                 connman_error("Failed to parse server %s address: %s\n",
1930                               server, gai_strerror(ret));
1931                 return NULL;
1932         }
1933         /* Do not blindly copy this code elsewhere; it doesn't loop over the
1934            results using ->ai_next as it should. That's OK in *this* case
1935            because it was a numeric lookup; we *know* there's only one. */
1936
1937         sk = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
1938         if (sk < 0) {
1939                 connman_error("Failed to create server %s socket", server);
1940                 freeaddrinfo(rp);
1941                 return NULL;
1942         }
1943
1944         if (interface != NULL) {
1945                 if (setsockopt(sk, SOL_SOCKET, SO_BINDTODEVICE,
1946                                 interface, strlen(interface) + 1) < 0) {
1947                         connman_error("Failed to bind server %s "
1948                                                 "to interface %s",
1949                                                         server, interface);
1950                         freeaddrinfo(rp);
1951                         close(sk);
1952                         return NULL;
1953                 }
1954         }
1955
1956         data = g_try_new0(struct server_data, 1);
1957         if (data == NULL) {
1958                 connman_error("Failed to allocate server %s data", server);
1959                 freeaddrinfo(rp);
1960                 close(sk);
1961                 return NULL;
1962         }
1963
1964         data->channel = g_io_channel_unix_new(sk);
1965         if (data->channel == NULL) {
1966                 connman_error("Failed to create server %s channel", server);
1967                 freeaddrinfo(rp);
1968                 close(sk);
1969                 g_free(data);
1970                 return NULL;
1971         }
1972
1973         g_io_channel_set_close_on_unref(data->channel, TRUE);
1974
1975         if (protocol == IPPROTO_TCP) {
1976                 g_io_channel_set_flags(data->channel, G_IO_FLAG_NONBLOCK, NULL);
1977                 data->watch = g_io_add_watch(data->channel,
1978                         G_IO_OUT | G_IO_IN | G_IO_HUP | G_IO_NVAL | G_IO_ERR,
1979                                                 tcp_server_event, data);
1980                 data->timeout = g_timeout_add_seconds(30, tcp_idle_timeout,
1981                                                                 data);
1982         } else
1983                 data->watch = g_io_add_watch(data->channel,
1984                         G_IO_IN | G_IO_NVAL | G_IO_ERR | G_IO_HUP,
1985                                                 udp_server_event, data);
1986
1987         data->interface = g_strdup(interface);
1988         if (domain)
1989                 data->domains = g_list_append(data->domains, g_strdup(domain));
1990         data->server = g_strdup(server);
1991         data->protocol = protocol;
1992
1993         ret = connect(sk, rp->ai_addr, rp->ai_addrlen);
1994         freeaddrinfo(rp);
1995         if (ret < 0) {
1996                 if ((protocol == IPPROTO_TCP && errno != EINPROGRESS) ||
1997                                 protocol == IPPROTO_UDP) {
1998                         GList *list;
1999
2000                         connman_error("Failed to connect to server %s", server);
2001                         if (data->watch > 0)
2002                                 g_source_remove(data->watch);
2003                         if (data->timeout > 0)
2004                                 g_source_remove(data->timeout);
2005
2006                         g_io_channel_unref(data->channel);
2007                         close(sk);
2008
2009                         g_free(data->server);
2010                         g_free(data->interface);
2011                         for (list = data->domains; list; list = list->next) {
2012                                 char *domain = list->data;
2013
2014                                 data->domains = g_list_remove(data->domains,
2015                                                                         domain);
2016                                 g_free(domain);
2017                         }
2018                         g_free(data);
2019                         return NULL;
2020                 }
2021         }
2022
2023         if (__sync_fetch_and_add(&cache_refcount, 1) == 0)
2024                 cache = g_hash_table_new_full(g_str_hash,
2025                                         g_str_equal,
2026                                         NULL,
2027                                         cache_element_destroy);
2028
2029         if (protocol == IPPROTO_UDP) {
2030                 /* Enable new servers by default */
2031                 data->enabled = TRUE;
2032                 connman_info("Adding DNS server %s", data->server);
2033
2034                 server_list = g_slist_append(server_list, data);
2035
2036                 return data;
2037         }
2038
2039         return NULL;
2040 }
2041
2042 static gboolean resolv(struct request_data *req,
2043                                 gpointer request, gpointer name)
2044 {
2045         GSList *list;
2046         int status;
2047
2048         for (list = server_list; list; list = list->next) {
2049                 struct server_data *data = list->data;
2050
2051                 DBG("server %s enabled %d", data->server, data->enabled);
2052
2053                 if (data->enabled == FALSE)
2054                         continue;
2055
2056                 if (data->watch == 0 && data->protocol == IPPROTO_UDP)
2057                         data->watch = g_io_add_watch(data->channel,
2058                                 G_IO_IN | G_IO_NVAL | G_IO_ERR | G_IO_HUP,
2059                                                 udp_server_event, data);
2060
2061                 status = ns_resolv(data, req, request, name);
2062                 if (status < 0)
2063                         continue;
2064
2065                 if (status > 0) {
2066                         if (req->timeout > 0) {
2067                                 g_source_remove(req->timeout);
2068                                 req->timeout = 0;
2069                         }
2070                 }
2071         }
2072
2073         return TRUE;
2074 }
2075
2076 static void append_domain(const char *interface, const char *domain)
2077 {
2078         GSList *list;
2079
2080         DBG("interface %s domain %s", interface, domain);
2081
2082         if (domain == NULL)
2083                 return;
2084
2085         for (list = server_list; list; list = list->next) {
2086                 struct server_data *data = list->data;
2087                 GList *dom_list;
2088                 char *dom;
2089                 gboolean dom_found = FALSE;
2090
2091                 if (data->interface == NULL)
2092                         continue;
2093
2094                 if (g_str_equal(data->interface, interface) == FALSE)
2095                         continue;
2096
2097                 for (dom_list = data->domains; dom_list;
2098                                 dom_list = dom_list->next) {
2099                         dom = dom_list->data;
2100
2101                         if (g_str_equal(dom, domain)) {
2102                                 dom_found = TRUE;
2103                                 break;
2104                         }
2105                 }
2106
2107                 if (dom_found == FALSE) {
2108                         data->domains =
2109                                 g_list_append(data->domains, g_strdup(domain));
2110                 }
2111         }
2112 }
2113
2114 int __connman_dnsproxy_append(const char *interface, const char *domain,
2115                                                         const char *server)
2116 {
2117         struct server_data *data;
2118
2119         DBG("interface %s server %s", interface, server);
2120
2121         if (server == NULL && domain == NULL)
2122                 return -EINVAL;
2123
2124         if (server == NULL) {
2125                 append_domain(interface, domain);
2126
2127                 return 0;
2128         }
2129
2130         if (g_str_equal(server, "127.0.0.1") == TRUE)
2131                 return -ENODEV;
2132
2133         data = find_server(interface, server, IPPROTO_UDP);
2134         if (data != NULL) {
2135                 append_domain(interface, domain);
2136                 return 0;
2137         }
2138
2139         data = create_server(interface, domain, server, IPPROTO_UDP);
2140         if (data == NULL)
2141                 return -EIO;
2142
2143         return 0;
2144 }
2145
2146 static void remove_server(const char *interface, const char *domain,
2147                         const char *server, int protocol)
2148 {
2149         struct server_data *data;
2150
2151         data = find_server(interface, server, protocol);
2152         if (data == NULL)
2153                 return;
2154
2155         destroy_server(data);
2156 }
2157
2158 int __connman_dnsproxy_remove(const char *interface, const char *domain,
2159                                                         const char *server)
2160 {
2161         DBG("interface %s server %s", interface, server);
2162
2163         if (server == NULL)
2164                 return -EINVAL;
2165
2166         if (g_str_equal(server, "127.0.0.1") == TRUE)
2167                 return -ENODEV;
2168
2169         remove_server(interface, domain, server, IPPROTO_UDP);
2170         remove_server(interface, domain, server, IPPROTO_TCP);
2171
2172         return 0;
2173 }
2174
2175 void __connman_dnsproxy_flush(void)
2176 {
2177         GSList *list;
2178
2179         list = request_pending_list;
2180         while (list) {
2181                 struct request_data *req = list->data;
2182
2183                 list = list->next;
2184
2185                 request_pending_list =
2186                                 g_slist_remove(request_pending_list, req);
2187                 resolv(req, req->request, req->name);
2188                 g_free(req->request);
2189                 g_free(req->name);
2190         }
2191 }
2192
2193 static void dnsproxy_offline_mode(connman_bool_t enabled)
2194 {
2195         GSList *list;
2196
2197         DBG("enabled %d", enabled);
2198
2199         for (list = server_list; list; list = list->next) {
2200                 struct server_data *data = list->data;
2201
2202                 if (enabled == FALSE) {
2203                         connman_info("Enabling DNS server %s", data->server);
2204                         data->enabled = TRUE;
2205                         cache_invalidate();
2206                         cache_refresh();
2207                 } else {
2208                         connman_info("Disabling DNS server %s", data->server);
2209                         data->enabled = FALSE;
2210                         cache_invalidate();
2211                 }
2212         }
2213 }
2214
2215 static void dnsproxy_default_changed(struct connman_service *service)
2216 {
2217         GSList *list;
2218         char *interface;
2219
2220         DBG("service %p", service);
2221
2222         /* DNS has changed, invalidate the cache */
2223         cache_invalidate();
2224
2225         if (service == NULL) {
2226                 /* When no services are active, then disable DNS proxying */
2227                 dnsproxy_offline_mode(TRUE);
2228                 return;
2229         }
2230
2231         interface = connman_service_get_interface(service);
2232         if (interface == NULL)
2233                 return;
2234
2235         for (list = server_list; list; list = list->next) {
2236                 struct server_data *data = list->data;
2237
2238                 if (g_strcmp0(data->interface, interface) == 0) {
2239                         connman_info("Enabling DNS server %s", data->server);
2240                         data->enabled = TRUE;
2241                 } else {
2242                         connman_info("Disabling DNS server %s", data->server);
2243                         data->enabled = FALSE;
2244                 }
2245         }
2246
2247         g_free(interface);
2248         cache_refresh();
2249 }
2250
2251 static struct connman_notifier dnsproxy_notifier = {
2252         .name                   = "dnsproxy",
2253         .default_changed        = dnsproxy_default_changed,
2254         .offline_mode           = dnsproxy_offline_mode,
2255 };
2256
2257 static unsigned char opt_edns0_type[2] = { 0x00, 0x29 };
2258
2259 static int parse_request(unsigned char *buf, int len,
2260                                         char *name, unsigned int size)
2261 {
2262         struct domain_hdr *hdr = (void *) buf;
2263         uint16_t qdcount = ntohs(hdr->qdcount);
2264         uint16_t arcount = ntohs(hdr->arcount);
2265         unsigned char *ptr;
2266         char *last_label = NULL;
2267         unsigned int remain, used = 0;
2268
2269         if (len < 12)
2270                 return -EINVAL;
2271
2272         DBG("id 0x%04x qr %d opcode %d qdcount %d arcount %d",
2273                                         hdr->id, hdr->qr, hdr->opcode,
2274                                                         qdcount, arcount);
2275
2276         if (hdr->qr != 0 || qdcount != 1)
2277                 return -EINVAL;
2278
2279         memset(name, 0, size);
2280
2281         ptr = buf + sizeof(struct domain_hdr);
2282         remain = len - sizeof(struct domain_hdr);
2283
2284         while (remain > 0) {
2285                 uint8_t len = *ptr;
2286
2287                 if (len == 0x00) {
2288                         last_label = (char *) (ptr + 1);
2289                         break;
2290                 }
2291
2292                 if (used + len + 1 > size)
2293                         return -ENOBUFS;
2294
2295                 strncat(name, (char *) (ptr + 1), len);
2296                 strcat(name, ".");
2297
2298                 used += len + 1;
2299
2300                 ptr += len + 1;
2301                 remain -= len + 1;
2302         }
2303
2304         if (last_label && arcount && remain >= 9 && last_label[4] == 0 &&
2305                                 !memcmp(last_label + 5, opt_edns0_type, 2)) {
2306                 uint16_t edns0_bufsize;
2307
2308                 edns0_bufsize = last_label[7] << 8 | last_label[8];
2309
2310                 DBG("EDNS0 buffer size %u", edns0_bufsize);
2311
2312                 /* This is an evil hack until full TCP support has been
2313                  * implemented.
2314                  *
2315                  * Somtimes the EDNS0 request gets send with a too-small
2316                  * buffer size. Since glibc doesn't seem to crash when it
2317                  * gets a response biffer then it requested, just bump
2318                  * the buffer size up to 4KiB.
2319                  */
2320                 if (edns0_bufsize < 0x1000) {
2321                         last_label[7] = 0x10;
2322                         last_label[8] = 0x00;
2323                 }
2324         }
2325
2326         DBG("query %s", name);
2327
2328         return 0;
2329 }
2330
2331 static gboolean tcp_listener_event(GIOChannel *channel, GIOCondition condition,
2332                                                         gpointer user_data)
2333 {
2334         unsigned char buf[768];
2335         char query[512];
2336         struct request_data *req;
2337         struct server_data *server;
2338         int sk, client_sk, len, err;
2339         struct sockaddr_in6 client_addr;
2340         socklen_t client_addr_len = sizeof(client_addr);
2341         GSList *list;
2342         struct listener_data *ifdata = user_data;
2343
2344         DBG("condition 0x%x", condition);
2345
2346         if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
2347                 if (ifdata->tcp_listener_watch > 0)
2348                         g_source_remove(ifdata->tcp_listener_watch);
2349                 ifdata->tcp_listener_watch = 0;
2350
2351                 connman_error("Error with TCP listener channel");
2352
2353                 return FALSE;
2354         }
2355
2356         sk = g_io_channel_unix_get_fd(channel);
2357
2358         client_sk = accept(sk, (void *)&client_addr, &client_addr_len);
2359         if (client_sk < 0) {
2360                 connman_error("Accept failure on TCP listener");
2361                 ifdata->tcp_listener_watch = 0;
2362                 return FALSE;
2363         }
2364
2365         len = recv(client_sk, buf, sizeof(buf), 0);
2366         if (len < 2)
2367                 return TRUE;
2368
2369         DBG("Received %d bytes (id 0x%04x)", len, buf[2] | buf[3] << 8);
2370
2371         err = parse_request(buf + 2, len - 2, query, sizeof(query));
2372         if (err < 0 || (g_slist_length(server_list) == 0)) {
2373                 send_response(client_sk, buf, len, NULL, 0, IPPROTO_TCP);
2374                 return TRUE;
2375         }
2376
2377         req = g_try_new0(struct request_data, 1);
2378         if (req == NULL)
2379                 return TRUE;
2380
2381         memcpy(&req->sa, &client_addr, client_addr_len);
2382         req->sa_len = client_addr_len;
2383         req->client_sk = client_sk;
2384         req->protocol = IPPROTO_TCP;
2385
2386         request_id += 2;
2387         if (request_id == 0x0000 || request_id == 0xffff)
2388                 request_id += 2;
2389
2390         req->srcid = buf[2] | (buf[3] << 8);
2391         req->dstid = request_id;
2392         req->altid = request_id + 1;
2393         req->request_len = len;
2394
2395         buf[2] = req->dstid & 0xff;
2396         buf[3] = req->dstid >> 8;
2397
2398         req->numserv = 0;
2399         req->ifdata = (struct listener_data *) ifdata;
2400         req->append_domain = FALSE;
2401         request_list = g_slist_append(request_list, req);
2402
2403         for (list = server_list; list; list = list->next) {
2404                 struct server_data *data = list->data;
2405                 GList *domains;
2406
2407                 if (data->protocol != IPPROTO_UDP || data->enabled == FALSE)
2408                         continue;
2409
2410                 server = create_server(data->interface, NULL,
2411                                         data->server, IPPROTO_TCP);
2412
2413                 /*
2414                  * If server is NULL, we're not connected yet.
2415                  * Copy the relevant buffers and continue with
2416                  * the next nameserver.
2417                  * The request will actually be sent once we're
2418                  * properly connected over TCP to this nameserver.
2419                  */
2420                 if (server == NULL) {
2421                         req->request = g_try_malloc0(req->request_len);
2422                         if (req->request == NULL)
2423                                 return TRUE;
2424
2425                         memcpy(req->request, buf, req->request_len);
2426
2427                         req->name = g_try_malloc0(sizeof(query));
2428                         if (req->name == NULL) {
2429                                 g_free(req->request);
2430                                 return TRUE;
2431                         }
2432                         memcpy(req->name, query, sizeof(query));
2433
2434                         continue;
2435                 }
2436
2437                 if (req->timeout > 0)
2438                         g_source_remove(req->timeout);
2439
2440                 for (domains = data->domains; domains;
2441                                 domains = domains->next) {
2442                         char *dom = domains->data;
2443
2444                         DBG("Adding domain %s to %s", dom, server->server);
2445
2446                         server->domains = g_list_append(server->domains,
2447                                                 g_strdup(dom));
2448                 }
2449
2450                 req->timeout = g_timeout_add_seconds(30, request_timeout, req);
2451                 if (ns_resolv(server, req, buf, query) > 0) {
2452                         if (req->timeout > 0) {
2453                                 g_source_remove(req->timeout);
2454                                 req->timeout = 0;
2455                         }
2456                 }
2457         }
2458
2459         return TRUE;
2460 }
2461
2462 static gboolean udp_listener_event(GIOChannel *channel, GIOCondition condition,
2463                                                         gpointer user_data)
2464 {
2465         unsigned char buf[768];
2466         char query[512];
2467         struct request_data *req;
2468         struct sockaddr_in6 client_addr;
2469         socklen_t client_addr_len = sizeof(client_addr);
2470         int sk, err, len;
2471         struct listener_data *ifdata = user_data;
2472
2473         if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
2474                 connman_error("Error with UDP listener channel");
2475                 ifdata->udp_listener_watch = 0;
2476                 return FALSE;
2477         }
2478
2479         sk = g_io_channel_unix_get_fd(channel);
2480
2481         memset(&client_addr, 0, client_addr_len);
2482         len = recvfrom(sk, buf, sizeof(buf), 0, (void *)&client_addr,
2483                        &client_addr_len);
2484         if (len < 2)
2485                 return TRUE;
2486
2487         DBG("Received %d bytes (id 0x%04x)", len, buf[0] | buf[1] << 8);
2488
2489         err = parse_request(buf, len, query, sizeof(query));
2490         if (err < 0 || (g_slist_length(server_list) == 0)) {
2491                 send_response(sk, buf, len, (void *)&client_addr,
2492                                 client_addr_len, IPPROTO_UDP);
2493                 return TRUE;
2494         }
2495
2496         req = g_try_new0(struct request_data, 1);
2497         if (req == NULL)
2498                 return TRUE;
2499
2500         memcpy(&req->sa, &client_addr, client_addr_len);
2501         req->sa_len = client_addr_len;
2502         req->client_sk = 0;
2503         req->protocol = IPPROTO_UDP;
2504
2505         request_id += 2;
2506         if (request_id == 0x0000 || request_id == 0xffff)
2507                 request_id += 2;
2508
2509         req->srcid = buf[0] | (buf[1] << 8);
2510         req->dstid = request_id;
2511         req->altid = request_id + 1;
2512         req->request_len = len;
2513
2514         buf[0] = req->dstid & 0xff;
2515         buf[1] = req->dstid >> 8;
2516
2517         req->numserv = 0;
2518         req->ifdata = (struct listener_data *) ifdata;
2519         req->timeout = g_timeout_add_seconds(5, request_timeout, req);
2520         req->append_domain = FALSE;
2521         request_list = g_slist_append(request_list, req);
2522
2523         return resolv(req, buf, query);
2524 }
2525
2526 static int create_dns_listener(int protocol, struct listener_data *ifdata)
2527 {
2528         GIOChannel *channel;
2529         const char *proto;
2530         union {
2531                 struct sockaddr sa;
2532                 struct sockaddr_in6 sin6;
2533                 struct sockaddr_in sin;
2534         } s;
2535         socklen_t slen;
2536         int sk, type, v6only = 0;
2537         int family = AF_INET6;
2538
2539
2540         DBG("interface %s", ifdata->ifname);
2541
2542         switch (protocol) {
2543         case IPPROTO_UDP:
2544                 proto = "UDP";
2545                 type = SOCK_DGRAM | SOCK_CLOEXEC;
2546                 break;
2547
2548         case IPPROTO_TCP:
2549                 proto = "TCP";
2550                 type = SOCK_STREAM | SOCK_CLOEXEC;
2551                 break;
2552
2553         default:
2554                 return -EINVAL;
2555         }
2556
2557         sk = socket(family, type, protocol);
2558         if (sk < 0 && family == AF_INET6 && errno == EAFNOSUPPORT) {
2559                 connman_error("No IPv6 support; DNS proxy listening only on Legacy IP");
2560                 family = AF_INET;
2561                 sk = socket(family, type, protocol);
2562         }
2563         if (sk < 0) {
2564                 connman_error("Failed to create %s listener socket", proto);
2565                 return -EIO;
2566         }
2567
2568         if (setsockopt(sk, SOL_SOCKET, SO_BINDTODEVICE,
2569                                         ifdata->ifname,
2570                                         strlen(ifdata->ifname) + 1) < 0) {
2571                 connman_error("Failed to bind %s listener interface", proto);
2572                 close(sk);
2573                 return -EIO;
2574         }
2575         /* Ensure it accepts Legacy IP connections too */
2576         if (family == AF_INET6 &&
2577                         setsockopt(sk, SOL_IPV6, IPV6_V6ONLY,
2578                                         &v6only, sizeof(v6only)) < 0) {
2579                 connman_error("Failed to clear V6ONLY on %s listener socket",
2580                               proto);
2581                 close(sk);
2582                 return -EIO;
2583         }
2584
2585         if (family == AF_INET) {
2586                 memset(&s.sin, 0, sizeof(s.sin));
2587                 s.sin.sin_family = AF_INET;
2588                 s.sin.sin_port = htons(53);
2589                 s.sin.sin_addr.s_addr = htonl(INADDR_ANY);
2590                 slen = sizeof(s.sin);
2591         } else {
2592                 memset(&s.sin6, 0, sizeof(s.sin6));
2593                 s.sin6.sin6_family = AF_INET6;
2594                 s.sin6.sin6_port = htons(53);
2595                 s.sin6.sin6_addr = in6addr_any;
2596                 slen = sizeof(s.sin6);
2597         }
2598
2599         if (bind(sk, &s.sa, slen) < 0) {
2600                 connman_error("Failed to bind %s listener socket", proto);
2601                 close(sk);
2602                 return -EIO;
2603         }
2604
2605         if (protocol == IPPROTO_TCP && listen(sk, 10) < 0) {
2606                 connman_error("Failed to listen on TCP socket");
2607                 close(sk);
2608                 return -EIO;
2609         }
2610
2611         channel = g_io_channel_unix_new(sk);
2612         if (channel == NULL) {
2613                 connman_error("Failed to create %s listener channel", proto);
2614                 close(sk);
2615                 return -EIO;
2616         }
2617
2618         g_io_channel_set_close_on_unref(channel, TRUE);
2619
2620         if (protocol == IPPROTO_TCP) {
2621                 ifdata->tcp_listener_channel = channel;
2622                 ifdata->tcp_listener_watch = g_io_add_watch(channel,
2623                                 G_IO_IN, tcp_listener_event, (gpointer) ifdata);
2624         } else {
2625                 ifdata->udp_listener_channel = channel;
2626                 ifdata->udp_listener_watch = g_io_add_watch(channel,
2627                                 G_IO_IN, udp_listener_event, (gpointer) ifdata);
2628         }
2629
2630         return 0;
2631 }
2632
2633 static void destroy_udp_listener(struct listener_data *ifdata)
2634 {
2635         DBG("interface %s", ifdata->ifname);
2636
2637         if (ifdata->udp_listener_watch > 0)
2638                 g_source_remove(ifdata->udp_listener_watch);
2639
2640         g_io_channel_unref(ifdata->udp_listener_channel);
2641 }
2642
2643 static void destroy_tcp_listener(struct listener_data *ifdata)
2644 {
2645         DBG("interface %s", ifdata->ifname);
2646
2647         if (ifdata->tcp_listener_watch > 0)
2648                 g_source_remove(ifdata->tcp_listener_watch);
2649
2650         g_io_channel_unref(ifdata->tcp_listener_channel);
2651 }
2652
2653 static int create_listener(struct listener_data *ifdata)
2654 {
2655         int err;
2656
2657         err = create_dns_listener(IPPROTO_UDP, ifdata);
2658         if (err < 0)
2659                 return err;
2660
2661         err = create_dns_listener(IPPROTO_TCP, ifdata);
2662         if (err < 0) {
2663                 destroy_udp_listener(ifdata);
2664                 return err;
2665         }
2666
2667         if (g_strcmp0(ifdata->ifname, "lo") == 0)
2668                 __connman_resolvfile_append("lo", NULL, "127.0.0.1");
2669
2670         return 0;
2671 }
2672
2673 static void destroy_request_data(struct request_data *req)
2674 {
2675         if (req->timeout > 0)
2676                 g_source_remove(req->timeout);
2677
2678         g_free(req->resp);
2679         g_free(req->request);
2680         g_free(req->name);
2681         g_free(req);
2682 }
2683
2684 static void destroy_listener(struct listener_data *ifdata)
2685 {
2686         GSList *list;
2687
2688         if (g_strcmp0(ifdata->ifname, "lo") == 0)
2689                 __connman_resolvfile_remove("lo", NULL, "127.0.0.1");
2690
2691         for (list = request_pending_list; list; list = list->next) {
2692                 struct request_data *req = list->data;
2693
2694                 DBG("Dropping pending request (id 0x%04x -> 0x%04x)",
2695                                                 req->srcid, req->dstid);
2696                 destroy_request_data(req);
2697                 list->data = NULL;
2698         }
2699
2700         g_slist_free(request_pending_list);
2701         request_pending_list = NULL;
2702
2703         for (list = request_list; list; list = list->next) {
2704                 struct request_data *req = list->data;
2705
2706                 DBG("Dropping request (id 0x%04x -> 0x%04x)",
2707                                                 req->srcid, req->dstid);
2708                 destroy_request_data(req);
2709                 list->data = NULL;
2710         }
2711
2712         g_slist_free(request_list);
2713         request_list = NULL;
2714
2715         destroy_tcp_listener(ifdata);
2716         destroy_udp_listener(ifdata);
2717 }
2718
2719 int __connman_dnsproxy_add_listener(const char *interface)
2720 {
2721         struct listener_data *ifdata;
2722         int err;
2723
2724         DBG("interface %s", interface);
2725
2726         if (g_hash_table_lookup(listener_table, interface) != NULL)
2727                 return 0;
2728
2729         ifdata = g_try_new0(struct listener_data, 1);
2730         if (ifdata == NULL)
2731                 return -ENOMEM;
2732
2733         ifdata->ifname = g_strdup(interface);
2734         ifdata->udp_listener_channel = NULL;
2735         ifdata->udp_listener_watch = 0;
2736         ifdata->tcp_listener_channel = NULL;
2737         ifdata->tcp_listener_watch = 0;
2738
2739         err = create_listener(ifdata);
2740         if (err < 0) {
2741                 connman_error("Couldn't create listener for %s err %d",
2742                                 interface, err);
2743                 g_free(ifdata->ifname);
2744                 g_free(ifdata);
2745                 return err;
2746         }
2747         g_hash_table_insert(listener_table, ifdata->ifname, ifdata);
2748         return 0;
2749 }
2750
2751 void __connman_dnsproxy_remove_listener(const char *interface)
2752 {
2753         struct listener_data *ifdata;
2754
2755         DBG("interface %s", interface);
2756
2757         ifdata = g_hash_table_lookup(listener_table, interface);
2758         if (ifdata == NULL)
2759                 return;
2760
2761         destroy_listener(ifdata);
2762
2763         g_hash_table_remove(listener_table, interface);
2764 }
2765
2766 static void remove_listener(gpointer key, gpointer value, gpointer user_data)
2767 {
2768         const char *interface = key;
2769         struct listener_data *ifdata = value;
2770
2771         DBG("interface %s", interface);
2772
2773         destroy_listener(ifdata);
2774 }
2775
2776 int __connman_dnsproxy_init(void)
2777 {
2778         int err;
2779
2780         DBG("");
2781
2782         listener_table = g_hash_table_new_full(g_str_hash, g_str_equal,
2783                                                         g_free, g_free);
2784         err = __connman_dnsproxy_add_listener("lo");
2785         if (err < 0)
2786                 return err;
2787
2788         err = connman_notifier_register(&dnsproxy_notifier);
2789         if (err < 0)
2790                 goto destroy;
2791
2792         return 0;
2793
2794 destroy:
2795         __connman_dnsproxy_remove_listener("lo");
2796         g_hash_table_destroy(listener_table);
2797
2798         return err;
2799 }
2800
2801 void __connman_dnsproxy_cleanup(void)
2802 {
2803         DBG("");
2804
2805         connman_notifier_unregister(&dnsproxy_notifier);
2806
2807         g_hash_table_foreach(listener_table, remove_listener, NULL);
2808
2809         g_hash_table_destroy(listener_table);
2810 }