5 * Copyright (C) 2007-2010 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
30 #include <arpa/inet.h>
31 #include <netinet/in.h>
32 #include <sys/types.h>
33 #include <sys/socket.h>
36 #include <gweb/gresolv.h>
42 #if __BYTE_ORDER == __LITTLE_ENDIAN
57 } __attribute__ ((packed));
58 #elif __BYTE_ORDER == __BIG_ENDIAN
73 } __attribute__ ((packed));
75 #error "Unknown byte order"
78 struct partial_reply {
94 struct partial_reply *incoming_reply;
99 struct sockaddr_in6 __sin6; /* Only for the length */
117 struct listener_data *ifdata;
118 gboolean append_domain;
121 struct listener_data {
123 GIOChannel *udp_listener_channel;
124 guint udp_listener_watch;
125 GIOChannel *tcp_listener_channel;
126 guint tcp_listener_watch;
136 unsigned int data_len;
137 unsigned char *data; /* contains DNS header + body */
144 struct cache_data *ipv4;
145 struct cache_data *ipv6;
148 struct domain_question {
151 } __attribute__ ((packed));
158 } __attribute__ ((packed));
161 * We limit how long the cached DNS entry stays in the cache.
162 * By default the TTL (time-to-live) of the DNS response is used
163 * when setting the cache entry life time. The value is in seconds.
165 #define MAX_CACHE_TTL (60 * 30)
167 * Also limit the other end, cache at least for 30 seconds.
169 #define MIN_CACHE_TTL (30)
172 * We limit the cache size to some sane value so that cached data does
173 * not occupy too much memory. Each cached entry occupies on average
174 * about 100 bytes memory (depending on DNS name length).
175 * Example: caching www.connman.net uses 97 bytes memory.
176 * The value is the max amount of cached DNS responses (count).
178 #define MAX_CACHE_SIZE 256
180 static int cache_size;
181 static GHashTable *cache;
182 static int cache_refcount;
183 static GSList *server_list = NULL;
184 static GSList *request_list = NULL;
185 static GSList *request_pending_list = NULL;
186 static guint16 request_id = 0x0000;
187 static GHashTable *listener_table = NULL;
188 static time_t next_refresh;
190 static int protocol_offset(int protocol)
206 * There is a power and efficiency benefit to have entries
207 * in our cache expire at the same time. To this extend,
208 * we round down the cache valid time to common boundaries.
210 static time_t round_down_ttl(time_t end_time, int ttl)
215 /* Less than 5 minutes, round to 10 second boundary */
217 end_time = end_time / 10;
218 end_time = end_time * 10;
219 } else { /* 5 or more minutes, round to 30 seconds */
220 end_time = end_time / 30;
221 end_time = end_time * 30;
226 static struct request_data *find_request(guint16 id)
230 for (list = request_list; list; list = list->next) {
231 struct request_data *req = list->data;
233 if (req->dstid == id || req->altid == id)
240 static struct server_data *find_server(const char *interface,
246 DBG("interface %s server %s", interface, server);
248 for (list = server_list; list; list = list->next) {
249 struct server_data *data = list->data;
251 if (interface == NULL && data->interface == NULL &&
252 g_str_equal(data->server, server) == TRUE &&
253 data->protocol == protocol)
256 if (interface == NULL ||
257 data->interface == NULL || data->server == NULL)
260 if (g_str_equal(data->interface, interface) == TRUE &&
261 g_str_equal(data->server, server) == TRUE &&
262 data->protocol == protocol)
269 /* we can keep using the same resolve's */
270 static GResolv *ipv4_resolve;
271 static GResolv *ipv6_resolve;
273 static void dummy_resolve_func(GResolvResultStatus status,
274 char **results, gpointer user_data)
279 * Refresh a DNS entry, but also age the hit count a bit */
280 static void refresh_dns_entry(struct cache_entry *entry, char *name)
284 if (ipv4_resolve == NULL) {
285 ipv4_resolve = g_resolv_new(0);
286 g_resolv_set_address_family(ipv4_resolve, AF_INET);
287 g_resolv_add_nameserver(ipv4_resolve, "127.0.0.1", 53, 0);
290 if (ipv6_resolve == NULL) {
291 ipv6_resolve = g_resolv_new(0);
292 g_resolv_set_address_family(ipv6_resolve, AF_INET6);
293 g_resolv_add_nameserver(ipv6_resolve, "127.0.0.1", 53, 0);
296 if (entry->ipv4 == NULL) {
297 DBG("Refresing A record for %s", name);
298 g_resolv_lookup_hostname(ipv4_resolve, name,
299 dummy_resolve_func, NULL);
303 if (entry->ipv6 == NULL) {
304 DBG("Refresing AAAA record for %s", name);
305 g_resolv_lookup_hostname(ipv6_resolve, name,
306 dummy_resolve_func, NULL);
315 static int dns_name_length(unsigned char *buf)
317 if ((buf[0] & NS_CMPRSFLGS) == NS_CMPRSFLGS) /* compressed name */
319 return strlen((char *)buf);
322 static void update_cached_ttl(unsigned char *buf, int len, int new_ttl)
329 /* skip the header */
333 /* skip the query, which is a name and 2 16 bit words */
334 l = dns_name_length(c);
340 /* now we get the answer records */
344 l = dns_name_length(c);
349 /* then type + class, 2 bytes each */
355 /* now the 4 byte TTL field */
363 /* now the 2 byte rdlen field */
366 len -= ntohs(*w) + 2;
370 static void send_cached_response(int sk, unsigned char *buf, int len,
371 const struct sockaddr *to, socklen_t tolen,
372 int protocol, int id, uint16_t answers, int ttl)
374 struct domain_hdr *hdr;
375 int err, offset = protocol_offset(protocol);
383 hdr = (void *) (buf + offset);
388 hdr->ancount = htons(answers);
392 /* if this is a negative reply, we are authorative */
396 update_cached_ttl(buf, len, ttl);
398 DBG("id 0x%04x answers %d", hdr->id, answers);
400 err = sendto(sk, buf, len, 0, to, tolen);
402 connman_error("Cannot send cached DNS response: %s",
408 static void send_response(int sk, unsigned char *buf, int len,
409 const struct sockaddr *to, socklen_t tolen,
412 struct domain_hdr *hdr;
413 int err, offset = protocol_offset(protocol);
423 hdr = (void *) (buf + offset);
425 DBG("id 0x%04x qr %d opcode %d", hdr->id, hdr->qr, hdr->opcode);
434 err = sendto(sk, buf, len, 0, to, tolen);
436 connman_error("Failed to send DNS response: %s",
442 static gboolean request_timeout(gpointer user_data)
444 struct request_data *req = user_data;
445 struct listener_data *ifdata;
447 DBG("id 0x%04x", req->srcid);
452 ifdata = req->ifdata;
454 request_list = g_slist_remove(request_list, req);
457 if (req->resplen > 0 && req->resp != NULL) {
460 sk = g_io_channel_unix_get_fd(ifdata->udp_listener_channel);
462 err = sendto(sk, req->resp, req->resplen, 0,
463 &req->sa, req->sa_len);
466 } else if (req->request && req->numserv == 0) {
467 struct domain_hdr *hdr;
469 if (req->protocol == IPPROTO_TCP) {
470 hdr = (void *) (req->request + 2);
471 hdr->id = req->srcid;
472 send_response(req->client_sk, req->request,
473 req->request_len, NULL, 0, IPPROTO_TCP);
475 } else if (req->protocol == IPPROTO_UDP) {
478 hdr = (void *) (req->request);
479 hdr->id = req->srcid;
480 sk = g_io_channel_unix_get_fd(
481 ifdata->udp_listener_channel);
482 send_response(sk, req->request, req->request_len,
483 &req->sa, req->sa_len, IPPROTO_UDP);
493 static int append_query(unsigned char *buf, unsigned int size,
494 const char *query, const char *domain)
496 unsigned char *ptr = buf;
500 DBG("query %s domain %s", query, domain);
502 offset = (char *) query;
503 while (offset != NULL) {
506 tmp = strchr(offset, '.');
508 len = strlen(offset);
512 memcpy(ptr + 1, offset, len);
518 memcpy(ptr + 1, offset, tmp - offset);
519 ptr += tmp - offset + 1;
524 offset = (char *) domain;
525 while (offset != NULL) {
528 tmp = strchr(offset, '.');
530 len = strlen(offset);
534 memcpy(ptr + 1, offset, len);
540 memcpy(ptr + 1, offset, tmp - offset);
541 ptr += tmp - offset + 1;
551 static gboolean cache_check_is_valid(struct cache_data *data,
557 if (data->cache_until < current_time)
564 * remove stale cached entries so that they can be refreshed
566 static void cache_enforce_validity(struct cache_entry *entry)
568 time_t current_time = time(NULL);
570 if (cache_check_is_valid(entry->ipv4, current_time) == FALSE
572 DBG("cache timeout \"%s\" type A", entry->key);
573 g_free(entry->ipv4->data);
579 if (cache_check_is_valid(entry->ipv6, current_time) == FALSE
581 DBG("cache timeout \"%s\" type AAAA", entry->key);
582 g_free(entry->ipv6->data);
588 static uint16_t cache_check_validity(char *question, uint16_t type,
589 struct cache_entry *entry)
591 time_t current_time = time(NULL);
592 int want_refresh = 0;
595 * if we have a popular entry, we want a refresh instead of
596 * total destruction of the entry.
601 cache_enforce_validity(entry);
605 if (cache_check_is_valid(entry->ipv4, current_time) == FALSE) {
606 DBG("cache %s \"%s\" type A", entry->ipv4 ?
607 "timeout" : "entry missing", question);
610 entry->want_refresh = 1;
613 * We do not remove cache entry if there is still
614 * valid IPv6 entry found in the cache.
616 if (cache_check_is_valid(entry->ipv6, current_time)
617 == FALSE && want_refresh == FALSE) {
618 g_hash_table_remove(cache, question);
625 if (cache_check_is_valid(entry->ipv6, current_time) == FALSE) {
626 DBG("cache %s \"%s\" type AAAA", entry->ipv6 ?
627 "timeout" : "entry missing", question);
630 entry->want_refresh = 1;
632 if (cache_check_is_valid(entry->ipv4, current_time)
633 == FALSE && want_refresh == FALSE) {
634 g_hash_table_remove(cache, question);
644 static struct cache_entry *cache_check(gpointer request, int *qtype)
646 char *question = request + 12;
647 struct cache_entry *entry;
648 struct domain_question *q;
652 offset = strlen(question) + 1;
653 q = (void *) (question + offset);
654 type = ntohs(q->type);
656 /* We only cache either A (1) or AAAA (28) requests */
657 if (type != 1 && type != 28)
660 entry = g_hash_table_lookup(cache, question);
664 type = cache_check_validity(question, type, entry);
673 * Get a label/name from DNS resource record. The function decompresses the
674 * label if necessary. The function does not convert the name to presentation
675 * form. This means that the result string will contain label lengths instead
676 * of dots between labels. We intentionally do not want to convert to dotted
677 * format so that we can cache the wire format string directly.
679 static int get_name(int counter,
680 unsigned char *pkt, unsigned char *start, unsigned char *max,
681 unsigned char *output, int output_max, int *output_len,
682 unsigned char **end, char *name, int *name_len)
686 /* Limit recursion to 10 (this means up to 10 labels in domain name) */
692 if ((*p & NS_CMPRSFLGS) == NS_CMPRSFLGS) {
693 uint16_t offset = (*p & 0x3F) * 256 + *(p + 1);
695 if (offset >= max - pkt)
701 return get_name(counter + 1, pkt, pkt + offset, max,
702 output, output_max, output_len, end,
705 unsigned label_len = *p;
707 if (pkt + label_len > max)
710 if (*output_len > output_max)
714 * We need the original name in order to check
715 * if this answer is the correct one.
717 name[(*name_len)++] = label_len;
718 memcpy(name + *name_len, p + 1, label_len + 1);
719 *name_len += label_len;
721 /* We compress the result */
722 output[0] = NS_CMPRSFLGS;
739 static int parse_rr(unsigned char *buf, unsigned char *start,
741 unsigned char *response, unsigned int *response_size,
742 uint16_t *type, uint16_t *class, int *ttl, int *rdlen,
746 struct domain_rr *rr;
748 int name_len = 0, output_len = 0, max_rsp = *response_size;
750 err = get_name(0, buf, start, max, response, max_rsp,
751 &output_len, end, name, &name_len);
757 if ((unsigned int) offset > *response_size)
760 rr = (void *) (*end);
765 *type = ntohs(rr->type);
766 *class = ntohs(rr->class);
767 *ttl = ntohl(rr->ttl);
768 *rdlen = ntohs(rr->rdlen);
773 memcpy(response + offset, *end, sizeof(struct domain_rr));
775 offset += sizeof(struct domain_rr);
776 *end += sizeof(struct domain_rr);
778 if ((unsigned int) (offset + *rdlen) > *response_size)
781 memcpy(response + offset, *end, *rdlen);
785 *response_size = offset + *rdlen;
790 static gboolean check_alias(GSList *aliases, char *name)
794 if (aliases != NULL) {
795 for (list = aliases; list; list = list->next) {
796 int len = strlen((char *)list->data);
797 if (strncmp((char *)list->data, name, len) == 0)
805 static int parse_response(unsigned char *buf, int buflen,
806 char *question, int qlen,
807 uint16_t *type, uint16_t *class, int *ttl,
808 unsigned char *response, unsigned int *response_len,
811 struct domain_hdr *hdr = (void *) buf;
812 struct domain_question *q;
814 uint16_t qdcount = ntohs(hdr->qdcount);
815 uint16_t ancount = ntohs(hdr->ancount);
817 uint16_t qtype, qclass;
818 unsigned char *next = NULL;
819 unsigned int maxlen = *response_len;
820 GSList *aliases = NULL, *list;
821 char name[NS_MAXDNAME + 1];
826 DBG("qr %d qdcount %d", hdr->qr, qdcount);
828 /* We currently only cache responses where question count is 1 */
829 if (hdr->qr != 1 || qdcount != 1)
832 ptr = buf + sizeof(struct domain_hdr);
834 strncpy(question, (char *) ptr, qlen);
835 qlen = strlen(question);
836 ptr += qlen + 1; /* skip \0 */
839 qtype = ntohs(q->type);
841 /* We cache only A and AAAA records */
842 if (qtype != 1 && qtype != 28)
845 qclass = ntohs(q->class);
847 ptr += 2 + 2; /* ptr points now to answers */
854 * We have a bunch of answers (like A, AAAA, CNAME etc) to
855 * A or AAAA question. We traverse the answers and parse the
856 * resource records. Only A and AAAA records are cached, all
857 * the other records in answers are skipped.
859 for (i = 0; i < ancount; i++) {
861 * Get one address at a time to this buffer.
862 * The max size of the answer is
863 * 2 (pointer) + 2 (type) + 2 (class) +
864 * 4 (ttl) + 2 (rdlen) + addr (16 or 4) = 28
865 * for A or AAAA record.
866 * For CNAME the size can be bigger.
868 unsigned char rsp[NS_MAXCDNAME];
869 unsigned int rsp_len = sizeof(rsp) - 1;
872 memset(rsp, 0, sizeof(rsp));
874 ret = parse_rr(buf, ptr, buf + buflen, rsp, &rsp_len,
875 type, class, ttl, &rdlen, &next, name);
882 * Now rsp contains compressed or uncompressed resource
883 * record. Next we check if this record answers the question.
884 * The name var contains the uncompressed label.
885 * One tricky bit is the CNAME records as they alias
886 * the name we might be interested in.
890 * Go to next answer if the class is not the one we are
893 if (*class != qclass) {
900 * Try to resolve aliases also, type is CNAME(5).
901 * This is important as otherwise the aliased names would not
902 * be cached at all as the cache would not contain the aliased
905 * If any CNAME is found in DNS packet, then we cache the alias
906 * IP address instead of the question (as the server
907 * said that question has only an alias).
908 * This means in practice that if e.g., ipv6.google.com is
909 * queried, DNS server returns CNAME of that name which is
910 * ipv6.l.google.com. We then cache the address of the CNAME
911 * but return the question name to client. So the alias
912 * status of the name is not saved in cache and thus not
913 * returned to the client. We do not return DNS packets from
914 * cache to client saying that ipv6.google.com is an alias to
915 * ipv6.l.google.com but we return instead a DNS packet that
916 * says ipv6.google.com has address xxx which is in fact the
917 * address of ipv6.l.google.com. For caching purposes this
918 * should not cause any issues.
920 if (*type == 5 && strncmp(question, name, qlen) == 0) {
922 * So now the alias answered the question. This is
923 * not very useful from caching point of view as
924 * the following A or AAAA records will not match the
925 * question. We need to find the real A/AAAA record
926 * of the alias and cache that.
928 unsigned char *end = NULL;
929 int name_len = 0, output_len;
931 memset(rsp, 0, sizeof(rsp));
932 rsp_len = sizeof(rsp) - 1;
935 * Alias is in rdata part of the message,
936 * and next-rdlen points to it. So we need to get
937 * the real name of the alias.
939 ret = get_name(0, buf, next - rdlen, buf + buflen,
940 rsp, rsp_len, &output_len, &end,
943 /* just ignore the error at this point */
950 * We should now have the alias of the entry we might
951 * want to cache. Just remember it for a while.
952 * We check the alias list when we have parsed the
955 aliases = g_slist_prepend(aliases, g_strdup(name));
962 if (*type == qtype) {
964 * We found correct type (A or AAAA)
966 if (check_alias(aliases, name) == TRUE ||
967 (aliases == NULL && strncmp(question, name,
970 * We found an alias or the name of the rr
971 * matches the question. If so, we append
972 * the compressed label to the cache.
973 * The end result is a response buffer that
974 * will contain one or more cached and
975 * compressed resource records.
977 if (*response_len + rsp_len > maxlen) {
981 memcpy(response + *response_len, rsp, rsp_len);
982 *response_len += rsp_len;
993 for (list = aliases; list; list = list->next)
995 g_slist_free(aliases);
1000 struct cache_timeout {
1001 time_t current_time;
1006 static gboolean cache_check_entry(gpointer key, gpointer value,
1009 struct cache_timeout *data = user_data;
1010 struct cache_entry *entry = value;
1013 /* Scale the number of hits by half as part of cache aging */
1018 * If either IPv4 or IPv6 cached entry has expired, we
1019 * remove both from the cache.
1022 if (entry->ipv4 != NULL && entry->ipv4->timeout > 0) {
1023 max_timeout = entry->ipv4->cache_until;
1024 if (max_timeout > data->max_timeout)
1025 data->max_timeout = max_timeout;
1027 if (entry->ipv4->cache_until < data->current_time)
1031 if (entry->ipv6 != NULL && entry->ipv6->timeout > 0) {
1032 max_timeout = entry->ipv6->cache_until;
1033 if (max_timeout > data->max_timeout)
1034 data->max_timeout = max_timeout;
1036 if (entry->ipv6->cache_until < data->current_time)
1041 * if we're asked to try harder, also remove entries that have
1044 if (data->try_harder && entry->hits < 4)
1050 static void cache_cleanup(void)
1052 static int max_timeout;
1053 struct cache_timeout data;
1056 data.current_time = time(NULL);
1057 data.max_timeout = 0;
1058 data.try_harder = 0;
1061 * In the first pass, we only remove entries that have timed out.
1062 * We use a cache of the first time to expire to do this only
1063 * when it makes sense.
1065 if (max_timeout <= data.current_time) {
1066 count = g_hash_table_foreach_remove(cache, cache_check_entry,
1069 DBG("removed %d in the first pass", count);
1072 * In the second pass, if the first pass turned up blank,
1073 * we also expire entries with a low hit count,
1074 * while aging the hit count at the same time.
1076 data.try_harder = 1;
1078 count = g_hash_table_foreach_remove(cache, cache_check_entry,
1083 * If we could not remove anything, then remember
1084 * what is the max timeout and do nothing if we
1085 * have not yet reached it. This will prevent
1086 * constant traversal of the cache if it is full.
1088 max_timeout = data.max_timeout;
1093 static gboolean cache_invalidate_entry(gpointer key, gpointer value,
1096 struct cache_entry *entry = value;
1098 /* first, delete any expired elements */
1099 cache_enforce_validity(entry);
1101 /* if anything is not expired, mark the entry for refresh */
1102 if (entry->hits > 0 && (entry->ipv4 || entry->ipv6))
1103 entry->want_refresh = 1;
1105 /* delete the cached data */
1107 g_free(entry->ipv4->data);
1108 g_free(entry->ipv4);
1113 g_free(entry->ipv6->data);
1114 g_free(entry->ipv6);
1118 /* keep the entry if we want it refreshed, delete it otherwise */
1119 if (entry->want_refresh)
1126 * cache_invalidate is called from places where the DNS landscape
1127 * has changed, say because connections are added or we entered a VPN.
1128 * The logic is to wipe all cache data, but mark all non-expired
1129 * parts of the cache for refresh rather than deleting the whole cache.
1131 static void cache_invalidate(void)
1133 DBG("Invalidating the DNS cache %p", cache);
1138 g_hash_table_foreach_remove(cache, cache_invalidate_entry, NULL);
1141 static void cache_refresh_entry(struct cache_entry *entry)
1144 cache_enforce_validity(entry);
1146 if (entry->hits > 2 && entry->ipv4 == NULL)
1147 entry->want_refresh = 1;
1148 if (entry->hits > 2 && entry->ipv6 == NULL)
1149 entry->want_refresh = 1;
1151 if (entry->want_refresh) {
1153 char dns_name[NS_MAXDNAME + 1];
1154 entry->want_refresh = 0;
1156 /* turn a DNS name into a hostname with dots */
1157 strncpy(dns_name, entry->key, NS_MAXDNAME);
1165 DBG("Refreshing %s\n", dns_name);
1166 /* then refresh the hostname */
1167 refresh_dns_entry(entry, &dns_name[1]);
1171 static void cache_refresh_iterator(gpointer key, gpointer value,
1174 struct cache_entry *entry = value;
1176 cache_refresh_entry(entry);
1179 static void cache_refresh(void)
1184 g_hash_table_foreach(cache, cache_refresh_iterator, NULL);
1187 static int reply_query_type(unsigned char *msg, int len)
1194 /* skip the header */
1195 c = msg + sizeof(struct domain_hdr);
1196 len -= sizeof(struct domain_hdr);
1201 /* now the query, which is a name and 2 16 bit words */
1202 l = dns_name_length(c) + 1;
1211 static int cache_update(struct server_data *srv, unsigned char *msg,
1212 unsigned int msg_len)
1214 int offset = protocol_offset(srv->protocol);
1215 int err, qlen, ttl = 0;
1216 uint16_t answers = 0, type = 0, class = 0;
1217 struct domain_question *q;
1218 struct cache_entry *entry;
1219 struct cache_data *data;
1220 char question[NS_MAXDNAME + 1];
1221 unsigned char response[NS_MAXDNAME + 1];
1223 unsigned int rsplen;
1224 gboolean new_entry = TRUE;
1225 time_t current_time;
1227 if (cache_size >= MAX_CACHE_SIZE) {
1229 if (cache_size >= MAX_CACHE_SIZE)
1233 current_time = time(NULL);
1235 /* don't do a cache refresh more than twice a minute */
1236 if (next_refresh < current_time) {
1238 next_refresh = current_time + 30;
1242 /* Continue only if response code is 0 (=ok) */
1249 rsplen = sizeof(response) - 1;
1250 question[sizeof(question) - 1] = '\0';
1252 err = parse_response(msg + offset, msg_len - offset,
1253 question, sizeof(question) - 1,
1254 &type, &class, &ttl,
1255 response, &rsplen, &answers);
1258 * special case: if we do a ipv6 lookup and get no result
1259 * for a record that's already in our ipv4 cache.. we want
1260 * to cache the negative response.
1262 if ((err == -ENOMSG || err == -ENOBUFS) &&
1263 reply_query_type(msg, msg_len) == 28) {
1264 entry = g_hash_table_lookup(cache, question);
1265 if (entry && entry->ipv4 && entry->ipv6 == NULL) {
1266 data = g_try_new(struct cache_data, 1);
1269 data->inserted = entry->ipv4->inserted;
1271 data->answers = msg[5];
1272 data->timeout = entry->ipv4->timeout;
1273 data->data_len = msg_len;
1274 data->data = ptr = g_malloc(msg_len);
1275 data->valid_until = entry->ipv4->valid_until;
1276 data->cache_until = entry->ipv4->cache_until;
1277 memcpy(data->data, msg, msg_len);
1280 * we will get a "hit" when we serve the response
1284 if (entry->hits < 0)
1290 if (err < 0 || ttl == 0)
1293 qlen = strlen(question);
1296 * If the cache contains already data, check if the
1297 * type of the cached data is the same and do not add
1298 * to cache if data is already there.
1299 * This is needed so that we can cache both A and AAAA
1300 * records for the same name.
1302 entry = g_hash_table_lookup(cache, question);
1303 if (entry == NULL) {
1304 entry = g_try_new(struct cache_entry, 1);
1308 data = g_try_new(struct cache_data, 1);
1314 entry->key = g_strdup(question);
1315 entry->ipv4 = entry->ipv6 = NULL;
1316 entry->want_refresh = 0;
1324 if (type == 1 && entry->ipv4 != NULL)
1327 if (type == 28 && entry->ipv6 != NULL)
1330 data = g_try_new(struct cache_data, 1);
1340 * compensate for the hit we'll get for serving
1341 * the response out of the cache
1344 if (entry->hits < 0)
1350 if (ttl < MIN_CACHE_TTL)
1351 ttl = MIN_CACHE_TTL;
1353 data->inserted = current_time;
1355 data->answers = answers;
1356 data->timeout = ttl;
1357 data->data_len = 12 + qlen + 1 + 2 + 2 + rsplen;
1358 data->data = ptr = g_malloc(data->data_len);
1359 data->valid_until = current_time + ttl;
1362 * Restrict the cached DNS record TTL to some sane value
1363 * in order to prevent data staying in the cache too long.
1365 if (ttl > MAX_CACHE_TTL)
1366 ttl = MAX_CACHE_TTL;
1368 data->cache_until = round_down_ttl(current_time + ttl, ttl);
1370 if (data->data == NULL) {
1377 memcpy(ptr, msg, 12);
1378 memcpy(ptr + 12, question, qlen + 1); /* copy also the \0 */
1380 q = (void *) (ptr + 12 + qlen + 1);
1381 q->type = htons(type);
1382 q->class = htons(class);
1383 memcpy(ptr + 12 + qlen + 1 + sizeof(struct domain_question),
1386 if (new_entry == TRUE) {
1387 g_hash_table_replace(cache, entry->key, entry);
1391 DBG("cache %d %squestion \"%s\" type %d ttl %d size %zd",
1392 cache_size, new_entry ? "new " : "old ",
1393 question, type, ttl,
1394 sizeof(*entry) + sizeof(*data) + data->data_len + qlen);
1399 static int ns_resolv(struct server_data *server, struct request_data *req,
1400 gpointer request, gpointer name)
1403 int sk, err, type = 0;
1404 char *dot, *lookup = (char *) name;
1405 struct cache_entry *entry;
1407 entry = cache_check(request, &type);
1408 if (entry != NULL) {
1410 struct cache_data *data;
1412 DBG("cache hit %s type %s", lookup, type == 1 ? "A" : "AAAA");
1419 ttl_left = data->valid_until - time(NULL);
1423 if (data != NULL && req->protocol == IPPROTO_TCP) {
1424 send_cached_response(req->client_sk, data->data,
1425 data->data_len, NULL, 0, IPPROTO_TCP,
1426 req->srcid, data->answers, ttl_left);
1430 if (data != NULL && req->protocol == IPPROTO_UDP) {
1432 sk = g_io_channel_unix_get_fd(
1433 req->ifdata->udp_listener_channel);
1435 send_cached_response(sk, data->data,
1436 data->data_len, &req->sa, req->sa_len,
1437 IPPROTO_UDP, req->srcid, data->answers,
1443 sk = g_io_channel_unix_get_fd(server->channel);
1445 err = send(sk, request, req->request_len, 0);
1449 /* If we have more than one dot, we don't add domains */
1450 dot = strchr(lookup, '.');
1451 if (dot != NULL && dot != lookup + strlen(lookup) - 1)
1454 if (server->domains != NULL && server->domains->data != NULL)
1455 req->append_domain = TRUE;
1457 for (list = server->domains; list; list = list->next) {
1459 unsigned char alt[1024];
1460 struct domain_hdr *hdr = (void *) &alt;
1461 int altlen, domlen, offset;
1463 domain = list->data;
1468 offset = protocol_offset(server->protocol);
1472 domlen = strlen(domain) + 1;
1476 alt[offset] = req->altid & 0xff;
1477 alt[offset + 1] = req->altid >> 8;
1479 memcpy(alt + offset + 2, request + offset + 2, 10);
1480 hdr->qdcount = htons(1);
1482 altlen = append_query(alt + offset + 12, sizeof(alt) - 12,
1489 memcpy(alt + offset + altlen,
1490 request + offset + altlen - domlen,
1491 req->request_len - altlen - offset + domlen);
1493 if (server->protocol == IPPROTO_TCP) {
1494 int req_len = req->request_len + domlen - 2;
1496 alt[0] = (req_len >> 8) & 0xff;
1497 alt[1] = req_len & 0xff;
1500 err = send(sk, alt, req->request_len + domlen, 0);
1510 static int forward_dns_reply(unsigned char *reply, int reply_len, int protocol,
1511 struct server_data *data)
1513 struct domain_hdr *hdr;
1514 struct request_data *req;
1515 int dns_id, sk, err, offset = protocol_offset(protocol);
1516 struct listener_data *ifdata;
1521 hdr = (void *)(reply + offset);
1522 dns_id = reply[offset] | reply[offset + 1] << 8;
1524 DBG("Received %d bytes (id 0x%04x)", reply_len, dns_id);
1526 req = find_request(dns_id);
1530 DBG("id 0x%04x rcode %d", hdr->id, hdr->rcode);
1532 ifdata = req->ifdata;
1534 reply[offset] = req->srcid & 0xff;
1535 reply[offset + 1] = req->srcid >> 8;
1539 if (hdr->rcode == 0 || req->resp == NULL) {
1542 * If the domain name was append
1543 * remove it before forwarding the reply.
1545 if (req->append_domain == TRUE) {
1548 unsigned int domain_len;
1551 * ptr points to the first char of the hostname.
1552 * ->hostname.domain.net
1554 ptr = reply + offset + sizeof(struct domain_hdr);
1556 domain_len = strlen((const char *)ptr) - host_len - 1;
1559 * remove the domain name and replaced it by the end
1562 memmove(ptr + host_len + 1,
1563 ptr + host_len + domain_len + 1,
1564 reply_len - (ptr - reply + domain_len));
1566 reply_len = reply_len - domain_len;
1572 req->resp = g_try_malloc(reply_len);
1573 if (req->resp == NULL)
1576 memcpy(req->resp, reply, reply_len);
1577 req->resplen = reply_len;
1579 cache_update(data, reply, reply_len);
1582 if (hdr->rcode > 0 && req->numresp < req->numserv)
1585 if (req->timeout > 0)
1586 g_source_remove(req->timeout);
1588 request_list = g_slist_remove(request_list, req);
1590 if (protocol == IPPROTO_UDP) {
1591 sk = g_io_channel_unix_get_fd(ifdata->udp_listener_channel);
1592 err = sendto(sk, req->resp, req->resplen, 0,
1593 &req->sa, req->sa_len);
1595 sk = req->client_sk;
1596 err = send(sk, req->resp, req->resplen, 0);
1606 static void cache_element_destroy(gpointer value)
1608 struct cache_entry *entry = value;
1613 if (entry->ipv4 != NULL) {
1614 g_free(entry->ipv4->data);
1615 g_free(entry->ipv4);
1618 if (entry->ipv6 != NULL) {
1619 g_free(entry->ipv6->data);
1620 g_free(entry->ipv6);
1626 if (--cache_size < 0)
1630 static void destroy_server(struct server_data *server)
1634 DBG("interface %s server %s", server->interface, server->server);
1636 server_list = g_slist_remove(server_list, server);
1638 if (server->watch > 0)
1639 g_source_remove(server->watch);
1641 if (server->timeout > 0)
1642 g_source_remove(server->timeout);
1644 g_io_channel_unref(server->channel);
1646 if (server->protocol == IPPROTO_UDP)
1647 connman_info("Removing DNS server %s", server->server);
1649 g_free(server->incoming_reply);
1650 g_free(server->server);
1651 for (list = server->domains; list; list = list->next) {
1652 char *domain = list->data;
1654 server->domains = g_list_remove(server->domains, domain);
1657 g_free(server->interface);
1659 if (__sync_fetch_and_sub(&cache_refcount, 1) == 1) {
1660 g_hash_table_destroy(cache);
1667 static gboolean udp_server_event(GIOChannel *channel, GIOCondition condition,
1670 unsigned char buf[4096];
1672 struct server_data *data = user_data;
1674 if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
1675 connman_error("Error with UDP server %s", data->server);
1680 sk = g_io_channel_unix_get_fd(channel);
1682 len = recv(sk, buf, sizeof(buf), 0);
1686 err = forward_dns_reply(buf, len, IPPROTO_UDP, data);
1693 static gboolean tcp_server_event(GIOChannel *channel, GIOCondition condition,
1697 struct server_data *server = user_data;
1699 sk = g_io_channel_unix_get_fd(channel);
1703 if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
1706 DBG("TCP server channel closed");
1709 * Discard any partial response which is buffered; better
1710 * to get a proper response from a working server.
1712 g_free(server->incoming_reply);
1713 server->incoming_reply = NULL;
1715 for (list = request_list; list; list = list->next) {
1716 struct request_data *req = list->data;
1717 struct domain_hdr *hdr;
1719 if (req->protocol == IPPROTO_UDP)
1722 if (req->request == NULL)
1726 * If we're not waiting for any further response
1727 * from another name server, then we send an error
1728 * response to the client.
1730 if (req->numserv && --(req->numserv))
1733 hdr = (void *) (req->request + 2);
1734 hdr->id = req->srcid;
1735 send_response(req->client_sk, req->request,
1736 req->request_len, NULL, 0, IPPROTO_TCP);
1738 request_list = g_slist_remove(request_list, req);
1741 destroy_server(server);
1746 if ((condition & G_IO_OUT) && !server->connected) {
1749 struct server_data *udp_server;
1751 udp_server = find_server(server->interface, server->server,
1753 if (udp_server != NULL) {
1754 for (domains = udp_server->domains; domains;
1755 domains = domains->next) {
1756 char *dom = domains->data;
1758 DBG("Adding domain %s to %s",
1759 dom, server->server);
1761 server->domains = g_list_append(server->domains,
1766 server->connected = TRUE;
1767 server_list = g_slist_append(server_list, server);
1769 if (server->timeout > 0) {
1770 g_source_remove(server->timeout);
1771 server->timeout = 0;
1774 for (list = request_list; list; list = list->next) {
1775 struct request_data *req = list->data;
1777 if (req->protocol == IPPROTO_UDP)
1780 DBG("Sending req %s over TCP", (char *)req->name);
1782 if (req->timeout > 0)
1783 g_source_remove(req->timeout);
1785 req->timeout = g_timeout_add_seconds(30,
1786 request_timeout, req);
1787 if (ns_resolv(server, req, req->request,
1789 /* We sent cached result so no need for timeout
1792 if (req->timeout > 0) {
1793 g_source_remove(req->timeout);
1799 } else if (condition & G_IO_IN) {
1800 struct partial_reply *reply = server->incoming_reply;
1804 unsigned char reply_len_buf[2];
1807 bytes_recv = recv(sk, reply_len_buf, 2, MSG_PEEK);
1810 } else if (bytes_recv < 0) {
1811 if (errno == EAGAIN || errno == EWOULDBLOCK)
1814 connman_error("DNS proxy error %s",
1817 } else if (bytes_recv < 2)
1820 reply_len = reply_len_buf[1] | reply_len_buf[0] << 8;
1823 DBG("TCP reply %d bytes", reply_len);
1825 reply = g_try_malloc(sizeof(*reply) + reply_len + 2);
1829 reply->len = reply_len;
1830 reply->received = 0;
1832 server->incoming_reply = reply;
1835 while (reply->received < reply->len) {
1836 bytes_recv = recv(sk, reply->buf + reply->received,
1837 reply->len - reply->received, 0);
1839 connman_error("DNS proxy TCP disconnect");
1841 } else if (bytes_recv < 0) {
1842 if (errno == EAGAIN || errno == EWOULDBLOCK)
1845 connman_error("DNS proxy error %s",
1849 reply->received += bytes_recv;
1852 forward_dns_reply(reply->buf, reply->received, IPPROTO_TCP,
1856 server->incoming_reply = NULL;
1858 destroy_server(server);
1866 static gboolean tcp_idle_timeout(gpointer user_data)
1868 struct server_data *server = user_data;
1875 destroy_server(server);
1880 static struct server_data *create_server(const char *interface,
1881 const char *domain, const char *server,
1884 struct addrinfo hints, *rp;
1885 struct server_data *data;
1888 DBG("interface %s server %s", interface, server);
1890 memset(&hints, 0, sizeof(hints));
1894 hints.ai_socktype = SOCK_DGRAM;
1898 hints.ai_socktype = SOCK_STREAM;
1904 hints.ai_family = AF_UNSPEC;
1905 hints.ai_flags = AI_PASSIVE | AI_NUMERICSERV | AI_NUMERICHOST;
1907 ret = getaddrinfo(server, "53", &hints, &rp);
1909 connman_error("Failed to parse server %s address: %s\n",
1910 server, gai_strerror(ret));
1913 /* Do not blindly copy this code elsewhere; it doesn't loop over the
1914 results using ->ai_next as it should. That's OK in *this* case
1915 because it was a numeric lookup; we *know* there's only one. */
1917 sk = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
1919 connman_error("Failed to create server %s socket", server);
1924 if (interface != NULL) {
1925 if (setsockopt(sk, SOL_SOCKET, SO_BINDTODEVICE,
1926 interface, strlen(interface) + 1) < 0) {
1927 connman_error("Failed to bind server %s "
1936 data = g_try_new0(struct server_data, 1);
1938 connman_error("Failed to allocate server %s data", server);
1944 data->channel = g_io_channel_unix_new(sk);
1945 if (data->channel == NULL) {
1946 connman_error("Failed to create server %s channel", server);
1953 g_io_channel_set_close_on_unref(data->channel, TRUE);
1955 if (protocol == IPPROTO_TCP) {
1956 g_io_channel_set_flags(data->channel, G_IO_FLAG_NONBLOCK, NULL);
1957 data->watch = g_io_add_watch(data->channel,
1958 G_IO_OUT | G_IO_IN | G_IO_HUP | G_IO_NVAL | G_IO_ERR,
1959 tcp_server_event, data);
1960 data->timeout = g_timeout_add_seconds(30, tcp_idle_timeout,
1963 data->watch = g_io_add_watch(data->channel,
1964 G_IO_IN | G_IO_NVAL | G_IO_ERR | G_IO_HUP,
1965 udp_server_event, data);
1967 data->interface = g_strdup(interface);
1969 data->domains = g_list_append(data->domains, g_strdup(domain));
1970 data->server = g_strdup(server);
1971 data->protocol = protocol;
1973 ret = connect(sk, rp->ai_addr, rp->ai_addrlen);
1976 if ((protocol == IPPROTO_TCP && errno != EINPROGRESS) ||
1977 protocol == IPPROTO_UDP) {
1980 connman_error("Failed to connect to server %s", server);
1981 if (data->watch > 0)
1982 g_source_remove(data->watch);
1983 if (data->timeout > 0)
1984 g_source_remove(data->timeout);
1986 g_io_channel_unref(data->channel);
1989 g_free(data->server);
1990 g_free(data->interface);
1991 for (list = data->domains; list; list = list->next) {
1992 char *domain = list->data;
1994 data->domains = g_list_remove(data->domains,
2003 if (__sync_fetch_and_add(&cache_refcount, 1) == 0)
2004 cache = g_hash_table_new_full(g_str_hash,
2007 cache_element_destroy);
2009 if (protocol == IPPROTO_UDP) {
2010 /* Enable new servers by default */
2011 data->enabled = TRUE;
2012 connman_info("Adding DNS server %s", data->server);
2014 server_list = g_slist_append(server_list, data);
2022 static gboolean resolv(struct request_data *req,
2023 gpointer request, gpointer name)
2028 for (list = server_list; list; list = list->next) {
2029 struct server_data *data = list->data;
2031 DBG("server %s enabled %d", data->server, data->enabled);
2033 if (data->enabled == FALSE)
2036 if (data->watch == 0 && data->protocol == IPPROTO_UDP)
2037 data->watch = g_io_add_watch(data->channel,
2038 G_IO_IN | G_IO_NVAL | G_IO_ERR | G_IO_HUP,
2039 udp_server_event, data);
2041 status = ns_resolv(data, req, request, name);
2046 if (req->timeout > 0) {
2047 g_source_remove(req->timeout);
2056 static void append_domain(const char *interface, const char *domain)
2060 DBG("interface %s domain %s", interface, domain);
2065 for (list = server_list; list; list = list->next) {
2066 struct server_data *data = list->data;
2069 gboolean dom_found = FALSE;
2071 if (data->interface == NULL)
2074 if (g_str_equal(data->interface, interface) == FALSE)
2077 for (dom_list = data->domains; dom_list;
2078 dom_list = dom_list->next) {
2079 dom = dom_list->data;
2081 if (g_str_equal(dom, domain)) {
2087 if (dom_found == FALSE) {
2089 g_list_append(data->domains, g_strdup(domain));
2094 int __connman_dnsproxy_append(const char *interface, const char *domain,
2097 struct server_data *data;
2099 DBG("interface %s server %s", interface, server);
2101 if (server == NULL && domain == NULL)
2104 if (server == NULL) {
2105 append_domain(interface, domain);
2110 if (g_str_equal(server, "127.0.0.1") == TRUE)
2113 data = find_server(interface, server, IPPROTO_UDP);
2115 append_domain(interface, domain);
2119 data = create_server(interface, domain, server, IPPROTO_UDP);
2126 static void remove_server(const char *interface, const char *domain,
2127 const char *server, int protocol)
2129 struct server_data *data;
2131 data = find_server(interface, server, protocol);
2135 destroy_server(data);
2138 int __connman_dnsproxy_remove(const char *interface, const char *domain,
2141 DBG("interface %s server %s", interface, server);
2146 if (g_str_equal(server, "127.0.0.1") == TRUE)
2149 remove_server(interface, domain, server, IPPROTO_UDP);
2150 remove_server(interface, domain, server, IPPROTO_TCP);
2155 void __connman_dnsproxy_flush(void)
2159 list = request_pending_list;
2161 struct request_data *req = list->data;
2165 request_pending_list =
2166 g_slist_remove(request_pending_list, req);
2167 resolv(req, req->request, req->name);
2168 g_free(req->request);
2173 static void dnsproxy_offline_mode(connman_bool_t enabled)
2177 DBG("enabled %d", enabled);
2179 for (list = server_list; list; list = list->next) {
2180 struct server_data *data = list->data;
2182 if (enabled == FALSE) {
2183 connman_info("Enabling DNS server %s", data->server);
2184 data->enabled = TRUE;
2188 connman_info("Disabling DNS server %s", data->server);
2189 data->enabled = FALSE;
2195 static void dnsproxy_default_changed(struct connman_service *service)
2200 DBG("service %p", service);
2202 /* DNS has changed, invalidate the cache */
2205 if (service == NULL) {
2206 /* When no services are active, then disable DNS proxying */
2207 dnsproxy_offline_mode(TRUE);
2211 interface = connman_service_get_interface(service);
2212 if (interface == NULL)
2215 for (list = server_list; list; list = list->next) {
2216 struct server_data *data = list->data;
2218 if (g_strcmp0(data->interface, interface) == 0) {
2219 connman_info("Enabling DNS server %s", data->server);
2220 data->enabled = TRUE;
2222 connman_info("Disabling DNS server %s", data->server);
2223 data->enabled = FALSE;
2231 static struct connman_notifier dnsproxy_notifier = {
2233 .default_changed = dnsproxy_default_changed,
2234 .offline_mode = dnsproxy_offline_mode,
2237 static unsigned char opt_edns0_type[2] = { 0x00, 0x29 };
2239 static int parse_request(unsigned char *buf, int len,
2240 char *name, unsigned int size)
2242 struct domain_hdr *hdr = (void *) buf;
2243 uint16_t qdcount = ntohs(hdr->qdcount);
2244 uint16_t arcount = ntohs(hdr->arcount);
2246 char *last_label = NULL;
2247 unsigned int remain, used = 0;
2252 DBG("id 0x%04x qr %d opcode %d qdcount %d arcount %d",
2253 hdr->id, hdr->qr, hdr->opcode,
2256 if (hdr->qr != 0 || qdcount != 1)
2259 memset(name, 0, size);
2261 ptr = buf + sizeof(struct domain_hdr);
2262 remain = len - sizeof(struct domain_hdr);
2264 while (remain > 0) {
2268 last_label = (char *) (ptr + 1);
2272 if (used + len + 1 > size)
2275 strncat(name, (char *) (ptr + 1), len);
2284 if (last_label && arcount && remain >= 9 && last_label[4] == 0 &&
2285 !memcmp(last_label + 5, opt_edns0_type, 2)) {
2286 uint16_t edns0_bufsize;
2288 edns0_bufsize = last_label[7] << 8 | last_label[8];
2290 DBG("EDNS0 buffer size %u", edns0_bufsize);
2292 /* This is an evil hack until full TCP support has been
2295 * Somtimes the EDNS0 request gets send with a too-small
2296 * buffer size. Since glibc doesn't seem to crash when it
2297 * gets a response biffer then it requested, just bump
2298 * the buffer size up to 4KiB.
2300 if (edns0_bufsize < 0x1000) {
2301 last_label[7] = 0x10;
2302 last_label[8] = 0x00;
2306 DBG("query %s", name);
2311 static gboolean tcp_listener_event(GIOChannel *channel, GIOCondition condition,
2314 unsigned char buf[768];
2316 struct request_data *req;
2317 struct server_data *server;
2318 int sk, client_sk, len, err;
2319 struct sockaddr_in6 client_addr;
2320 socklen_t client_addr_len = sizeof(client_addr);
2322 struct listener_data *ifdata = user_data;
2324 DBG("condition 0x%x", condition);
2326 if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
2327 if (ifdata->tcp_listener_watch > 0)
2328 g_source_remove(ifdata->tcp_listener_watch);
2329 ifdata->tcp_listener_watch = 0;
2331 connman_error("Error with TCP listener channel");
2336 sk = g_io_channel_unix_get_fd(channel);
2338 client_sk = accept(sk, (void *)&client_addr, &client_addr_len);
2339 if (client_sk < 0) {
2340 connman_error("Accept failure on TCP listener");
2341 ifdata->tcp_listener_watch = 0;
2345 len = recv(client_sk, buf, sizeof(buf), 0);
2349 DBG("Received %d bytes (id 0x%04x)", len, buf[2] | buf[3] << 8);
2351 err = parse_request(buf + 2, len - 2, query, sizeof(query));
2352 if (err < 0 || (g_slist_length(server_list) == 0)) {
2353 send_response(client_sk, buf, len, NULL, 0, IPPROTO_TCP);
2357 req = g_try_new0(struct request_data, 1);
2361 memcpy(&req->sa, &client_addr, client_addr_len);
2362 req->sa_len = client_addr_len;
2363 req->client_sk = client_sk;
2364 req->protocol = IPPROTO_TCP;
2367 if (request_id == 0x0000 || request_id == 0xffff)
2370 req->srcid = buf[2] | (buf[3] << 8);
2371 req->dstid = request_id;
2372 req->altid = request_id + 1;
2373 req->request_len = len;
2375 buf[2] = req->dstid & 0xff;
2376 buf[3] = req->dstid >> 8;
2379 req->ifdata = (struct listener_data *) ifdata;
2380 req->append_domain = FALSE;
2381 request_list = g_slist_append(request_list, req);
2383 for (list = server_list; list; list = list->next) {
2384 struct server_data *data = list->data;
2387 if (data->protocol != IPPROTO_UDP || data->enabled == FALSE)
2390 server = create_server(data->interface, NULL,
2391 data->server, IPPROTO_TCP);
2394 * If server is NULL, we're not connected yet.
2395 * Copy the relevant buffers and continue with
2396 * the next nameserver.
2397 * The request will actually be sent once we're
2398 * properly connected over TCP to this nameserver.
2400 if (server == NULL) {
2401 req->request = g_try_malloc0(req->request_len);
2402 if (req->request == NULL)
2405 memcpy(req->request, buf, req->request_len);
2407 req->name = g_try_malloc0(sizeof(query));
2408 if (req->name == NULL) {
2409 g_free(req->request);
2412 memcpy(req->name, query, sizeof(query));
2417 if (req->timeout > 0)
2418 g_source_remove(req->timeout);
2420 for (domains = data->domains; domains;
2421 domains = domains->next) {
2422 char *dom = domains->data;
2424 DBG("Adding domain %s to %s", dom, server->server);
2426 server->domains = g_list_append(server->domains,
2430 req->timeout = g_timeout_add_seconds(30, request_timeout, req);
2431 if (ns_resolv(server, req, buf, query) > 0) {
2432 if (req->timeout > 0) {
2433 g_source_remove(req->timeout);
2442 static gboolean udp_listener_event(GIOChannel *channel, GIOCondition condition,
2445 unsigned char buf[768];
2447 struct request_data *req;
2448 struct sockaddr_in6 client_addr;
2449 socklen_t client_addr_len = sizeof(client_addr);
2451 struct listener_data *ifdata = user_data;
2453 if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
2454 connman_error("Error with UDP listener channel");
2455 ifdata->udp_listener_watch = 0;
2459 sk = g_io_channel_unix_get_fd(channel);
2461 memset(&client_addr, 0, client_addr_len);
2462 len = recvfrom(sk, buf, sizeof(buf), 0, (void *)&client_addr,
2467 DBG("Received %d bytes (id 0x%04x)", len, buf[0] | buf[1] << 8);
2469 err = parse_request(buf, len, query, sizeof(query));
2470 if (err < 0 || (g_slist_length(server_list) == 0)) {
2471 send_response(sk, buf, len, (void *)&client_addr,
2472 client_addr_len, IPPROTO_UDP);
2476 req = g_try_new0(struct request_data, 1);
2480 memcpy(&req->sa, &client_addr, client_addr_len);
2481 req->sa_len = client_addr_len;
2483 req->protocol = IPPROTO_UDP;
2486 if (request_id == 0x0000 || request_id == 0xffff)
2489 req->srcid = buf[0] | (buf[1] << 8);
2490 req->dstid = request_id;
2491 req->altid = request_id + 1;
2492 req->request_len = len;
2494 buf[0] = req->dstid & 0xff;
2495 buf[1] = req->dstid >> 8;
2498 req->ifdata = (struct listener_data *) ifdata;
2499 req->timeout = g_timeout_add_seconds(5, request_timeout, req);
2500 req->append_domain = FALSE;
2501 request_list = g_slist_append(request_list, req);
2503 return resolv(req, buf, query);
2506 static int create_dns_listener(int protocol, struct listener_data *ifdata)
2508 GIOChannel *channel;
2512 struct sockaddr_in6 sin6;
2513 struct sockaddr_in sin;
2516 int sk, type, v6only = 0;
2517 int family = AF_INET6;
2520 DBG("interface %s", ifdata->ifname);
2525 type = SOCK_DGRAM | SOCK_CLOEXEC;
2530 type = SOCK_STREAM | SOCK_CLOEXEC;
2537 sk = socket(family, type, protocol);
2538 if (sk < 0 && family == AF_INET6 && errno == EAFNOSUPPORT) {
2539 connman_error("No IPv6 support; DNS proxy listening only on Legacy IP");
2541 sk = socket(family, type, protocol);
2544 connman_error("Failed to create %s listener socket", proto);
2548 if (setsockopt(sk, SOL_SOCKET, SO_BINDTODEVICE,
2550 strlen(ifdata->ifname) + 1) < 0) {
2551 connman_error("Failed to bind %s listener interface", proto);
2555 /* Ensure it accepts Legacy IP connections too */
2556 if (family == AF_INET6 &&
2557 setsockopt(sk, SOL_IPV6, IPV6_V6ONLY,
2558 &v6only, sizeof(v6only)) < 0) {
2559 connman_error("Failed to clear V6ONLY on %s listener socket",
2565 if (family == AF_INET) {
2566 memset(&s.sin, 0, sizeof(s.sin));
2567 s.sin.sin_family = AF_INET;
2568 s.sin.sin_port = htons(53);
2569 s.sin.sin_addr.s_addr = htonl(INADDR_ANY);
2570 slen = sizeof(s.sin);
2572 memset(&s.sin6, 0, sizeof(s.sin6));
2573 s.sin6.sin6_family = AF_INET6;
2574 s.sin6.sin6_port = htons(53);
2575 s.sin6.sin6_addr = in6addr_any;
2576 slen = sizeof(s.sin6);
2579 if (bind(sk, &s.sa, slen) < 0) {
2580 connman_error("Failed to bind %s listener socket", proto);
2585 if (protocol == IPPROTO_TCP && listen(sk, 10) < 0) {
2586 connman_error("Failed to listen on TCP socket");
2591 channel = g_io_channel_unix_new(sk);
2592 if (channel == NULL) {
2593 connman_error("Failed to create %s listener channel", proto);
2598 g_io_channel_set_close_on_unref(channel, TRUE);
2600 if (protocol == IPPROTO_TCP) {
2601 ifdata->tcp_listener_channel = channel;
2602 ifdata->tcp_listener_watch = g_io_add_watch(channel,
2603 G_IO_IN, tcp_listener_event, (gpointer) ifdata);
2605 ifdata->udp_listener_channel = channel;
2606 ifdata->udp_listener_watch = g_io_add_watch(channel,
2607 G_IO_IN, udp_listener_event, (gpointer) ifdata);
2613 static void destroy_udp_listener(struct listener_data *ifdata)
2615 DBG("interface %s", ifdata->ifname);
2617 if (ifdata->udp_listener_watch > 0)
2618 g_source_remove(ifdata->udp_listener_watch);
2620 g_io_channel_unref(ifdata->udp_listener_channel);
2623 static void destroy_tcp_listener(struct listener_data *ifdata)
2625 DBG("interface %s", ifdata->ifname);
2627 if (ifdata->tcp_listener_watch > 0)
2628 g_source_remove(ifdata->tcp_listener_watch);
2630 g_io_channel_unref(ifdata->tcp_listener_channel);
2633 static int create_listener(struct listener_data *ifdata)
2637 err = create_dns_listener(IPPROTO_UDP, ifdata);
2641 err = create_dns_listener(IPPROTO_TCP, ifdata);
2643 destroy_udp_listener(ifdata);
2647 if (g_strcmp0(ifdata->ifname, "lo") == 0)
2648 __connman_resolvfile_append("lo", NULL, "127.0.0.1");
2653 static void destroy_listener(struct listener_data *ifdata)
2657 if (g_strcmp0(ifdata->ifname, "lo") == 0)
2658 __connman_resolvfile_remove("lo", NULL, "127.0.0.1");
2660 for (list = request_pending_list; list; list = list->next) {
2661 struct request_data *req = list->data;
2663 DBG("Dropping pending request (id 0x%04x -> 0x%04x)",
2664 req->srcid, req->dstid);
2667 g_free(req->request);
2673 g_slist_free(request_pending_list);
2674 request_pending_list = NULL;
2676 for (list = request_list; list; list = list->next) {
2677 struct request_data *req = list->data;
2679 DBG("Dropping request (id 0x%04x -> 0x%04x)",
2680 req->srcid, req->dstid);
2683 g_free(req->request);
2689 g_slist_free(request_list);
2690 request_list = NULL;
2692 destroy_tcp_listener(ifdata);
2693 destroy_udp_listener(ifdata);
2696 int __connman_dnsproxy_add_listener(const char *interface)
2698 struct listener_data *ifdata;
2701 DBG("interface %s", interface);
2703 if (g_hash_table_lookup(listener_table, interface) != NULL)
2706 ifdata = g_try_new0(struct listener_data, 1);
2710 ifdata->ifname = g_strdup(interface);
2711 ifdata->udp_listener_channel = NULL;
2712 ifdata->udp_listener_watch = 0;
2713 ifdata->tcp_listener_channel = NULL;
2714 ifdata->tcp_listener_watch = 0;
2716 err = create_listener(ifdata);
2718 connman_error("Couldn't create listener for %s err %d",
2720 g_free(ifdata->ifname);
2724 g_hash_table_insert(listener_table, ifdata->ifname, ifdata);
2728 void __connman_dnsproxy_remove_listener(const char *interface)
2730 struct listener_data *ifdata;
2732 DBG("interface %s", interface);
2734 ifdata = g_hash_table_lookup(listener_table, interface);
2738 destroy_listener(ifdata);
2740 g_hash_table_remove(listener_table, interface);
2743 static void remove_listener(gpointer key, gpointer value, gpointer user_data)
2745 const char *interface = key;
2746 struct listener_data *ifdata = value;
2748 DBG("interface %s", interface);
2750 destroy_listener(ifdata);
2753 int __connman_dnsproxy_init(void)
2759 listener_table = g_hash_table_new_full(g_str_hash, g_str_equal,
2761 err = __connman_dnsproxy_add_listener("lo");
2765 err = connman_notifier_register(&dnsproxy_notifier);
2772 __connman_dnsproxy_remove_listener("lo");
2773 g_hash_table_destroy(listener_table);
2778 void __connman_dnsproxy_cleanup(void)
2782 connman_notifier_unregister(&dnsproxy_notifier);
2784 g_hash_table_foreach(listener_table, remove_listener, NULL);
2786 g_hash_table_destroy(listener_table);