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, "127.0.0.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 gboolean request_timeout(gpointer user_data)
495 struct request_data *req = user_data;
497 DBG("id 0x%04x", req->srcid);
502 request_list = g_slist_remove(request_list, req);
505 if (req->resplen > 0 && req->resp != NULL) {
508 sk = get_req_udp_socket(req);
512 err = sendto(sk, req->resp, req->resplen, MSG_NOSIGNAL,
513 &req->sa, req->sa_len);
516 } else if (req->request && req->numserv == 0) {
517 struct domain_hdr *hdr;
519 if (req->protocol == IPPROTO_TCP) {
520 hdr = (void *) (req->request + 2);
521 hdr->id = req->srcid;
522 send_response(req->client_sk, req->request,
523 req->request_len, NULL, 0, IPPROTO_TCP);
525 } else if (req->protocol == IPPROTO_UDP) {
528 hdr = (void *) (req->request);
529 hdr->id = req->srcid;
531 sk = get_req_udp_socket(req);
533 send_response(sk, req->request,
534 req->request_len, &req->sa,
535 req->sa_len, IPPROTO_UDP);
545 static int append_query(unsigned char *buf, unsigned int size,
546 const char *query, const char *domain)
548 unsigned char *ptr = buf;
551 DBG("query %s domain %s", query, domain);
553 while (query != NULL) {
556 tmp = strchr(query, '.');
562 memcpy(ptr + 1, query, len);
568 memcpy(ptr + 1, query, tmp - query);
569 ptr += tmp - query + 1;
574 while (domain != NULL) {
577 tmp = strchr(domain, '.');
579 len = strlen(domain);
583 memcpy(ptr + 1, domain, len);
589 memcpy(ptr + 1, domain, tmp - domain);
590 ptr += tmp - domain + 1;
600 static gboolean cache_check_is_valid(struct cache_data *data,
606 if (data->cache_until < current_time)
613 * remove stale cached entries so that they can be refreshed
615 static void cache_enforce_validity(struct cache_entry *entry)
617 time_t current_time = time(NULL);
619 if (cache_check_is_valid(entry->ipv4, current_time) == FALSE
621 DBG("cache timeout \"%s\" type A", entry->key);
622 g_free(entry->ipv4->data);
628 if (cache_check_is_valid(entry->ipv6, current_time) == FALSE
630 DBG("cache timeout \"%s\" type AAAA", entry->key);
631 g_free(entry->ipv6->data);
637 static uint16_t cache_check_validity(char *question, uint16_t type,
638 struct cache_entry *entry)
640 time_t current_time = time(NULL);
641 int want_refresh = 0;
644 * if we have a popular entry, we want a refresh instead of
645 * total destruction of the entry.
650 cache_enforce_validity(entry);
654 if (cache_check_is_valid(entry->ipv4, current_time) == FALSE) {
655 DBG("cache %s \"%s\" type A", entry->ipv4 ?
656 "timeout" : "entry missing", question);
659 entry->want_refresh = 1;
662 * We do not remove cache entry if there is still
663 * valid IPv6 entry found in the cache.
665 if (cache_check_is_valid(entry->ipv6, current_time)
666 == FALSE && want_refresh == FALSE) {
667 g_hash_table_remove(cache, question);
674 if (cache_check_is_valid(entry->ipv6, current_time) == FALSE) {
675 DBG("cache %s \"%s\" type AAAA", entry->ipv6 ?
676 "timeout" : "entry missing", question);
679 entry->want_refresh = 1;
681 if (cache_check_is_valid(entry->ipv4, current_time)
682 == FALSE && want_refresh == FALSE) {
683 g_hash_table_remove(cache, question);
693 static struct cache_entry *cache_check(gpointer request, int *qtype, int proto)
696 struct cache_entry *entry;
697 struct domain_question *q;
699 int offset, proto_offset;
704 proto_offset = protocol_offset(proto);
705 if (proto_offset < 0)
708 question = request + proto_offset + 12;
710 offset = strlen(question) + 1;
711 q = (void *) (question + offset);
712 type = ntohs(q->type);
714 /* We only cache either A (1) or AAAA (28) requests */
715 if (type != 1 && type != 28)
718 entry = g_hash_table_lookup(cache, question);
722 type = cache_check_validity(question, type, entry);
731 * Get a label/name from DNS resource record. The function decompresses the
732 * label if necessary. The function does not convert the name to presentation
733 * form. This means that the result string will contain label lengths instead
734 * of dots between labels. We intentionally do not want to convert to dotted
735 * format so that we can cache the wire format string directly.
737 static int get_name(int counter,
738 unsigned char *pkt, unsigned char *start, unsigned char *max,
739 unsigned char *output, int output_max, int *output_len,
740 unsigned char **end, char *name, int *name_len)
744 /* Limit recursion to 10 (this means up to 10 labels in domain name) */
750 if ((*p & NS_CMPRSFLGS) == NS_CMPRSFLGS) {
751 uint16_t offset = (*p & 0x3F) * 256 + *(p + 1);
753 if (offset >= max - pkt)
759 return get_name(counter + 1, pkt, pkt + offset, max,
760 output, output_max, output_len, end,
763 unsigned label_len = *p;
765 if (pkt + label_len > max)
768 if (*output_len > output_max)
772 * We need the original name in order to check
773 * if this answer is the correct one.
775 name[(*name_len)++] = label_len;
776 memcpy(name + *name_len, p + 1, label_len + 1);
777 *name_len += label_len;
779 /* We compress the result */
780 output[0] = NS_CMPRSFLGS;
797 static int parse_rr(unsigned char *buf, unsigned char *start,
799 unsigned char *response, unsigned int *response_size,
800 uint16_t *type, uint16_t *class, int *ttl, int *rdlen,
804 struct domain_rr *rr;
806 int name_len = 0, output_len = 0, max_rsp = *response_size;
808 err = get_name(0, buf, start, max, response, max_rsp,
809 &output_len, end, name, &name_len);
815 if ((unsigned int) offset > *response_size)
818 rr = (void *) (*end);
823 *type = ntohs(rr->type);
824 *class = ntohs(rr->class);
825 *ttl = ntohl(rr->ttl);
826 *rdlen = ntohs(rr->rdlen);
831 memcpy(response + offset, *end, sizeof(struct domain_rr));
833 offset += sizeof(struct domain_rr);
834 *end += sizeof(struct domain_rr);
836 if ((unsigned int) (offset + *rdlen) > *response_size)
839 memcpy(response + offset, *end, *rdlen);
843 *response_size = offset + *rdlen;
848 static gboolean check_alias(GSList *aliases, char *name)
852 if (aliases != NULL) {
853 for (list = aliases; list; list = list->next) {
854 int len = strlen((char *)list->data);
855 if (strncmp((char *)list->data, name, len) == 0)
863 static int parse_response(unsigned char *buf, int buflen,
864 char *question, int qlen,
865 uint16_t *type, uint16_t *class, int *ttl,
866 unsigned char *response, unsigned int *response_len,
869 struct domain_hdr *hdr = (void *) buf;
870 struct domain_question *q;
872 uint16_t qdcount = ntohs(hdr->qdcount);
873 uint16_t ancount = ntohs(hdr->ancount);
875 uint16_t qtype, qclass;
876 unsigned char *next = NULL;
877 unsigned int maxlen = *response_len;
878 GSList *aliases = NULL, *list;
879 char name[NS_MAXDNAME + 1];
884 DBG("qr %d qdcount %d", hdr->qr, qdcount);
886 /* We currently only cache responses where question count is 1 */
887 if (hdr->qr != 1 || qdcount != 1)
890 ptr = buf + sizeof(struct domain_hdr);
892 strncpy(question, (char *) ptr, qlen);
893 qlen = strlen(question);
894 ptr += qlen + 1; /* skip \0 */
897 qtype = ntohs(q->type);
899 /* We cache only A and AAAA records */
900 if (qtype != 1 && qtype != 28)
903 qclass = ntohs(q->class);
905 ptr += 2 + 2; /* ptr points now to answers */
912 * We have a bunch of answers (like A, AAAA, CNAME etc) to
913 * A or AAAA question. We traverse the answers and parse the
914 * resource records. Only A and AAAA records are cached, all
915 * the other records in answers are skipped.
917 for (i = 0; i < ancount; i++) {
919 * Get one address at a time to this buffer.
920 * The max size of the answer is
921 * 2 (pointer) + 2 (type) + 2 (class) +
922 * 4 (ttl) + 2 (rdlen) + addr (16 or 4) = 28
923 * for A or AAAA record.
924 * For CNAME the size can be bigger.
926 unsigned char rsp[NS_MAXCDNAME];
927 unsigned int rsp_len = sizeof(rsp) - 1;
930 memset(rsp, 0, sizeof(rsp));
932 ret = parse_rr(buf, ptr, buf + buflen, rsp, &rsp_len,
933 type, class, ttl, &rdlen, &next, name);
940 * Now rsp contains compressed or uncompressed resource
941 * record. Next we check if this record answers the question.
942 * The name var contains the uncompressed label.
943 * One tricky bit is the CNAME records as they alias
944 * the name we might be interested in.
948 * Go to next answer if the class is not the one we are
951 if (*class != qclass) {
958 * Try to resolve aliases also, type is CNAME(5).
959 * This is important as otherwise the aliased names would not
960 * be cached at all as the cache would not contain the aliased
963 * If any CNAME is found in DNS packet, then we cache the alias
964 * IP address instead of the question (as the server
965 * said that question has only an alias).
966 * This means in practice that if e.g., ipv6.google.com is
967 * queried, DNS server returns CNAME of that name which is
968 * ipv6.l.google.com. We then cache the address of the CNAME
969 * but return the question name to client. So the alias
970 * status of the name is not saved in cache and thus not
971 * returned to the client. We do not return DNS packets from
972 * cache to client saying that ipv6.google.com is an alias to
973 * ipv6.l.google.com but we return instead a DNS packet that
974 * says ipv6.google.com has address xxx which is in fact the
975 * address of ipv6.l.google.com. For caching purposes this
976 * should not cause any issues.
978 if (*type == 5 && strncmp(question, name, qlen) == 0) {
980 * So now the alias answered the question. This is
981 * not very useful from caching point of view as
982 * the following A or AAAA records will not match the
983 * question. We need to find the real A/AAAA record
984 * of the alias and cache that.
986 unsigned char *end = NULL;
987 int name_len = 0, output_len;
989 memset(rsp, 0, sizeof(rsp));
990 rsp_len = sizeof(rsp) - 1;
993 * Alias is in rdata part of the message,
994 * and next-rdlen points to it. So we need to get
995 * the real name of the alias.
997 ret = get_name(0, buf, next - rdlen, buf + buflen,
998 rsp, rsp_len, &output_len, &end,
1001 /* just ignore the error at this point */
1008 * We should now have the alias of the entry we might
1009 * want to cache. Just remember it for a while.
1010 * We check the alias list when we have parsed the
1013 aliases = g_slist_prepend(aliases, g_strdup(name));
1020 if (*type == qtype) {
1022 * We found correct type (A or AAAA)
1024 if (check_alias(aliases, name) == TRUE ||
1025 (aliases == NULL && strncmp(question, name,
1028 * We found an alias or the name of the rr
1029 * matches the question. If so, we append
1030 * the compressed label to the cache.
1031 * The end result is a response buffer that
1032 * will contain one or more cached and
1033 * compressed resource records.
1035 if (*response_len + rsp_len > maxlen) {
1039 memcpy(response + *response_len, rsp, rsp_len);
1040 *response_len += rsp_len;
1051 for (list = aliases; list; list = list->next)
1053 g_slist_free(aliases);
1058 struct cache_timeout {
1059 time_t current_time;
1064 static gboolean cache_check_entry(gpointer key, gpointer value,
1067 struct cache_timeout *data = user_data;
1068 struct cache_entry *entry = value;
1071 /* Scale the number of hits by half as part of cache aging */
1076 * If either IPv4 or IPv6 cached entry has expired, we
1077 * remove both from the cache.
1080 if (entry->ipv4 != NULL && entry->ipv4->timeout > 0) {
1081 max_timeout = entry->ipv4->cache_until;
1082 if (max_timeout > data->max_timeout)
1083 data->max_timeout = max_timeout;
1085 if (entry->ipv4->cache_until < data->current_time)
1089 if (entry->ipv6 != NULL && entry->ipv6->timeout > 0) {
1090 max_timeout = entry->ipv6->cache_until;
1091 if (max_timeout > data->max_timeout)
1092 data->max_timeout = max_timeout;
1094 if (entry->ipv6->cache_until < data->current_time)
1099 * if we're asked to try harder, also remove entries that have
1102 if (data->try_harder && entry->hits < 4)
1108 static void cache_cleanup(void)
1110 static int max_timeout;
1111 struct cache_timeout data;
1114 data.current_time = time(NULL);
1115 data.max_timeout = 0;
1116 data.try_harder = 0;
1119 * In the first pass, we only remove entries that have timed out.
1120 * We use a cache of the first time to expire to do this only
1121 * when it makes sense.
1123 if (max_timeout <= data.current_time) {
1124 count = g_hash_table_foreach_remove(cache, cache_check_entry,
1127 DBG("removed %d in the first pass", count);
1130 * In the second pass, if the first pass turned up blank,
1131 * we also expire entries with a low hit count,
1132 * while aging the hit count at the same time.
1134 data.try_harder = 1;
1136 count = g_hash_table_foreach_remove(cache, cache_check_entry,
1141 * If we could not remove anything, then remember
1142 * what is the max timeout and do nothing if we
1143 * have not yet reached it. This will prevent
1144 * constant traversal of the cache if it is full.
1146 max_timeout = data.max_timeout;
1151 static gboolean cache_invalidate_entry(gpointer key, gpointer value,
1154 struct cache_entry *entry = value;
1156 /* first, delete any expired elements */
1157 cache_enforce_validity(entry);
1159 /* if anything is not expired, mark the entry for refresh */
1160 if (entry->hits > 0 && (entry->ipv4 || entry->ipv6))
1161 entry->want_refresh = 1;
1163 /* delete the cached data */
1165 g_free(entry->ipv4->data);
1166 g_free(entry->ipv4);
1171 g_free(entry->ipv6->data);
1172 g_free(entry->ipv6);
1176 /* keep the entry if we want it refreshed, delete it otherwise */
1177 if (entry->want_refresh)
1184 * cache_invalidate is called from places where the DNS landscape
1185 * has changed, say because connections are added or we entered a VPN.
1186 * The logic is to wipe all cache data, but mark all non-expired
1187 * parts of the cache for refresh rather than deleting the whole cache.
1189 static void cache_invalidate(void)
1191 DBG("Invalidating the DNS cache %p", cache);
1196 g_hash_table_foreach_remove(cache, cache_invalidate_entry, NULL);
1199 static void cache_refresh_entry(struct cache_entry *entry)
1202 cache_enforce_validity(entry);
1204 if (entry->hits > 2 && entry->ipv4 == NULL)
1205 entry->want_refresh = 1;
1206 if (entry->hits > 2 && entry->ipv6 == NULL)
1207 entry->want_refresh = 1;
1209 if (entry->want_refresh) {
1211 char dns_name[NS_MAXDNAME + 1];
1212 entry->want_refresh = 0;
1214 /* turn a DNS name into a hostname with dots */
1215 strncpy(dns_name, entry->key, NS_MAXDNAME);
1223 DBG("Refreshing %s\n", dns_name);
1224 /* then refresh the hostname */
1225 refresh_dns_entry(entry, &dns_name[1]);
1229 static void cache_refresh_iterator(gpointer key, gpointer value,
1232 struct cache_entry *entry = value;
1234 cache_refresh_entry(entry);
1237 static void cache_refresh(void)
1242 g_hash_table_foreach(cache, cache_refresh_iterator, NULL);
1245 static int reply_query_type(unsigned char *msg, int len)
1252 /* skip the header */
1253 c = msg + sizeof(struct domain_hdr);
1254 len -= sizeof(struct domain_hdr);
1259 /* now the query, which is a name and 2 16 bit words */
1260 l = dns_name_length(c) + 1;
1268 static int cache_update(struct server_data *srv, unsigned char *msg,
1269 unsigned int msg_len)
1271 int offset = protocol_offset(srv->protocol);
1272 int err, qlen, ttl = 0;
1273 uint16_t answers = 0, type = 0, class = 0;
1274 struct domain_hdr *hdr = (void *)(msg + offset);
1275 struct domain_question *q;
1276 struct cache_entry *entry;
1277 struct cache_data *data;
1278 char question[NS_MAXDNAME + 1];
1279 unsigned char response[NS_MAXDNAME + 1];
1281 unsigned int rsplen;
1282 gboolean new_entry = TRUE;
1283 time_t current_time;
1285 if (cache_size >= MAX_CACHE_SIZE) {
1287 if (cache_size >= MAX_CACHE_SIZE)
1291 current_time = time(NULL);
1293 /* don't do a cache refresh more than twice a minute */
1294 if (next_refresh < current_time) {
1296 next_refresh = current_time + 30;
1302 DBG("offset %d hdr %p msg %p rcode %d", offset, hdr, msg, hdr->rcode);
1304 /* Continue only if response code is 0 (=ok) */
1305 if (hdr->rcode != 0)
1308 rsplen = sizeof(response) - 1;
1309 question[sizeof(question) - 1] = '\0';
1311 err = parse_response(msg + offset, msg_len - offset,
1312 question, sizeof(question) - 1,
1313 &type, &class, &ttl,
1314 response, &rsplen, &answers);
1317 * special case: if we do a ipv6 lookup and get no result
1318 * for a record that's already in our ipv4 cache.. we want
1319 * to cache the negative response.
1321 if ((err == -ENOMSG || err == -ENOBUFS) &&
1322 reply_query_type(msg + offset,
1323 msg_len - offset) == 28) {
1324 entry = g_hash_table_lookup(cache, question);
1325 if (entry && entry->ipv4 && entry->ipv6 == NULL) {
1326 int cache_offset = 0;
1328 data = g_try_new(struct cache_data, 1);
1331 data->inserted = entry->ipv4->inserted;
1333 data->answers = ntohs(hdr->ancount);
1334 data->timeout = entry->ipv4->timeout;
1335 if (srv->protocol == IPPROTO_UDP)
1337 data->data_len = msg_len + cache_offset;
1338 data->data = ptr = g_malloc(data->data_len);
1339 ptr[0] = (data->data_len - 2) / 256;
1340 ptr[1] = (data->data_len - 2) - ptr[0] * 256;
1341 if (srv->protocol == IPPROTO_UDP)
1343 data->valid_until = entry->ipv4->valid_until;
1344 data->cache_until = entry->ipv4->cache_until;
1345 memcpy(ptr, msg, msg_len);
1348 * we will get a "hit" when we serve the response
1352 if (entry->hits < 0)
1358 if (err < 0 || ttl == 0)
1361 qlen = strlen(question);
1364 * If the cache contains already data, check if the
1365 * type of the cached data is the same and do not add
1366 * to cache if data is already there.
1367 * This is needed so that we can cache both A and AAAA
1368 * records for the same name.
1370 entry = g_hash_table_lookup(cache, question);
1371 if (entry == NULL) {
1372 entry = g_try_new(struct cache_entry, 1);
1376 data = g_try_new(struct cache_data, 1);
1382 entry->key = g_strdup(question);
1383 entry->ipv4 = entry->ipv6 = NULL;
1384 entry->want_refresh = 0;
1392 if (type == 1 && entry->ipv4 != NULL)
1395 if (type == 28 && entry->ipv6 != NULL)
1398 data = g_try_new(struct cache_data, 1);
1408 * compensate for the hit we'll get for serving
1409 * the response out of the cache
1412 if (entry->hits < 0)
1418 if (ttl < MIN_CACHE_TTL)
1419 ttl = MIN_CACHE_TTL;
1421 data->inserted = current_time;
1423 data->answers = answers;
1424 data->timeout = ttl;
1426 * The "2" in start of the length is the TCP offset. We allocate it
1427 * here even for UDP packet because it simplifies the sending
1430 data->data_len = 2 + 12 + qlen + 1 + 2 + 2 + rsplen;
1431 data->data = ptr = g_malloc(data->data_len);
1432 data->valid_until = current_time + ttl;
1435 * Restrict the cached DNS record TTL to some sane value
1436 * in order to prevent data staying in the cache too long.
1438 if (ttl > MAX_CACHE_TTL)
1439 ttl = MAX_CACHE_TTL;
1441 data->cache_until = round_down_ttl(current_time + ttl, ttl);
1443 if (data->data == NULL) {
1451 * We cache the two extra bytes at the start of the message
1452 * in a TCP packet. When sending UDP packet, we skip the first
1453 * two bytes. This way we do not need to know the format
1454 * (UDP/TCP) of the cached message.
1456 ptr[0] = (data->data_len - 2) / 256;
1457 ptr[1] = (data->data_len - 2) - ptr[0] * 256;
1458 if (srv->protocol == IPPROTO_UDP)
1461 memcpy(ptr, msg, offset + 12);
1462 memcpy(ptr + offset + 12, question, qlen + 1); /* copy also the \0 */
1464 q = (void *) (ptr + offset + 12 + qlen + 1);
1465 q->type = htons(type);
1466 q->class = htons(class);
1467 memcpy(ptr + offset + 12 + qlen + 1 + sizeof(struct domain_question),
1470 if (new_entry == TRUE) {
1471 g_hash_table_replace(cache, entry->key, entry);
1475 DBG("cache %d %squestion \"%s\" type %d ttl %d size %zd packet %u "
1477 cache_size, new_entry ? "new " : "old ",
1478 question, type, ttl,
1479 sizeof(*entry) + sizeof(*data) + data->data_len + qlen,
1481 srv->protocol == IPPROTO_TCP ?
1482 (unsigned int)(data->data[0] * 256 + data->data[1]) :
1488 static int ns_resolv(struct server_data *server, struct request_data *req,
1489 gpointer request, gpointer name)
1492 int sk, err, type = 0;
1493 char *dot, *lookup = (char *) name;
1494 struct cache_entry *entry;
1496 entry = cache_check(request, &type, req->protocol);
1497 if (entry != NULL) {
1499 struct cache_data *data;
1501 DBG("cache hit %s type %s", lookup, type == 1 ? "A" : "AAAA");
1508 ttl_left = data->valid_until - time(NULL);
1512 if (data != NULL && req->protocol == IPPROTO_TCP) {
1513 send_cached_response(req->client_sk, data->data,
1514 data->data_len, NULL, 0, IPPROTO_TCP,
1515 req->srcid, data->answers, ttl_left);
1519 if (data != NULL && req->protocol == IPPROTO_UDP) {
1520 int udp_sk = get_req_udp_socket(req);
1522 send_cached_response(udp_sk, data->data,
1523 data->data_len, &req->sa, req->sa_len,
1524 IPPROTO_UDP, req->srcid, data->answers,
1530 sk = g_io_channel_unix_get_fd(server->channel);
1532 err = sendto(sk, request, req->request_len, MSG_NOSIGNAL,
1533 server->server_addr, server->server_addr_len);
1535 DBG("Cannot send message to server %s sock %d "
1536 "protocol %d (%s/%d)",
1537 server->server, sk, server->protocol,
1538 strerror(errno), errno);
1544 /* If we have more than one dot, we don't add domains */
1545 dot = strchr(lookup, '.');
1546 if (dot != NULL && dot != lookup + strlen(lookup) - 1)
1549 if (server->domains != NULL && server->domains->data != NULL)
1550 req->append_domain = TRUE;
1552 for (list = server->domains; list; list = list->next) {
1554 unsigned char alt[1024];
1555 struct domain_hdr *hdr = (void *) &alt;
1556 int altlen, domlen, offset;
1558 domain = list->data;
1563 offset = protocol_offset(server->protocol);
1567 domlen = strlen(domain) + 1;
1571 alt[offset] = req->altid & 0xff;
1572 alt[offset + 1] = req->altid >> 8;
1574 memcpy(alt + offset + 2, request + offset + 2, 10);
1575 hdr->qdcount = htons(1);
1577 altlen = append_query(alt + offset + 12, sizeof(alt) - 12,
1584 memcpy(alt + offset + altlen,
1585 request + offset + altlen - domlen,
1586 req->request_len - altlen - offset + domlen);
1588 if (server->protocol == IPPROTO_TCP) {
1589 int req_len = req->request_len + domlen - 2;
1591 alt[0] = (req_len >> 8) & 0xff;
1592 alt[1] = req_len & 0xff;
1595 DBG("req %p dstid 0x%04x altid 0x%04x", req, req->dstid,
1598 err = send(sk, alt, req->request_len + domlen, MSG_NOSIGNAL);
1608 static void destroy_request_data(struct request_data *req)
1610 if (req->timeout > 0)
1611 g_source_remove(req->timeout);
1614 g_free(req->request);
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 data = find_server(index, server, IPPROTO_UDP);
2332 append_domain(index, domain);
2336 data = create_server(index, domain, server, IPPROTO_UDP);
2343 static void remove_server(int index, const char *domain,
2344 const char *server, int protocol)
2346 struct server_data *data;
2348 data = find_server(index, server, protocol);
2352 destroy_server(data);
2355 int __connman_dnsproxy_remove(int index, const char *domain,
2358 DBG("index %d server %s", index, server);
2363 if (g_str_equal(server, "127.0.0.1") == TRUE)
2366 remove_server(index, domain, server, IPPROTO_UDP);
2367 remove_server(index, domain, server, IPPROTO_TCP);
2372 void __connman_dnsproxy_flush(void)
2376 list = request_list;
2378 struct request_data *req = list->data;
2382 if (resolv(req, req->request, req->name) == TRUE) {
2384 * A cached result was sent,
2385 * so the request can be released
2388 g_slist_remove(request_list, req);
2389 destroy_request_data(req);
2393 if (req->timeout > 0)
2394 g_source_remove(req->timeout);
2395 req->timeout = g_timeout_add_seconds(5, request_timeout, req);
2399 static void dnsproxy_offline_mode(connman_bool_t enabled)
2403 DBG("enabled %d", enabled);
2405 for (list = server_list; list; list = list->next) {
2406 struct server_data *data = list->data;
2408 if (enabled == FALSE) {
2409 DBG("Enabling DNS server %s", data->server);
2410 data->enabled = TRUE;
2414 DBG("Disabling DNS server %s", data->server);
2415 data->enabled = FALSE;
2421 static void dnsproxy_default_changed(struct connman_service *service)
2426 DBG("service %p", service);
2428 /* DNS has changed, invalidate the cache */
2431 if (service == NULL) {
2432 /* When no services are active, then disable DNS proxying */
2433 dnsproxy_offline_mode(TRUE);
2437 index = __connman_service_get_index(service);
2441 for (list = server_list; list; list = list->next) {
2442 struct server_data *data = list->data;
2444 if (data->index == index) {
2445 DBG("Enabling DNS server %s", data->server);
2446 data->enabled = TRUE;
2448 DBG("Disabling DNS server %s", data->server);
2449 data->enabled = FALSE;
2456 static struct connman_notifier dnsproxy_notifier = {
2458 .default_changed = dnsproxy_default_changed,
2459 .offline_mode = dnsproxy_offline_mode,
2462 static unsigned char opt_edns0_type[2] = { 0x00, 0x29 };
2464 static int parse_request(unsigned char *buf, int len,
2465 char *name, unsigned int size)
2467 struct domain_hdr *hdr = (void *) buf;
2468 uint16_t qdcount = ntohs(hdr->qdcount);
2469 uint16_t arcount = ntohs(hdr->arcount);
2471 char *last_label = NULL;
2472 unsigned int remain, used = 0;
2477 DBG("id 0x%04x qr %d opcode %d qdcount %d arcount %d",
2478 hdr->id, hdr->qr, hdr->opcode,
2481 if (hdr->qr != 0 || qdcount != 1)
2486 ptr = buf + sizeof(struct domain_hdr);
2487 remain = len - sizeof(struct domain_hdr);
2489 while (remain > 0) {
2490 uint8_t label_len = *ptr;
2492 if (label_len == 0x00) {
2493 last_label = (char *) (ptr + 1);
2497 if (used + label_len + 1 > size)
2500 strncat(name, (char *) (ptr + 1), label_len);
2503 used += label_len + 1;
2505 ptr += label_len + 1;
2506 remain -= label_len + 1;
2509 if (last_label && arcount && remain >= 9 && last_label[4] == 0 &&
2510 !memcmp(last_label + 5, opt_edns0_type, 2)) {
2511 uint16_t edns0_bufsize;
2513 edns0_bufsize = last_label[7] << 8 | last_label[8];
2515 DBG("EDNS0 buffer size %u", edns0_bufsize);
2517 /* This is an evil hack until full TCP support has been
2520 * Somtimes the EDNS0 request gets send with a too-small
2521 * buffer size. Since glibc doesn't seem to crash when it
2522 * gets a response biffer then it requested, just bump
2523 * the buffer size up to 4KiB.
2525 if (edns0_bufsize < 0x1000) {
2526 last_label[7] = 0x10;
2527 last_label[8] = 0x00;
2531 DBG("query %s", name);
2536 static gboolean tcp_listener_event(GIOChannel *channel, GIOCondition condition,
2537 struct listener_data *ifdata, int family,
2538 guint *listener_watch)
2540 unsigned char buf[768];
2542 struct request_data *req;
2543 int sk, client_sk, len, err;
2544 struct sockaddr_in6 client_addr6;
2545 socklen_t client_addr6_len = sizeof(client_addr6);
2546 struct sockaddr_in client_addr4;
2547 socklen_t client_addr4_len = sizeof(client_addr4);
2549 socklen_t *client_addr_len;
2551 int waiting_for_connect = FALSE, qtype = 0;
2552 struct cache_entry *entry;
2554 DBG("condition 0x%x", condition);
2556 if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
2557 if (*listener_watch > 0)
2558 g_source_remove(*listener_watch);
2559 *listener_watch = 0;
2561 connman_error("Error with TCP listener channel");
2566 sk = g_io_channel_unix_get_fd(channel);
2568 if (family == AF_INET) {
2569 client_addr = &client_addr4;
2570 client_addr_len = &client_addr4_len;
2572 client_addr = &client_addr6;
2573 client_addr_len = &client_addr6_len;
2576 client_sk = accept(sk, client_addr, client_addr_len);
2578 if (client_sk < 0) {
2579 connman_error("Accept failure on TCP listener");
2580 *listener_watch = 0;
2584 len = recv(client_sk, buf, sizeof(buf), 0);
2588 DBG("Received %d bytes (id 0x%04x) from %d", len,
2589 buf[2] | buf[3] << 8, client_sk);
2591 err = parse_request(buf + 2, len - 2, query, sizeof(query));
2592 if (err < 0 || (g_slist_length(server_list) == 0)) {
2593 send_response(client_sk, buf, len, NULL, 0, IPPROTO_TCP);
2597 req = g_try_new0(struct request_data, 1);
2601 memcpy(&req->sa, client_addr, *client_addr_len);
2602 req->sa_len = *client_addr_len;
2603 req->client_sk = client_sk;
2604 req->protocol = IPPROTO_TCP;
2605 req->family = family;
2607 req->srcid = buf[2] | (buf[3] << 8);
2608 req->dstid = get_id();
2609 req->altid = get_id();
2610 req->request_len = len;
2612 buf[2] = req->dstid & 0xff;
2613 buf[3] = req->dstid >> 8;
2616 req->ifdata = ifdata;
2617 req->append_domain = FALSE;
2620 * Check if the answer is found in the cache before
2621 * creating sockets to the server.
2623 entry = cache_check(buf, &qtype, IPPROTO_TCP);
2624 if (entry != NULL) {
2626 struct cache_data *data;
2628 DBG("cache hit %s type %s", query, qtype == 1 ? "A" : "AAAA");
2635 ttl_left = data->valid_until - time(NULL);
2638 send_cached_response(client_sk, data->data,
2639 data->data_len, NULL, 0, IPPROTO_TCP,
2640 req->srcid, data->answers, ttl_left);
2645 DBG("data missing, ignoring cache for this query");
2648 for (list = server_list; list; list = list->next) {
2649 struct server_data *data = list->data;
2651 if (data->protocol != IPPROTO_UDP || data->enabled == FALSE)
2654 if(create_server(data->index, NULL,
2655 data->server, IPPROTO_TCP) == NULL)
2658 waiting_for_connect = TRUE;
2661 if (waiting_for_connect == FALSE) {
2662 /* No server is waiting for connect */
2663 send_response(client_sk, buf, len, NULL, 0, IPPROTO_TCP);
2669 * The server is not connected yet.
2670 * Copy the relevant buffers.
2671 * The request will actually be sent once we're
2672 * properly connected over TCP to the nameserver.
2674 req->request = g_try_malloc0(req->request_len);
2675 if (req->request == NULL) {
2676 send_response(client_sk, buf, len, NULL, 0, IPPROTO_TCP);
2680 memcpy(req->request, buf, req->request_len);
2682 req->name = g_try_malloc0(sizeof(query));
2683 if (req->name == NULL) {
2684 send_response(client_sk, buf, len, NULL, 0, IPPROTO_TCP);
2685 g_free(req->request);
2689 memcpy(req->name, query, sizeof(query));
2691 req->timeout = g_timeout_add_seconds(30, request_timeout, req);
2693 request_list = g_slist_append(request_list, req);
2698 static gboolean tcp4_listener_event(GIOChannel *channel, GIOCondition condition,
2701 struct listener_data *ifdata = user_data;
2703 return tcp_listener_event(channel, condition, ifdata, AF_INET,
2704 &ifdata->tcp4_listener_watch);
2707 static gboolean tcp6_listener_event(GIOChannel *channel, GIOCondition condition,
2710 struct listener_data *ifdata = user_data;
2712 return tcp_listener_event(channel, condition, user_data, AF_INET6,
2713 &ifdata->tcp6_listener_watch);
2716 static gboolean udp_listener_event(GIOChannel *channel, GIOCondition condition,
2717 struct listener_data *ifdata, int family,
2718 guint *listener_watch)
2720 unsigned char buf[768];
2722 struct request_data *req;
2723 struct sockaddr_in6 client_addr6;
2724 socklen_t client_addr6_len = sizeof(client_addr6);
2725 struct sockaddr_in client_addr4;
2726 socklen_t client_addr4_len = sizeof(client_addr4);
2728 socklen_t *client_addr_len;
2731 if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
2732 connman_error("Error with UDP listener channel");
2733 *listener_watch = 0;
2737 sk = g_io_channel_unix_get_fd(channel);
2739 if (family == AF_INET) {
2740 client_addr = &client_addr4;
2741 client_addr_len = &client_addr4_len;
2743 client_addr = &client_addr6;
2744 client_addr_len = &client_addr6_len;
2747 memset(client_addr, 0, *client_addr_len);
2748 len = recvfrom(sk, buf, sizeof(buf), 0, client_addr, client_addr_len);
2752 DBG("Received %d bytes (id 0x%04x)", len, buf[0] | buf[1] << 8);
2754 err = parse_request(buf, len, query, sizeof(query));
2755 if (err < 0 || (g_slist_length(server_list) == 0)) {
2756 send_response(sk, buf, len, client_addr,
2757 *client_addr_len, IPPROTO_UDP);
2761 req = g_try_new0(struct request_data, 1);
2765 memcpy(&req->sa, client_addr, *client_addr_len);
2766 req->sa_len = *client_addr_len;
2768 req->protocol = IPPROTO_UDP;
2769 req->family = family;
2771 req->srcid = buf[0] | (buf[1] << 8);
2772 req->dstid = get_id();
2773 req->altid = get_id();
2774 req->request_len = len;
2776 buf[0] = req->dstid & 0xff;
2777 buf[1] = req->dstid >> 8;
2780 req->ifdata = ifdata;
2781 req->append_domain = FALSE;
2783 if (resolv(req, buf, query) == TRUE) {
2784 /* a cached result was sent, so the request can be released */
2789 req->timeout = g_timeout_add_seconds(5, request_timeout, req);
2790 request_list = g_slist_append(request_list, req);
2795 static gboolean udp4_listener_event(GIOChannel *channel, GIOCondition condition,
2798 struct listener_data *ifdata = user_data;
2800 return udp_listener_event(channel, condition, ifdata, AF_INET,
2801 &ifdata->udp4_listener_watch);
2804 static gboolean udp6_listener_event(GIOChannel *channel, GIOCondition condition,
2807 struct listener_data *ifdata = user_data;
2809 return udp_listener_event(channel, condition, user_data, AF_INET6,
2810 &ifdata->udp6_listener_watch);
2813 static GIOChannel *get_listener(int family, int protocol, int index)
2815 GIOChannel *channel;
2819 struct sockaddr_in6 sin6;
2820 struct sockaddr_in sin;
2826 DBG("family %d protocol %d index %d", family, protocol, index);
2831 type = SOCK_DGRAM | SOCK_CLOEXEC;
2836 type = SOCK_STREAM | SOCK_CLOEXEC;
2843 sk = socket(family, type, protocol);
2844 if (sk < 0 && family == AF_INET6 && errno == EAFNOSUPPORT) {
2845 connman_error("No IPv6 support");
2850 connman_error("Failed to create %s listener socket", proto);
2854 interface = connman_inet_ifname(index);
2855 if (interface == NULL || setsockopt(sk, SOL_SOCKET, SO_BINDTODEVICE,
2857 strlen(interface) + 1) < 0) {
2858 connman_error("Failed to bind %s listener interface "
2860 proto, family == AF_INET ? "IPv4" : "IPv6",
2861 -errno, strerror(errno));
2868 if (family == AF_INET6) {
2869 memset(&s.sin6, 0, sizeof(s.sin6));
2870 s.sin6.sin6_family = AF_INET6;
2871 s.sin6.sin6_port = htons(53);
2872 slen = sizeof(s.sin6);
2874 if (__connman_inet_get_interface_address(index,
2876 &s.sin6.sin6_addr) < 0) {
2877 /* So we could not find suitable IPv6 address for
2878 * the interface. This could happen if we have
2879 * disabled IPv6 for the interface.
2885 } else if (family == AF_INET) {
2886 memset(&s.sin, 0, sizeof(s.sin));
2887 s.sin.sin_family = AF_INET;
2888 s.sin.sin_port = htons(53);
2889 slen = sizeof(s.sin);
2891 if (__connman_inet_get_interface_address(index,
2893 &s.sin.sin_addr) < 0) {
2902 if (bind(sk, &s.sa, slen) < 0) {
2903 connman_error("Failed to bind %s listener socket", proto);
2908 if (protocol == IPPROTO_TCP && listen(sk, 10) < 0) {
2909 connman_error("Failed to listen on TCP socket %d/%s", -errno,
2915 channel = g_io_channel_unix_new(sk);
2916 if (channel == NULL) {
2917 connman_error("Failed to create %s listener channel", proto);
2922 g_io_channel_set_close_on_unref(channel, TRUE);
2927 #define UDP_IPv4_FAILED 0x01
2928 #define TCP_IPv4_FAILED 0x02
2929 #define UDP_IPv6_FAILED 0x04
2930 #define TCP_IPv6_FAILED 0x08
2931 #define UDP_FAILED (UDP_IPv4_FAILED | UDP_IPv6_FAILED)
2932 #define TCP_FAILED (TCP_IPv4_FAILED | TCP_IPv6_FAILED)
2933 #define IPv6_FAILED (UDP_IPv6_FAILED | TCP_IPv6_FAILED)
2934 #define IPv4_FAILED (UDP_IPv4_FAILED | TCP_IPv4_FAILED)
2936 static int create_dns_listener(int protocol, struct listener_data *ifdata)
2940 if (protocol == IPPROTO_TCP) {
2941 ifdata->tcp4_listener_channel = get_listener(AF_INET, protocol,
2943 if (ifdata->tcp4_listener_channel != NULL)
2944 ifdata->tcp4_listener_watch =
2945 g_io_add_watch(ifdata->tcp4_listener_channel,
2946 G_IO_IN, tcp4_listener_event,
2949 ret |= TCP_IPv4_FAILED;
2951 ifdata->tcp6_listener_channel = get_listener(AF_INET6, protocol,
2953 if (ifdata->tcp6_listener_channel != NULL)
2954 ifdata->tcp6_listener_watch =
2955 g_io_add_watch(ifdata->tcp6_listener_channel,
2956 G_IO_IN, tcp6_listener_event,
2959 ret |= TCP_IPv6_FAILED;
2961 ifdata->udp4_listener_channel = get_listener(AF_INET, protocol,
2963 if (ifdata->udp4_listener_channel != NULL)
2964 ifdata->udp4_listener_watch =
2965 g_io_add_watch(ifdata->udp4_listener_channel,
2966 G_IO_IN, udp4_listener_event,
2969 ret |= UDP_IPv4_FAILED;
2971 ifdata->udp6_listener_channel = get_listener(AF_INET6, protocol,
2973 if (ifdata->udp6_listener_channel != NULL)
2974 ifdata->udp6_listener_watch =
2975 g_io_add_watch(ifdata->udp6_listener_channel,
2976 G_IO_IN, udp6_listener_event,
2979 ret |= UDP_IPv6_FAILED;
2985 static void destroy_udp_listener(struct listener_data *ifdata)
2987 DBG("index %d", ifdata->index);
2989 if (ifdata->udp4_listener_watch > 0)
2990 g_source_remove(ifdata->udp4_listener_watch);
2992 if (ifdata->udp6_listener_watch > 0)
2993 g_source_remove(ifdata->udp6_listener_watch);
2995 g_io_channel_unref(ifdata->udp4_listener_channel);
2996 g_io_channel_unref(ifdata->udp6_listener_channel);
2999 static void destroy_tcp_listener(struct listener_data *ifdata)
3001 DBG("index %d", ifdata->index);
3003 if (ifdata->tcp4_listener_watch > 0)
3004 g_source_remove(ifdata->tcp4_listener_watch);
3005 if (ifdata->tcp6_listener_watch > 0)
3006 g_source_remove(ifdata->tcp6_listener_watch);
3008 g_io_channel_unref(ifdata->tcp4_listener_channel);
3009 g_io_channel_unref(ifdata->tcp6_listener_channel);
3012 static int create_listener(struct listener_data *ifdata)
3016 err = create_dns_listener(IPPROTO_UDP, ifdata);
3017 if ((err & UDP_FAILED) == UDP_FAILED)
3020 err |= create_dns_listener(IPPROTO_TCP, ifdata);
3021 if ((err & TCP_FAILED) == TCP_FAILED) {
3022 destroy_udp_listener(ifdata);
3026 index = connman_inet_ifindex("lo");
3027 if (ifdata->index == index) {
3028 if ((err & IPv6_FAILED) != IPv6_FAILED)
3029 __connman_resolvfile_append(index, NULL, "::1");
3031 if ((err & IPv4_FAILED) != IPv4_FAILED)
3032 __connman_resolvfile_append(index, NULL, "127.0.0.1");
3038 static void destroy_listener(struct listener_data *ifdata)
3043 index = connman_inet_ifindex("lo");
3044 if (ifdata->index == index) {
3045 __connman_resolvfile_remove(index, NULL, "127.0.0.1");
3046 __connman_resolvfile_remove(index, NULL, "::1");
3049 for (list = request_list; list; list = list->next) {
3050 struct request_data *req = list->data;
3052 DBG("Dropping request (id 0x%04x -> 0x%04x)",
3053 req->srcid, req->dstid);
3054 destroy_request_data(req);
3058 g_slist_free(request_list);
3059 request_list = NULL;
3061 destroy_tcp_listener(ifdata);
3062 destroy_udp_listener(ifdata);
3065 int __connman_dnsproxy_add_listener(int index)
3067 struct listener_data *ifdata;
3070 DBG("index %d", index);
3075 if (listener_table == NULL)
3078 if (g_hash_table_lookup(listener_table, GINT_TO_POINTER(index)) != NULL)
3081 ifdata = g_try_new0(struct listener_data, 1);
3085 ifdata->index = index;
3086 ifdata->udp4_listener_channel = NULL;
3087 ifdata->udp4_listener_watch = 0;
3088 ifdata->tcp4_listener_channel = NULL;
3089 ifdata->tcp4_listener_watch = 0;
3090 ifdata->udp6_listener_channel = NULL;
3091 ifdata->udp6_listener_watch = 0;
3092 ifdata->tcp6_listener_channel = NULL;
3093 ifdata->tcp6_listener_watch = 0;
3095 err = create_listener(ifdata);
3097 connman_error("Couldn't create listener for index %d err %d",
3102 g_hash_table_insert(listener_table, GINT_TO_POINTER(ifdata->index),
3107 void __connman_dnsproxy_remove_listener(int index)
3109 struct listener_data *ifdata;
3111 DBG("index %d", index);
3113 if (listener_table == NULL)
3116 ifdata = g_hash_table_lookup(listener_table, GINT_TO_POINTER(index));
3120 destroy_listener(ifdata);
3122 g_hash_table_remove(listener_table, GINT_TO_POINTER(index));
3125 static void remove_listener(gpointer key, gpointer value, gpointer user_data)
3127 int index = GPOINTER_TO_INT(key);
3128 struct listener_data *ifdata = value;
3130 DBG("index %d", index);
3132 destroy_listener(ifdata);
3135 int __connman_dnsproxy_init(void)
3141 srandom(time(NULL));
3143 listener_table = g_hash_table_new_full(g_direct_hash, g_direct_equal,
3146 index = connman_inet_ifindex("lo");
3147 err = __connman_dnsproxy_add_listener(index);
3151 err = connman_notifier_register(&dnsproxy_notifier);
3158 __connman_dnsproxy_remove_listener(index);
3159 g_hash_table_destroy(listener_table);
3164 void __connman_dnsproxy_cleanup(void)
3168 connman_notifier_unregister(&dnsproxy_notifier);
3170 g_hash_table_foreach(listener_table, remove_listener, NULL);
3172 g_hash_table_destroy(listener_table);