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 {
95 struct partial_reply *incoming_reply;
100 struct sockaddr_in6 __sin6; /* Only for the length */
118 struct listener_data *ifdata;
119 gboolean append_domain;
122 struct listener_data {
124 GIOChannel *udp_listener_channel;
125 guint udp_listener_watch;
126 GIOChannel *tcp_listener_channel;
127 guint tcp_listener_watch;
137 unsigned int data_len;
138 unsigned char *data; /* contains DNS header + body */
145 struct cache_data *ipv4;
146 struct cache_data *ipv6;
149 struct domain_question {
152 } __attribute__ ((packed));
159 } __attribute__ ((packed));
162 * We limit how long the cached DNS entry stays in the cache.
163 * By default the TTL (time-to-live) of the DNS response is used
164 * when setting the cache entry life time. The value is in seconds.
166 #define MAX_CACHE_TTL (60 * 30)
168 * Also limit the other end, cache at least for 30 seconds.
170 #define MIN_CACHE_TTL (30)
173 * We limit the cache size to some sane value so that cached data does
174 * not occupy too much memory. Each cached entry occupies on average
175 * about 100 bytes memory (depending on DNS name length).
176 * Example: caching www.connman.net uses 97 bytes memory.
177 * The value is the max amount of cached DNS responses (count).
179 #define MAX_CACHE_SIZE 256
181 static int cache_size;
182 static GHashTable *cache;
183 static int cache_refcount;
184 static GSList *server_list = NULL;
185 static GSList *request_list = NULL;
186 static GSList *request_pending_list = NULL;
187 static GHashTable *listener_table = NULL;
188 static time_t next_refresh;
190 static guint16 get_id()
195 static int protocol_offset(int protocol)
211 * There is a power and efficiency benefit to have entries
212 * in our cache expire at the same time. To this extend,
213 * we round down the cache valid time to common boundaries.
215 static time_t round_down_ttl(time_t end_time, int ttl)
220 /* Less than 5 minutes, round to 10 second boundary */
222 end_time = end_time / 10;
223 end_time = end_time * 10;
224 } else { /* 5 or more minutes, round to 30 seconds */
225 end_time = end_time / 30;
226 end_time = end_time * 30;
231 static struct request_data *find_request(guint16 id)
235 for (list = request_list; list; list = list->next) {
236 struct request_data *req = list->data;
238 if (req->dstid == id || req->altid == id)
245 static struct server_data *find_server(const char *interface,
251 DBG("interface %s server %s", interface, server);
253 for (list = server_list; list; list = list->next) {
254 struct server_data *data = list->data;
256 if (interface == NULL && data->interface == NULL &&
257 g_str_equal(data->server, server) == TRUE &&
258 data->protocol == protocol)
261 if (interface == NULL ||
262 data->interface == NULL || data->server == NULL)
265 if (g_str_equal(data->interface, interface) == TRUE &&
266 g_str_equal(data->server, server) == TRUE &&
267 data->protocol == protocol)
274 /* we can keep using the same resolve's */
275 static GResolv *ipv4_resolve;
276 static GResolv *ipv6_resolve;
278 static void dummy_resolve_func(GResolvResultStatus status,
279 char **results, gpointer user_data)
284 * Refresh a DNS entry, but also age the hit count a bit */
285 static void refresh_dns_entry(struct cache_entry *entry, char *name)
289 if (ipv4_resolve == NULL) {
290 ipv4_resolve = g_resolv_new(0);
291 g_resolv_set_address_family(ipv4_resolve, AF_INET);
292 g_resolv_add_nameserver(ipv4_resolve, "127.0.0.1", 53, 0);
295 if (ipv6_resolve == NULL) {
296 ipv6_resolve = g_resolv_new(0);
297 g_resolv_set_address_family(ipv6_resolve, AF_INET6);
298 g_resolv_add_nameserver(ipv6_resolve, "127.0.0.1", 53, 0);
301 if (entry->ipv4 == NULL) {
302 DBG("Refresing A record for %s", name);
303 g_resolv_lookup_hostname(ipv4_resolve, name,
304 dummy_resolve_func, NULL);
308 if (entry->ipv6 == NULL) {
309 DBG("Refresing AAAA record for %s", name);
310 g_resolv_lookup_hostname(ipv6_resolve, name,
311 dummy_resolve_func, NULL);
320 static int dns_name_length(unsigned char *buf)
322 if ((buf[0] & NS_CMPRSFLGS) == NS_CMPRSFLGS) /* compressed name */
324 return strlen((char *)buf);
327 static void update_cached_ttl(unsigned char *buf, int len, int new_ttl)
334 /* skip the header */
338 /* skip the query, which is a name and 2 16 bit words */
339 l = dns_name_length(c);
345 /* now we get the answer records */
349 l = dns_name_length(c);
354 /* then type + class, 2 bytes each */
360 /* now the 4 byte TTL field */
368 /* now the 2 byte rdlen field */
371 len -= ntohs(*w) + 2;
375 static void send_cached_response(int sk, unsigned char *buf, int len,
376 const struct sockaddr *to, socklen_t tolen,
377 int protocol, int id, uint16_t answers, int ttl)
379 struct domain_hdr *hdr;
380 int err, offset = protocol_offset(protocol);
388 hdr = (void *) (buf + offset);
393 hdr->ancount = htons(answers);
397 /* if this is a negative reply, we are authorative */
401 update_cached_ttl(buf, len, ttl);
403 DBG("id 0x%04x answers %d", hdr->id, answers);
405 err = sendto(sk, buf, len, 0, to, tolen);
407 connman_error("Cannot send cached DNS response: %s",
413 static void send_response(int sk, unsigned char *buf, int len,
414 const struct sockaddr *to, socklen_t tolen,
417 struct domain_hdr *hdr;
418 int err, offset = protocol_offset(protocol);
428 hdr = (void *) (buf + offset);
430 DBG("id 0x%04x qr %d opcode %d", hdr->id, hdr->qr, hdr->opcode);
439 err = sendto(sk, buf, len, 0, to, tolen);
441 connman_error("Failed to send DNS response: %s",
447 static gboolean request_timeout(gpointer user_data)
449 struct request_data *req = user_data;
450 struct listener_data *ifdata;
452 DBG("id 0x%04x", req->srcid);
457 ifdata = req->ifdata;
459 request_list = g_slist_remove(request_list, req);
462 if (req->resplen > 0 && req->resp != NULL) {
465 sk = g_io_channel_unix_get_fd(ifdata->udp_listener_channel);
467 err = sendto(sk, req->resp, req->resplen, 0,
468 &req->sa, req->sa_len);
471 } else if (req->request && req->numserv == 0) {
472 struct domain_hdr *hdr;
474 if (req->protocol == IPPROTO_TCP) {
475 hdr = (void *) (req->request + 2);
476 hdr->id = req->srcid;
477 send_response(req->client_sk, req->request,
478 req->request_len, NULL, 0, IPPROTO_TCP);
480 } else if (req->protocol == IPPROTO_UDP) {
483 hdr = (void *) (req->request);
484 hdr->id = req->srcid;
485 sk = g_io_channel_unix_get_fd(
486 ifdata->udp_listener_channel);
487 send_response(sk, req->request, req->request_len,
488 &req->sa, req->sa_len, IPPROTO_UDP);
498 static int append_query(unsigned char *buf, unsigned int size,
499 const char *query, const char *domain)
501 unsigned char *ptr = buf;
504 DBG("query %s domain %s", query, domain);
506 while (query != NULL) {
509 tmp = strchr(query, '.');
515 memcpy(ptr + 1, query, len);
521 memcpy(ptr + 1, query, tmp - query);
522 ptr += tmp - query + 1;
527 while (domain != NULL) {
530 tmp = strchr(domain, '.');
532 len = strlen(domain);
536 memcpy(ptr + 1, domain, len);
542 memcpy(ptr + 1, domain, tmp - domain);
543 ptr += tmp - domain + 1;
553 static gboolean cache_check_is_valid(struct cache_data *data,
559 if (data->cache_until < current_time)
566 * remove stale cached entries so that they can be refreshed
568 static void cache_enforce_validity(struct cache_entry *entry)
570 time_t current_time = time(NULL);
572 if (cache_check_is_valid(entry->ipv4, current_time) == FALSE
574 DBG("cache timeout \"%s\" type A", entry->key);
575 g_free(entry->ipv4->data);
581 if (cache_check_is_valid(entry->ipv6, current_time) == FALSE
583 DBG("cache timeout \"%s\" type AAAA", entry->key);
584 g_free(entry->ipv6->data);
590 static uint16_t cache_check_validity(char *question, uint16_t type,
591 struct cache_entry *entry)
593 time_t current_time = time(NULL);
594 int want_refresh = 0;
597 * if we have a popular entry, we want a refresh instead of
598 * total destruction of the entry.
603 cache_enforce_validity(entry);
607 if (cache_check_is_valid(entry->ipv4, current_time) == FALSE) {
608 DBG("cache %s \"%s\" type A", entry->ipv4 ?
609 "timeout" : "entry missing", question);
612 entry->want_refresh = 1;
615 * We do not remove cache entry if there is still
616 * valid IPv6 entry found in the cache.
618 if (cache_check_is_valid(entry->ipv6, current_time)
619 == FALSE && want_refresh == FALSE) {
620 g_hash_table_remove(cache, question);
627 if (cache_check_is_valid(entry->ipv6, current_time) == FALSE) {
628 DBG("cache %s \"%s\" type AAAA", entry->ipv6 ?
629 "timeout" : "entry missing", question);
632 entry->want_refresh = 1;
634 if (cache_check_is_valid(entry->ipv4, current_time)
635 == FALSE && want_refresh == FALSE) {
636 g_hash_table_remove(cache, question);
646 static struct cache_entry *cache_check(gpointer request, int *qtype)
648 char *question = request + 12;
649 struct cache_entry *entry;
650 struct domain_question *q;
654 offset = strlen(question) + 1;
655 q = (void *) (question + offset);
656 type = ntohs(q->type);
658 /* We only cache either A (1) or AAAA (28) requests */
659 if (type != 1 && type != 28)
662 entry = g_hash_table_lookup(cache, question);
666 type = cache_check_validity(question, type, entry);
675 * Get a label/name from DNS resource record. The function decompresses the
676 * label if necessary. The function does not convert the name to presentation
677 * form. This means that the result string will contain label lengths instead
678 * of dots between labels. We intentionally do not want to convert to dotted
679 * format so that we can cache the wire format string directly.
681 static int get_name(int counter,
682 unsigned char *pkt, unsigned char *start, unsigned char *max,
683 unsigned char *output, int output_max, int *output_len,
684 unsigned char **end, char *name, int *name_len)
688 /* Limit recursion to 10 (this means up to 10 labels in domain name) */
694 if ((*p & NS_CMPRSFLGS) == NS_CMPRSFLGS) {
695 uint16_t offset = (*p & 0x3F) * 256 + *(p + 1);
697 if (offset >= max - pkt)
703 return get_name(counter + 1, pkt, pkt + offset, max,
704 output, output_max, output_len, end,
707 unsigned label_len = *p;
709 if (pkt + label_len > max)
712 if (*output_len > output_max)
716 * We need the original name in order to check
717 * if this answer is the correct one.
719 name[(*name_len)++] = label_len;
720 memcpy(name + *name_len, p + 1, label_len + 1);
721 *name_len += label_len;
723 /* We compress the result */
724 output[0] = NS_CMPRSFLGS;
741 static int parse_rr(unsigned char *buf, unsigned char *start,
743 unsigned char *response, unsigned int *response_size,
744 uint16_t *type, uint16_t *class, int *ttl, int *rdlen,
748 struct domain_rr *rr;
750 int name_len = 0, output_len = 0, max_rsp = *response_size;
752 err = get_name(0, buf, start, max, response, max_rsp,
753 &output_len, end, name, &name_len);
759 if ((unsigned int) offset > *response_size)
762 rr = (void *) (*end);
767 *type = ntohs(rr->type);
768 *class = ntohs(rr->class);
769 *ttl = ntohl(rr->ttl);
770 *rdlen = ntohs(rr->rdlen);
775 memcpy(response + offset, *end, sizeof(struct domain_rr));
777 offset += sizeof(struct domain_rr);
778 *end += sizeof(struct domain_rr);
780 if ((unsigned int) (offset + *rdlen) > *response_size)
783 memcpy(response + offset, *end, *rdlen);
787 *response_size = offset + *rdlen;
792 static gboolean check_alias(GSList *aliases, char *name)
796 if (aliases != NULL) {
797 for (list = aliases; list; list = list->next) {
798 int len = strlen((char *)list->data);
799 if (strncmp((char *)list->data, name, len) == 0)
807 static int parse_response(unsigned char *buf, int buflen,
808 char *question, int qlen,
809 uint16_t *type, uint16_t *class, int *ttl,
810 unsigned char *response, unsigned int *response_len,
813 struct domain_hdr *hdr = (void *) buf;
814 struct domain_question *q;
816 uint16_t qdcount = ntohs(hdr->qdcount);
817 uint16_t ancount = ntohs(hdr->ancount);
819 uint16_t qtype, qclass;
820 unsigned char *next = NULL;
821 unsigned int maxlen = *response_len;
822 GSList *aliases = NULL, *list;
823 char name[NS_MAXDNAME + 1];
828 DBG("qr %d qdcount %d", hdr->qr, qdcount);
830 /* We currently only cache responses where question count is 1 */
831 if (hdr->qr != 1 || qdcount != 1)
834 ptr = buf + sizeof(struct domain_hdr);
836 strncpy(question, (char *) ptr, qlen);
837 qlen = strlen(question);
838 ptr += qlen + 1; /* skip \0 */
841 qtype = ntohs(q->type);
843 /* We cache only A and AAAA records */
844 if (qtype != 1 && qtype != 28)
847 qclass = ntohs(q->class);
849 ptr += 2 + 2; /* ptr points now to answers */
856 * We have a bunch of answers (like A, AAAA, CNAME etc) to
857 * A or AAAA question. We traverse the answers and parse the
858 * resource records. Only A and AAAA records are cached, all
859 * the other records in answers are skipped.
861 for (i = 0; i < ancount; i++) {
863 * Get one address at a time to this buffer.
864 * The max size of the answer is
865 * 2 (pointer) + 2 (type) + 2 (class) +
866 * 4 (ttl) + 2 (rdlen) + addr (16 or 4) = 28
867 * for A or AAAA record.
868 * For CNAME the size can be bigger.
870 unsigned char rsp[NS_MAXCDNAME];
871 unsigned int rsp_len = sizeof(rsp) - 1;
874 memset(rsp, 0, sizeof(rsp));
876 ret = parse_rr(buf, ptr, buf + buflen, rsp, &rsp_len,
877 type, class, ttl, &rdlen, &next, name);
884 * Now rsp contains compressed or uncompressed resource
885 * record. Next we check if this record answers the question.
886 * The name var contains the uncompressed label.
887 * One tricky bit is the CNAME records as they alias
888 * the name we might be interested in.
892 * Go to next answer if the class is not the one we are
895 if (*class != qclass) {
902 * Try to resolve aliases also, type is CNAME(5).
903 * This is important as otherwise the aliased names would not
904 * be cached at all as the cache would not contain the aliased
907 * If any CNAME is found in DNS packet, then we cache the alias
908 * IP address instead of the question (as the server
909 * said that question has only an alias).
910 * This means in practice that if e.g., ipv6.google.com is
911 * queried, DNS server returns CNAME of that name which is
912 * ipv6.l.google.com. We then cache the address of the CNAME
913 * but return the question name to client. So the alias
914 * status of the name is not saved in cache and thus not
915 * returned to the client. We do not return DNS packets from
916 * cache to client saying that ipv6.google.com is an alias to
917 * ipv6.l.google.com but we return instead a DNS packet that
918 * says ipv6.google.com has address xxx which is in fact the
919 * address of ipv6.l.google.com. For caching purposes this
920 * should not cause any issues.
922 if (*type == 5 && strncmp(question, name, qlen) == 0) {
924 * So now the alias answered the question. This is
925 * not very useful from caching point of view as
926 * the following A or AAAA records will not match the
927 * question. We need to find the real A/AAAA record
928 * of the alias and cache that.
930 unsigned char *end = NULL;
931 int name_len = 0, output_len;
933 memset(rsp, 0, sizeof(rsp));
934 rsp_len = sizeof(rsp) - 1;
937 * Alias is in rdata part of the message,
938 * and next-rdlen points to it. So we need to get
939 * the real name of the alias.
941 ret = get_name(0, buf, next - rdlen, buf + buflen,
942 rsp, rsp_len, &output_len, &end,
945 /* just ignore the error at this point */
952 * We should now have the alias of the entry we might
953 * want to cache. Just remember it for a while.
954 * We check the alias list when we have parsed the
957 aliases = g_slist_prepend(aliases, g_strdup(name));
964 if (*type == qtype) {
966 * We found correct type (A or AAAA)
968 if (check_alias(aliases, name) == TRUE ||
969 (aliases == NULL && strncmp(question, name,
972 * We found an alias or the name of the rr
973 * matches the question. If so, we append
974 * the compressed label to the cache.
975 * The end result is a response buffer that
976 * will contain one or more cached and
977 * compressed resource records.
979 if (*response_len + rsp_len > maxlen) {
983 memcpy(response + *response_len, rsp, rsp_len);
984 *response_len += rsp_len;
995 for (list = aliases; list; list = list->next)
997 g_slist_free(aliases);
1002 struct cache_timeout {
1003 time_t current_time;
1008 static gboolean cache_check_entry(gpointer key, gpointer value,
1011 struct cache_timeout *data = user_data;
1012 struct cache_entry *entry = value;
1015 /* Scale the number of hits by half as part of cache aging */
1020 * If either IPv4 or IPv6 cached entry has expired, we
1021 * remove both from the cache.
1024 if (entry->ipv4 != NULL && entry->ipv4->timeout > 0) {
1025 max_timeout = entry->ipv4->cache_until;
1026 if (max_timeout > data->max_timeout)
1027 data->max_timeout = max_timeout;
1029 if (entry->ipv4->cache_until < data->current_time)
1033 if (entry->ipv6 != NULL && entry->ipv6->timeout > 0) {
1034 max_timeout = entry->ipv6->cache_until;
1035 if (max_timeout > data->max_timeout)
1036 data->max_timeout = max_timeout;
1038 if (entry->ipv6->cache_until < data->current_time)
1043 * if we're asked to try harder, also remove entries that have
1046 if (data->try_harder && entry->hits < 4)
1052 static void cache_cleanup(void)
1054 static int max_timeout;
1055 struct cache_timeout data;
1058 data.current_time = time(NULL);
1059 data.max_timeout = 0;
1060 data.try_harder = 0;
1063 * In the first pass, we only remove entries that have timed out.
1064 * We use a cache of the first time to expire to do this only
1065 * when it makes sense.
1067 if (max_timeout <= data.current_time) {
1068 count = g_hash_table_foreach_remove(cache, cache_check_entry,
1071 DBG("removed %d in the first pass", count);
1074 * In the second pass, if the first pass turned up blank,
1075 * we also expire entries with a low hit count,
1076 * while aging the hit count at the same time.
1078 data.try_harder = 1;
1080 count = g_hash_table_foreach_remove(cache, cache_check_entry,
1085 * If we could not remove anything, then remember
1086 * what is the max timeout and do nothing if we
1087 * have not yet reached it. This will prevent
1088 * constant traversal of the cache if it is full.
1090 max_timeout = data.max_timeout;
1095 static gboolean cache_invalidate_entry(gpointer key, gpointer value,
1098 struct cache_entry *entry = value;
1100 /* first, delete any expired elements */
1101 cache_enforce_validity(entry);
1103 /* if anything is not expired, mark the entry for refresh */
1104 if (entry->hits > 0 && (entry->ipv4 || entry->ipv6))
1105 entry->want_refresh = 1;
1107 /* delete the cached data */
1109 g_free(entry->ipv4->data);
1110 g_free(entry->ipv4);
1115 g_free(entry->ipv6->data);
1116 g_free(entry->ipv6);
1120 /* keep the entry if we want it refreshed, delete it otherwise */
1121 if (entry->want_refresh)
1128 * cache_invalidate is called from places where the DNS landscape
1129 * has changed, say because connections are added or we entered a VPN.
1130 * The logic is to wipe all cache data, but mark all non-expired
1131 * parts of the cache for refresh rather than deleting the whole cache.
1133 static void cache_invalidate(void)
1135 DBG("Invalidating the DNS cache %p", cache);
1140 g_hash_table_foreach_remove(cache, cache_invalidate_entry, NULL);
1143 static void cache_refresh_entry(struct cache_entry *entry)
1146 cache_enforce_validity(entry);
1148 if (entry->hits > 2 && entry->ipv4 == NULL)
1149 entry->want_refresh = 1;
1150 if (entry->hits > 2 && entry->ipv6 == NULL)
1151 entry->want_refresh = 1;
1153 if (entry->want_refresh) {
1155 char dns_name[NS_MAXDNAME + 1];
1156 entry->want_refresh = 0;
1158 /* turn a DNS name into a hostname with dots */
1159 strncpy(dns_name, entry->key, NS_MAXDNAME);
1167 DBG("Refreshing %s\n", dns_name);
1168 /* then refresh the hostname */
1169 refresh_dns_entry(entry, &dns_name[1]);
1173 static void cache_refresh_iterator(gpointer key, gpointer value,
1176 struct cache_entry *entry = value;
1178 cache_refresh_entry(entry);
1181 static void cache_refresh(void)
1186 g_hash_table_foreach(cache, cache_refresh_iterator, NULL);
1189 static int reply_query_type(unsigned char *msg, int len)
1196 /* skip the header */
1197 c = msg + sizeof(struct domain_hdr);
1198 len -= sizeof(struct domain_hdr);
1203 /* now the query, which is a name and 2 16 bit words */
1204 l = dns_name_length(c) + 1;
1212 static int cache_update(struct server_data *srv, unsigned char *msg,
1213 unsigned int msg_len)
1215 int offset = protocol_offset(srv->protocol);
1216 int err, qlen, ttl = 0;
1217 uint16_t answers = 0, type = 0, class = 0;
1218 struct domain_question *q;
1219 struct cache_entry *entry;
1220 struct cache_data *data;
1221 char question[NS_MAXDNAME + 1];
1222 unsigned char response[NS_MAXDNAME + 1];
1224 unsigned int rsplen;
1225 gboolean new_entry = TRUE;
1226 time_t current_time;
1228 if (cache_size >= MAX_CACHE_SIZE) {
1230 if (cache_size >= MAX_CACHE_SIZE)
1234 current_time = time(NULL);
1236 /* don't do a cache refresh more than twice a minute */
1237 if (next_refresh < current_time) {
1239 next_refresh = current_time + 30;
1243 /* Continue only if response code is 0 (=ok) */
1250 rsplen = sizeof(response) - 1;
1251 question[sizeof(question) - 1] = '\0';
1253 err = parse_response(msg + offset, msg_len - offset,
1254 question, sizeof(question) - 1,
1255 &type, &class, &ttl,
1256 response, &rsplen, &answers);
1259 * special case: if we do a ipv6 lookup and get no result
1260 * for a record that's already in our ipv4 cache.. we want
1261 * to cache the negative response.
1263 if ((err == -ENOMSG || err == -ENOBUFS) &&
1264 reply_query_type(msg, msg_len) == 28) {
1265 entry = g_hash_table_lookup(cache, question);
1266 if (entry && entry->ipv4 && entry->ipv6 == NULL) {
1267 data = g_try_new(struct cache_data, 1);
1270 data->inserted = entry->ipv4->inserted;
1272 data->answers = msg[5];
1273 data->timeout = entry->ipv4->timeout;
1274 data->data_len = msg_len;
1275 data->data = ptr = g_malloc(msg_len);
1276 data->valid_until = entry->ipv4->valid_until;
1277 data->cache_until = entry->ipv4->cache_until;
1278 memcpy(data->data, msg, msg_len);
1281 * we will get a "hit" when we serve the response
1285 if (entry->hits < 0)
1291 if (err < 0 || ttl == 0)
1294 qlen = strlen(question);
1297 * If the cache contains already data, check if the
1298 * type of the cached data is the same and do not add
1299 * to cache if data is already there.
1300 * This is needed so that we can cache both A and AAAA
1301 * records for the same name.
1303 entry = g_hash_table_lookup(cache, question);
1304 if (entry == NULL) {
1305 entry = g_try_new(struct cache_entry, 1);
1309 data = g_try_new(struct cache_data, 1);
1315 entry->key = g_strdup(question);
1316 entry->ipv4 = entry->ipv6 = NULL;
1317 entry->want_refresh = 0;
1325 if (type == 1 && entry->ipv4 != NULL)
1328 if (type == 28 && entry->ipv6 != NULL)
1331 data = g_try_new(struct cache_data, 1);
1341 * compensate for the hit we'll get for serving
1342 * the response out of the cache
1345 if (entry->hits < 0)
1351 if (ttl < MIN_CACHE_TTL)
1352 ttl = MIN_CACHE_TTL;
1354 data->inserted = current_time;
1356 data->answers = answers;
1357 data->timeout = ttl;
1358 data->data_len = 12 + qlen + 1 + 2 + 2 + rsplen;
1359 data->data = ptr = g_malloc(data->data_len);
1360 data->valid_until = current_time + ttl;
1363 * Restrict the cached DNS record TTL to some sane value
1364 * in order to prevent data staying in the cache too long.
1366 if (ttl > MAX_CACHE_TTL)
1367 ttl = MAX_CACHE_TTL;
1369 data->cache_until = round_down_ttl(current_time + ttl, ttl);
1371 if (data->data == NULL) {
1378 memcpy(ptr, msg, 12);
1379 memcpy(ptr + 12, question, qlen + 1); /* copy also the \0 */
1381 q = (void *) (ptr + 12 + qlen + 1);
1382 q->type = htons(type);
1383 q->class = htons(class);
1384 memcpy(ptr + 12 + qlen + 1 + sizeof(struct domain_question),
1387 if (new_entry == TRUE) {
1388 g_hash_table_replace(cache, entry->key, entry);
1392 DBG("cache %d %squestion \"%s\" type %d ttl %d size %zd",
1393 cache_size, new_entry ? "new " : "old ",
1394 question, type, ttl,
1395 sizeof(*entry) + sizeof(*data) + data->data_len + qlen);
1400 static int ns_resolv(struct server_data *server, struct request_data *req,
1401 gpointer request, gpointer name)
1404 int sk, err, type = 0;
1405 char *dot, *lookup = (char *) name;
1406 struct cache_entry *entry;
1408 entry = cache_check(request, &type);
1409 if (entry != NULL) {
1411 struct cache_data *data;
1413 DBG("cache hit %s type %s", lookup, type == 1 ? "A" : "AAAA");
1420 ttl_left = data->valid_until - time(NULL);
1424 if (data != NULL && req->protocol == IPPROTO_TCP) {
1425 send_cached_response(req->client_sk, data->data,
1426 data->data_len, NULL, 0, IPPROTO_TCP,
1427 req->srcid, data->answers, ttl_left);
1431 if (data != NULL && req->protocol == IPPROTO_UDP) {
1433 sk = g_io_channel_unix_get_fd(
1434 req->ifdata->udp_listener_channel);
1436 send_cached_response(sk, data->data,
1437 data->data_len, &req->sa, req->sa_len,
1438 IPPROTO_UDP, req->srcid, data->answers,
1444 sk = g_io_channel_unix_get_fd(server->channel);
1446 err = send(sk, request, req->request_len, 0);
1452 /* If we have more than one dot, we don't add domains */
1453 dot = strchr(lookup, '.');
1454 if (dot != NULL && dot != lookup + strlen(lookup) - 1)
1457 if (server->domains != NULL && server->domains->data != NULL)
1458 req->append_domain = TRUE;
1460 for (list = server->domains; list; list = list->next) {
1462 unsigned char alt[1024];
1463 struct domain_hdr *hdr = (void *) &alt;
1464 int altlen, domlen, offset;
1466 domain = list->data;
1471 offset = protocol_offset(server->protocol);
1475 domlen = strlen(domain) + 1;
1479 alt[offset] = req->altid & 0xff;
1480 alt[offset + 1] = req->altid >> 8;
1482 memcpy(alt + offset + 2, request + offset + 2, 10);
1483 hdr->qdcount = htons(1);
1485 altlen = append_query(alt + offset + 12, sizeof(alt) - 12,
1492 memcpy(alt + offset + altlen,
1493 request + offset + altlen - domlen,
1494 req->request_len - altlen - offset + domlen);
1496 if (server->protocol == IPPROTO_TCP) {
1497 int req_len = req->request_len + domlen - 2;
1499 alt[0] = (req_len >> 8) & 0xff;
1500 alt[1] = req_len & 0xff;
1503 err = send(sk, alt, req->request_len + domlen, 0);
1513 static int forward_dns_reply(unsigned char *reply, int reply_len, int protocol,
1514 struct server_data *data)
1516 struct domain_hdr *hdr;
1517 struct request_data *req;
1518 int dns_id, sk, err, offset = protocol_offset(protocol);
1519 struct listener_data *ifdata;
1524 hdr = (void *)(reply + offset);
1525 dns_id = reply[offset] | reply[offset + 1] << 8;
1527 DBG("Received %d bytes (id 0x%04x)", reply_len, dns_id);
1529 req = find_request(dns_id);
1533 DBG("id 0x%04x rcode %d", hdr->id, hdr->rcode);
1535 ifdata = req->ifdata;
1537 reply[offset] = req->srcid & 0xff;
1538 reply[offset + 1] = req->srcid >> 8;
1542 if (hdr->rcode == 0 || req->resp == NULL) {
1545 * If the domain name was append
1546 * remove it before forwarding the reply.
1548 if (req->append_domain == TRUE) {
1551 unsigned int domain_len;
1554 * ptr points to the first char of the hostname.
1555 * ->hostname.domain.net
1557 ptr = reply + offset + sizeof(struct domain_hdr);
1559 domain_len = strlen((const char *)ptr + host_len + 1);
1562 * Remove the domain name and replace it by the end
1563 * of reply. Check if the domain is really there
1564 * before trying to copy the data. The domain_len can
1565 * be 0 because if the original query did not contain
1566 * a domain name, then we are sending two packets,
1567 * first without the domain name and the second packet
1568 * with domain name. The append_domain is set to true
1569 * even if we sent the first packet without domain
1570 * name. In this case we end up in this branch.
1572 if (domain_len > 0) {
1574 * Note that we must use memmove() here,
1575 * because the memory areas can overlap.
1577 memmove(ptr + host_len + 1,
1578 ptr + host_len + domain_len + 1,
1579 reply_len - (ptr - reply + domain_len));
1581 reply_len = reply_len - domain_len;
1588 req->resp = g_try_malloc(reply_len);
1589 if (req->resp == NULL)
1592 memcpy(req->resp, reply, reply_len);
1593 req->resplen = reply_len;
1595 cache_update(data, reply, reply_len);
1598 if (hdr->rcode > 0 && req->numresp < req->numserv)
1601 if (req->timeout > 0)
1602 g_source_remove(req->timeout);
1604 request_list = g_slist_remove(request_list, req);
1606 if (protocol == IPPROTO_UDP) {
1607 sk = g_io_channel_unix_get_fd(ifdata->udp_listener_channel);
1608 err = sendto(sk, req->resp, req->resplen, 0,
1609 &req->sa, req->sa_len);
1611 sk = req->client_sk;
1612 err = send(sk, req->resp, req->resplen, 0);
1622 static void cache_element_destroy(gpointer value)
1624 struct cache_entry *entry = value;
1629 if (entry->ipv4 != NULL) {
1630 g_free(entry->ipv4->data);
1631 g_free(entry->ipv4);
1634 if (entry->ipv6 != NULL) {
1635 g_free(entry->ipv6->data);
1636 g_free(entry->ipv6);
1642 if (--cache_size < 0)
1646 static gboolean try_remove_cache(gpointer user_data)
1648 if (__sync_fetch_and_sub(&cache_refcount, 1) == 1) {
1649 DBG("No cache users, removing it.");
1651 g_hash_table_destroy(cache);
1658 static void destroy_server(struct server_data *server)
1662 DBG("interface %s server %s", server->interface, server->server);
1664 server_list = g_slist_remove(server_list, server);
1666 if (server->watch > 0)
1667 g_source_remove(server->watch);
1669 if (server->timeout > 0)
1670 g_source_remove(server->timeout);
1672 g_io_channel_unref(server->channel);
1674 if (server->protocol == IPPROTO_UDP)
1675 DBG("Removing DNS server %s", server->server);
1677 g_free(server->incoming_reply);
1678 g_free(server->server);
1679 for (list = server->domains; list; list = list->next) {
1680 char *domain = list->data;
1682 server->domains = g_list_remove(server->domains, domain);
1685 g_free(server->interface);
1688 * We do not remove cache right away but delay it few seconds.
1689 * The idea is that when IPv6 DNS server is added via RDNSS, it has a
1690 * lifetime. When the lifetime expires we decrease the refcount so it
1691 * is possible that the cache is then removed. Because a new DNS server
1692 * is usually created almost immediately we would then loose the cache
1693 * without any good reason. The small delay allows the new RDNSS to
1694 * create a new DNS server instance and the refcount does not go to 0.
1696 g_timeout_add_seconds(3, try_remove_cache, NULL);
1701 static gboolean udp_server_event(GIOChannel *channel, GIOCondition condition,
1704 unsigned char buf[4096];
1706 struct server_data *data = user_data;
1708 if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
1709 connman_error("Error with UDP server %s", data->server);
1714 sk = g_io_channel_unix_get_fd(channel);
1716 len = recv(sk, buf, sizeof(buf), 0);
1720 err = forward_dns_reply(buf, len, IPPROTO_UDP, data);
1727 static gboolean tcp_server_event(GIOChannel *channel, GIOCondition condition,
1731 struct server_data *server = user_data;
1733 sk = g_io_channel_unix_get_fd(channel);
1737 if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
1740 DBG("TCP server channel closed");
1743 * Discard any partial response which is buffered; better
1744 * to get a proper response from a working server.
1746 g_free(server->incoming_reply);
1747 server->incoming_reply = NULL;
1749 for (list = request_list; list; list = list->next) {
1750 struct request_data *req = list->data;
1751 struct domain_hdr *hdr;
1753 if (req->protocol == IPPROTO_UDP)
1756 if (req->request == NULL)
1760 * If we're not waiting for any further response
1761 * from another name server, then we send an error
1762 * response to the client.
1764 if (req->numserv && --(req->numserv))
1767 hdr = (void *) (req->request + 2);
1768 hdr->id = req->srcid;
1769 send_response(req->client_sk, req->request,
1770 req->request_len, NULL, 0, IPPROTO_TCP);
1772 request_list = g_slist_remove(request_list, req);
1775 destroy_server(server);
1780 if ((condition & G_IO_OUT) && !server->connected) {
1783 struct server_data *udp_server;
1785 udp_server = find_server(server->interface, server->server,
1787 if (udp_server != NULL) {
1788 for (domains = udp_server->domains; domains;
1789 domains = domains->next) {
1790 char *dom = domains->data;
1792 DBG("Adding domain %s to %s",
1793 dom, server->server);
1795 server->domains = g_list_append(server->domains,
1800 server->connected = TRUE;
1801 server_list = g_slist_append(server_list, server);
1803 if (server->timeout > 0) {
1804 g_source_remove(server->timeout);
1805 server->timeout = 0;
1808 for (list = request_list; list; list = list->next) {
1809 struct request_data *req = list->data;
1811 if (req->protocol == IPPROTO_UDP)
1814 DBG("Sending req %s over TCP", (char *)req->name);
1816 if (req->timeout > 0)
1817 g_source_remove(req->timeout);
1819 req->timeout = g_timeout_add_seconds(30,
1820 request_timeout, req);
1821 if (ns_resolv(server, req, req->request,
1823 /* We sent cached result so no need for timeout
1826 if (req->timeout > 0) {
1827 g_source_remove(req->timeout);
1833 } else if (condition & G_IO_IN) {
1834 struct partial_reply *reply = server->incoming_reply;
1838 unsigned char reply_len_buf[2];
1841 bytes_recv = recv(sk, reply_len_buf, 2, MSG_PEEK);
1844 } else if (bytes_recv < 0) {
1845 if (errno == EAGAIN || errno == EWOULDBLOCK)
1848 connman_error("DNS proxy error %s",
1851 } else if (bytes_recv < 2)
1854 reply_len = reply_len_buf[1] | reply_len_buf[0] << 8;
1857 DBG("TCP reply %d bytes", reply_len);
1859 reply = g_try_malloc(sizeof(*reply) + reply_len + 2);
1863 reply->len = reply_len;
1864 reply->received = 0;
1866 server->incoming_reply = reply;
1869 while (reply->received < reply->len) {
1870 bytes_recv = recv(sk, reply->buf + reply->received,
1871 reply->len - reply->received, 0);
1873 connman_error("DNS proxy TCP disconnect");
1875 } else if (bytes_recv < 0) {
1876 if (errno == EAGAIN || errno == EWOULDBLOCK)
1879 connman_error("DNS proxy error %s",
1883 reply->received += bytes_recv;
1886 forward_dns_reply(reply->buf, reply->received, IPPROTO_TCP,
1890 server->incoming_reply = NULL;
1892 destroy_server(server);
1900 static gboolean tcp_idle_timeout(gpointer user_data)
1902 struct server_data *server = user_data;
1909 destroy_server(server);
1914 static struct server_data *create_server(const char *interface,
1915 const char *domain, const char *server,
1918 struct addrinfo hints, *rp;
1919 struct server_data *data;
1922 DBG("interface %s server %s", interface, server);
1924 memset(&hints, 0, sizeof(hints));
1928 hints.ai_socktype = SOCK_DGRAM;
1932 hints.ai_socktype = SOCK_STREAM;
1938 hints.ai_family = AF_UNSPEC;
1939 hints.ai_flags = AI_PASSIVE | AI_NUMERICSERV | AI_NUMERICHOST;
1941 ret = getaddrinfo(server, "53", &hints, &rp);
1943 connman_error("Failed to parse server %s address: %s\n",
1944 server, gai_strerror(ret));
1947 /* Do not blindly copy this code elsewhere; it doesn't loop over the
1948 results using ->ai_next as it should. That's OK in *this* case
1949 because it was a numeric lookup; we *know* there's only one. */
1951 sk = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
1953 connman_error("Failed to create server %s socket", server);
1958 if (interface != NULL) {
1959 if (setsockopt(sk, SOL_SOCKET, SO_BINDTODEVICE,
1960 interface, strlen(interface) + 1) < 0) {
1961 connman_error("Failed to bind server %s "
1970 data = g_try_new0(struct server_data, 1);
1972 connman_error("Failed to allocate server %s data", server);
1978 data->channel = g_io_channel_unix_new(sk);
1979 if (data->channel == NULL) {
1980 connman_error("Failed to create server %s channel", server);
1987 g_io_channel_set_close_on_unref(data->channel, TRUE);
1989 if (protocol == IPPROTO_TCP) {
1990 g_io_channel_set_flags(data->channel, G_IO_FLAG_NONBLOCK, NULL);
1991 data->watch = g_io_add_watch(data->channel,
1992 G_IO_OUT | G_IO_IN | G_IO_HUP | G_IO_NVAL | G_IO_ERR,
1993 tcp_server_event, data);
1994 data->timeout = g_timeout_add_seconds(30, tcp_idle_timeout,
1997 data->watch = g_io_add_watch(data->channel,
1998 G_IO_IN | G_IO_NVAL | G_IO_ERR | G_IO_HUP,
1999 udp_server_event, data);
2001 data->interface = g_strdup(interface);
2003 data->domains = g_list_append(data->domains, g_strdup(domain));
2004 data->server = g_strdup(server);
2005 data->protocol = protocol;
2007 ret = connect(sk, rp->ai_addr, rp->ai_addrlen);
2010 if ((protocol == IPPROTO_TCP && errno != EINPROGRESS) ||
2011 protocol == IPPROTO_UDP) {
2014 connman_error("Failed to connect to server %s", server);
2015 if (data->watch > 0)
2016 g_source_remove(data->watch);
2017 if (data->timeout > 0)
2018 g_source_remove(data->timeout);
2020 g_io_channel_unref(data->channel);
2023 g_free(data->server);
2024 g_free(data->interface);
2025 for (list = data->domains; list; list = list->next) {
2026 char *domain = list->data;
2028 data->domains = g_list_remove(data->domains,
2037 if (__sync_fetch_and_add(&cache_refcount, 1) == 0)
2038 cache = g_hash_table_new_full(g_str_hash,
2041 cache_element_destroy);
2043 if (protocol == IPPROTO_UDP) {
2044 /* Enable new servers by default */
2045 data->enabled = TRUE;
2046 DBG("Adding DNS server %s", data->server);
2048 server_list = g_slist_append(server_list, data);
2056 static gboolean resolv(struct request_data *req,
2057 gpointer request, gpointer name)
2061 for (list = server_list; list; list = list->next) {
2062 struct server_data *data = list->data;
2064 DBG("server %s enabled %d", data->server, data->enabled);
2066 if (data->enabled == FALSE)
2069 if (data->watch == 0 && data->protocol == IPPROTO_UDP)
2070 data->watch = g_io_add_watch(data->channel,
2071 G_IO_IN | G_IO_NVAL | G_IO_ERR | G_IO_HUP,
2072 udp_server_event, data);
2074 if (ns_resolv(data, req, request, name) > 0)
2081 static void append_domain(const char *interface, const char *domain)
2085 DBG("interface %s domain %s", interface, domain);
2090 for (list = server_list; list; list = list->next) {
2091 struct server_data *data = list->data;
2094 gboolean dom_found = FALSE;
2096 if (data->interface == NULL)
2099 if (g_str_equal(data->interface, interface) == FALSE)
2102 for (dom_list = data->domains; dom_list;
2103 dom_list = dom_list->next) {
2104 dom = dom_list->data;
2106 if (g_str_equal(dom, domain)) {
2112 if (dom_found == FALSE) {
2114 g_list_append(data->domains, g_strdup(domain));
2119 int __connman_dnsproxy_append(const char *interface, const char *domain,
2122 struct server_data *data;
2124 DBG("interface %s server %s", interface, server);
2126 if (server == NULL && domain == NULL)
2129 if (server == NULL) {
2130 append_domain(interface, domain);
2135 if (g_str_equal(server, "127.0.0.1") == TRUE)
2138 data = find_server(interface, server, IPPROTO_UDP);
2140 append_domain(interface, domain);
2144 data = create_server(interface, domain, server, IPPROTO_UDP);
2151 static void remove_server(const char *interface, const char *domain,
2152 const char *server, int protocol)
2154 struct server_data *data;
2156 data = find_server(interface, server, protocol);
2160 destroy_server(data);
2163 int __connman_dnsproxy_remove(const char *interface, const char *domain,
2166 DBG("interface %s server %s", interface, server);
2171 if (g_str_equal(server, "127.0.0.1") == TRUE)
2174 remove_server(interface, domain, server, IPPROTO_UDP);
2175 remove_server(interface, domain, server, IPPROTO_TCP);
2180 void __connman_dnsproxy_flush(void)
2184 list = request_pending_list;
2186 struct request_data *req = list->data;
2190 request_pending_list =
2191 g_slist_remove(request_pending_list, req);
2192 resolv(req, req->request, req->name);
2193 g_free(req->request);
2198 static void dnsproxy_offline_mode(connman_bool_t enabled)
2202 DBG("enabled %d", enabled);
2204 for (list = server_list; list; list = list->next) {
2205 struct server_data *data = list->data;
2207 if (enabled == FALSE) {
2208 DBG("Enabling DNS server %s", data->server);
2209 data->enabled = TRUE;
2213 DBG("Disabling DNS server %s", data->server);
2214 data->enabled = FALSE;
2220 static void dnsproxy_default_changed(struct connman_service *service)
2225 DBG("service %p", service);
2227 /* DNS has changed, invalidate the cache */
2230 if (service == NULL) {
2231 /* When no services are active, then disable DNS proxying */
2232 dnsproxy_offline_mode(TRUE);
2236 interface = connman_service_get_interface(service);
2237 if (interface == NULL)
2240 for (list = server_list; list; list = list->next) {
2241 struct server_data *data = list->data;
2243 if (g_strcmp0(data->interface, interface) == 0) {
2244 DBG("Enabling DNS server %s", data->server);
2245 data->enabled = TRUE;
2247 DBG("Disabling DNS server %s", data->server);
2248 data->enabled = FALSE;
2256 static struct connman_notifier dnsproxy_notifier = {
2258 .default_changed = dnsproxy_default_changed,
2259 .offline_mode = dnsproxy_offline_mode,
2262 static unsigned char opt_edns0_type[2] = { 0x00, 0x29 };
2264 static int parse_request(unsigned char *buf, int len,
2265 char *name, unsigned int size)
2267 struct domain_hdr *hdr = (void *) buf;
2268 uint16_t qdcount = ntohs(hdr->qdcount);
2269 uint16_t arcount = ntohs(hdr->arcount);
2271 char *last_label = NULL;
2272 unsigned int remain, used = 0;
2277 DBG("id 0x%04x qr %d opcode %d qdcount %d arcount %d",
2278 hdr->id, hdr->qr, hdr->opcode,
2281 if (hdr->qr != 0 || qdcount != 1)
2286 ptr = buf + sizeof(struct domain_hdr);
2287 remain = len - sizeof(struct domain_hdr);
2289 while (remain > 0) {
2293 last_label = (char *) (ptr + 1);
2297 if (used + len + 1 > size)
2300 strncat(name, (char *) (ptr + 1), len);
2309 if (last_label && arcount && remain >= 9 && last_label[4] == 0 &&
2310 !memcmp(last_label + 5, opt_edns0_type, 2)) {
2311 uint16_t edns0_bufsize;
2313 edns0_bufsize = last_label[7] << 8 | last_label[8];
2315 DBG("EDNS0 buffer size %u", edns0_bufsize);
2317 /* This is an evil hack until full TCP support has been
2320 * Somtimes the EDNS0 request gets send with a too-small
2321 * buffer size. Since glibc doesn't seem to crash when it
2322 * gets a response biffer then it requested, just bump
2323 * the buffer size up to 4KiB.
2325 if (edns0_bufsize < 0x1000) {
2326 last_label[7] = 0x10;
2327 last_label[8] = 0x00;
2331 DBG("query %s", name);
2336 static gboolean tcp_listener_event(GIOChannel *channel, GIOCondition condition,
2339 unsigned char buf[768];
2341 struct request_data *req;
2342 struct server_data *server;
2343 int sk, client_sk, len, err;
2344 struct sockaddr_in6 client_addr;
2345 socklen_t client_addr_len = sizeof(client_addr);
2347 struct listener_data *ifdata = user_data;
2349 DBG("condition 0x%x", condition);
2351 if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
2352 if (ifdata->tcp_listener_watch > 0)
2353 g_source_remove(ifdata->tcp_listener_watch);
2354 ifdata->tcp_listener_watch = 0;
2356 connman_error("Error with TCP listener channel");
2361 sk = g_io_channel_unix_get_fd(channel);
2363 client_sk = accept(sk, (void *)&client_addr, &client_addr_len);
2364 if (client_sk < 0) {
2365 connman_error("Accept failure on TCP listener");
2366 ifdata->tcp_listener_watch = 0;
2370 len = recv(client_sk, buf, sizeof(buf), 0);
2374 DBG("Received %d bytes (id 0x%04x)", len, buf[2] | buf[3] << 8);
2376 err = parse_request(buf + 2, len - 2, query, sizeof(query));
2377 if (err < 0 || (g_slist_length(server_list) == 0)) {
2378 send_response(client_sk, buf, len, NULL, 0, IPPROTO_TCP);
2382 req = g_try_new0(struct request_data, 1);
2386 memcpy(&req->sa, &client_addr, client_addr_len);
2387 req->sa_len = client_addr_len;
2388 req->client_sk = client_sk;
2389 req->protocol = IPPROTO_TCP;
2391 req->srcid = buf[2] | (buf[3] << 8);
2392 req->dstid = get_id();
2393 req->altid = get_id();
2394 req->request_len = len;
2396 buf[2] = req->dstid & 0xff;
2397 buf[3] = req->dstid >> 8;
2400 req->ifdata = (struct listener_data *) ifdata;
2401 req->append_domain = FALSE;
2402 request_list = g_slist_append(request_list, req);
2404 for (list = server_list; list; list = list->next) {
2405 struct server_data *data = list->data;
2408 if (data->protocol != IPPROTO_UDP || data->enabled == FALSE)
2411 server = create_server(data->interface, NULL,
2412 data->server, IPPROTO_TCP);
2415 * If server is NULL, we're not connected yet.
2416 * Copy the relevant buffers and continue with
2417 * the next nameserver.
2418 * The request will actually be sent once we're
2419 * properly connected over TCP to this nameserver.
2421 if (server == NULL) {
2422 req->request = g_try_malloc0(req->request_len);
2423 if (req->request == NULL)
2426 memcpy(req->request, buf, req->request_len);
2428 req->name = g_try_malloc0(sizeof(query));
2429 if (req->name == NULL) {
2430 g_free(req->request);
2433 memcpy(req->name, query, sizeof(query));
2438 if (req->timeout > 0)
2439 g_source_remove(req->timeout);
2441 for (domains = data->domains; domains;
2442 domains = domains->next) {
2443 char *dom = domains->data;
2445 DBG("Adding domain %s to %s", dom, server->server);
2447 server->domains = g_list_append(server->domains,
2451 req->timeout = g_timeout_add_seconds(30, request_timeout, req);
2452 if (ns_resolv(server, req, buf, query) > 0) {
2453 if (req->timeout > 0) {
2454 g_source_remove(req->timeout);
2463 static gboolean udp_listener_event(GIOChannel *channel, GIOCondition condition,
2466 unsigned char buf[768];
2468 struct request_data *req;
2469 struct sockaddr_in6 client_addr;
2470 socklen_t client_addr_len = sizeof(client_addr);
2472 struct listener_data *ifdata = user_data;
2474 if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
2475 connman_error("Error with UDP listener channel");
2476 ifdata->udp_listener_watch = 0;
2480 sk = g_io_channel_unix_get_fd(channel);
2482 memset(&client_addr, 0, client_addr_len);
2483 len = recvfrom(sk, buf, sizeof(buf), 0, (void *)&client_addr,
2488 DBG("Received %d bytes (id 0x%04x)", len, buf[0] | buf[1] << 8);
2490 err = parse_request(buf, len, query, sizeof(query));
2491 if (err < 0 || (g_slist_length(server_list) == 0)) {
2492 send_response(sk, buf, len, (void *)&client_addr,
2493 client_addr_len, IPPROTO_UDP);
2497 req = g_try_new0(struct request_data, 1);
2501 memcpy(&req->sa, &client_addr, client_addr_len);
2502 req->sa_len = client_addr_len;
2504 req->protocol = IPPROTO_UDP;
2506 req->srcid = buf[0] | (buf[1] << 8);
2507 req->dstid = get_id();
2508 req->altid = get_id();
2509 req->request_len = len;
2511 buf[0] = req->dstid & 0xff;
2512 buf[1] = req->dstid >> 8;
2515 req->ifdata = (struct listener_data *) ifdata;
2516 req->append_domain = FALSE;
2518 if (resolv(req, buf, query) == TRUE) {
2519 /* a cached result was sent, so the request can be released */
2524 req->timeout = g_timeout_add_seconds(5, request_timeout, req);
2525 request_list = g_slist_append(request_list, req);
2530 static int create_dns_listener(int protocol, struct listener_data *ifdata)
2532 GIOChannel *channel;
2536 struct sockaddr_in6 sin6;
2537 struct sockaddr_in sin;
2540 int sk, type, v6only = 0;
2541 int family = AF_INET6;
2544 DBG("interface %s", ifdata->ifname);
2549 type = SOCK_DGRAM | SOCK_CLOEXEC;
2554 type = SOCK_STREAM | SOCK_CLOEXEC;
2561 sk = socket(family, type, protocol);
2562 if (sk < 0 && family == AF_INET6 && errno == EAFNOSUPPORT) {
2563 connman_error("No IPv6 support; DNS proxy listening only on Legacy IP");
2565 sk = socket(family, type, protocol);
2568 connman_error("Failed to create %s listener socket", proto);
2572 if (setsockopt(sk, SOL_SOCKET, SO_BINDTODEVICE,
2574 strlen(ifdata->ifname) + 1) < 0) {
2575 connman_error("Failed to bind %s listener interface", proto);
2579 /* Ensure it accepts Legacy IP connections too */
2580 if (family == AF_INET6 &&
2581 setsockopt(sk, SOL_IPV6, IPV6_V6ONLY,
2582 &v6only, sizeof(v6only)) < 0) {
2583 connman_error("Failed to clear V6ONLY on %s listener socket",
2589 if (family == AF_INET) {
2590 memset(&s.sin, 0, sizeof(s.sin));
2591 s.sin.sin_family = AF_INET;
2592 s.sin.sin_port = htons(53);
2593 s.sin.sin_addr.s_addr = htonl(INADDR_ANY);
2594 slen = sizeof(s.sin);
2596 memset(&s.sin6, 0, sizeof(s.sin6));
2597 s.sin6.sin6_family = AF_INET6;
2598 s.sin6.sin6_port = htons(53);
2599 s.sin6.sin6_addr = in6addr_any;
2600 slen = sizeof(s.sin6);
2603 if (bind(sk, &s.sa, slen) < 0) {
2604 connman_error("Failed to bind %s listener socket", proto);
2609 if (protocol == IPPROTO_TCP && listen(sk, 10) < 0) {
2610 connman_error("Failed to listen on TCP socket");
2615 channel = g_io_channel_unix_new(sk);
2616 if (channel == NULL) {
2617 connman_error("Failed to create %s listener channel", proto);
2622 g_io_channel_set_close_on_unref(channel, TRUE);
2624 if (protocol == IPPROTO_TCP) {
2625 ifdata->tcp_listener_channel = channel;
2626 ifdata->tcp_listener_watch = g_io_add_watch(channel,
2627 G_IO_IN, tcp_listener_event, (gpointer) ifdata);
2629 ifdata->udp_listener_channel = channel;
2630 ifdata->udp_listener_watch = g_io_add_watch(channel,
2631 G_IO_IN, udp_listener_event, (gpointer) ifdata);
2637 static void destroy_udp_listener(struct listener_data *ifdata)
2639 DBG("interface %s", ifdata->ifname);
2641 if (ifdata->udp_listener_watch > 0)
2642 g_source_remove(ifdata->udp_listener_watch);
2644 g_io_channel_unref(ifdata->udp_listener_channel);
2647 static void destroy_tcp_listener(struct listener_data *ifdata)
2649 DBG("interface %s", ifdata->ifname);
2651 if (ifdata->tcp_listener_watch > 0)
2652 g_source_remove(ifdata->tcp_listener_watch);
2654 g_io_channel_unref(ifdata->tcp_listener_channel);
2657 static int create_listener(struct listener_data *ifdata)
2661 err = create_dns_listener(IPPROTO_UDP, ifdata);
2665 err = create_dns_listener(IPPROTO_TCP, ifdata);
2667 destroy_udp_listener(ifdata);
2671 if (g_strcmp0(ifdata->ifname, "lo") == 0)
2672 __connman_resolvfile_append("lo", NULL, "127.0.0.1");
2677 static void destroy_request_data(struct request_data *req)
2679 if (req->timeout > 0)
2680 g_source_remove(req->timeout);
2683 g_free(req->request);
2688 static void destroy_listener(struct listener_data *ifdata)
2692 if (g_strcmp0(ifdata->ifname, "lo") == 0)
2693 __connman_resolvfile_remove("lo", NULL, "127.0.0.1");
2695 for (list = request_pending_list; list; list = list->next) {
2696 struct request_data *req = list->data;
2698 DBG("Dropping pending request (id 0x%04x -> 0x%04x)",
2699 req->srcid, req->dstid);
2700 destroy_request_data(req);
2704 g_slist_free(request_pending_list);
2705 request_pending_list = NULL;
2707 for (list = request_list; list; list = list->next) {
2708 struct request_data *req = list->data;
2710 DBG("Dropping request (id 0x%04x -> 0x%04x)",
2711 req->srcid, req->dstid);
2712 destroy_request_data(req);
2716 g_slist_free(request_list);
2717 request_list = NULL;
2719 destroy_tcp_listener(ifdata);
2720 destroy_udp_listener(ifdata);
2723 int __connman_dnsproxy_add_listener(const char *interface)
2725 struct listener_data *ifdata;
2728 DBG("interface %s", interface);
2730 if (g_hash_table_lookup(listener_table, interface) != NULL)
2733 ifdata = g_try_new0(struct listener_data, 1);
2737 ifdata->ifname = g_strdup(interface);
2738 ifdata->udp_listener_channel = NULL;
2739 ifdata->udp_listener_watch = 0;
2740 ifdata->tcp_listener_channel = NULL;
2741 ifdata->tcp_listener_watch = 0;
2743 err = create_listener(ifdata);
2745 connman_error("Couldn't create listener for %s err %d",
2747 g_free(ifdata->ifname);
2751 g_hash_table_insert(listener_table, ifdata->ifname, ifdata);
2755 void __connman_dnsproxy_remove_listener(const char *interface)
2757 struct listener_data *ifdata;
2759 DBG("interface %s", interface);
2761 ifdata = g_hash_table_lookup(listener_table, interface);
2765 destroy_listener(ifdata);
2767 g_hash_table_remove(listener_table, interface);
2770 static void remove_listener(gpointer key, gpointer value, gpointer user_data)
2772 const char *interface = key;
2773 struct listener_data *ifdata = value;
2775 DBG("interface %s", interface);
2777 destroy_listener(ifdata);
2780 int __connman_dnsproxy_init(void)
2786 srandom(time(NULL));
2788 listener_table = g_hash_table_new_full(g_str_hash, g_str_equal,
2790 err = __connman_dnsproxy_add_listener("lo");
2794 err = connman_notifier_register(&dnsproxy_notifier);
2801 __connman_dnsproxy_remove_listener("lo");
2802 g_hash_table_destroy(listener_table);
2807 void __connman_dnsproxy_cleanup(void)
2811 connman_notifier_unregister(&dnsproxy_notifier);
2813 g_hash_table_foreach(listener_table, remove_listener, NULL);
2815 g_hash_table_destroy(listener_table);