5 * Copyright (C) 2007-2012 Intel Corporation. All rights reserved.
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.
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.
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
31 #include <arpa/inet.h>
32 #include <netinet/in.h>
33 #include <sys/types.h>
34 #include <sys/socket.h>
37 #include <gweb/gresolv.h>
43 #if __BYTE_ORDER == __LITTLE_ENDIAN
58 } __attribute__ ((packed));
59 #elif __BYTE_ORDER == __BIG_ENDIAN
74 } __attribute__ ((packed));
76 #error "Unknown byte order"
79 struct partial_reply {
89 struct sockaddr *server_addr;
90 socklen_t server_addr_len;
97 struct partial_reply *incoming_reply;
100 struct request_data {
102 struct sockaddr_in6 __sin6; /* Only for the length */
121 struct listener_data *ifdata;
122 gboolean append_domain;
125 struct listener_data {
128 GIOChannel *udp4_listener_channel;
129 GIOChannel *tcp4_listener_channel;
130 guint udp4_listener_watch;
131 guint tcp4_listener_watch;
133 GIOChannel *udp6_listener_channel;
134 GIOChannel *tcp6_listener_channel;
135 guint udp6_listener_watch;
136 guint tcp6_listener_watch;
146 unsigned int data_len;
147 unsigned char *data; /* contains DNS header + body */
154 struct cache_data *ipv4;
155 struct cache_data *ipv6;
158 struct domain_question {
161 } __attribute__ ((packed));
168 } __attribute__ ((packed));
171 * We limit how long the cached DNS entry stays in the cache.
172 * By default the TTL (time-to-live) of the DNS response is used
173 * when setting the cache entry life time. The value is in seconds.
175 #define MAX_CACHE_TTL (60 * 30)
177 * Also limit the other end, cache at least for 30 seconds.
179 #define MIN_CACHE_TTL (30)
182 * We limit the cache size to some sane value so that cached data does
183 * not occupy too much memory. Each cached entry occupies on average
184 * about 100 bytes memory (depending on DNS name length).
185 * Example: caching www.connman.net uses 97 bytes memory.
186 * The value is the max amount of cached DNS responses (count).
188 #define MAX_CACHE_SIZE 256
190 static int cache_size;
191 static GHashTable *cache;
192 static int cache_refcount;
193 static GSList *server_list = NULL;
194 static GSList *request_list = NULL;
195 static GHashTable *listener_table = NULL;
196 static time_t next_refresh;
198 static guint16 get_id()
203 static int protocol_offset(int protocol)
219 * There is a power and efficiency benefit to have entries
220 * in our cache expire at the same time. To this extend,
221 * we round down the cache valid time to common boundaries.
223 static time_t round_down_ttl(time_t end_time, int ttl)
228 /* Less than 5 minutes, round to 10 second boundary */
230 end_time = end_time / 10;
231 end_time = end_time * 10;
232 } else { /* 5 or more minutes, round to 30 seconds */
233 end_time = end_time / 30;
234 end_time = end_time * 30;
239 static struct request_data *find_request(guint16 id)
243 for (list = request_list; list; list = list->next) {
244 struct request_data *req = list->data;
246 if (req->dstid == id || req->altid == id)
253 static struct server_data *find_server(int index,
259 DBG("index %d server %s proto %d", index, server, protocol);
261 for (list = server_list; list; list = list->next) {
262 struct server_data *data = list->data;
264 if (index < 0 && data->index < 0 &&
265 g_str_equal(data->server, server) == TRUE &&
266 data->protocol == protocol)
270 data->index < 0 || data->server == NULL)
273 if (data->index == index &&
274 g_str_equal(data->server, server) == TRUE &&
275 data->protocol == protocol)
282 /* we can keep using the same resolve's */
283 static GResolv *ipv4_resolve;
284 static GResolv *ipv6_resolve;
286 static void dummy_resolve_func(GResolvResultStatus status,
287 char **results, gpointer user_data)
292 * Refresh a DNS entry, but also age the hit count a bit */
293 static void refresh_dns_entry(struct cache_entry *entry, char *name)
297 if (ipv4_resolve == NULL) {
298 ipv4_resolve = g_resolv_new(0);
299 g_resolv_set_address_family(ipv4_resolve, AF_INET);
300 g_resolv_add_nameserver(ipv4_resolve, "127.0.0.1", 53, 0);
303 if (ipv6_resolve == NULL) {
304 ipv6_resolve = g_resolv_new(0);
305 g_resolv_set_address_family(ipv6_resolve, AF_INET6);
306 g_resolv_add_nameserver(ipv6_resolve, "::1", 53, 0);
309 if (entry->ipv4 == NULL) {
310 DBG("Refresing A record for %s", name);
311 g_resolv_lookup_hostname(ipv4_resolve, name,
312 dummy_resolve_func, NULL);
316 if (entry->ipv6 == NULL) {
317 DBG("Refresing AAAA record for %s", name);
318 g_resolv_lookup_hostname(ipv6_resolve, name,
319 dummy_resolve_func, NULL);
328 static int dns_name_length(unsigned char *buf)
330 if ((buf[0] & NS_CMPRSFLGS) == NS_CMPRSFLGS) /* compressed name */
332 return strlen((char *)buf);
335 static void update_cached_ttl(unsigned char *buf, int len, int new_ttl)
342 /* skip the header */
346 /* skip the query, which is a name and 2 16 bit words */
347 l = dns_name_length(c);
353 /* now we get the answer records */
357 l = dns_name_length(c);
362 /* then type + class, 2 bytes each */
368 /* now the 4 byte TTL field */
376 /* now the 2 byte rdlen field */
379 len -= ntohs(*w) + 2;
383 static void send_cached_response(int sk, unsigned char *buf, int len,
384 const struct sockaddr *to, socklen_t tolen,
385 int protocol, int id, uint16_t answers, int ttl)
387 struct domain_hdr *hdr;
388 unsigned char *ptr = buf;
389 int err, offset, dns_len, adj_len = len - 2;
392 * The cached packet contains always the TCP offset (two bytes)
393 * so skip them for UDP.
404 dns_len = ptr[0] * 256 + ptr[1];
413 hdr = (void *) (ptr + offset);
418 hdr->ancount = htons(answers);
422 /* if this is a negative reply, we are authorative */
426 update_cached_ttl((unsigned char *)hdr, adj_len, ttl);
428 DBG("sk %d id 0x%04x answers %d ptr %p length %d dns %d",
429 sk, hdr->id, answers, ptr, len, dns_len);
431 err = sendto(sk, ptr, len, MSG_NOSIGNAL, to, tolen);
433 connman_error("Cannot send cached DNS response: %s",
438 if (err != len || (dns_len != (len - 2) && protocol == IPPROTO_TCP) ||
439 (dns_len != len && protocol == IPPROTO_UDP))
440 DBG("Packet length mismatch, sent %d wanted %d dns %d",
444 static void send_response(int sk, unsigned char *buf, int len,
445 const struct sockaddr *to, socklen_t tolen,
448 struct domain_hdr *hdr;
449 int err, offset = protocol_offset(protocol);
459 hdr = (void *) (buf + offset);
461 DBG("id 0x%04x qr %d opcode %d", hdr->id, hdr->qr, hdr->opcode);
470 err = sendto(sk, buf, len, MSG_NOSIGNAL, to, tolen);
472 connman_error("Failed to send DNS response to %d: %s",
473 sk, strerror(errno));
478 static int get_req_udp_socket(struct request_data *req)
482 if (req->family == AF_INET)
483 channel = req->ifdata->udp4_listener_channel;
485 channel = req->ifdata->udp6_listener_channel;
490 return g_io_channel_unix_get_fd(channel);
493 static void destroy_request_data(struct request_data *req)
495 if (req->timeout > 0)
496 g_source_remove(req->timeout);
499 g_free(req->request);
504 static gboolean request_timeout(gpointer user_data)
506 struct request_data *req = user_data;
511 DBG("id 0x%04x", req->srcid);
513 request_list = g_slist_remove(request_list, req);
516 if (req->resplen > 0 && req->resp != NULL) {
519 sk = get_req_udp_socket(req);
523 err = sendto(sk, req->resp, req->resplen, MSG_NOSIGNAL,
524 &req->sa, req->sa_len);
527 } else if (req->request && req->numserv == 0) {
528 struct domain_hdr *hdr;
530 if (req->protocol == IPPROTO_TCP) {
531 hdr = (void *) (req->request + 2);
532 hdr->id = req->srcid;
533 send_response(req->client_sk, req->request,
534 req->request_len, NULL, 0, IPPROTO_TCP);
536 } else if (req->protocol == IPPROTO_UDP) {
539 hdr = (void *) (req->request);
540 hdr->id = req->srcid;
542 sk = get_req_udp_socket(req);
544 send_response(sk, req->request,
545 req->request_len, &req->sa,
546 req->sa_len, IPPROTO_UDP);
551 destroy_request_data(req);
556 static int append_query(unsigned char *buf, unsigned int size,
557 const char *query, const char *domain)
559 unsigned char *ptr = buf;
562 DBG("query %s domain %s", query, domain);
564 while (query != NULL) {
567 tmp = strchr(query, '.');
573 memcpy(ptr + 1, query, len);
579 memcpy(ptr + 1, query, tmp - query);
580 ptr += tmp - query + 1;
585 while (domain != NULL) {
588 tmp = strchr(domain, '.');
590 len = strlen(domain);
594 memcpy(ptr + 1, domain, len);
600 memcpy(ptr + 1, domain, tmp - domain);
601 ptr += tmp - domain + 1;
611 static gboolean cache_check_is_valid(struct cache_data *data,
617 if (data->cache_until < current_time)
624 * remove stale cached entries so that they can be refreshed
626 static void cache_enforce_validity(struct cache_entry *entry)
628 time_t current_time = time(NULL);
630 if (cache_check_is_valid(entry->ipv4, current_time) == FALSE
632 DBG("cache timeout \"%s\" type A", entry->key);
633 g_free(entry->ipv4->data);
639 if (cache_check_is_valid(entry->ipv6, current_time) == FALSE
641 DBG("cache timeout \"%s\" type AAAA", entry->key);
642 g_free(entry->ipv6->data);
648 static uint16_t cache_check_validity(char *question, uint16_t type,
649 struct cache_entry *entry)
651 time_t current_time = time(NULL);
652 int want_refresh = 0;
655 * if we have a popular entry, we want a refresh instead of
656 * total destruction of the entry.
661 cache_enforce_validity(entry);
665 if (cache_check_is_valid(entry->ipv4, current_time) == FALSE) {
666 DBG("cache %s \"%s\" type A", entry->ipv4 ?
667 "timeout" : "entry missing", question);
670 entry->want_refresh = 1;
673 * We do not remove cache entry if there is still
674 * valid IPv6 entry found in the cache.
676 if (cache_check_is_valid(entry->ipv6, current_time)
677 == FALSE && want_refresh == FALSE) {
678 g_hash_table_remove(cache, question);
685 if (cache_check_is_valid(entry->ipv6, current_time) == FALSE) {
686 DBG("cache %s \"%s\" type AAAA", entry->ipv6 ?
687 "timeout" : "entry missing", question);
690 entry->want_refresh = 1;
692 if (cache_check_is_valid(entry->ipv4, current_time)
693 == FALSE && want_refresh == FALSE) {
694 g_hash_table_remove(cache, question);
704 static struct cache_entry *cache_check(gpointer request, int *qtype, int proto)
707 struct cache_entry *entry;
708 struct domain_question *q;
710 int offset, proto_offset;
715 proto_offset = protocol_offset(proto);
716 if (proto_offset < 0)
719 question = request + proto_offset + 12;
721 offset = strlen(question) + 1;
722 q = (void *) (question + offset);
723 type = ntohs(q->type);
725 /* We only cache either A (1) or AAAA (28) requests */
726 if (type != 1 && type != 28)
729 entry = g_hash_table_lookup(cache, question);
733 type = cache_check_validity(question, type, entry);
742 * Get a label/name from DNS resource record. The function decompresses the
743 * label if necessary. The function does not convert the name to presentation
744 * form. This means that the result string will contain label lengths instead
745 * of dots between labels. We intentionally do not want to convert to dotted
746 * format so that we can cache the wire format string directly.
748 static int get_name(int counter,
749 unsigned char *pkt, unsigned char *start, unsigned char *max,
750 unsigned char *output, int output_max, int *output_len,
751 unsigned char **end, char *name, int *name_len)
755 /* Limit recursion to 10 (this means up to 10 labels in domain name) */
761 if ((*p & NS_CMPRSFLGS) == NS_CMPRSFLGS) {
762 uint16_t offset = (*p & 0x3F) * 256 + *(p + 1);
764 if (offset >= max - pkt)
770 return get_name(counter + 1, pkt, pkt + offset, max,
771 output, output_max, output_len, end,
774 unsigned label_len = *p;
776 if (pkt + label_len > max)
779 if (*output_len > output_max)
783 * We need the original name in order to check
784 * if this answer is the correct one.
786 name[(*name_len)++] = label_len;
787 memcpy(name + *name_len, p + 1, label_len + 1);
788 *name_len += label_len;
790 /* We compress the result */
791 output[0] = NS_CMPRSFLGS;
808 static int parse_rr(unsigned char *buf, unsigned char *start,
810 unsigned char *response, unsigned int *response_size,
811 uint16_t *type, uint16_t *class, int *ttl, int *rdlen,
815 struct domain_rr *rr;
817 int name_len = 0, output_len = 0, max_rsp = *response_size;
819 err = get_name(0, buf, start, max, response, max_rsp,
820 &output_len, end, name, &name_len);
826 if ((unsigned int) offset > *response_size)
829 rr = (void *) (*end);
834 *type = ntohs(rr->type);
835 *class = ntohs(rr->class);
836 *ttl = ntohl(rr->ttl);
837 *rdlen = ntohs(rr->rdlen);
842 memcpy(response + offset, *end, sizeof(struct domain_rr));
844 offset += sizeof(struct domain_rr);
845 *end += sizeof(struct domain_rr);
847 if ((unsigned int) (offset + *rdlen) > *response_size)
850 memcpy(response + offset, *end, *rdlen);
854 *response_size = offset + *rdlen;
859 static gboolean check_alias(GSList *aliases, char *name)
863 if (aliases != NULL) {
864 for (list = aliases; list; list = list->next) {
865 int len = strlen((char *)list->data);
866 if (strncmp((char *)list->data, name, len) == 0)
874 static int parse_response(unsigned char *buf, int buflen,
875 char *question, int qlen,
876 uint16_t *type, uint16_t *class, int *ttl,
877 unsigned char *response, unsigned int *response_len,
880 struct domain_hdr *hdr = (void *) buf;
881 struct domain_question *q;
883 uint16_t qdcount = ntohs(hdr->qdcount);
884 uint16_t ancount = ntohs(hdr->ancount);
886 uint16_t qtype, qclass;
887 unsigned char *next = NULL;
888 unsigned int maxlen = *response_len;
889 GSList *aliases = NULL, *list;
890 char name[NS_MAXDNAME + 1];
895 DBG("qr %d qdcount %d", hdr->qr, qdcount);
897 /* We currently only cache responses where question count is 1 */
898 if (hdr->qr != 1 || qdcount != 1)
901 ptr = buf + sizeof(struct domain_hdr);
903 strncpy(question, (char *) ptr, qlen);
904 qlen = strlen(question);
905 ptr += qlen + 1; /* skip \0 */
908 qtype = ntohs(q->type);
910 /* We cache only A and AAAA records */
911 if (qtype != 1 && qtype != 28)
914 qclass = ntohs(q->class);
916 ptr += 2 + 2; /* ptr points now to answers */
923 * We have a bunch of answers (like A, AAAA, CNAME etc) to
924 * A or AAAA question. We traverse the answers and parse the
925 * resource records. Only A and AAAA records are cached, all
926 * the other records in answers are skipped.
928 for (i = 0; i < ancount; i++) {
930 * Get one address at a time to this buffer.
931 * The max size of the answer is
932 * 2 (pointer) + 2 (type) + 2 (class) +
933 * 4 (ttl) + 2 (rdlen) + addr (16 or 4) = 28
934 * for A or AAAA record.
935 * For CNAME the size can be bigger.
937 unsigned char rsp[NS_MAXCDNAME];
938 unsigned int rsp_len = sizeof(rsp) - 1;
941 memset(rsp, 0, sizeof(rsp));
943 ret = parse_rr(buf, ptr, buf + buflen, rsp, &rsp_len,
944 type, class, ttl, &rdlen, &next, name);
951 * Now rsp contains compressed or uncompressed resource
952 * record. Next we check if this record answers the question.
953 * The name var contains the uncompressed label.
954 * One tricky bit is the CNAME records as they alias
955 * the name we might be interested in.
959 * Go to next answer if the class is not the one we are
962 if (*class != qclass) {
969 * Try to resolve aliases also, type is CNAME(5).
970 * This is important as otherwise the aliased names would not
971 * be cached at all as the cache would not contain the aliased
974 * If any CNAME is found in DNS packet, then we cache the alias
975 * IP address instead of the question (as the server
976 * said that question has only an alias).
977 * This means in practice that if e.g., ipv6.google.com is
978 * queried, DNS server returns CNAME of that name which is
979 * ipv6.l.google.com. We then cache the address of the CNAME
980 * but return the question name to client. So the alias
981 * status of the name is not saved in cache and thus not
982 * returned to the client. We do not return DNS packets from
983 * cache to client saying that ipv6.google.com is an alias to
984 * ipv6.l.google.com but we return instead a DNS packet that
985 * says ipv6.google.com has address xxx which is in fact the
986 * address of ipv6.l.google.com. For caching purposes this
987 * should not cause any issues.
989 if (*type == 5 && strncmp(question, name, qlen) == 0) {
991 * So now the alias answered the question. This is
992 * not very useful from caching point of view as
993 * the following A or AAAA records will not match the
994 * question. We need to find the real A/AAAA record
995 * of the alias and cache that.
997 unsigned char *end = NULL;
998 int name_len = 0, output_len;
1000 memset(rsp, 0, sizeof(rsp));
1001 rsp_len = sizeof(rsp) - 1;
1004 * Alias is in rdata part of the message,
1005 * and next-rdlen points to it. So we need to get
1006 * the real name of the alias.
1008 ret = get_name(0, buf, next - rdlen, buf + buflen,
1009 rsp, rsp_len, &output_len, &end,
1012 /* just ignore the error at this point */
1019 * We should now have the alias of the entry we might
1020 * want to cache. Just remember it for a while.
1021 * We check the alias list when we have parsed the
1024 aliases = g_slist_prepend(aliases, g_strdup(name));
1031 if (*type == qtype) {
1033 * We found correct type (A or AAAA)
1035 if (check_alias(aliases, name) == TRUE ||
1036 (aliases == NULL && strncmp(question, name,
1039 * We found an alias or the name of the rr
1040 * matches the question. If so, we append
1041 * the compressed label to the cache.
1042 * The end result is a response buffer that
1043 * will contain one or more cached and
1044 * compressed resource records.
1046 if (*response_len + rsp_len > maxlen) {
1050 memcpy(response + *response_len, rsp, rsp_len);
1051 *response_len += rsp_len;
1062 for (list = aliases; list; list = list->next)
1064 g_slist_free(aliases);
1069 struct cache_timeout {
1070 time_t current_time;
1075 static gboolean cache_check_entry(gpointer key, gpointer value,
1078 struct cache_timeout *data = user_data;
1079 struct cache_entry *entry = value;
1082 /* Scale the number of hits by half as part of cache aging */
1087 * If either IPv4 or IPv6 cached entry has expired, we
1088 * remove both from the cache.
1091 if (entry->ipv4 != NULL && entry->ipv4->timeout > 0) {
1092 max_timeout = entry->ipv4->cache_until;
1093 if (max_timeout > data->max_timeout)
1094 data->max_timeout = max_timeout;
1096 if (entry->ipv4->cache_until < data->current_time)
1100 if (entry->ipv6 != NULL && entry->ipv6->timeout > 0) {
1101 max_timeout = entry->ipv6->cache_until;
1102 if (max_timeout > data->max_timeout)
1103 data->max_timeout = max_timeout;
1105 if (entry->ipv6->cache_until < data->current_time)
1110 * if we're asked to try harder, also remove entries that have
1113 if (data->try_harder && entry->hits < 4)
1119 static void cache_cleanup(void)
1121 static int max_timeout;
1122 struct cache_timeout data;
1125 data.current_time = time(NULL);
1126 data.max_timeout = 0;
1127 data.try_harder = 0;
1130 * In the first pass, we only remove entries that have timed out.
1131 * We use a cache of the first time to expire to do this only
1132 * when it makes sense.
1134 if (max_timeout <= data.current_time) {
1135 count = g_hash_table_foreach_remove(cache, cache_check_entry,
1138 DBG("removed %d in the first pass", count);
1141 * In the second pass, if the first pass turned up blank,
1142 * we also expire entries with a low hit count,
1143 * while aging the hit count at the same time.
1145 data.try_harder = 1;
1147 count = g_hash_table_foreach_remove(cache, cache_check_entry,
1152 * If we could not remove anything, then remember
1153 * what is the max timeout and do nothing if we
1154 * have not yet reached it. This will prevent
1155 * constant traversal of the cache if it is full.
1157 max_timeout = data.max_timeout;
1162 static gboolean cache_invalidate_entry(gpointer key, gpointer value,
1165 struct cache_entry *entry = value;
1167 /* first, delete any expired elements */
1168 cache_enforce_validity(entry);
1170 /* if anything is not expired, mark the entry for refresh */
1171 if (entry->hits > 0 && (entry->ipv4 || entry->ipv6))
1172 entry->want_refresh = 1;
1174 /* delete the cached data */
1176 g_free(entry->ipv4->data);
1177 g_free(entry->ipv4);
1182 g_free(entry->ipv6->data);
1183 g_free(entry->ipv6);
1187 /* keep the entry if we want it refreshed, delete it otherwise */
1188 if (entry->want_refresh)
1195 * cache_invalidate is called from places where the DNS landscape
1196 * has changed, say because connections are added or we entered a VPN.
1197 * The logic is to wipe all cache data, but mark all non-expired
1198 * parts of the cache for refresh rather than deleting the whole cache.
1200 static void cache_invalidate(void)
1202 DBG("Invalidating the DNS cache %p", cache);
1207 g_hash_table_foreach_remove(cache, cache_invalidate_entry, NULL);
1210 static void cache_refresh_entry(struct cache_entry *entry)
1213 cache_enforce_validity(entry);
1215 if (entry->hits > 2 && entry->ipv4 == NULL)
1216 entry->want_refresh = 1;
1217 if (entry->hits > 2 && entry->ipv6 == NULL)
1218 entry->want_refresh = 1;
1220 if (entry->want_refresh) {
1222 char dns_name[NS_MAXDNAME + 1];
1223 entry->want_refresh = 0;
1225 /* turn a DNS name into a hostname with dots */
1226 strncpy(dns_name, entry->key, NS_MAXDNAME);
1234 DBG("Refreshing %s\n", dns_name);
1235 /* then refresh the hostname */
1236 refresh_dns_entry(entry, &dns_name[1]);
1240 static void cache_refresh_iterator(gpointer key, gpointer value,
1243 struct cache_entry *entry = value;
1245 cache_refresh_entry(entry);
1248 static void cache_refresh(void)
1253 g_hash_table_foreach(cache, cache_refresh_iterator, NULL);
1256 static int reply_query_type(unsigned char *msg, int len)
1263 /* skip the header */
1264 c = msg + sizeof(struct domain_hdr);
1265 len -= sizeof(struct domain_hdr);
1270 /* now the query, which is a name and 2 16 bit words */
1271 l = dns_name_length(c) + 1;
1279 static int cache_update(struct server_data *srv, unsigned char *msg,
1280 unsigned int msg_len)
1282 int offset = protocol_offset(srv->protocol);
1283 int err, qlen, ttl = 0;
1284 uint16_t answers = 0, type = 0, class = 0;
1285 struct domain_hdr *hdr = (void *)(msg + offset);
1286 struct domain_question *q;
1287 struct cache_entry *entry;
1288 struct cache_data *data;
1289 char question[NS_MAXDNAME + 1];
1290 unsigned char response[NS_MAXDNAME + 1];
1292 unsigned int rsplen;
1293 gboolean new_entry = TRUE;
1294 time_t current_time;
1296 if (cache_size >= MAX_CACHE_SIZE) {
1298 if (cache_size >= MAX_CACHE_SIZE)
1302 current_time = time(NULL);
1304 /* don't do a cache refresh more than twice a minute */
1305 if (next_refresh < current_time) {
1307 next_refresh = current_time + 30;
1313 DBG("offset %d hdr %p msg %p rcode %d", offset, hdr, msg, hdr->rcode);
1315 /* Continue only if response code is 0 (=ok) */
1316 if (hdr->rcode != 0)
1319 rsplen = sizeof(response) - 1;
1320 question[sizeof(question) - 1] = '\0';
1322 err = parse_response(msg + offset, msg_len - offset,
1323 question, sizeof(question) - 1,
1324 &type, &class, &ttl,
1325 response, &rsplen, &answers);
1328 * special case: if we do a ipv6 lookup and get no result
1329 * for a record that's already in our ipv4 cache.. we want
1330 * to cache the negative response.
1332 if ((err == -ENOMSG || err == -ENOBUFS) &&
1333 reply_query_type(msg + offset,
1334 msg_len - offset) == 28) {
1335 entry = g_hash_table_lookup(cache, question);
1336 if (entry && entry->ipv4 && entry->ipv6 == NULL) {
1337 int cache_offset = 0;
1339 data = g_try_new(struct cache_data, 1);
1342 data->inserted = entry->ipv4->inserted;
1344 data->answers = ntohs(hdr->ancount);
1345 data->timeout = entry->ipv4->timeout;
1346 if (srv->protocol == IPPROTO_UDP)
1348 data->data_len = msg_len + cache_offset;
1349 data->data = ptr = g_malloc(data->data_len);
1350 ptr[0] = (data->data_len - 2) / 256;
1351 ptr[1] = (data->data_len - 2) - ptr[0] * 256;
1352 if (srv->protocol == IPPROTO_UDP)
1354 data->valid_until = entry->ipv4->valid_until;
1355 data->cache_until = entry->ipv4->cache_until;
1356 memcpy(ptr, msg, msg_len);
1359 * we will get a "hit" when we serve the response
1363 if (entry->hits < 0)
1369 if (err < 0 || ttl == 0)
1372 qlen = strlen(question);
1375 * If the cache contains already data, check if the
1376 * type of the cached data is the same and do not add
1377 * to cache if data is already there.
1378 * This is needed so that we can cache both A and AAAA
1379 * records for the same name.
1381 entry = g_hash_table_lookup(cache, question);
1382 if (entry == NULL) {
1383 entry = g_try_new(struct cache_entry, 1);
1387 data = g_try_new(struct cache_data, 1);
1393 entry->key = g_strdup(question);
1394 entry->ipv4 = entry->ipv6 = NULL;
1395 entry->want_refresh = 0;
1403 if (type == 1 && entry->ipv4 != NULL)
1406 if (type == 28 && entry->ipv6 != NULL)
1409 data = g_try_new(struct cache_data, 1);
1419 * compensate for the hit we'll get for serving
1420 * the response out of the cache
1423 if (entry->hits < 0)
1429 if (ttl < MIN_CACHE_TTL)
1430 ttl = MIN_CACHE_TTL;
1432 data->inserted = current_time;
1434 data->answers = answers;
1435 data->timeout = ttl;
1437 * The "2" in start of the length is the TCP offset. We allocate it
1438 * here even for UDP packet because it simplifies the sending
1441 data->data_len = 2 + 12 + qlen + 1 + 2 + 2 + rsplen;
1442 data->data = ptr = g_malloc(data->data_len);
1443 data->valid_until = current_time + ttl;
1446 * Restrict the cached DNS record TTL to some sane value
1447 * in order to prevent data staying in the cache too long.
1449 if (ttl > MAX_CACHE_TTL)
1450 ttl = MAX_CACHE_TTL;
1452 data->cache_until = round_down_ttl(current_time + ttl, ttl);
1454 if (data->data == NULL) {
1462 * We cache the two extra bytes at the start of the message
1463 * in a TCP packet. When sending UDP packet, we skip the first
1464 * two bytes. This way we do not need to know the format
1465 * (UDP/TCP) of the cached message.
1467 ptr[0] = (data->data_len - 2) / 256;
1468 ptr[1] = (data->data_len - 2) - ptr[0] * 256;
1469 if (srv->protocol == IPPROTO_UDP)
1472 memcpy(ptr, msg, offset + 12);
1473 memcpy(ptr + offset + 12, question, qlen + 1); /* copy also the \0 */
1475 q = (void *) (ptr + offset + 12 + qlen + 1);
1476 q->type = htons(type);
1477 q->class = htons(class);
1478 memcpy(ptr + offset + 12 + qlen + 1 + sizeof(struct domain_question),
1481 if (new_entry == TRUE) {
1482 g_hash_table_replace(cache, entry->key, entry);
1486 DBG("cache %d %squestion \"%s\" type %d ttl %d size %zd packet %u "
1488 cache_size, new_entry ? "new " : "old ",
1489 question, type, ttl,
1490 sizeof(*entry) + sizeof(*data) + data->data_len + qlen,
1492 srv->protocol == IPPROTO_TCP ?
1493 (unsigned int)(data->data[0] * 256 + data->data[1]) :
1499 static int ns_resolv(struct server_data *server, struct request_data *req,
1500 gpointer request, gpointer name)
1503 int sk, err, type = 0;
1504 char *dot, *lookup = (char *) name;
1505 struct cache_entry *entry;
1507 entry = cache_check(request, &type, req->protocol);
1508 if (entry != NULL) {
1510 struct cache_data *data;
1512 DBG("cache hit %s type %s", lookup, type == 1 ? "A" : "AAAA");
1519 ttl_left = data->valid_until - time(NULL);
1523 if (data != NULL && req->protocol == IPPROTO_TCP) {
1524 send_cached_response(req->client_sk, data->data,
1525 data->data_len, NULL, 0, IPPROTO_TCP,
1526 req->srcid, data->answers, ttl_left);
1530 if (data != NULL && req->protocol == IPPROTO_UDP) {
1531 int udp_sk = get_req_udp_socket(req);
1533 send_cached_response(udp_sk, data->data,
1534 data->data_len, &req->sa, req->sa_len,
1535 IPPROTO_UDP, req->srcid, data->answers,
1541 sk = g_io_channel_unix_get_fd(server->channel);
1543 err = sendto(sk, request, req->request_len, MSG_NOSIGNAL,
1544 server->server_addr, server->server_addr_len);
1546 DBG("Cannot send message to server %s sock %d "
1547 "protocol %d (%s/%d)",
1548 server->server, sk, server->protocol,
1549 strerror(errno), errno);
1555 /* If we have more than one dot, we don't add domains */
1556 dot = strchr(lookup, '.');
1557 if (dot != NULL && dot != lookup + strlen(lookup) - 1)
1560 if (server->domains != NULL && server->domains->data != NULL)
1561 req->append_domain = TRUE;
1563 for (list = server->domains; list; list = list->next) {
1565 unsigned char alt[1024];
1566 struct domain_hdr *hdr = (void *) &alt;
1567 int altlen, domlen, offset;
1569 domain = list->data;
1574 offset = protocol_offset(server->protocol);
1578 domlen = strlen(domain) + 1;
1582 alt[offset] = req->altid & 0xff;
1583 alt[offset + 1] = req->altid >> 8;
1585 memcpy(alt + offset + 2, request + offset + 2, 10);
1586 hdr->qdcount = htons(1);
1588 altlen = append_query(alt + offset + 12, sizeof(alt) - 12,
1595 memcpy(alt + offset + altlen,
1596 request + offset + altlen - domlen,
1597 req->request_len - altlen - offset + domlen);
1599 if (server->protocol == IPPROTO_TCP) {
1600 int req_len = req->request_len + domlen - 2;
1602 alt[0] = (req_len >> 8) & 0xff;
1603 alt[1] = req_len & 0xff;
1606 DBG("req %p dstid 0x%04x altid 0x%04x", req, req->dstid,
1609 err = send(sk, alt, req->request_len + domlen, MSG_NOSIGNAL);
1619 static int forward_dns_reply(unsigned char *reply, int reply_len, int protocol,
1620 struct server_data *data)
1622 struct domain_hdr *hdr;
1623 struct request_data *req;
1624 int dns_id, sk, err, offset = protocol_offset(protocol);
1629 hdr = (void *)(reply + offset);
1630 dns_id = reply[offset] | reply[offset + 1] << 8;
1632 DBG("Received %d bytes (id 0x%04x)", reply_len, dns_id);
1634 req = find_request(dns_id);
1638 DBG("req %p dstid 0x%04x altid 0x%04x rcode %d",
1639 req, req->dstid, req->altid, hdr->rcode);
1641 reply[offset] = req->srcid & 0xff;
1642 reply[offset + 1] = req->srcid >> 8;
1646 if (hdr->rcode == 0 || req->resp == NULL) {
1649 * If the domain name was append
1650 * remove it before forwarding the reply.
1652 if (req->append_domain == TRUE) {
1653 unsigned int domain_len = 0;
1656 unsigned int header_len;
1659 * ptr points to the first char of the hostname.
1660 * ->hostname.domain.net
1662 header_len = offset + sizeof(struct domain_hdr);
1663 ptr = reply + header_len;
1666 domain_len = strnlen((const char *)ptr + 1 +
1668 reply_len - header_len);
1671 DBG("host len %d domain len %d", host_len, domain_len);
1674 * Remove the domain name and replace it by the end
1675 * of reply. Check if the domain is really there
1676 * before trying to copy the data. The domain_len can
1677 * be 0 because if the original query did not contain
1678 * a domain name, then we are sending two packets,
1679 * first without the domain name and the second packet
1680 * with domain name. The append_domain is set to true
1681 * even if we sent the first packet without domain
1682 * name. In this case we end up in this branch.
1684 if (domain_len > 0) {
1686 * Note that we must use memmove() here,
1687 * because the memory areas can overlap.
1689 memmove(ptr + host_len + 1,
1690 ptr + host_len + domain_len + 1,
1691 reply_len - header_len - domain_len);
1693 reply_len = reply_len - domain_len;
1700 req->resp = g_try_malloc(reply_len);
1701 if (req->resp == NULL)
1704 memcpy(req->resp, reply, reply_len);
1705 req->resplen = reply_len;
1707 cache_update(data, reply, reply_len);
1710 if (hdr->rcode > 0 && req->numresp < req->numserv)
1713 request_list = g_slist_remove(request_list, req);
1715 if (protocol == IPPROTO_UDP) {
1716 sk = get_req_udp_socket(req);
1717 err = sendto(sk, req->resp, req->resplen, 0,
1718 &req->sa, req->sa_len);
1720 sk = req->client_sk;
1721 err = send(sk, req->resp, req->resplen, MSG_NOSIGNAL);
1726 DBG("Cannot send msg, sk %d proto %d errno %d/%s", sk,
1727 protocol, errno, strerror(errno));
1729 DBG("proto %d sent %d bytes to %d", protocol, err, sk);
1731 destroy_request_data(req);
1736 static void cache_element_destroy(gpointer value)
1738 struct cache_entry *entry = value;
1743 if (entry->ipv4 != NULL) {
1744 g_free(entry->ipv4->data);
1745 g_free(entry->ipv4);
1748 if (entry->ipv6 != NULL) {
1749 g_free(entry->ipv6->data);
1750 g_free(entry->ipv6);
1756 if (--cache_size < 0)
1760 static gboolean try_remove_cache(gpointer user_data)
1762 if (__sync_fetch_and_sub(&cache_refcount, 1) == 1) {
1763 DBG("No cache users, removing it.");
1765 g_hash_table_destroy(cache);
1772 static void server_destroy_socket(struct server_data *data)
1774 DBG("index %d server %s proto %d", data->index,
1775 data->server, data->protocol);
1777 if (data->watch > 0) {
1778 g_source_remove(data->watch);
1782 if (data->timeout > 0) {
1783 g_source_remove(data->timeout);
1787 if (data->channel != NULL) {
1788 g_io_channel_shutdown(data->channel, TRUE, NULL);
1789 g_io_channel_unref(data->channel);
1790 data->channel = NULL;
1793 g_free(data->incoming_reply);
1794 data->incoming_reply = NULL;
1797 static void destroy_server(struct server_data *server)
1801 DBG("index %d server %s sock %d", server->index, server->server,
1802 server->channel != NULL ?
1803 g_io_channel_unix_get_fd(server->channel): -1);
1805 server_list = g_slist_remove(server_list, server);
1806 server_destroy_socket(server);
1808 if (server->protocol == IPPROTO_UDP && server->enabled)
1809 DBG("Removing DNS server %s", server->server);
1811 g_free(server->server);
1812 for (list = server->domains; list; list = list->next) {
1813 char *domain = list->data;
1815 server->domains = g_list_remove(server->domains, domain);
1818 g_free(server->server_addr);
1821 * We do not remove cache right away but delay it few seconds.
1822 * The idea is that when IPv6 DNS server is added via RDNSS, it has a
1823 * lifetime. When the lifetime expires we decrease the refcount so it
1824 * is possible that the cache is then removed. Because a new DNS server
1825 * is usually created almost immediately we would then loose the cache
1826 * without any good reason. The small delay allows the new RDNSS to
1827 * create a new DNS server instance and the refcount does not go to 0.
1829 g_timeout_add_seconds(3, try_remove_cache, NULL);
1834 static gboolean udp_server_event(GIOChannel *channel, GIOCondition condition,
1837 unsigned char buf[4096];
1839 struct server_data *data = user_data;
1841 if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
1842 connman_error("Error with UDP server %s", data->server);
1843 server_destroy_socket(data);
1847 sk = g_io_channel_unix_get_fd(channel);
1849 len = recv(sk, buf, sizeof(buf), 0);
1853 err = forward_dns_reply(buf, len, IPPROTO_UDP, data);
1860 static gboolean tcp_server_event(GIOChannel *channel, GIOCondition condition,
1864 struct server_data *server = user_data;
1866 sk = g_io_channel_unix_get_fd(channel);
1870 if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
1873 DBG("TCP server channel closed, sk %d", sk);
1876 * Discard any partial response which is buffered; better
1877 * to get a proper response from a working server.
1879 g_free(server->incoming_reply);
1880 server->incoming_reply = NULL;
1882 for (list = request_list; list; list = list->next) {
1883 struct request_data *req = list->data;
1884 struct domain_hdr *hdr;
1886 if (req->protocol == IPPROTO_UDP)
1889 if (req->request == NULL)
1893 * If we're not waiting for any further response
1894 * from another name server, then we send an error
1895 * response to the client.
1897 if (req->numserv && --(req->numserv))
1900 hdr = (void *) (req->request + 2);
1901 hdr->id = req->srcid;
1902 send_response(req->client_sk, req->request,
1903 req->request_len, NULL, 0, IPPROTO_TCP);
1905 request_list = g_slist_remove(request_list, req);
1908 destroy_server(server);
1913 if ((condition & G_IO_OUT) && !server->connected) {
1916 int no_request_sent = TRUE;
1917 struct server_data *udp_server;
1919 udp_server = find_server(server->index, server->server,
1921 if (udp_server != NULL) {
1922 for (domains = udp_server->domains; domains;
1923 domains = domains->next) {
1924 char *dom = domains->data;
1926 DBG("Adding domain %s to %s",
1927 dom, server->server);
1929 server->domains = g_list_append(server->domains,
1934 server->connected = TRUE;
1935 server_list = g_slist_append(server_list, server);
1937 if (server->timeout > 0) {
1938 g_source_remove(server->timeout);
1939 server->timeout = 0;
1942 for (list = request_list; list; ) {
1943 struct request_data *req = list->data;
1946 if (req->protocol == IPPROTO_UDP) {
1951 DBG("Sending req %s over TCP", (char *)req->name);
1953 status = ns_resolv(server, req,
1954 req->request, req->name);
1957 * A cached result was sent,
1958 * so the request can be released
1961 request_list = g_slist_remove(request_list, req);
1962 destroy_request_data(req);
1971 no_request_sent = FALSE;
1973 if (req->timeout > 0)
1974 g_source_remove(req->timeout);
1976 req->timeout = g_timeout_add_seconds(30,
1977 request_timeout, req);
1981 if (no_request_sent == TRUE) {
1982 destroy_server(server);
1986 } else if (condition & G_IO_IN) {
1987 struct partial_reply *reply = server->incoming_reply;
1991 unsigned char reply_len_buf[2];
1994 bytes_recv = recv(sk, reply_len_buf, 2, MSG_PEEK);
1997 } else if (bytes_recv < 0) {
1998 if (errno == EAGAIN || errno == EWOULDBLOCK)
2001 connman_error("DNS proxy error %s",
2004 } else if (bytes_recv < 2)
2007 reply_len = reply_len_buf[1] | reply_len_buf[0] << 8;
2010 DBG("TCP reply %d bytes from %d", reply_len, sk);
2012 reply = g_try_malloc(sizeof(*reply) + reply_len + 2);
2016 reply->len = reply_len;
2017 reply->received = 0;
2019 server->incoming_reply = reply;
2022 while (reply->received < reply->len) {
2023 bytes_recv = recv(sk, reply->buf + reply->received,
2024 reply->len - reply->received, 0);
2026 connman_error("DNS proxy TCP disconnect");
2028 } else if (bytes_recv < 0) {
2029 if (errno == EAGAIN || errno == EWOULDBLOCK)
2032 connman_error("DNS proxy error %s",
2036 reply->received += bytes_recv;
2039 forward_dns_reply(reply->buf, reply->received, IPPROTO_TCP,
2043 server->incoming_reply = NULL;
2045 destroy_server(server);
2053 static gboolean tcp_idle_timeout(gpointer user_data)
2055 struct server_data *server = user_data;
2062 destroy_server(server);
2067 static int server_create_socket(struct server_data *data)
2072 DBG("index %d server %s proto %d", data->index,
2073 data->server, data->protocol);
2075 sk = socket(data->server_addr->sa_family,
2076 data->protocol == IPPROTO_TCP ? SOCK_STREAM : SOCK_DGRAM,
2080 connman_error("Failed to create server %s socket",
2082 server_destroy_socket(data);
2088 interface = connman_inet_ifname(data->index);
2089 if (interface != NULL) {
2090 if (setsockopt(sk, SOL_SOCKET, SO_BINDTODEVICE,
2092 strlen(interface) + 1) < 0) {
2094 connman_error("Failed to bind server %s "
2096 data->server, interface);
2098 server_destroy_socket(data);
2105 data->channel = g_io_channel_unix_new(sk);
2106 if (data->channel == NULL) {
2107 connman_error("Failed to create server %s channel",
2110 server_destroy_socket(data);
2114 g_io_channel_set_close_on_unref(data->channel, TRUE);
2116 if (data->protocol == IPPROTO_TCP) {
2117 g_io_channel_set_flags(data->channel, G_IO_FLAG_NONBLOCK, NULL);
2118 data->watch = g_io_add_watch(data->channel,
2119 G_IO_OUT | G_IO_IN | G_IO_HUP | G_IO_NVAL | G_IO_ERR,
2120 tcp_server_event, data);
2121 data->timeout = g_timeout_add_seconds(30, tcp_idle_timeout,
2124 data->watch = g_io_add_watch(data->channel,
2125 G_IO_IN | G_IO_NVAL | G_IO_ERR | G_IO_HUP,
2126 udp_server_event, data);
2128 if (connect(sk, data->server_addr, data->server_addr_len) < 0) {
2131 if ((data->protocol == IPPROTO_TCP && errno != EINPROGRESS) ||
2132 data->protocol == IPPROTO_UDP) {
2134 connman_error("Failed to connect to server %s",
2136 server_destroy_socket(data);
2141 if (__sync_fetch_and_add(&cache_refcount, 1) == 0)
2142 cache = g_hash_table_new_full(g_str_hash,
2145 cache_element_destroy);
2150 static struct server_data *create_server(int index,
2151 const char *domain, const char *server,
2154 struct server_data *data;
2155 struct addrinfo hints, *rp;
2158 DBG("index %d server %s", index, server);
2160 data = g_try_new0(struct server_data, 1);
2162 connman_error("Failed to allocate server %s data", server);
2166 data->index = index;
2168 data->domains = g_list_append(data->domains, g_strdup(domain));
2169 data->server = g_strdup(server);
2170 data->protocol = protocol;
2172 memset(&hints, 0, sizeof(hints));
2176 hints.ai_socktype = SOCK_DGRAM;
2180 hints.ai_socktype = SOCK_STREAM;
2184 destroy_server(data);
2187 hints.ai_family = AF_UNSPEC;
2188 hints.ai_flags = AI_NUMERICSERV | AI_NUMERICHOST;
2190 ret = getaddrinfo(data->server, "53", &hints, &rp);
2192 connman_error("Failed to parse server %s address: %s\n",
2193 data->server, gai_strerror(ret));
2194 destroy_server(data);
2198 /* Do not blindly copy this code elsewhere; it doesn't loop over the
2199 results using ->ai_next as it should. That's OK in *this* case
2200 because it was a numeric lookup; we *know* there's only one. */
2202 data->server_addr_len = rp->ai_addrlen;
2204 switch (rp->ai_family) {
2206 data->server_addr = (struct sockaddr *)
2207 g_try_new0(struct sockaddr_in, 1);
2210 data->server_addr = (struct sockaddr *)
2211 g_try_new0(struct sockaddr_in6, 1);
2214 connman_error("Wrong address family %d", rp->ai_family);
2217 if (data->server_addr == NULL) {
2219 destroy_server(data);
2222 memcpy(data->server_addr, rp->ai_addr, rp->ai_addrlen);
2225 if (server_create_socket(data) != 0) {
2226 destroy_server(data);
2230 if (protocol == IPPROTO_UDP) {
2231 /* Enable new servers by default */
2232 data->enabled = TRUE;
2233 DBG("Adding DNS server %s", data->server);
2235 server_list = g_slist_append(server_list, data);
2241 static gboolean resolv(struct request_data *req,
2242 gpointer request, gpointer name)
2246 for (list = server_list; list; list = list->next) {
2247 struct server_data *data = list->data;
2249 if (data->protocol == IPPROTO_TCP) {
2250 DBG("server %s ignored proto TCP", data->server);
2254 DBG("server %s enabled %d", data->server, data->enabled);
2256 if (data->enabled == FALSE)
2259 if (data->channel == NULL && data->protocol == IPPROTO_UDP) {
2260 if (server_create_socket(data) < 0) {
2261 DBG("socket creation failed while resolving");
2266 if (ns_resolv(data, req, request, name) > 0)
2273 static void append_domain(int index, const char *domain)
2277 DBG("index %d domain %s", index, domain);
2282 for (list = server_list; list; list = list->next) {
2283 struct server_data *data = list->data;
2286 gboolean dom_found = FALSE;
2288 if (data->index < 0)
2291 if (data->index != index)
2294 for (dom_list = data->domains; dom_list;
2295 dom_list = dom_list->next) {
2296 dom = dom_list->data;
2298 if (g_str_equal(dom, domain)) {
2304 if (dom_found == FALSE) {
2306 g_list_append(data->domains, g_strdup(domain));
2311 int __connman_dnsproxy_append(int index, const char *domain,
2314 struct server_data *data;
2316 DBG("index %d server %s", index, server);
2318 if (server == NULL && domain == NULL)
2321 if (server == NULL) {
2322 append_domain(index, domain);
2327 if (g_str_equal(server, "127.0.0.1") == TRUE)
2330 if (g_str_equal(server, "::1") == TRUE)
2333 data = find_server(index, server, IPPROTO_UDP);
2335 append_domain(index, domain);
2339 data = create_server(index, domain, server, IPPROTO_UDP);
2346 static void remove_server(int index, const char *domain,
2347 const char *server, int protocol)
2349 struct server_data *data;
2351 data = find_server(index, server, protocol);
2355 destroy_server(data);
2358 int __connman_dnsproxy_remove(int index, const char *domain,
2361 DBG("index %d server %s", index, server);
2366 if (g_str_equal(server, "127.0.0.1") == TRUE)
2369 if (g_str_equal(server, "::1") == TRUE)
2372 remove_server(index, domain, server, IPPROTO_UDP);
2373 remove_server(index, domain, server, IPPROTO_TCP);
2378 void __connman_dnsproxy_flush(void)
2382 list = request_list;
2384 struct request_data *req = list->data;
2388 if (resolv(req, req->request, req->name) == TRUE) {
2390 * A cached result was sent,
2391 * so the request can be released
2394 g_slist_remove(request_list, req);
2395 destroy_request_data(req);
2399 if (req->timeout > 0)
2400 g_source_remove(req->timeout);
2401 req->timeout = g_timeout_add_seconds(5, request_timeout, req);
2405 static void dnsproxy_offline_mode(connman_bool_t enabled)
2409 DBG("enabled %d", enabled);
2411 for (list = server_list; list; list = list->next) {
2412 struct server_data *data = list->data;
2414 if (enabled == FALSE) {
2415 DBG("Enabling DNS server %s", data->server);
2416 data->enabled = TRUE;
2420 DBG("Disabling DNS server %s", data->server);
2421 data->enabled = FALSE;
2427 static void dnsproxy_default_changed(struct connman_service *service)
2432 DBG("service %p", service);
2434 /* DNS has changed, invalidate the cache */
2437 if (service == NULL) {
2438 /* When no services are active, then disable DNS proxying */
2439 dnsproxy_offline_mode(TRUE);
2443 index = __connman_service_get_index(service);
2447 for (list = server_list; list; list = list->next) {
2448 struct server_data *data = list->data;
2450 if (data->index == index) {
2451 DBG("Enabling DNS server %s", data->server);
2452 data->enabled = TRUE;
2454 DBG("Disabling DNS server %s", data->server);
2455 data->enabled = FALSE;
2462 static struct connman_notifier dnsproxy_notifier = {
2464 .default_changed = dnsproxy_default_changed,
2465 .offline_mode = dnsproxy_offline_mode,
2468 static unsigned char opt_edns0_type[2] = { 0x00, 0x29 };
2470 static int parse_request(unsigned char *buf, int len,
2471 char *name, unsigned int size)
2473 struct domain_hdr *hdr = (void *) buf;
2474 uint16_t qdcount = ntohs(hdr->qdcount);
2475 uint16_t arcount = ntohs(hdr->arcount);
2477 char *last_label = NULL;
2478 unsigned int remain, used = 0;
2483 DBG("id 0x%04x qr %d opcode %d qdcount %d arcount %d",
2484 hdr->id, hdr->qr, hdr->opcode,
2487 if (hdr->qr != 0 || qdcount != 1)
2492 ptr = buf + sizeof(struct domain_hdr);
2493 remain = len - sizeof(struct domain_hdr);
2495 while (remain > 0) {
2496 uint8_t label_len = *ptr;
2498 if (label_len == 0x00) {
2499 last_label = (char *) (ptr + 1);
2503 if (used + label_len + 1 > size)
2506 strncat(name, (char *) (ptr + 1), label_len);
2509 used += label_len + 1;
2511 ptr += label_len + 1;
2512 remain -= label_len + 1;
2515 if (last_label && arcount && remain >= 9 && last_label[4] == 0 &&
2516 !memcmp(last_label + 5, opt_edns0_type, 2)) {
2517 uint16_t edns0_bufsize;
2519 edns0_bufsize = last_label[7] << 8 | last_label[8];
2521 DBG("EDNS0 buffer size %u", edns0_bufsize);
2523 /* This is an evil hack until full TCP support has been
2526 * Somtimes the EDNS0 request gets send with a too-small
2527 * buffer size. Since glibc doesn't seem to crash when it
2528 * gets a response biffer then it requested, just bump
2529 * the buffer size up to 4KiB.
2531 if (edns0_bufsize < 0x1000) {
2532 last_label[7] = 0x10;
2533 last_label[8] = 0x00;
2537 DBG("query %s", name);
2542 static gboolean tcp_listener_event(GIOChannel *channel, GIOCondition condition,
2543 struct listener_data *ifdata, int family,
2544 guint *listener_watch)
2546 unsigned char buf[768];
2548 struct request_data *req;
2549 int sk, client_sk, len, err;
2550 struct sockaddr_in6 client_addr6;
2551 socklen_t client_addr6_len = sizeof(client_addr6);
2552 struct sockaddr_in client_addr4;
2553 socklen_t client_addr4_len = sizeof(client_addr4);
2555 socklen_t *client_addr_len;
2557 int waiting_for_connect = FALSE, qtype = 0;
2558 struct cache_entry *entry;
2560 DBG("condition 0x%x", condition);
2562 if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
2563 if (*listener_watch > 0)
2564 g_source_remove(*listener_watch);
2565 *listener_watch = 0;
2567 connman_error("Error with TCP listener channel");
2572 sk = g_io_channel_unix_get_fd(channel);
2574 if (family == AF_INET) {
2575 client_addr = &client_addr4;
2576 client_addr_len = &client_addr4_len;
2578 client_addr = &client_addr6;
2579 client_addr_len = &client_addr6_len;
2582 client_sk = accept(sk, client_addr, client_addr_len);
2584 if (client_sk < 0) {
2585 connman_error("Accept failure on TCP listener");
2586 *listener_watch = 0;
2590 len = recv(client_sk, buf, sizeof(buf), 0);
2594 DBG("Received %d bytes (id 0x%04x) from %d", len,
2595 buf[2] | buf[3] << 8, client_sk);
2597 err = parse_request(buf + 2, len - 2, query, sizeof(query));
2598 if (err < 0 || (g_slist_length(server_list) == 0)) {
2599 send_response(client_sk, buf, len, NULL, 0, IPPROTO_TCP);
2603 req = g_try_new0(struct request_data, 1);
2607 memcpy(&req->sa, client_addr, *client_addr_len);
2608 req->sa_len = *client_addr_len;
2609 req->client_sk = client_sk;
2610 req->protocol = IPPROTO_TCP;
2611 req->family = family;
2613 req->srcid = buf[2] | (buf[3] << 8);
2614 req->dstid = get_id();
2615 req->altid = get_id();
2616 req->request_len = len;
2618 buf[2] = req->dstid & 0xff;
2619 buf[3] = req->dstid >> 8;
2622 req->ifdata = ifdata;
2623 req->append_domain = FALSE;
2626 * Check if the answer is found in the cache before
2627 * creating sockets to the server.
2629 entry = cache_check(buf, &qtype, IPPROTO_TCP);
2630 if (entry != NULL) {
2632 struct cache_data *data;
2634 DBG("cache hit %s type %s", query, qtype == 1 ? "A" : "AAAA");
2641 ttl_left = data->valid_until - time(NULL);
2644 send_cached_response(client_sk, data->data,
2645 data->data_len, NULL, 0, IPPROTO_TCP,
2646 req->srcid, data->answers, ttl_left);
2651 DBG("data missing, ignoring cache for this query");
2654 for (list = server_list; list; list = list->next) {
2655 struct server_data *data = list->data;
2657 if (data->protocol != IPPROTO_UDP || data->enabled == FALSE)
2660 if(create_server(data->index, NULL,
2661 data->server, IPPROTO_TCP) == NULL)
2664 waiting_for_connect = TRUE;
2667 if (waiting_for_connect == FALSE) {
2668 /* No server is waiting for connect */
2669 send_response(client_sk, buf, len, NULL, 0, IPPROTO_TCP);
2675 * The server is not connected yet.
2676 * Copy the relevant buffers.
2677 * The request will actually be sent once we're
2678 * properly connected over TCP to the nameserver.
2680 req->request = g_try_malloc0(req->request_len);
2681 if (req->request == NULL) {
2682 send_response(client_sk, buf, len, NULL, 0, IPPROTO_TCP);
2686 memcpy(req->request, buf, req->request_len);
2688 req->name = g_try_malloc0(sizeof(query));
2689 if (req->name == NULL) {
2690 send_response(client_sk, buf, len, NULL, 0, IPPROTO_TCP);
2691 g_free(req->request);
2695 memcpy(req->name, query, sizeof(query));
2697 req->timeout = g_timeout_add_seconds(30, request_timeout, req);
2699 request_list = g_slist_append(request_list, req);
2704 static gboolean tcp4_listener_event(GIOChannel *channel, GIOCondition condition,
2707 struct listener_data *ifdata = user_data;
2709 return tcp_listener_event(channel, condition, ifdata, AF_INET,
2710 &ifdata->tcp4_listener_watch);
2713 static gboolean tcp6_listener_event(GIOChannel *channel, GIOCondition condition,
2716 struct listener_data *ifdata = user_data;
2718 return tcp_listener_event(channel, condition, user_data, AF_INET6,
2719 &ifdata->tcp6_listener_watch);
2722 static gboolean udp_listener_event(GIOChannel *channel, GIOCondition condition,
2723 struct listener_data *ifdata, int family,
2724 guint *listener_watch)
2726 unsigned char buf[768];
2728 struct request_data *req;
2729 struct sockaddr_in6 client_addr6;
2730 socklen_t client_addr6_len = sizeof(client_addr6);
2731 struct sockaddr_in client_addr4;
2732 socklen_t client_addr4_len = sizeof(client_addr4);
2734 socklen_t *client_addr_len;
2737 if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
2738 connman_error("Error with UDP listener channel");
2739 *listener_watch = 0;
2743 sk = g_io_channel_unix_get_fd(channel);
2745 if (family == AF_INET) {
2746 client_addr = &client_addr4;
2747 client_addr_len = &client_addr4_len;
2749 client_addr = &client_addr6;
2750 client_addr_len = &client_addr6_len;
2753 memset(client_addr, 0, *client_addr_len);
2754 len = recvfrom(sk, buf, sizeof(buf), 0, client_addr, client_addr_len);
2758 DBG("Received %d bytes (id 0x%04x)", len, buf[0] | buf[1] << 8);
2760 err = parse_request(buf, len, query, sizeof(query));
2761 if (err < 0 || (g_slist_length(server_list) == 0)) {
2762 send_response(sk, buf, len, client_addr,
2763 *client_addr_len, IPPROTO_UDP);
2767 req = g_try_new0(struct request_data, 1);
2771 memcpy(&req->sa, client_addr, *client_addr_len);
2772 req->sa_len = *client_addr_len;
2774 req->protocol = IPPROTO_UDP;
2775 req->family = family;
2777 req->srcid = buf[0] | (buf[1] << 8);
2778 req->dstid = get_id();
2779 req->altid = get_id();
2780 req->request_len = len;
2782 buf[0] = req->dstid & 0xff;
2783 buf[1] = req->dstid >> 8;
2786 req->ifdata = ifdata;
2787 req->append_domain = FALSE;
2789 if (resolv(req, buf, query) == TRUE) {
2790 /* a cached result was sent, so the request can be released */
2795 req->timeout = g_timeout_add_seconds(5, request_timeout, req);
2796 request_list = g_slist_append(request_list, req);
2801 static gboolean udp4_listener_event(GIOChannel *channel, GIOCondition condition,
2804 struct listener_data *ifdata = user_data;
2806 return udp_listener_event(channel, condition, ifdata, AF_INET,
2807 &ifdata->udp4_listener_watch);
2810 static gboolean udp6_listener_event(GIOChannel *channel, GIOCondition condition,
2813 struct listener_data *ifdata = user_data;
2815 return udp_listener_event(channel, condition, user_data, AF_INET6,
2816 &ifdata->udp6_listener_watch);
2819 static GIOChannel *get_listener(int family, int protocol, int index)
2821 GIOChannel *channel;
2825 struct sockaddr_in6 sin6;
2826 struct sockaddr_in sin;
2832 DBG("family %d protocol %d index %d", family, protocol, index);
2837 type = SOCK_DGRAM | SOCK_CLOEXEC;
2842 type = SOCK_STREAM | SOCK_CLOEXEC;
2849 sk = socket(family, type, protocol);
2850 if (sk < 0 && family == AF_INET6 && errno == EAFNOSUPPORT) {
2851 connman_error("No IPv6 support");
2856 connman_error("Failed to create %s listener socket", proto);
2860 interface = connman_inet_ifname(index);
2861 if (interface == NULL || setsockopt(sk, SOL_SOCKET, SO_BINDTODEVICE,
2863 strlen(interface) + 1) < 0) {
2864 connman_error("Failed to bind %s listener interface "
2866 proto, family == AF_INET ? "IPv4" : "IPv6",
2867 -errno, strerror(errno));
2874 if (family == AF_INET6) {
2875 memset(&s.sin6, 0, sizeof(s.sin6));
2876 s.sin6.sin6_family = AF_INET6;
2877 s.sin6.sin6_port = htons(53);
2878 slen = sizeof(s.sin6);
2880 if (__connman_inet_get_interface_address(index,
2882 &s.sin6.sin6_addr) < 0) {
2883 /* So we could not find suitable IPv6 address for
2884 * the interface. This could happen if we have
2885 * disabled IPv6 for the interface.
2891 } else if (family == AF_INET) {
2892 memset(&s.sin, 0, sizeof(s.sin));
2893 s.sin.sin_family = AF_INET;
2894 s.sin.sin_port = htons(53);
2895 slen = sizeof(s.sin);
2897 if (__connman_inet_get_interface_address(index,
2899 &s.sin.sin_addr) < 0) {
2908 if (bind(sk, &s.sa, slen) < 0) {
2909 connman_error("Failed to bind %s listener socket", proto);
2914 if (protocol == IPPROTO_TCP && listen(sk, 10) < 0) {
2915 connman_error("Failed to listen on TCP socket %d/%s", -errno,
2921 channel = g_io_channel_unix_new(sk);
2922 if (channel == NULL) {
2923 connman_error("Failed to create %s listener channel", proto);
2928 g_io_channel_set_close_on_unref(channel, TRUE);
2933 #define UDP_IPv4_FAILED 0x01
2934 #define TCP_IPv4_FAILED 0x02
2935 #define UDP_IPv6_FAILED 0x04
2936 #define TCP_IPv6_FAILED 0x08
2937 #define UDP_FAILED (UDP_IPv4_FAILED | UDP_IPv6_FAILED)
2938 #define TCP_FAILED (TCP_IPv4_FAILED | TCP_IPv6_FAILED)
2939 #define IPv6_FAILED (UDP_IPv6_FAILED | TCP_IPv6_FAILED)
2940 #define IPv4_FAILED (UDP_IPv4_FAILED | TCP_IPv4_FAILED)
2942 static int create_dns_listener(int protocol, struct listener_data *ifdata)
2946 if (protocol == IPPROTO_TCP) {
2947 ifdata->tcp4_listener_channel = get_listener(AF_INET, protocol,
2949 if (ifdata->tcp4_listener_channel != NULL)
2950 ifdata->tcp4_listener_watch =
2951 g_io_add_watch(ifdata->tcp4_listener_channel,
2952 G_IO_IN, tcp4_listener_event,
2955 ret |= TCP_IPv4_FAILED;
2957 ifdata->tcp6_listener_channel = get_listener(AF_INET6, protocol,
2959 if (ifdata->tcp6_listener_channel != NULL)
2960 ifdata->tcp6_listener_watch =
2961 g_io_add_watch(ifdata->tcp6_listener_channel,
2962 G_IO_IN, tcp6_listener_event,
2965 ret |= TCP_IPv6_FAILED;
2967 ifdata->udp4_listener_channel = get_listener(AF_INET, protocol,
2969 if (ifdata->udp4_listener_channel != NULL)
2970 ifdata->udp4_listener_watch =
2971 g_io_add_watch(ifdata->udp4_listener_channel,
2972 G_IO_IN, udp4_listener_event,
2975 ret |= UDP_IPv4_FAILED;
2977 ifdata->udp6_listener_channel = get_listener(AF_INET6, protocol,
2979 if (ifdata->udp6_listener_channel != NULL)
2980 ifdata->udp6_listener_watch =
2981 g_io_add_watch(ifdata->udp6_listener_channel,
2982 G_IO_IN, udp6_listener_event,
2985 ret |= UDP_IPv6_FAILED;
2991 static void destroy_udp_listener(struct listener_data *ifdata)
2993 DBG("index %d", ifdata->index);
2995 if (ifdata->udp4_listener_watch > 0)
2996 g_source_remove(ifdata->udp4_listener_watch);
2998 if (ifdata->udp6_listener_watch > 0)
2999 g_source_remove(ifdata->udp6_listener_watch);
3001 g_io_channel_unref(ifdata->udp4_listener_channel);
3002 g_io_channel_unref(ifdata->udp6_listener_channel);
3005 static void destroy_tcp_listener(struct listener_data *ifdata)
3007 DBG("index %d", ifdata->index);
3009 if (ifdata->tcp4_listener_watch > 0)
3010 g_source_remove(ifdata->tcp4_listener_watch);
3011 if (ifdata->tcp6_listener_watch > 0)
3012 g_source_remove(ifdata->tcp6_listener_watch);
3014 g_io_channel_unref(ifdata->tcp4_listener_channel);
3015 g_io_channel_unref(ifdata->tcp6_listener_channel);
3018 static int create_listener(struct listener_data *ifdata)
3022 err = create_dns_listener(IPPROTO_UDP, ifdata);
3023 if ((err & UDP_FAILED) == UDP_FAILED)
3026 err |= create_dns_listener(IPPROTO_TCP, ifdata);
3027 if ((err & TCP_FAILED) == TCP_FAILED) {
3028 destroy_udp_listener(ifdata);
3032 index = connman_inet_ifindex("lo");
3033 if (ifdata->index == index) {
3034 if ((err & IPv6_FAILED) != IPv6_FAILED)
3035 __connman_resolvfile_append(index, NULL, "::1");
3037 if ((err & IPv4_FAILED) != IPv4_FAILED)
3038 __connman_resolvfile_append(index, NULL, "127.0.0.1");
3044 static void destroy_listener(struct listener_data *ifdata)
3049 index = connman_inet_ifindex("lo");
3050 if (ifdata->index == index) {
3051 __connman_resolvfile_remove(index, NULL, "127.0.0.1");
3052 __connman_resolvfile_remove(index, NULL, "::1");
3055 for (list = request_list; list; list = list->next) {
3056 struct request_data *req = list->data;
3058 DBG("Dropping request (id 0x%04x -> 0x%04x)",
3059 req->srcid, req->dstid);
3060 destroy_request_data(req);
3064 g_slist_free(request_list);
3065 request_list = NULL;
3067 destroy_tcp_listener(ifdata);
3068 destroy_udp_listener(ifdata);
3071 int __connman_dnsproxy_add_listener(int index)
3073 struct listener_data *ifdata;
3076 DBG("index %d", index);
3081 if (listener_table == NULL)
3084 if (g_hash_table_lookup(listener_table, GINT_TO_POINTER(index)) != NULL)
3087 ifdata = g_try_new0(struct listener_data, 1);
3091 ifdata->index = index;
3092 ifdata->udp4_listener_channel = NULL;
3093 ifdata->udp4_listener_watch = 0;
3094 ifdata->tcp4_listener_channel = NULL;
3095 ifdata->tcp4_listener_watch = 0;
3096 ifdata->udp6_listener_channel = NULL;
3097 ifdata->udp6_listener_watch = 0;
3098 ifdata->tcp6_listener_channel = NULL;
3099 ifdata->tcp6_listener_watch = 0;
3101 err = create_listener(ifdata);
3103 connman_error("Couldn't create listener for index %d err %d",
3108 g_hash_table_insert(listener_table, GINT_TO_POINTER(ifdata->index),
3113 void __connman_dnsproxy_remove_listener(int index)
3115 struct listener_data *ifdata;
3117 DBG("index %d", index);
3119 if (listener_table == NULL)
3122 ifdata = g_hash_table_lookup(listener_table, GINT_TO_POINTER(index));
3126 destroy_listener(ifdata);
3128 g_hash_table_remove(listener_table, GINT_TO_POINTER(index));
3131 static void remove_listener(gpointer key, gpointer value, gpointer user_data)
3133 int index = GPOINTER_TO_INT(key);
3134 struct listener_data *ifdata = value;
3136 DBG("index %d", index);
3138 destroy_listener(ifdata);
3141 int __connman_dnsproxy_init(void)
3147 srandom(time(NULL));
3149 listener_table = g_hash_table_new_full(g_direct_hash, g_direct_equal,
3152 index = connman_inet_ifindex("lo");
3153 err = __connman_dnsproxy_add_listener(index);
3157 err = connman_notifier_register(&dnsproxy_notifier);
3164 __connman_dnsproxy_remove_listener(index);
3165 g_hash_table_destroy(listener_table);
3170 void __connman_dnsproxy_cleanup(void)
3174 connman_notifier_unregister(&dnsproxy_notifier);
3176 g_hash_table_foreach(listener_table, remove_listener, NULL);
3178 g_hash_table_destroy(listener_table);