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 void cache_element_destroy(gpointer value)
706 struct cache_entry *entry = value;
711 if (entry->ipv4 != NULL) {
712 g_free(entry->ipv4->data);
716 if (entry->ipv6 != NULL) {
717 g_free(entry->ipv6->data);
724 if (--cache_size < 0)
728 static gboolean try_remove_cache(gpointer user_data)
730 if (__sync_fetch_and_sub(&cache_refcount, 1) == 1) {
731 DBG("No cache users, removing it.");
733 g_hash_table_destroy(cache);
740 static void create_cache()
742 if (__sync_fetch_and_add(&cache_refcount, 1) == 0)
743 cache = g_hash_table_new_full(g_str_hash,
746 cache_element_destroy);
749 static struct cache_entry *cache_check(gpointer request, int *qtype, int proto)
752 struct cache_entry *entry;
753 struct domain_question *q;
755 int offset, proto_offset;
760 proto_offset = protocol_offset(proto);
761 if (proto_offset < 0)
764 question = request + proto_offset + 12;
766 offset = strlen(question) + 1;
767 q = (void *) (question + offset);
768 type = ntohs(q->type);
770 /* We only cache either A (1) or AAAA (28) requests */
771 if (type != 1 && type != 28)
779 entry = g_hash_table_lookup(cache, question);
783 type = cache_check_validity(question, type, entry);
792 * Get a label/name from DNS resource record. The function decompresses the
793 * label if necessary. The function does not convert the name to presentation
794 * form. This means that the result string will contain label lengths instead
795 * of dots between labels. We intentionally do not want to convert to dotted
796 * format so that we can cache the wire format string directly.
798 static int get_name(int counter,
799 unsigned char *pkt, unsigned char *start, unsigned char *max,
800 unsigned char *output, int output_max, int *output_len,
801 unsigned char **end, char *name, int *name_len)
805 /* Limit recursion to 10 (this means up to 10 labels in domain name) */
811 if ((*p & NS_CMPRSFLGS) == NS_CMPRSFLGS) {
812 uint16_t offset = (*p & 0x3F) * 256 + *(p + 1);
814 if (offset >= max - pkt)
820 return get_name(counter + 1, pkt, pkt + offset, max,
821 output, output_max, output_len, end,
824 unsigned label_len = *p;
826 if (pkt + label_len > max)
829 if (*output_len > output_max)
833 * We need the original name in order to check
834 * if this answer is the correct one.
836 name[(*name_len)++] = label_len;
837 memcpy(name + *name_len, p + 1, label_len + 1);
838 *name_len += label_len;
840 /* We compress the result */
841 output[0] = NS_CMPRSFLGS;
858 static int parse_rr(unsigned char *buf, unsigned char *start,
860 unsigned char *response, unsigned int *response_size,
861 uint16_t *type, uint16_t *class, int *ttl, int *rdlen,
865 struct domain_rr *rr;
867 int name_len = 0, output_len = 0, max_rsp = *response_size;
869 err = get_name(0, buf, start, max, response, max_rsp,
870 &output_len, end, name, &name_len);
876 if ((unsigned int) offset > *response_size)
879 rr = (void *) (*end);
884 *type = ntohs(rr->type);
885 *class = ntohs(rr->class);
886 *ttl = ntohl(rr->ttl);
887 *rdlen = ntohs(rr->rdlen);
892 memcpy(response + offset, *end, sizeof(struct domain_rr));
894 offset += sizeof(struct domain_rr);
895 *end += sizeof(struct domain_rr);
897 if ((unsigned int) (offset + *rdlen) > *response_size)
900 memcpy(response + offset, *end, *rdlen);
904 *response_size = offset + *rdlen;
909 static gboolean check_alias(GSList *aliases, char *name)
913 if (aliases != NULL) {
914 for (list = aliases; list; list = list->next) {
915 int len = strlen((char *)list->data);
916 if (strncmp((char *)list->data, name, len) == 0)
924 static int parse_response(unsigned char *buf, int buflen,
925 char *question, int qlen,
926 uint16_t *type, uint16_t *class, int *ttl,
927 unsigned char *response, unsigned int *response_len,
930 struct domain_hdr *hdr = (void *) buf;
931 struct domain_question *q;
933 uint16_t qdcount = ntohs(hdr->qdcount);
934 uint16_t ancount = ntohs(hdr->ancount);
936 uint16_t qtype, qclass;
937 unsigned char *next = NULL;
938 unsigned int maxlen = *response_len;
939 GSList *aliases = NULL, *list;
940 char name[NS_MAXDNAME + 1];
945 DBG("qr %d qdcount %d", hdr->qr, qdcount);
947 /* We currently only cache responses where question count is 1 */
948 if (hdr->qr != 1 || qdcount != 1)
951 ptr = buf + sizeof(struct domain_hdr);
953 strncpy(question, (char *) ptr, qlen);
954 qlen = strlen(question);
955 ptr += qlen + 1; /* skip \0 */
958 qtype = ntohs(q->type);
960 /* We cache only A and AAAA records */
961 if (qtype != 1 && qtype != 28)
964 qclass = ntohs(q->class);
966 ptr += 2 + 2; /* ptr points now to answers */
973 * We have a bunch of answers (like A, AAAA, CNAME etc) to
974 * A or AAAA question. We traverse the answers and parse the
975 * resource records. Only A and AAAA records are cached, all
976 * the other records in answers are skipped.
978 for (i = 0; i < ancount; i++) {
980 * Get one address at a time to this buffer.
981 * The max size of the answer is
982 * 2 (pointer) + 2 (type) + 2 (class) +
983 * 4 (ttl) + 2 (rdlen) + addr (16 or 4) = 28
984 * for A or AAAA record.
985 * For CNAME the size can be bigger.
987 unsigned char rsp[NS_MAXCDNAME];
988 unsigned int rsp_len = sizeof(rsp) - 1;
991 memset(rsp, 0, sizeof(rsp));
993 ret = parse_rr(buf, ptr, buf + buflen, rsp, &rsp_len,
994 type, class, ttl, &rdlen, &next, name);
1001 * Now rsp contains compressed or uncompressed resource
1002 * record. Next we check if this record answers the question.
1003 * The name var contains the uncompressed label.
1004 * One tricky bit is the CNAME records as they alias
1005 * the name we might be interested in.
1009 * Go to next answer if the class is not the one we are
1012 if (*class != qclass) {
1019 * Try to resolve aliases also, type is CNAME(5).
1020 * This is important as otherwise the aliased names would not
1021 * be cached at all as the cache would not contain the aliased
1024 * If any CNAME is found in DNS packet, then we cache the alias
1025 * IP address instead of the question (as the server
1026 * said that question has only an alias).
1027 * This means in practice that if e.g., ipv6.google.com is
1028 * queried, DNS server returns CNAME of that name which is
1029 * ipv6.l.google.com. We then cache the address of the CNAME
1030 * but return the question name to client. So the alias
1031 * status of the name is not saved in cache and thus not
1032 * returned to the client. We do not return DNS packets from
1033 * cache to client saying that ipv6.google.com is an alias to
1034 * ipv6.l.google.com but we return instead a DNS packet that
1035 * says ipv6.google.com has address xxx which is in fact the
1036 * address of ipv6.l.google.com. For caching purposes this
1037 * should not cause any issues.
1039 if (*type == 5 && strncmp(question, name, qlen) == 0) {
1041 * So now the alias answered the question. This is
1042 * not very useful from caching point of view as
1043 * the following A or AAAA records will not match the
1044 * question. We need to find the real A/AAAA record
1045 * of the alias and cache that.
1047 unsigned char *end = NULL;
1048 int name_len = 0, output_len;
1050 memset(rsp, 0, sizeof(rsp));
1051 rsp_len = sizeof(rsp) - 1;
1054 * Alias is in rdata part of the message,
1055 * and next-rdlen points to it. So we need to get
1056 * the real name of the alias.
1058 ret = get_name(0, buf, next - rdlen, buf + buflen,
1059 rsp, rsp_len, &output_len, &end,
1062 /* just ignore the error at this point */
1069 * We should now have the alias of the entry we might
1070 * want to cache. Just remember it for a while.
1071 * We check the alias list when we have parsed the
1074 aliases = g_slist_prepend(aliases, g_strdup(name));
1081 if (*type == qtype) {
1083 * We found correct type (A or AAAA)
1085 if (check_alias(aliases, name) == TRUE ||
1086 (aliases == NULL && strncmp(question, name,
1089 * We found an alias or the name of the rr
1090 * matches the question. If so, we append
1091 * the compressed label to the cache.
1092 * The end result is a response buffer that
1093 * will contain one or more cached and
1094 * compressed resource records.
1096 if (*response_len + rsp_len > maxlen) {
1100 memcpy(response + *response_len, rsp, rsp_len);
1101 *response_len += rsp_len;
1112 for (list = aliases; list; list = list->next)
1114 g_slist_free(aliases);
1119 struct cache_timeout {
1120 time_t current_time;
1125 static gboolean cache_check_entry(gpointer key, gpointer value,
1128 struct cache_timeout *data = user_data;
1129 struct cache_entry *entry = value;
1132 /* Scale the number of hits by half as part of cache aging */
1137 * If either IPv4 or IPv6 cached entry has expired, we
1138 * remove both from the cache.
1141 if (entry->ipv4 != NULL && entry->ipv4->timeout > 0) {
1142 max_timeout = entry->ipv4->cache_until;
1143 if (max_timeout > data->max_timeout)
1144 data->max_timeout = max_timeout;
1146 if (entry->ipv4->cache_until < data->current_time)
1150 if (entry->ipv6 != NULL && entry->ipv6->timeout > 0) {
1151 max_timeout = entry->ipv6->cache_until;
1152 if (max_timeout > data->max_timeout)
1153 data->max_timeout = max_timeout;
1155 if (entry->ipv6->cache_until < data->current_time)
1160 * if we're asked to try harder, also remove entries that have
1163 if (data->try_harder && entry->hits < 4)
1169 static void cache_cleanup(void)
1171 static int max_timeout;
1172 struct cache_timeout data;
1175 data.current_time = time(NULL);
1176 data.max_timeout = 0;
1177 data.try_harder = 0;
1180 * In the first pass, we only remove entries that have timed out.
1181 * We use a cache of the first time to expire to do this only
1182 * when it makes sense.
1184 if (max_timeout <= data.current_time) {
1185 count = g_hash_table_foreach_remove(cache, cache_check_entry,
1188 DBG("removed %d in the first pass", count);
1191 * In the second pass, if the first pass turned up blank,
1192 * we also expire entries with a low hit count,
1193 * while aging the hit count at the same time.
1195 data.try_harder = 1;
1197 count = g_hash_table_foreach_remove(cache, cache_check_entry,
1202 * If we could not remove anything, then remember
1203 * what is the max timeout and do nothing if we
1204 * have not yet reached it. This will prevent
1205 * constant traversal of the cache if it is full.
1207 max_timeout = data.max_timeout;
1212 static gboolean cache_invalidate_entry(gpointer key, gpointer value,
1215 struct cache_entry *entry = value;
1217 /* first, delete any expired elements */
1218 cache_enforce_validity(entry);
1220 /* if anything is not expired, mark the entry for refresh */
1221 if (entry->hits > 0 && (entry->ipv4 || entry->ipv6))
1222 entry->want_refresh = 1;
1224 /* delete the cached data */
1226 g_free(entry->ipv4->data);
1227 g_free(entry->ipv4);
1232 g_free(entry->ipv6->data);
1233 g_free(entry->ipv6);
1237 /* keep the entry if we want it refreshed, delete it otherwise */
1238 if (entry->want_refresh)
1245 * cache_invalidate is called from places where the DNS landscape
1246 * has changed, say because connections are added or we entered a VPN.
1247 * The logic is to wipe all cache data, but mark all non-expired
1248 * parts of the cache for refresh rather than deleting the whole cache.
1250 static void cache_invalidate(void)
1252 DBG("Invalidating the DNS cache %p", cache);
1257 g_hash_table_foreach_remove(cache, cache_invalidate_entry, NULL);
1260 static void cache_refresh_entry(struct cache_entry *entry)
1263 cache_enforce_validity(entry);
1265 if (entry->hits > 2 && entry->ipv4 == NULL)
1266 entry->want_refresh = 1;
1267 if (entry->hits > 2 && entry->ipv6 == NULL)
1268 entry->want_refresh = 1;
1270 if (entry->want_refresh) {
1272 char dns_name[NS_MAXDNAME + 1];
1273 entry->want_refresh = 0;
1275 /* turn a DNS name into a hostname with dots */
1276 strncpy(dns_name, entry->key, NS_MAXDNAME);
1284 DBG("Refreshing %s\n", dns_name);
1285 /* then refresh the hostname */
1286 refresh_dns_entry(entry, &dns_name[1]);
1290 static void cache_refresh_iterator(gpointer key, gpointer value,
1293 struct cache_entry *entry = value;
1295 cache_refresh_entry(entry);
1298 static void cache_refresh(void)
1303 g_hash_table_foreach(cache, cache_refresh_iterator, NULL);
1306 static int reply_query_type(unsigned char *msg, int len)
1313 /* skip the header */
1314 c = msg + sizeof(struct domain_hdr);
1315 len -= sizeof(struct domain_hdr);
1320 /* now the query, which is a name and 2 16 bit words */
1321 l = dns_name_length(c) + 1;
1329 static int cache_update(struct server_data *srv, unsigned char *msg,
1330 unsigned int msg_len)
1332 int offset = protocol_offset(srv->protocol);
1333 int err, qlen, ttl = 0;
1334 uint16_t answers = 0, type = 0, class = 0;
1335 struct domain_hdr *hdr = (void *)(msg + offset);
1336 struct domain_question *q;
1337 struct cache_entry *entry;
1338 struct cache_data *data;
1339 char question[NS_MAXDNAME + 1];
1340 unsigned char response[NS_MAXDNAME + 1];
1342 unsigned int rsplen;
1343 gboolean new_entry = TRUE;
1344 time_t current_time;
1346 if (cache_size >= MAX_CACHE_SIZE) {
1348 if (cache_size >= MAX_CACHE_SIZE)
1352 current_time = time(NULL);
1354 /* don't do a cache refresh more than twice a minute */
1355 if (next_refresh < current_time) {
1357 next_refresh = current_time + 30;
1363 DBG("offset %d hdr %p msg %p rcode %d", offset, hdr, msg, hdr->rcode);
1365 /* Continue only if response code is 0 (=ok) */
1366 if (hdr->rcode != 0)
1369 rsplen = sizeof(response) - 1;
1370 question[sizeof(question) - 1] = '\0';
1372 err = parse_response(msg + offset, msg_len - offset,
1373 question, sizeof(question) - 1,
1374 &type, &class, &ttl,
1375 response, &rsplen, &answers);
1378 * special case: if we do a ipv6 lookup and get no result
1379 * for a record that's already in our ipv4 cache.. we want
1380 * to cache the negative response.
1382 if ((err == -ENOMSG || err == -ENOBUFS) &&
1383 reply_query_type(msg + offset,
1384 msg_len - offset) == 28) {
1385 if (cache == NULL) {
1389 entry = g_hash_table_lookup(cache, question);
1390 if (entry && entry->ipv4 && entry->ipv6 == NULL) {
1391 int cache_offset = 0;
1393 data = g_try_new(struct cache_data, 1);
1396 data->inserted = entry->ipv4->inserted;
1398 data->answers = ntohs(hdr->ancount);
1399 data->timeout = entry->ipv4->timeout;
1400 if (srv->protocol == IPPROTO_UDP)
1402 data->data_len = msg_len + cache_offset;
1403 data->data = ptr = g_malloc(data->data_len);
1404 ptr[0] = (data->data_len - 2) / 256;
1405 ptr[1] = (data->data_len - 2) - ptr[0] * 256;
1406 if (srv->protocol == IPPROTO_UDP)
1408 data->valid_until = entry->ipv4->valid_until;
1409 data->cache_until = entry->ipv4->cache_until;
1410 memcpy(ptr, msg, msg_len);
1413 * we will get a "hit" when we serve the response
1417 if (entry->hits < 0)
1423 if (err < 0 || ttl == 0)
1426 qlen = strlen(question);
1429 * If the cache contains already data, check if the
1430 * type of the cached data is the same and do not add
1431 * to cache if data is already there.
1432 * This is needed so that we can cache both A and AAAA
1433 * records for the same name.
1435 entry = g_hash_table_lookup(cache, question);
1436 if (entry == NULL) {
1437 entry = g_try_new(struct cache_entry, 1);
1441 data = g_try_new(struct cache_data, 1);
1447 entry->key = g_strdup(question);
1448 entry->ipv4 = entry->ipv6 = NULL;
1449 entry->want_refresh = 0;
1457 if (type == 1 && entry->ipv4 != NULL)
1460 if (type == 28 && entry->ipv6 != NULL)
1463 data = g_try_new(struct cache_data, 1);
1473 * compensate for the hit we'll get for serving
1474 * the response out of the cache
1477 if (entry->hits < 0)
1483 if (ttl < MIN_CACHE_TTL)
1484 ttl = MIN_CACHE_TTL;
1486 data->inserted = current_time;
1488 data->answers = answers;
1489 data->timeout = ttl;
1491 * The "2" in start of the length is the TCP offset. We allocate it
1492 * here even for UDP packet because it simplifies the sending
1495 data->data_len = 2 + 12 + qlen + 1 + 2 + 2 + rsplen;
1496 data->data = ptr = g_malloc(data->data_len);
1497 data->valid_until = current_time + ttl;
1500 * Restrict the cached DNS record TTL to some sane value
1501 * in order to prevent data staying in the cache too long.
1503 if (ttl > MAX_CACHE_TTL)
1504 ttl = MAX_CACHE_TTL;
1506 data->cache_until = round_down_ttl(current_time + ttl, ttl);
1508 if (data->data == NULL) {
1516 * We cache the two extra bytes at the start of the message
1517 * in a TCP packet. When sending UDP packet, we skip the first
1518 * two bytes. This way we do not need to know the format
1519 * (UDP/TCP) of the cached message.
1521 ptr[0] = (data->data_len - 2) / 256;
1522 ptr[1] = (data->data_len - 2) - ptr[0] * 256;
1523 if (srv->protocol == IPPROTO_UDP)
1526 memcpy(ptr, msg, offset + 12);
1527 memcpy(ptr + offset + 12, question, qlen + 1); /* copy also the \0 */
1529 q = (void *) (ptr + offset + 12 + qlen + 1);
1530 q->type = htons(type);
1531 q->class = htons(class);
1532 memcpy(ptr + offset + 12 + qlen + 1 + sizeof(struct domain_question),
1535 if (new_entry == TRUE) {
1536 g_hash_table_replace(cache, entry->key, entry);
1540 DBG("cache %d %squestion \"%s\" type %d ttl %d size %zd packet %u "
1542 cache_size, new_entry ? "new " : "old ",
1543 question, type, ttl,
1544 sizeof(*entry) + sizeof(*data) + data->data_len + qlen,
1546 srv->protocol == IPPROTO_TCP ?
1547 (unsigned int)(data->data[0] * 256 + data->data[1]) :
1553 static int ns_resolv(struct server_data *server, struct request_data *req,
1554 gpointer request, gpointer name)
1557 int sk, err, type = 0;
1558 char *dot, *lookup = (char *) name;
1559 struct cache_entry *entry;
1561 entry = cache_check(request, &type, req->protocol);
1562 if (entry != NULL) {
1564 struct cache_data *data;
1566 DBG("cache hit %s type %s", lookup, type == 1 ? "A" : "AAAA");
1573 ttl_left = data->valid_until - time(NULL);
1577 if (data != NULL && req->protocol == IPPROTO_TCP) {
1578 send_cached_response(req->client_sk, data->data,
1579 data->data_len, NULL, 0, IPPROTO_TCP,
1580 req->srcid, data->answers, ttl_left);
1584 if (data != NULL && req->protocol == IPPROTO_UDP) {
1585 int udp_sk = get_req_udp_socket(req);
1587 send_cached_response(udp_sk, data->data,
1588 data->data_len, &req->sa, req->sa_len,
1589 IPPROTO_UDP, req->srcid, data->answers,
1595 sk = g_io_channel_unix_get_fd(server->channel);
1597 err = sendto(sk, request, req->request_len, MSG_NOSIGNAL,
1598 server->server_addr, server->server_addr_len);
1600 DBG("Cannot send message to server %s sock %d "
1601 "protocol %d (%s/%d)",
1602 server->server, sk, server->protocol,
1603 strerror(errno), errno);
1609 /* If we have more than one dot, we don't add domains */
1610 dot = strchr(lookup, '.');
1611 if (dot != NULL && dot != lookup + strlen(lookup) - 1)
1614 if (server->domains != NULL && server->domains->data != NULL)
1615 req->append_domain = TRUE;
1617 for (list = server->domains; list; list = list->next) {
1619 unsigned char alt[1024];
1620 struct domain_hdr *hdr = (void *) &alt;
1621 int altlen, domlen, offset;
1623 domain = list->data;
1628 offset = protocol_offset(server->protocol);
1632 domlen = strlen(domain) + 1;
1636 alt[offset] = req->altid & 0xff;
1637 alt[offset + 1] = req->altid >> 8;
1639 memcpy(alt + offset + 2, request + offset + 2, 10);
1640 hdr->qdcount = htons(1);
1642 altlen = append_query(alt + offset + 12, sizeof(alt) - 12,
1649 memcpy(alt + offset + altlen,
1650 request + offset + altlen - domlen,
1651 req->request_len - altlen - offset + domlen);
1653 if (server->protocol == IPPROTO_TCP) {
1654 int req_len = req->request_len + domlen - 2;
1656 alt[0] = (req_len >> 8) & 0xff;
1657 alt[1] = req_len & 0xff;
1660 DBG("req %p dstid 0x%04x altid 0x%04x", req, req->dstid,
1663 err = send(sk, alt, req->request_len + domlen, MSG_NOSIGNAL);
1673 static int forward_dns_reply(unsigned char *reply, int reply_len, int protocol,
1674 struct server_data *data)
1676 struct domain_hdr *hdr;
1677 struct request_data *req;
1678 int dns_id, sk, err, offset = protocol_offset(protocol);
1683 hdr = (void *)(reply + offset);
1684 dns_id = reply[offset] | reply[offset + 1] << 8;
1686 DBG("Received %d bytes (id 0x%04x)", reply_len, dns_id);
1688 req = find_request(dns_id);
1692 DBG("req %p dstid 0x%04x altid 0x%04x rcode %d",
1693 req, req->dstid, req->altid, hdr->rcode);
1695 reply[offset] = req->srcid & 0xff;
1696 reply[offset + 1] = req->srcid >> 8;
1700 if (hdr->rcode == 0 || req->resp == NULL) {
1703 * If the domain name was append
1704 * remove it before forwarding the reply.
1706 if (req->append_domain == TRUE) {
1707 unsigned int domain_len = 0;
1710 unsigned int header_len;
1713 * ptr points to the first char of the hostname.
1714 * ->hostname.domain.net
1716 header_len = offset + sizeof(struct domain_hdr);
1717 ptr = reply + header_len;
1720 domain_len = strnlen((const char *)ptr + 1 +
1722 reply_len - header_len);
1725 DBG("host len %d domain len %d", host_len, domain_len);
1728 * Remove the domain name and replace it by the end
1729 * of reply. Check if the domain is really there
1730 * before trying to copy the data. The domain_len can
1731 * be 0 because if the original query did not contain
1732 * a domain name, then we are sending two packets,
1733 * first without the domain name and the second packet
1734 * with domain name. The append_domain is set to true
1735 * even if we sent the first packet without domain
1736 * name. In this case we end up in this branch.
1738 if (domain_len > 0) {
1740 * Note that we must use memmove() here,
1741 * because the memory areas can overlap.
1743 memmove(ptr + host_len + 1,
1744 ptr + host_len + domain_len + 1,
1745 reply_len - header_len - domain_len);
1747 reply_len = reply_len - domain_len;
1754 req->resp = g_try_malloc(reply_len);
1755 if (req->resp == NULL)
1758 memcpy(req->resp, reply, reply_len);
1759 req->resplen = reply_len;
1761 cache_update(data, reply, reply_len);
1764 if (hdr->rcode > 0 && req->numresp < req->numserv)
1767 request_list = g_slist_remove(request_list, req);
1769 if (protocol == IPPROTO_UDP) {
1770 sk = get_req_udp_socket(req);
1771 err = sendto(sk, req->resp, req->resplen, 0,
1772 &req->sa, req->sa_len);
1774 sk = req->client_sk;
1775 err = send(sk, req->resp, req->resplen, MSG_NOSIGNAL);
1780 DBG("Cannot send msg, sk %d proto %d errno %d/%s", sk,
1781 protocol, errno, strerror(errno));
1783 DBG("proto %d sent %d bytes to %d", protocol, err, sk);
1785 destroy_request_data(req);
1790 static void server_destroy_socket(struct server_data *data)
1792 DBG("index %d server %s proto %d", data->index,
1793 data->server, data->protocol);
1795 if (data->watch > 0) {
1796 g_source_remove(data->watch);
1800 if (data->timeout > 0) {
1801 g_source_remove(data->timeout);
1805 if (data->channel != NULL) {
1806 g_io_channel_shutdown(data->channel, TRUE, NULL);
1807 g_io_channel_unref(data->channel);
1808 data->channel = NULL;
1811 g_free(data->incoming_reply);
1812 data->incoming_reply = NULL;
1815 static void destroy_server(struct server_data *server)
1819 DBG("index %d server %s sock %d", server->index, server->server,
1820 server->channel != NULL ?
1821 g_io_channel_unix_get_fd(server->channel): -1);
1823 server_list = g_slist_remove(server_list, server);
1824 server_destroy_socket(server);
1826 if (server->protocol == IPPROTO_UDP && server->enabled)
1827 DBG("Removing DNS server %s", server->server);
1829 g_free(server->server);
1830 for (list = server->domains; list; list = list->next) {
1831 char *domain = list->data;
1833 server->domains = g_list_remove(server->domains, domain);
1836 g_free(server->server_addr);
1839 * We do not remove cache right away but delay it few seconds.
1840 * The idea is that when IPv6 DNS server is added via RDNSS, it has a
1841 * lifetime. When the lifetime expires we decrease the refcount so it
1842 * is possible that the cache is then removed. Because a new DNS server
1843 * is usually created almost immediately we would then loose the cache
1844 * without any good reason. The small delay allows the new RDNSS to
1845 * create a new DNS server instance and the refcount does not go to 0.
1847 g_timeout_add_seconds(3, try_remove_cache, NULL);
1852 static gboolean udp_server_event(GIOChannel *channel, GIOCondition condition,
1855 unsigned char buf[4096];
1857 struct server_data *data = user_data;
1859 if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
1860 connman_error("Error with UDP server %s", data->server);
1861 server_destroy_socket(data);
1865 sk = g_io_channel_unix_get_fd(channel);
1867 len = recv(sk, buf, sizeof(buf), 0);
1871 err = forward_dns_reply(buf, len, IPPROTO_UDP, data);
1878 static gboolean tcp_server_event(GIOChannel *channel, GIOCondition condition,
1882 struct server_data *server = user_data;
1884 sk = g_io_channel_unix_get_fd(channel);
1888 if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
1891 DBG("TCP server channel closed, sk %d", sk);
1894 * Discard any partial response which is buffered; better
1895 * to get a proper response from a working server.
1897 g_free(server->incoming_reply);
1898 server->incoming_reply = NULL;
1900 for (list = request_list; list; list = list->next) {
1901 struct request_data *req = list->data;
1902 struct domain_hdr *hdr;
1904 if (req->protocol == IPPROTO_UDP)
1907 if (req->request == NULL)
1911 * If we're not waiting for any further response
1912 * from another name server, then we send an error
1913 * response to the client.
1915 if (req->numserv && --(req->numserv))
1918 hdr = (void *) (req->request + 2);
1919 hdr->id = req->srcid;
1920 send_response(req->client_sk, req->request,
1921 req->request_len, NULL, 0, IPPROTO_TCP);
1923 request_list = g_slist_remove(request_list, req);
1926 destroy_server(server);
1931 if ((condition & G_IO_OUT) && !server->connected) {
1934 int no_request_sent = TRUE;
1935 struct server_data *udp_server;
1937 udp_server = find_server(server->index, server->server,
1939 if (udp_server != NULL) {
1940 for (domains = udp_server->domains; domains;
1941 domains = domains->next) {
1942 char *dom = domains->data;
1944 DBG("Adding domain %s to %s",
1945 dom, server->server);
1947 server->domains = g_list_append(server->domains,
1952 server->connected = TRUE;
1953 server_list = g_slist_append(server_list, server);
1955 if (server->timeout > 0) {
1956 g_source_remove(server->timeout);
1957 server->timeout = 0;
1960 for (list = request_list; list; ) {
1961 struct request_data *req = list->data;
1964 if (req->protocol == IPPROTO_UDP) {
1969 DBG("Sending req %s over TCP", (char *)req->name);
1971 status = ns_resolv(server, req,
1972 req->request, req->name);
1975 * A cached result was sent,
1976 * so the request can be released
1979 request_list = g_slist_remove(request_list, req);
1980 destroy_request_data(req);
1989 no_request_sent = FALSE;
1991 if (req->timeout > 0)
1992 g_source_remove(req->timeout);
1994 req->timeout = g_timeout_add_seconds(30,
1995 request_timeout, req);
1999 if (no_request_sent == TRUE) {
2000 destroy_server(server);
2004 } else if (condition & G_IO_IN) {
2005 struct partial_reply *reply = server->incoming_reply;
2009 unsigned char reply_len_buf[2];
2012 bytes_recv = recv(sk, reply_len_buf, 2, MSG_PEEK);
2015 } else if (bytes_recv < 0) {
2016 if (errno == EAGAIN || errno == EWOULDBLOCK)
2019 connman_error("DNS proxy error %s",
2022 } else if (bytes_recv < 2)
2025 reply_len = reply_len_buf[1] | reply_len_buf[0] << 8;
2028 DBG("TCP reply %d bytes from %d", reply_len, sk);
2030 reply = g_try_malloc(sizeof(*reply) + reply_len + 2);
2034 reply->len = reply_len;
2035 reply->received = 0;
2037 server->incoming_reply = reply;
2040 while (reply->received < reply->len) {
2041 bytes_recv = recv(sk, reply->buf + reply->received,
2042 reply->len - reply->received, 0);
2044 connman_error("DNS proxy TCP disconnect");
2046 } else if (bytes_recv < 0) {
2047 if (errno == EAGAIN || errno == EWOULDBLOCK)
2050 connman_error("DNS proxy error %s",
2054 reply->received += bytes_recv;
2057 forward_dns_reply(reply->buf, reply->received, IPPROTO_TCP,
2061 server->incoming_reply = NULL;
2063 destroy_server(server);
2071 static gboolean tcp_idle_timeout(gpointer user_data)
2073 struct server_data *server = user_data;
2080 destroy_server(server);
2085 static int server_create_socket(struct server_data *data)
2090 DBG("index %d server %s proto %d", data->index,
2091 data->server, data->protocol);
2093 sk = socket(data->server_addr->sa_family,
2094 data->protocol == IPPROTO_TCP ? SOCK_STREAM : SOCK_DGRAM,
2098 connman_error("Failed to create server %s socket",
2100 server_destroy_socket(data);
2106 interface = connman_inet_ifname(data->index);
2107 if (interface != NULL) {
2108 if (setsockopt(sk, SOL_SOCKET, SO_BINDTODEVICE,
2110 strlen(interface) + 1) < 0) {
2112 connman_error("Failed to bind server %s "
2114 data->server, interface);
2116 server_destroy_socket(data);
2123 data->channel = g_io_channel_unix_new(sk);
2124 if (data->channel == NULL) {
2125 connman_error("Failed to create server %s channel",
2128 server_destroy_socket(data);
2132 g_io_channel_set_close_on_unref(data->channel, TRUE);
2134 if (data->protocol == IPPROTO_TCP) {
2135 g_io_channel_set_flags(data->channel, G_IO_FLAG_NONBLOCK, NULL);
2136 data->watch = g_io_add_watch(data->channel,
2137 G_IO_OUT | G_IO_IN | G_IO_HUP | G_IO_NVAL | G_IO_ERR,
2138 tcp_server_event, data);
2139 data->timeout = g_timeout_add_seconds(30, tcp_idle_timeout,
2142 data->watch = g_io_add_watch(data->channel,
2143 G_IO_IN | G_IO_NVAL | G_IO_ERR | G_IO_HUP,
2144 udp_server_event, data);
2146 if (connect(sk, data->server_addr, data->server_addr_len) < 0) {
2149 if ((data->protocol == IPPROTO_TCP && errno != EINPROGRESS) ||
2150 data->protocol == IPPROTO_UDP) {
2152 connman_error("Failed to connect to server %s",
2154 server_destroy_socket(data);
2164 static struct server_data *create_server(int index,
2165 const char *domain, const char *server,
2168 struct server_data *data;
2169 struct addrinfo hints, *rp;
2172 DBG("index %d server %s", index, server);
2174 data = g_try_new0(struct server_data, 1);
2176 connman_error("Failed to allocate server %s data", server);
2180 data->index = index;
2182 data->domains = g_list_append(data->domains, g_strdup(domain));
2183 data->server = g_strdup(server);
2184 data->protocol = protocol;
2186 memset(&hints, 0, sizeof(hints));
2190 hints.ai_socktype = SOCK_DGRAM;
2194 hints.ai_socktype = SOCK_STREAM;
2198 destroy_server(data);
2201 hints.ai_family = AF_UNSPEC;
2202 hints.ai_flags = AI_NUMERICSERV | AI_NUMERICHOST;
2204 ret = getaddrinfo(data->server, "53", &hints, &rp);
2206 connman_error("Failed to parse server %s address: %s\n",
2207 data->server, gai_strerror(ret));
2208 destroy_server(data);
2212 /* Do not blindly copy this code elsewhere; it doesn't loop over the
2213 results using ->ai_next as it should. That's OK in *this* case
2214 because it was a numeric lookup; we *know* there's only one. */
2216 data->server_addr_len = rp->ai_addrlen;
2218 switch (rp->ai_family) {
2220 data->server_addr = (struct sockaddr *)
2221 g_try_new0(struct sockaddr_in, 1);
2224 data->server_addr = (struct sockaddr *)
2225 g_try_new0(struct sockaddr_in6, 1);
2228 connman_error("Wrong address family %d", rp->ai_family);
2231 if (data->server_addr == NULL) {
2233 destroy_server(data);
2236 memcpy(data->server_addr, rp->ai_addr, rp->ai_addrlen);
2239 if (server_create_socket(data) != 0) {
2240 destroy_server(data);
2244 if (protocol == IPPROTO_UDP) {
2245 /* Enable new servers by default */
2246 data->enabled = TRUE;
2247 DBG("Adding DNS server %s", data->server);
2249 server_list = g_slist_append(server_list, data);
2255 static gboolean resolv(struct request_data *req,
2256 gpointer request, gpointer name)
2260 for (list = server_list; list; list = list->next) {
2261 struct server_data *data = list->data;
2263 if (data->protocol == IPPROTO_TCP) {
2264 DBG("server %s ignored proto TCP", data->server);
2268 DBG("server %s enabled %d", data->server, data->enabled);
2270 if (data->enabled == FALSE)
2273 if (data->channel == NULL && data->protocol == IPPROTO_UDP) {
2274 if (server_create_socket(data) < 0) {
2275 DBG("socket creation failed while resolving");
2280 if (ns_resolv(data, req, request, name) > 0)
2287 static void append_domain(int index, const char *domain)
2291 DBG("index %d domain %s", index, domain);
2296 for (list = server_list; list; list = list->next) {
2297 struct server_data *data = list->data;
2300 gboolean dom_found = FALSE;
2302 if (data->index < 0)
2305 if (data->index != index)
2308 for (dom_list = data->domains; dom_list;
2309 dom_list = dom_list->next) {
2310 dom = dom_list->data;
2312 if (g_str_equal(dom, domain)) {
2318 if (dom_found == FALSE) {
2320 g_list_append(data->domains, g_strdup(domain));
2325 int __connman_dnsproxy_append(int index, const char *domain,
2328 struct server_data *data;
2330 DBG("index %d server %s", index, server);
2332 if (server == NULL && domain == NULL)
2335 if (server == NULL) {
2336 append_domain(index, domain);
2341 if (g_str_equal(server, "127.0.0.1") == TRUE)
2344 if (g_str_equal(server, "::1") == TRUE)
2347 data = find_server(index, server, IPPROTO_UDP);
2349 append_domain(index, domain);
2353 data = create_server(index, domain, server, IPPROTO_UDP);
2360 static void remove_server(int index, const char *domain,
2361 const char *server, int protocol)
2363 struct server_data *data;
2365 data = find_server(index, server, protocol);
2369 destroy_server(data);
2372 int __connman_dnsproxy_remove(int index, const char *domain,
2375 DBG("index %d server %s", index, server);
2380 if (g_str_equal(server, "127.0.0.1") == TRUE)
2383 if (g_str_equal(server, "::1") == TRUE)
2386 remove_server(index, domain, server, IPPROTO_UDP);
2387 remove_server(index, domain, server, IPPROTO_TCP);
2392 void __connman_dnsproxy_flush(void)
2396 list = request_list;
2398 struct request_data *req = list->data;
2402 if (resolv(req, req->request, req->name) == TRUE) {
2404 * A cached result was sent,
2405 * so the request can be released
2408 g_slist_remove(request_list, req);
2409 destroy_request_data(req);
2413 if (req->timeout > 0)
2414 g_source_remove(req->timeout);
2415 req->timeout = g_timeout_add_seconds(5, request_timeout, req);
2419 static void dnsproxy_offline_mode(connman_bool_t enabled)
2423 DBG("enabled %d", enabled);
2425 for (list = server_list; list; list = list->next) {
2426 struct server_data *data = list->data;
2428 if (enabled == FALSE) {
2429 DBG("Enabling DNS server %s", data->server);
2430 data->enabled = TRUE;
2434 DBG("Disabling DNS server %s", data->server);
2435 data->enabled = FALSE;
2441 static void dnsproxy_default_changed(struct connman_service *service)
2446 DBG("service %p", service);
2448 /* DNS has changed, invalidate the cache */
2451 if (service == NULL) {
2452 /* When no services are active, then disable DNS proxying */
2453 dnsproxy_offline_mode(TRUE);
2457 index = __connman_service_get_index(service);
2461 for (list = server_list; list; list = list->next) {
2462 struct server_data *data = list->data;
2464 if (data->index == index) {
2465 DBG("Enabling DNS server %s", data->server);
2466 data->enabled = TRUE;
2468 DBG("Disabling DNS server %s", data->server);
2469 data->enabled = FALSE;
2476 static struct connman_notifier dnsproxy_notifier = {
2478 .default_changed = dnsproxy_default_changed,
2479 .offline_mode = dnsproxy_offline_mode,
2482 static unsigned char opt_edns0_type[2] = { 0x00, 0x29 };
2484 static int parse_request(unsigned char *buf, int len,
2485 char *name, unsigned int size)
2487 struct domain_hdr *hdr = (void *) buf;
2488 uint16_t qdcount = ntohs(hdr->qdcount);
2489 uint16_t arcount = ntohs(hdr->arcount);
2491 char *last_label = NULL;
2492 unsigned int remain, used = 0;
2497 DBG("id 0x%04x qr %d opcode %d qdcount %d arcount %d",
2498 hdr->id, hdr->qr, hdr->opcode,
2501 if (hdr->qr != 0 || qdcount != 1)
2506 ptr = buf + sizeof(struct domain_hdr);
2507 remain = len - sizeof(struct domain_hdr);
2509 while (remain > 0) {
2510 uint8_t label_len = *ptr;
2512 if (label_len == 0x00) {
2513 last_label = (char *) (ptr + 1);
2517 if (used + label_len + 1 > size)
2520 strncat(name, (char *) (ptr + 1), label_len);
2523 used += label_len + 1;
2525 ptr += label_len + 1;
2526 remain -= label_len + 1;
2529 if (last_label && arcount && remain >= 9 && last_label[4] == 0 &&
2530 !memcmp(last_label + 5, opt_edns0_type, 2)) {
2531 uint16_t edns0_bufsize;
2533 edns0_bufsize = last_label[7] << 8 | last_label[8];
2535 DBG("EDNS0 buffer size %u", edns0_bufsize);
2537 /* This is an evil hack until full TCP support has been
2540 * Somtimes the EDNS0 request gets send with a too-small
2541 * buffer size. Since glibc doesn't seem to crash when it
2542 * gets a response biffer then it requested, just bump
2543 * the buffer size up to 4KiB.
2545 if (edns0_bufsize < 0x1000) {
2546 last_label[7] = 0x10;
2547 last_label[8] = 0x00;
2551 DBG("query %s", name);
2556 static gboolean tcp_listener_event(GIOChannel *channel, GIOCondition condition,
2557 struct listener_data *ifdata, int family,
2558 guint *listener_watch)
2560 unsigned char buf[768];
2562 struct request_data *req;
2563 int sk, client_sk, len, err;
2564 struct sockaddr_in6 client_addr6;
2565 socklen_t client_addr6_len = sizeof(client_addr6);
2566 struct sockaddr_in client_addr4;
2567 socklen_t client_addr4_len = sizeof(client_addr4);
2569 socklen_t *client_addr_len;
2571 int waiting_for_connect = FALSE, qtype = 0;
2572 struct cache_entry *entry;
2574 DBG("condition 0x%x", condition);
2576 if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
2577 if (*listener_watch > 0)
2578 g_source_remove(*listener_watch);
2579 *listener_watch = 0;
2581 connman_error("Error with TCP listener channel");
2586 sk = g_io_channel_unix_get_fd(channel);
2588 if (family == AF_INET) {
2589 client_addr = &client_addr4;
2590 client_addr_len = &client_addr4_len;
2592 client_addr = &client_addr6;
2593 client_addr_len = &client_addr6_len;
2596 client_sk = accept(sk, client_addr, client_addr_len);
2598 if (client_sk < 0) {
2599 connman_error("Accept failure on TCP listener");
2600 *listener_watch = 0;
2604 len = recv(client_sk, buf, sizeof(buf), 0);
2608 DBG("Received %d bytes (id 0x%04x) from %d", len,
2609 buf[2] | buf[3] << 8, client_sk);
2611 err = parse_request(buf + 2, len - 2, query, sizeof(query));
2612 if (err < 0 || (g_slist_length(server_list) == 0)) {
2613 send_response(client_sk, buf, len, NULL, 0, IPPROTO_TCP);
2617 req = g_try_new0(struct request_data, 1);
2621 memcpy(&req->sa, client_addr, *client_addr_len);
2622 req->sa_len = *client_addr_len;
2623 req->client_sk = client_sk;
2624 req->protocol = IPPROTO_TCP;
2625 req->family = family;
2627 req->srcid = buf[2] | (buf[3] << 8);
2628 req->dstid = get_id();
2629 req->altid = get_id();
2630 req->request_len = len;
2632 buf[2] = req->dstid & 0xff;
2633 buf[3] = req->dstid >> 8;
2636 req->ifdata = ifdata;
2637 req->append_domain = FALSE;
2640 * Check if the answer is found in the cache before
2641 * creating sockets to the server.
2643 entry = cache_check(buf, &qtype, IPPROTO_TCP);
2644 if (entry != NULL) {
2646 struct cache_data *data;
2648 DBG("cache hit %s type %s", query, qtype == 1 ? "A" : "AAAA");
2655 ttl_left = data->valid_until - time(NULL);
2658 send_cached_response(client_sk, data->data,
2659 data->data_len, NULL, 0, IPPROTO_TCP,
2660 req->srcid, data->answers, ttl_left);
2665 DBG("data missing, ignoring cache for this query");
2668 for (list = server_list; list; list = list->next) {
2669 struct server_data *data = list->data;
2671 if (data->protocol != IPPROTO_UDP || data->enabled == FALSE)
2674 if(create_server(data->index, NULL,
2675 data->server, IPPROTO_TCP) == NULL)
2678 waiting_for_connect = TRUE;
2681 if (waiting_for_connect == FALSE) {
2682 /* No server is waiting for connect */
2683 send_response(client_sk, buf, len, NULL, 0, IPPROTO_TCP);
2689 * The server is not connected yet.
2690 * Copy the relevant buffers.
2691 * The request will actually be sent once we're
2692 * properly connected over TCP to the nameserver.
2694 req->request = g_try_malloc0(req->request_len);
2695 if (req->request == NULL) {
2696 send_response(client_sk, buf, len, NULL, 0, IPPROTO_TCP);
2700 memcpy(req->request, buf, req->request_len);
2702 req->name = g_try_malloc0(sizeof(query));
2703 if (req->name == NULL) {
2704 send_response(client_sk, buf, len, NULL, 0, IPPROTO_TCP);
2705 g_free(req->request);
2709 memcpy(req->name, query, sizeof(query));
2711 req->timeout = g_timeout_add_seconds(30, request_timeout, req);
2713 request_list = g_slist_append(request_list, req);
2718 static gboolean tcp4_listener_event(GIOChannel *channel, GIOCondition condition,
2721 struct listener_data *ifdata = user_data;
2723 return tcp_listener_event(channel, condition, ifdata, AF_INET,
2724 &ifdata->tcp4_listener_watch);
2727 static gboolean tcp6_listener_event(GIOChannel *channel, GIOCondition condition,
2730 struct listener_data *ifdata = user_data;
2732 return tcp_listener_event(channel, condition, user_data, AF_INET6,
2733 &ifdata->tcp6_listener_watch);
2736 static gboolean udp_listener_event(GIOChannel *channel, GIOCondition condition,
2737 struct listener_data *ifdata, int family,
2738 guint *listener_watch)
2740 unsigned char buf[768];
2742 struct request_data *req;
2743 struct sockaddr_in6 client_addr6;
2744 socklen_t client_addr6_len = sizeof(client_addr6);
2745 struct sockaddr_in client_addr4;
2746 socklen_t client_addr4_len = sizeof(client_addr4);
2748 socklen_t *client_addr_len;
2751 if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
2752 connman_error("Error with UDP listener channel");
2753 *listener_watch = 0;
2757 sk = g_io_channel_unix_get_fd(channel);
2759 if (family == AF_INET) {
2760 client_addr = &client_addr4;
2761 client_addr_len = &client_addr4_len;
2763 client_addr = &client_addr6;
2764 client_addr_len = &client_addr6_len;
2767 memset(client_addr, 0, *client_addr_len);
2768 len = recvfrom(sk, buf, sizeof(buf), 0, client_addr, client_addr_len);
2772 DBG("Received %d bytes (id 0x%04x)", len, buf[0] | buf[1] << 8);
2774 err = parse_request(buf, len, query, sizeof(query));
2775 if (err < 0 || (g_slist_length(server_list) == 0)) {
2776 send_response(sk, buf, len, client_addr,
2777 *client_addr_len, IPPROTO_UDP);
2781 req = g_try_new0(struct request_data, 1);
2785 memcpy(&req->sa, client_addr, *client_addr_len);
2786 req->sa_len = *client_addr_len;
2788 req->protocol = IPPROTO_UDP;
2789 req->family = family;
2791 req->srcid = buf[0] | (buf[1] << 8);
2792 req->dstid = get_id();
2793 req->altid = get_id();
2794 req->request_len = len;
2796 buf[0] = req->dstid & 0xff;
2797 buf[1] = req->dstid >> 8;
2800 req->ifdata = ifdata;
2801 req->append_domain = FALSE;
2803 if (resolv(req, buf, query) == TRUE) {
2804 /* a cached result was sent, so the request can be released */
2809 req->timeout = g_timeout_add_seconds(5, request_timeout, req);
2810 request_list = g_slist_append(request_list, req);
2815 static gboolean udp4_listener_event(GIOChannel *channel, GIOCondition condition,
2818 struct listener_data *ifdata = user_data;
2820 return udp_listener_event(channel, condition, ifdata, AF_INET,
2821 &ifdata->udp4_listener_watch);
2824 static gboolean udp6_listener_event(GIOChannel *channel, GIOCondition condition,
2827 struct listener_data *ifdata = user_data;
2829 return udp_listener_event(channel, condition, user_data, AF_INET6,
2830 &ifdata->udp6_listener_watch);
2833 static GIOChannel *get_listener(int family, int protocol, int index)
2835 GIOChannel *channel;
2839 struct sockaddr_in6 sin6;
2840 struct sockaddr_in sin;
2846 DBG("family %d protocol %d index %d", family, protocol, index);
2851 type = SOCK_DGRAM | SOCK_CLOEXEC;
2856 type = SOCK_STREAM | SOCK_CLOEXEC;
2863 sk = socket(family, type, protocol);
2864 if (sk < 0 && family == AF_INET6 && errno == EAFNOSUPPORT) {
2865 connman_error("No IPv6 support");
2870 connman_error("Failed to create %s listener socket", proto);
2874 interface = connman_inet_ifname(index);
2875 if (interface == NULL || setsockopt(sk, SOL_SOCKET, SO_BINDTODEVICE,
2877 strlen(interface) + 1) < 0) {
2878 connman_error("Failed to bind %s listener interface "
2880 proto, family == AF_INET ? "IPv4" : "IPv6",
2881 -errno, strerror(errno));
2888 if (family == AF_INET6) {
2889 memset(&s.sin6, 0, sizeof(s.sin6));
2890 s.sin6.sin6_family = AF_INET6;
2891 s.sin6.sin6_port = htons(53);
2892 slen = sizeof(s.sin6);
2894 if (__connman_inet_get_interface_address(index,
2896 &s.sin6.sin6_addr) < 0) {
2897 /* So we could not find suitable IPv6 address for
2898 * the interface. This could happen if we have
2899 * disabled IPv6 for the interface.
2905 } else if (family == AF_INET) {
2906 memset(&s.sin, 0, sizeof(s.sin));
2907 s.sin.sin_family = AF_INET;
2908 s.sin.sin_port = htons(53);
2909 slen = sizeof(s.sin);
2911 if (__connman_inet_get_interface_address(index,
2913 &s.sin.sin_addr) < 0) {
2922 if (bind(sk, &s.sa, slen) < 0) {
2923 connman_error("Failed to bind %s listener socket", proto);
2928 if (protocol == IPPROTO_TCP && listen(sk, 10) < 0) {
2929 connman_error("Failed to listen on TCP socket %d/%s", -errno,
2935 channel = g_io_channel_unix_new(sk);
2936 if (channel == NULL) {
2937 connman_error("Failed to create %s listener channel", proto);
2942 g_io_channel_set_close_on_unref(channel, TRUE);
2947 #define UDP_IPv4_FAILED 0x01
2948 #define TCP_IPv4_FAILED 0x02
2949 #define UDP_IPv6_FAILED 0x04
2950 #define TCP_IPv6_FAILED 0x08
2951 #define UDP_FAILED (UDP_IPv4_FAILED | UDP_IPv6_FAILED)
2952 #define TCP_FAILED (TCP_IPv4_FAILED | TCP_IPv6_FAILED)
2953 #define IPv6_FAILED (UDP_IPv6_FAILED | TCP_IPv6_FAILED)
2954 #define IPv4_FAILED (UDP_IPv4_FAILED | TCP_IPv4_FAILED)
2956 static int create_dns_listener(int protocol, struct listener_data *ifdata)
2960 if (protocol == IPPROTO_TCP) {
2961 ifdata->tcp4_listener_channel = get_listener(AF_INET, protocol,
2963 if (ifdata->tcp4_listener_channel != NULL)
2964 ifdata->tcp4_listener_watch =
2965 g_io_add_watch(ifdata->tcp4_listener_channel,
2966 G_IO_IN, tcp4_listener_event,
2969 ret |= TCP_IPv4_FAILED;
2971 ifdata->tcp6_listener_channel = get_listener(AF_INET6, protocol,
2973 if (ifdata->tcp6_listener_channel != NULL)
2974 ifdata->tcp6_listener_watch =
2975 g_io_add_watch(ifdata->tcp6_listener_channel,
2976 G_IO_IN, tcp6_listener_event,
2979 ret |= TCP_IPv6_FAILED;
2981 ifdata->udp4_listener_channel = get_listener(AF_INET, protocol,
2983 if (ifdata->udp4_listener_channel != NULL)
2984 ifdata->udp4_listener_watch =
2985 g_io_add_watch(ifdata->udp4_listener_channel,
2986 G_IO_IN, udp4_listener_event,
2989 ret |= UDP_IPv4_FAILED;
2991 ifdata->udp6_listener_channel = get_listener(AF_INET6, protocol,
2993 if (ifdata->udp6_listener_channel != NULL)
2994 ifdata->udp6_listener_watch =
2995 g_io_add_watch(ifdata->udp6_listener_channel,
2996 G_IO_IN, udp6_listener_event,
2999 ret |= UDP_IPv6_FAILED;
3005 static void destroy_udp_listener(struct listener_data *ifdata)
3007 DBG("index %d", ifdata->index);
3009 if (ifdata->udp4_listener_watch > 0)
3010 g_source_remove(ifdata->udp4_listener_watch);
3012 if (ifdata->udp6_listener_watch > 0)
3013 g_source_remove(ifdata->udp6_listener_watch);
3015 g_io_channel_unref(ifdata->udp4_listener_channel);
3016 g_io_channel_unref(ifdata->udp6_listener_channel);
3019 static void destroy_tcp_listener(struct listener_data *ifdata)
3021 DBG("index %d", ifdata->index);
3023 if (ifdata->tcp4_listener_watch > 0)
3024 g_source_remove(ifdata->tcp4_listener_watch);
3025 if (ifdata->tcp6_listener_watch > 0)
3026 g_source_remove(ifdata->tcp6_listener_watch);
3028 g_io_channel_unref(ifdata->tcp4_listener_channel);
3029 g_io_channel_unref(ifdata->tcp6_listener_channel);
3032 static int create_listener(struct listener_data *ifdata)
3036 err = create_dns_listener(IPPROTO_UDP, ifdata);
3037 if ((err & UDP_FAILED) == UDP_FAILED)
3040 err |= create_dns_listener(IPPROTO_TCP, ifdata);
3041 if ((err & TCP_FAILED) == TCP_FAILED) {
3042 destroy_udp_listener(ifdata);
3046 index = connman_inet_ifindex("lo");
3047 if (ifdata->index == index) {
3048 if ((err & IPv6_FAILED) != IPv6_FAILED)
3049 __connman_resolvfile_append(index, NULL, "::1");
3051 if ((err & IPv4_FAILED) != IPv4_FAILED)
3052 __connman_resolvfile_append(index, NULL, "127.0.0.1");
3058 static void destroy_listener(struct listener_data *ifdata)
3063 index = connman_inet_ifindex("lo");
3064 if (ifdata->index == index) {
3065 __connman_resolvfile_remove(index, NULL, "127.0.0.1");
3066 __connman_resolvfile_remove(index, NULL, "::1");
3069 for (list = request_list; list; list = list->next) {
3070 struct request_data *req = list->data;
3072 DBG("Dropping request (id 0x%04x -> 0x%04x)",
3073 req->srcid, req->dstid);
3074 destroy_request_data(req);
3078 g_slist_free(request_list);
3079 request_list = NULL;
3081 destroy_tcp_listener(ifdata);
3082 destroy_udp_listener(ifdata);
3085 int __connman_dnsproxy_add_listener(int index)
3087 struct listener_data *ifdata;
3090 DBG("index %d", index);
3095 if (listener_table == NULL)
3098 if (g_hash_table_lookup(listener_table, GINT_TO_POINTER(index)) != NULL)
3101 ifdata = g_try_new0(struct listener_data, 1);
3105 ifdata->index = index;
3106 ifdata->udp4_listener_channel = NULL;
3107 ifdata->udp4_listener_watch = 0;
3108 ifdata->tcp4_listener_channel = NULL;
3109 ifdata->tcp4_listener_watch = 0;
3110 ifdata->udp6_listener_channel = NULL;
3111 ifdata->udp6_listener_watch = 0;
3112 ifdata->tcp6_listener_channel = NULL;
3113 ifdata->tcp6_listener_watch = 0;
3115 err = create_listener(ifdata);
3117 connman_error("Couldn't create listener for index %d err %d",
3122 g_hash_table_insert(listener_table, GINT_TO_POINTER(ifdata->index),
3127 void __connman_dnsproxy_remove_listener(int index)
3129 struct listener_data *ifdata;
3131 DBG("index %d", index);
3133 if (listener_table == NULL)
3136 ifdata = g_hash_table_lookup(listener_table, GINT_TO_POINTER(index));
3140 destroy_listener(ifdata);
3142 g_hash_table_remove(listener_table, GINT_TO_POINTER(index));
3145 static void remove_listener(gpointer key, gpointer value, gpointer user_data)
3147 int index = GPOINTER_TO_INT(key);
3148 struct listener_data *ifdata = value;
3150 DBG("index %d", index);
3152 destroy_listener(ifdata);
3155 int __connman_dnsproxy_init(void)
3161 srandom(time(NULL));
3163 listener_table = g_hash_table_new_full(g_direct_hash, g_direct_equal,
3166 index = connman_inet_ifindex("lo");
3167 err = __connman_dnsproxy_add_listener(index);
3171 err = connman_notifier_register(&dnsproxy_notifier);
3178 __connman_dnsproxy_remove_listener(index);
3179 g_hash_table_destroy(listener_table);
3184 void __connman_dnsproxy_cleanup(void)
3188 connman_notifier_unregister(&dnsproxy_notifier);
3190 g_hash_table_foreach(listener_table, remove_listener, NULL);
3192 g_hash_table_destroy(listener_table);