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
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;
499 DBG("query %s domain %s", query, domain);
501 while (query != NULL) {
504 tmp = strchr(query, '.');
510 memcpy(ptr + 1, query, len);
516 memcpy(ptr + 1, query, tmp - query);
517 ptr += tmp - query + 1;
522 while (domain != NULL) {
525 tmp = strchr(domain, '.');
527 len = strlen(domain);
531 memcpy(ptr + 1, domain, len);
537 memcpy(ptr + 1, domain, tmp - domain);
538 ptr += tmp - domain + 1;
548 static gboolean cache_check_is_valid(struct cache_data *data,
554 if (data->cache_until < current_time)
561 * remove stale cached entries so that they can be refreshed
563 static void cache_enforce_validity(struct cache_entry *entry)
565 time_t current_time = time(NULL);
567 if (cache_check_is_valid(entry->ipv4, current_time) == FALSE
569 DBG("cache timeout \"%s\" type A", entry->key);
570 g_free(entry->ipv4->data);
576 if (cache_check_is_valid(entry->ipv6, current_time) == FALSE
578 DBG("cache timeout \"%s\" type AAAA", entry->key);
579 g_free(entry->ipv6->data);
585 static uint16_t cache_check_validity(char *question, uint16_t type,
586 struct cache_entry *entry)
588 time_t current_time = time(NULL);
589 int want_refresh = 0;
592 * if we have a popular entry, we want a refresh instead of
593 * total destruction of the entry.
598 cache_enforce_validity(entry);
602 if (cache_check_is_valid(entry->ipv4, current_time) == FALSE) {
603 DBG("cache %s \"%s\" type A", entry->ipv4 ?
604 "timeout" : "entry missing", question);
607 entry->want_refresh = 1;
610 * We do not remove cache entry if there is still
611 * valid IPv6 entry found in the cache.
613 if (cache_check_is_valid(entry->ipv6, current_time)
614 == FALSE && want_refresh == FALSE) {
615 g_hash_table_remove(cache, question);
622 if (cache_check_is_valid(entry->ipv6, current_time) == FALSE) {
623 DBG("cache %s \"%s\" type AAAA", entry->ipv6 ?
624 "timeout" : "entry missing", question);
627 entry->want_refresh = 1;
629 if (cache_check_is_valid(entry->ipv4, current_time)
630 == FALSE && want_refresh == FALSE) {
631 g_hash_table_remove(cache, question);
641 static struct cache_entry *cache_check(gpointer request, int *qtype)
643 char *question = request + 12;
644 struct cache_entry *entry;
645 struct domain_question *q;
649 offset = strlen(question) + 1;
650 q = (void *) (question + offset);
651 type = ntohs(q->type);
653 /* We only cache either A (1) or AAAA (28) requests */
654 if (type != 1 && type != 28)
657 entry = g_hash_table_lookup(cache, question);
661 type = cache_check_validity(question, type, entry);
670 * Get a label/name from DNS resource record. The function decompresses the
671 * label if necessary. The function does not convert the name to presentation
672 * form. This means that the result string will contain label lengths instead
673 * of dots between labels. We intentionally do not want to convert to dotted
674 * format so that we can cache the wire format string directly.
676 static int get_name(int counter,
677 unsigned char *pkt, unsigned char *start, unsigned char *max,
678 unsigned char *output, int output_max, int *output_len,
679 unsigned char **end, char *name, int *name_len)
683 /* Limit recursion to 10 (this means up to 10 labels in domain name) */
689 if ((*p & NS_CMPRSFLGS) == NS_CMPRSFLGS) {
690 uint16_t offset = (*p & 0x3F) * 256 + *(p + 1);
692 if (offset >= max - pkt)
698 return get_name(counter + 1, pkt, pkt + offset, max,
699 output, output_max, output_len, end,
702 unsigned label_len = *p;
704 if (pkt + label_len > max)
707 if (*output_len > output_max)
711 * We need the original name in order to check
712 * if this answer is the correct one.
714 name[(*name_len)++] = label_len;
715 memcpy(name + *name_len, p + 1, label_len + 1);
716 *name_len += label_len;
718 /* We compress the result */
719 output[0] = NS_CMPRSFLGS;
736 static int parse_rr(unsigned char *buf, unsigned char *start,
738 unsigned char *response, unsigned int *response_size,
739 uint16_t *type, uint16_t *class, int *ttl, int *rdlen,
743 struct domain_rr *rr;
745 int name_len = 0, output_len = 0, max_rsp = *response_size;
747 err = get_name(0, buf, start, max, response, max_rsp,
748 &output_len, end, name, &name_len);
754 if ((unsigned int) offset > *response_size)
757 rr = (void *) (*end);
762 *type = ntohs(rr->type);
763 *class = ntohs(rr->class);
764 *ttl = ntohl(rr->ttl);
765 *rdlen = ntohs(rr->rdlen);
770 memcpy(response + offset, *end, sizeof(struct domain_rr));
772 offset += sizeof(struct domain_rr);
773 *end += sizeof(struct domain_rr);
775 if ((unsigned int) (offset + *rdlen) > *response_size)
778 memcpy(response + offset, *end, *rdlen);
782 *response_size = offset + *rdlen;
787 static gboolean check_alias(GSList *aliases, char *name)
791 if (aliases != NULL) {
792 for (list = aliases; list; list = list->next) {
793 int len = strlen((char *)list->data);
794 if (strncmp((char *)list->data, name, len) == 0)
802 static int parse_response(unsigned char *buf, int buflen,
803 char *question, int qlen,
804 uint16_t *type, uint16_t *class, int *ttl,
805 unsigned char *response, unsigned int *response_len,
808 struct domain_hdr *hdr = (void *) buf;
809 struct domain_question *q;
811 uint16_t qdcount = ntohs(hdr->qdcount);
812 uint16_t ancount = ntohs(hdr->ancount);
814 uint16_t qtype, qclass;
815 unsigned char *next = NULL;
816 unsigned int maxlen = *response_len;
817 GSList *aliases = NULL, *list;
818 char name[NS_MAXDNAME + 1];
823 DBG("qr %d qdcount %d", hdr->qr, qdcount);
825 /* We currently only cache responses where question count is 1 */
826 if (hdr->qr != 1 || qdcount != 1)
829 ptr = buf + sizeof(struct domain_hdr);
831 strncpy(question, (char *) ptr, qlen);
832 qlen = strlen(question);
833 ptr += qlen + 1; /* skip \0 */
836 qtype = ntohs(q->type);
838 /* We cache only A and AAAA records */
839 if (qtype != 1 && qtype != 28)
842 qclass = ntohs(q->class);
844 ptr += 2 + 2; /* ptr points now to answers */
851 * We have a bunch of answers (like A, AAAA, CNAME etc) to
852 * A or AAAA question. We traverse the answers and parse the
853 * resource records. Only A and AAAA records are cached, all
854 * the other records in answers are skipped.
856 for (i = 0; i < ancount; i++) {
858 * Get one address at a time to this buffer.
859 * The max size of the answer is
860 * 2 (pointer) + 2 (type) + 2 (class) +
861 * 4 (ttl) + 2 (rdlen) + addr (16 or 4) = 28
862 * for A or AAAA record.
863 * For CNAME the size can be bigger.
865 unsigned char rsp[NS_MAXCDNAME];
866 unsigned int rsp_len = sizeof(rsp) - 1;
869 memset(rsp, 0, sizeof(rsp));
871 ret = parse_rr(buf, ptr, buf + buflen, rsp, &rsp_len,
872 type, class, ttl, &rdlen, &next, name);
879 * Now rsp contains compressed or uncompressed resource
880 * record. Next we check if this record answers the question.
881 * The name var contains the uncompressed label.
882 * One tricky bit is the CNAME records as they alias
883 * the name we might be interested in.
887 * Go to next answer if the class is not the one we are
890 if (*class != qclass) {
897 * Try to resolve aliases also, type is CNAME(5).
898 * This is important as otherwise the aliased names would not
899 * be cached at all as the cache would not contain the aliased
902 * If any CNAME is found in DNS packet, then we cache the alias
903 * IP address instead of the question (as the server
904 * said that question has only an alias).
905 * This means in practice that if e.g., ipv6.google.com is
906 * queried, DNS server returns CNAME of that name which is
907 * ipv6.l.google.com. We then cache the address of the CNAME
908 * but return the question name to client. So the alias
909 * status of the name is not saved in cache and thus not
910 * returned to the client. We do not return DNS packets from
911 * cache to client saying that ipv6.google.com is an alias to
912 * ipv6.l.google.com but we return instead a DNS packet that
913 * says ipv6.google.com has address xxx which is in fact the
914 * address of ipv6.l.google.com. For caching purposes this
915 * should not cause any issues.
917 if (*type == 5 && strncmp(question, name, qlen) == 0) {
919 * So now the alias answered the question. This is
920 * not very useful from caching point of view as
921 * the following A or AAAA records will not match the
922 * question. We need to find the real A/AAAA record
923 * of the alias and cache that.
925 unsigned char *end = NULL;
926 int name_len = 0, output_len;
928 memset(rsp, 0, sizeof(rsp));
929 rsp_len = sizeof(rsp) - 1;
932 * Alias is in rdata part of the message,
933 * and next-rdlen points to it. So we need to get
934 * the real name of the alias.
936 ret = get_name(0, buf, next - rdlen, buf + buflen,
937 rsp, rsp_len, &output_len, &end,
940 /* just ignore the error at this point */
947 * We should now have the alias of the entry we might
948 * want to cache. Just remember it for a while.
949 * We check the alias list when we have parsed the
952 aliases = g_slist_prepend(aliases, g_strdup(name));
959 if (*type == qtype) {
961 * We found correct type (A or AAAA)
963 if (check_alias(aliases, name) == TRUE ||
964 (aliases == NULL && strncmp(question, name,
967 * We found an alias or the name of the rr
968 * matches the question. If so, we append
969 * the compressed label to the cache.
970 * The end result is a response buffer that
971 * will contain one or more cached and
972 * compressed resource records.
974 if (*response_len + rsp_len > maxlen) {
978 memcpy(response + *response_len, rsp, rsp_len);
979 *response_len += rsp_len;
990 for (list = aliases; list; list = list->next)
992 g_slist_free(aliases);
997 struct cache_timeout {
1003 static gboolean cache_check_entry(gpointer key, gpointer value,
1006 struct cache_timeout *data = user_data;
1007 struct cache_entry *entry = value;
1010 /* Scale the number of hits by half as part of cache aging */
1015 * If either IPv4 or IPv6 cached entry has expired, we
1016 * remove both from the cache.
1019 if (entry->ipv4 != NULL && entry->ipv4->timeout > 0) {
1020 max_timeout = entry->ipv4->cache_until;
1021 if (max_timeout > data->max_timeout)
1022 data->max_timeout = max_timeout;
1024 if (entry->ipv4->cache_until < data->current_time)
1028 if (entry->ipv6 != NULL && entry->ipv6->timeout > 0) {
1029 max_timeout = entry->ipv6->cache_until;
1030 if (max_timeout > data->max_timeout)
1031 data->max_timeout = max_timeout;
1033 if (entry->ipv6->cache_until < data->current_time)
1038 * if we're asked to try harder, also remove entries that have
1041 if (data->try_harder && entry->hits < 4)
1047 static void cache_cleanup(void)
1049 static int max_timeout;
1050 struct cache_timeout data;
1053 data.current_time = time(NULL);
1054 data.max_timeout = 0;
1055 data.try_harder = 0;
1058 * In the first pass, we only remove entries that have timed out.
1059 * We use a cache of the first time to expire to do this only
1060 * when it makes sense.
1062 if (max_timeout <= data.current_time) {
1063 count = g_hash_table_foreach_remove(cache, cache_check_entry,
1066 DBG("removed %d in the first pass", count);
1069 * In the second pass, if the first pass turned up blank,
1070 * we also expire entries with a low hit count,
1071 * while aging the hit count at the same time.
1073 data.try_harder = 1;
1075 count = g_hash_table_foreach_remove(cache, cache_check_entry,
1080 * If we could not remove anything, then remember
1081 * what is the max timeout and do nothing if we
1082 * have not yet reached it. This will prevent
1083 * constant traversal of the cache if it is full.
1085 max_timeout = data.max_timeout;
1090 static gboolean cache_invalidate_entry(gpointer key, gpointer value,
1093 struct cache_entry *entry = value;
1095 /* first, delete any expired elements */
1096 cache_enforce_validity(entry);
1098 /* if anything is not expired, mark the entry for refresh */
1099 if (entry->hits > 0 && (entry->ipv4 || entry->ipv6))
1100 entry->want_refresh = 1;
1102 /* delete the cached data */
1104 g_free(entry->ipv4->data);
1105 g_free(entry->ipv4);
1110 g_free(entry->ipv6->data);
1111 g_free(entry->ipv6);
1115 /* keep the entry if we want it refreshed, delete it otherwise */
1116 if (entry->want_refresh)
1123 * cache_invalidate is called from places where the DNS landscape
1124 * has changed, say because connections are added or we entered a VPN.
1125 * The logic is to wipe all cache data, but mark all non-expired
1126 * parts of the cache for refresh rather than deleting the whole cache.
1128 static void cache_invalidate(void)
1130 DBG("Invalidating the DNS cache %p", cache);
1135 g_hash_table_foreach_remove(cache, cache_invalidate_entry, NULL);
1138 static void cache_refresh_entry(struct cache_entry *entry)
1141 cache_enforce_validity(entry);
1143 if (entry->hits > 2 && entry->ipv4 == NULL)
1144 entry->want_refresh = 1;
1145 if (entry->hits > 2 && entry->ipv6 == NULL)
1146 entry->want_refresh = 1;
1148 if (entry->want_refresh) {
1150 char dns_name[NS_MAXDNAME + 1];
1151 entry->want_refresh = 0;
1153 /* turn a DNS name into a hostname with dots */
1154 strncpy(dns_name, entry->key, NS_MAXDNAME);
1162 DBG("Refreshing %s\n", dns_name);
1163 /* then refresh the hostname */
1164 refresh_dns_entry(entry, &dns_name[1]);
1168 static void cache_refresh_iterator(gpointer key, gpointer value,
1171 struct cache_entry *entry = value;
1173 cache_refresh_entry(entry);
1176 static void cache_refresh(void)
1181 g_hash_table_foreach(cache, cache_refresh_iterator, NULL);
1184 static int reply_query_type(unsigned char *msg, int len)
1191 /* skip the header */
1192 c = msg + sizeof(struct domain_hdr);
1193 len -= sizeof(struct domain_hdr);
1198 /* now the query, which is a name and 2 16 bit words */
1199 l = dns_name_length(c) + 1;
1207 static int cache_update(struct server_data *srv, unsigned char *msg,
1208 unsigned int msg_len)
1210 int offset = protocol_offset(srv->protocol);
1211 int err, qlen, ttl = 0;
1212 uint16_t answers = 0, type = 0, class = 0;
1213 struct domain_question *q;
1214 struct cache_entry *entry;
1215 struct cache_data *data;
1216 char question[NS_MAXDNAME + 1];
1217 unsigned char response[NS_MAXDNAME + 1];
1219 unsigned int rsplen;
1220 gboolean new_entry = TRUE;
1221 time_t current_time;
1223 if (cache_size >= MAX_CACHE_SIZE) {
1225 if (cache_size >= MAX_CACHE_SIZE)
1229 current_time = time(NULL);
1231 /* don't do a cache refresh more than twice a minute */
1232 if (next_refresh < current_time) {
1234 next_refresh = current_time + 30;
1238 /* Continue only if response code is 0 (=ok) */
1245 rsplen = sizeof(response) - 1;
1246 question[sizeof(question) - 1] = '\0';
1248 err = parse_response(msg + offset, msg_len - offset,
1249 question, sizeof(question) - 1,
1250 &type, &class, &ttl,
1251 response, &rsplen, &answers);
1254 * special case: if we do a ipv6 lookup and get no result
1255 * for a record that's already in our ipv4 cache.. we want
1256 * to cache the negative response.
1258 if ((err == -ENOMSG || err == -ENOBUFS) &&
1259 reply_query_type(msg, msg_len) == 28) {
1260 entry = g_hash_table_lookup(cache, question);
1261 if (entry && entry->ipv4 && entry->ipv6 == NULL) {
1262 data = g_try_new(struct cache_data, 1);
1265 data->inserted = entry->ipv4->inserted;
1267 data->answers = msg[5];
1268 data->timeout = entry->ipv4->timeout;
1269 data->data_len = msg_len;
1270 data->data = ptr = g_malloc(msg_len);
1271 data->valid_until = entry->ipv4->valid_until;
1272 data->cache_until = entry->ipv4->cache_until;
1273 memcpy(data->data, msg, msg_len);
1276 * we will get a "hit" when we serve the response
1280 if (entry->hits < 0)
1286 if (err < 0 || ttl == 0)
1289 qlen = strlen(question);
1292 * If the cache contains already data, check if the
1293 * type of the cached data is the same and do not add
1294 * to cache if data is already there.
1295 * This is needed so that we can cache both A and AAAA
1296 * records for the same name.
1298 entry = g_hash_table_lookup(cache, question);
1299 if (entry == NULL) {
1300 entry = g_try_new(struct cache_entry, 1);
1304 data = g_try_new(struct cache_data, 1);
1310 entry->key = g_strdup(question);
1311 entry->ipv4 = entry->ipv6 = NULL;
1312 entry->want_refresh = 0;
1320 if (type == 1 && entry->ipv4 != NULL)
1323 if (type == 28 && entry->ipv6 != NULL)
1326 data = g_try_new(struct cache_data, 1);
1336 * compensate for the hit we'll get for serving
1337 * the response out of the cache
1340 if (entry->hits < 0)
1346 if (ttl < MIN_CACHE_TTL)
1347 ttl = MIN_CACHE_TTL;
1349 data->inserted = current_time;
1351 data->answers = answers;
1352 data->timeout = ttl;
1353 data->data_len = 12 + qlen + 1 + 2 + 2 + rsplen;
1354 data->data = ptr = g_malloc(data->data_len);
1355 data->valid_until = current_time + ttl;
1358 * Restrict the cached DNS record TTL to some sane value
1359 * in order to prevent data staying in the cache too long.
1361 if (ttl > MAX_CACHE_TTL)
1362 ttl = MAX_CACHE_TTL;
1364 data->cache_until = round_down_ttl(current_time + ttl, ttl);
1366 if (data->data == NULL) {
1373 memcpy(ptr, msg, 12);
1374 memcpy(ptr + 12, question, qlen + 1); /* copy also the \0 */
1376 q = (void *) (ptr + 12 + qlen + 1);
1377 q->type = htons(type);
1378 q->class = htons(class);
1379 memcpy(ptr + 12 + qlen + 1 + sizeof(struct domain_question),
1382 if (new_entry == TRUE) {
1383 g_hash_table_replace(cache, entry->key, entry);
1387 DBG("cache %d %squestion \"%s\" type %d ttl %d size %zd",
1388 cache_size, new_entry ? "new " : "old ",
1389 question, type, ttl,
1390 sizeof(*entry) + sizeof(*data) + data->data_len + qlen);
1395 static int ns_resolv(struct server_data *server, struct request_data *req,
1396 gpointer request, gpointer name)
1399 int sk, err, type = 0;
1400 char *dot, *lookup = (char *) name;
1401 struct cache_entry *entry;
1403 entry = cache_check(request, &type);
1404 if (entry != NULL) {
1406 struct cache_data *data;
1408 DBG("cache hit %s type %s", lookup, type == 1 ? "A" : "AAAA");
1415 ttl_left = data->valid_until - time(NULL);
1419 if (data != NULL && req->protocol == IPPROTO_TCP) {
1420 send_cached_response(req->client_sk, data->data,
1421 data->data_len, NULL, 0, IPPROTO_TCP,
1422 req->srcid, data->answers, ttl_left);
1426 if (data != NULL && req->protocol == IPPROTO_UDP) {
1428 sk = g_io_channel_unix_get_fd(
1429 req->ifdata->udp_listener_channel);
1431 send_cached_response(sk, data->data,
1432 data->data_len, &req->sa, req->sa_len,
1433 IPPROTO_UDP, req->srcid, data->answers,
1439 sk = g_io_channel_unix_get_fd(server->channel);
1441 err = send(sk, request, req->request_len, 0);
1447 /* If we have more than one dot, we don't add domains */
1448 dot = strchr(lookup, '.');
1449 if (dot != NULL && dot != lookup + strlen(lookup) - 1)
1452 if (server->domains != NULL && server->domains->data != NULL)
1453 req->append_domain = TRUE;
1455 for (list = server->domains; list; list = list->next) {
1457 unsigned char alt[1024];
1458 struct domain_hdr *hdr = (void *) &alt;
1459 int altlen, domlen, offset;
1461 domain = list->data;
1466 offset = protocol_offset(server->protocol);
1470 domlen = strlen(domain) + 1;
1474 alt[offset] = req->altid & 0xff;
1475 alt[offset + 1] = req->altid >> 8;
1477 memcpy(alt + offset + 2, request + offset + 2, 10);
1478 hdr->qdcount = htons(1);
1480 altlen = append_query(alt + offset + 12, sizeof(alt) - 12,
1487 memcpy(alt + offset + altlen,
1488 request + offset + altlen - domlen,
1489 req->request_len - altlen - offset + domlen);
1491 if (server->protocol == IPPROTO_TCP) {
1492 int req_len = req->request_len + domlen - 2;
1494 alt[0] = (req_len >> 8) & 0xff;
1495 alt[1] = req_len & 0xff;
1498 err = send(sk, alt, req->request_len + domlen, 0);
1508 static int forward_dns_reply(unsigned char *reply, int reply_len, int protocol,
1509 struct server_data *data)
1511 struct domain_hdr *hdr;
1512 struct request_data *req;
1513 int dns_id, sk, err, offset = protocol_offset(protocol);
1514 struct listener_data *ifdata;
1519 hdr = (void *)(reply + offset);
1520 dns_id = reply[offset] | reply[offset + 1] << 8;
1522 DBG("Received %d bytes (id 0x%04x)", reply_len, dns_id);
1524 req = find_request(dns_id);
1528 DBG("id 0x%04x rcode %d", hdr->id, hdr->rcode);
1530 ifdata = req->ifdata;
1532 reply[offset] = req->srcid & 0xff;
1533 reply[offset + 1] = req->srcid >> 8;
1537 if (hdr->rcode == 0 || req->resp == NULL) {
1540 * If the domain name was append
1541 * remove it before forwarding the reply.
1543 if (req->append_domain == TRUE) {
1546 unsigned int domain_len;
1549 * ptr points to the first char of the hostname.
1550 * ->hostname.domain.net
1552 ptr = reply + offset + sizeof(struct domain_hdr);
1554 domain_len = strlen((const char *)ptr) - host_len - 1;
1557 * remove the domain name and replaced it by the end
1560 memmove(ptr + host_len + 1,
1561 ptr + host_len + domain_len + 1,
1562 reply_len - (ptr - reply + domain_len));
1564 reply_len = reply_len - domain_len;
1570 req->resp = g_try_malloc(reply_len);
1571 if (req->resp == NULL)
1574 memcpy(req->resp, reply, reply_len);
1575 req->resplen = reply_len;
1577 cache_update(data, reply, reply_len);
1580 if (hdr->rcode > 0 && req->numresp < req->numserv)
1583 if (req->timeout > 0)
1584 g_source_remove(req->timeout);
1586 request_list = g_slist_remove(request_list, req);
1588 if (protocol == IPPROTO_UDP) {
1589 sk = g_io_channel_unix_get_fd(ifdata->udp_listener_channel);
1590 err = sendto(sk, req->resp, req->resplen, 0,
1591 &req->sa, req->sa_len);
1593 sk = req->client_sk;
1594 err = send(sk, req->resp, req->resplen, 0);
1604 static void cache_element_destroy(gpointer value)
1606 struct cache_entry *entry = value;
1611 if (entry->ipv4 != NULL) {
1612 g_free(entry->ipv4->data);
1613 g_free(entry->ipv4);
1616 if (entry->ipv6 != NULL) {
1617 g_free(entry->ipv6->data);
1618 g_free(entry->ipv6);
1624 if (--cache_size < 0)
1628 static gboolean try_remove_cache(gpointer user_data)
1630 if (__sync_fetch_and_sub(&cache_refcount, 1) == 1) {
1631 DBG("No cache users, removing it.");
1633 g_hash_table_destroy(cache);
1640 static void destroy_server(struct server_data *server)
1644 DBG("interface %s server %s", server->interface, server->server);
1646 server_list = g_slist_remove(server_list, server);
1648 if (server->watch > 0)
1649 g_source_remove(server->watch);
1651 if (server->timeout > 0)
1652 g_source_remove(server->timeout);
1654 g_io_channel_unref(server->channel);
1656 if (server->protocol == IPPROTO_UDP)
1657 connman_info("Removing DNS server %s", server->server);
1659 g_free(server->incoming_reply);
1660 g_free(server->server);
1661 for (list = server->domains; list; list = list->next) {
1662 char *domain = list->data;
1664 server->domains = g_list_remove(server->domains, domain);
1667 g_free(server->interface);
1670 * We do not remove cache right away but delay it few seconds.
1671 * The idea is that when IPv6 DNS server is added via RDNSS, it has a
1672 * lifetime. When the lifetime expires we decrease the refcount so it
1673 * is possible that the cache is then removed. Because a new DNS server
1674 * is usually created almost immediately we would then loose the cache
1675 * without any good reason. The small delay allows the new RDNSS to
1676 * create a new DNS server instance and the refcount does not go to 0.
1678 g_timeout_add_seconds(3, try_remove_cache, NULL);
1683 static gboolean udp_server_event(GIOChannel *channel, GIOCondition condition,
1686 unsigned char buf[4096];
1688 struct server_data *data = user_data;
1690 if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
1691 connman_error("Error with UDP server %s", data->server);
1696 sk = g_io_channel_unix_get_fd(channel);
1698 len = recv(sk, buf, sizeof(buf), 0);
1702 err = forward_dns_reply(buf, len, IPPROTO_UDP, data);
1709 static gboolean tcp_server_event(GIOChannel *channel, GIOCondition condition,
1713 struct server_data *server = user_data;
1715 sk = g_io_channel_unix_get_fd(channel);
1719 if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
1722 DBG("TCP server channel closed");
1725 * Discard any partial response which is buffered; better
1726 * to get a proper response from a working server.
1728 g_free(server->incoming_reply);
1729 server->incoming_reply = NULL;
1731 for (list = request_list; list; list = list->next) {
1732 struct request_data *req = list->data;
1733 struct domain_hdr *hdr;
1735 if (req->protocol == IPPROTO_UDP)
1738 if (req->request == NULL)
1742 * If we're not waiting for any further response
1743 * from another name server, then we send an error
1744 * response to the client.
1746 if (req->numserv && --(req->numserv))
1749 hdr = (void *) (req->request + 2);
1750 hdr->id = req->srcid;
1751 send_response(req->client_sk, req->request,
1752 req->request_len, NULL, 0, IPPROTO_TCP);
1754 request_list = g_slist_remove(request_list, req);
1757 destroy_server(server);
1762 if ((condition & G_IO_OUT) && !server->connected) {
1765 struct server_data *udp_server;
1767 udp_server = find_server(server->interface, server->server,
1769 if (udp_server != NULL) {
1770 for (domains = udp_server->domains; domains;
1771 domains = domains->next) {
1772 char *dom = domains->data;
1774 DBG("Adding domain %s to %s",
1775 dom, server->server);
1777 server->domains = g_list_append(server->domains,
1782 server->connected = TRUE;
1783 server_list = g_slist_append(server_list, server);
1785 if (server->timeout > 0) {
1786 g_source_remove(server->timeout);
1787 server->timeout = 0;
1790 for (list = request_list; list; list = list->next) {
1791 struct request_data *req = list->data;
1793 if (req->protocol == IPPROTO_UDP)
1796 DBG("Sending req %s over TCP", (char *)req->name);
1798 if (req->timeout > 0)
1799 g_source_remove(req->timeout);
1801 req->timeout = g_timeout_add_seconds(30,
1802 request_timeout, req);
1803 if (ns_resolv(server, req, req->request,
1805 /* We sent cached result so no need for timeout
1808 if (req->timeout > 0) {
1809 g_source_remove(req->timeout);
1815 } else if (condition & G_IO_IN) {
1816 struct partial_reply *reply = server->incoming_reply;
1820 unsigned char reply_len_buf[2];
1823 bytes_recv = recv(sk, reply_len_buf, 2, MSG_PEEK);
1826 } else if (bytes_recv < 0) {
1827 if (errno == EAGAIN || errno == EWOULDBLOCK)
1830 connman_error("DNS proxy error %s",
1833 } else if (bytes_recv < 2)
1836 reply_len = reply_len_buf[1] | reply_len_buf[0] << 8;
1839 DBG("TCP reply %d bytes", reply_len);
1841 reply = g_try_malloc(sizeof(*reply) + reply_len + 2);
1845 reply->len = reply_len;
1846 reply->received = 0;
1848 server->incoming_reply = reply;
1851 while (reply->received < reply->len) {
1852 bytes_recv = recv(sk, reply->buf + reply->received,
1853 reply->len - reply->received, 0);
1855 connman_error("DNS proxy TCP disconnect");
1857 } else if (bytes_recv < 0) {
1858 if (errno == EAGAIN || errno == EWOULDBLOCK)
1861 connman_error("DNS proxy error %s",
1865 reply->received += bytes_recv;
1868 forward_dns_reply(reply->buf, reply->received, IPPROTO_TCP,
1872 server->incoming_reply = NULL;
1874 destroy_server(server);
1882 static gboolean tcp_idle_timeout(gpointer user_data)
1884 struct server_data *server = user_data;
1891 destroy_server(server);
1896 static struct server_data *create_server(const char *interface,
1897 const char *domain, const char *server,
1900 struct addrinfo hints, *rp;
1901 struct server_data *data;
1904 DBG("interface %s server %s", interface, server);
1906 memset(&hints, 0, sizeof(hints));
1910 hints.ai_socktype = SOCK_DGRAM;
1914 hints.ai_socktype = SOCK_STREAM;
1920 hints.ai_family = AF_UNSPEC;
1921 hints.ai_flags = AI_PASSIVE | AI_NUMERICSERV | AI_NUMERICHOST;
1923 ret = getaddrinfo(server, "53", &hints, &rp);
1925 connman_error("Failed to parse server %s address: %s\n",
1926 server, gai_strerror(ret));
1929 /* Do not blindly copy this code elsewhere; it doesn't loop over the
1930 results using ->ai_next as it should. That's OK in *this* case
1931 because it was a numeric lookup; we *know* there's only one. */
1933 sk = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
1935 connman_error("Failed to create server %s socket", server);
1940 if (interface != NULL) {
1941 if (setsockopt(sk, SOL_SOCKET, SO_BINDTODEVICE,
1942 interface, strlen(interface) + 1) < 0) {
1943 connman_error("Failed to bind server %s "
1952 data = g_try_new0(struct server_data, 1);
1954 connman_error("Failed to allocate server %s data", server);
1960 data->channel = g_io_channel_unix_new(sk);
1961 if (data->channel == NULL) {
1962 connman_error("Failed to create server %s channel", server);
1969 g_io_channel_set_close_on_unref(data->channel, TRUE);
1971 if (protocol == IPPROTO_TCP) {
1972 g_io_channel_set_flags(data->channel, G_IO_FLAG_NONBLOCK, NULL);
1973 data->watch = g_io_add_watch(data->channel,
1974 G_IO_OUT | G_IO_IN | G_IO_HUP | G_IO_NVAL | G_IO_ERR,
1975 tcp_server_event, data);
1976 data->timeout = g_timeout_add_seconds(30, tcp_idle_timeout,
1979 data->watch = g_io_add_watch(data->channel,
1980 G_IO_IN | G_IO_NVAL | G_IO_ERR | G_IO_HUP,
1981 udp_server_event, data);
1983 data->interface = g_strdup(interface);
1985 data->domains = g_list_append(data->domains, g_strdup(domain));
1986 data->server = g_strdup(server);
1987 data->protocol = protocol;
1989 ret = connect(sk, rp->ai_addr, rp->ai_addrlen);
1992 if ((protocol == IPPROTO_TCP && errno != EINPROGRESS) ||
1993 protocol == IPPROTO_UDP) {
1996 connman_error("Failed to connect to server %s", server);
1997 if (data->watch > 0)
1998 g_source_remove(data->watch);
1999 if (data->timeout > 0)
2000 g_source_remove(data->timeout);
2002 g_io_channel_unref(data->channel);
2005 g_free(data->server);
2006 g_free(data->interface);
2007 for (list = data->domains; list; list = list->next) {
2008 char *domain = list->data;
2010 data->domains = g_list_remove(data->domains,
2019 if (__sync_fetch_and_add(&cache_refcount, 1) == 0)
2020 cache = g_hash_table_new_full(g_str_hash,
2023 cache_element_destroy);
2025 if (protocol == IPPROTO_UDP) {
2026 /* Enable new servers by default */
2027 data->enabled = TRUE;
2028 connman_info("Adding DNS server %s", data->server);
2030 server_list = g_slist_append(server_list, data);
2038 static gboolean resolv(struct request_data *req,
2039 gpointer request, gpointer name)
2044 for (list = server_list; list; list = list->next) {
2045 struct server_data *data = list->data;
2047 DBG("server %s enabled %d", data->server, data->enabled);
2049 if (data->enabled == FALSE)
2052 if (data->watch == 0 && data->protocol == IPPROTO_UDP)
2053 data->watch = g_io_add_watch(data->channel,
2054 G_IO_IN | G_IO_NVAL | G_IO_ERR | G_IO_HUP,
2055 udp_server_event, data);
2057 status = ns_resolv(data, req, request, name);
2062 if (req->timeout > 0) {
2063 g_source_remove(req->timeout);
2072 static void append_domain(const char *interface, const char *domain)
2076 DBG("interface %s domain %s", interface, domain);
2081 for (list = server_list; list; list = list->next) {
2082 struct server_data *data = list->data;
2085 gboolean dom_found = FALSE;
2087 if (data->interface == NULL)
2090 if (g_str_equal(data->interface, interface) == FALSE)
2093 for (dom_list = data->domains; dom_list;
2094 dom_list = dom_list->next) {
2095 dom = dom_list->data;
2097 if (g_str_equal(dom, domain)) {
2103 if (dom_found == FALSE) {
2105 g_list_append(data->domains, g_strdup(domain));
2110 int __connman_dnsproxy_append(const char *interface, const char *domain,
2113 struct server_data *data;
2115 DBG("interface %s server %s", interface, server);
2117 if (server == NULL && domain == NULL)
2120 if (server == NULL) {
2121 append_domain(interface, domain);
2126 if (g_str_equal(server, "127.0.0.1") == TRUE)
2129 data = find_server(interface, server, IPPROTO_UDP);
2131 append_domain(interface, domain);
2135 data = create_server(interface, domain, server, IPPROTO_UDP);
2142 static void remove_server(const char *interface, const char *domain,
2143 const char *server, int protocol)
2145 struct server_data *data;
2147 data = find_server(interface, server, protocol);
2151 destroy_server(data);
2154 int __connman_dnsproxy_remove(const char *interface, const char *domain,
2157 DBG("interface %s server %s", interface, server);
2162 if (g_str_equal(server, "127.0.0.1") == TRUE)
2165 remove_server(interface, domain, server, IPPROTO_UDP);
2166 remove_server(interface, domain, server, IPPROTO_TCP);
2171 void __connman_dnsproxy_flush(void)
2175 list = request_pending_list;
2177 struct request_data *req = list->data;
2181 request_pending_list =
2182 g_slist_remove(request_pending_list, req);
2183 resolv(req, req->request, req->name);
2184 g_free(req->request);
2189 static void dnsproxy_offline_mode(connman_bool_t enabled)
2193 DBG("enabled %d", enabled);
2195 for (list = server_list; list; list = list->next) {
2196 struct server_data *data = list->data;
2198 if (enabled == FALSE) {
2199 connman_info("Enabling DNS server %s", data->server);
2200 data->enabled = TRUE;
2204 connman_info("Disabling DNS server %s", data->server);
2205 data->enabled = FALSE;
2211 static void dnsproxy_default_changed(struct connman_service *service)
2216 DBG("service %p", service);
2218 /* DNS has changed, invalidate the cache */
2221 if (service == NULL) {
2222 /* When no services are active, then disable DNS proxying */
2223 dnsproxy_offline_mode(TRUE);
2227 interface = connman_service_get_interface(service);
2228 if (interface == NULL)
2231 for (list = server_list; list; list = list->next) {
2232 struct server_data *data = list->data;
2234 if (g_strcmp0(data->interface, interface) == 0) {
2235 connman_info("Enabling DNS server %s", data->server);
2236 data->enabled = TRUE;
2238 connman_info("Disabling DNS server %s", data->server);
2239 data->enabled = FALSE;
2247 static struct connman_notifier dnsproxy_notifier = {
2249 .default_changed = dnsproxy_default_changed,
2250 .offline_mode = dnsproxy_offline_mode,
2253 static unsigned char opt_edns0_type[2] = { 0x00, 0x29 };
2255 static int parse_request(unsigned char *buf, int len,
2256 char *name, unsigned int size)
2258 struct domain_hdr *hdr = (void *) buf;
2259 uint16_t qdcount = ntohs(hdr->qdcount);
2260 uint16_t arcount = ntohs(hdr->arcount);
2262 char *last_label = NULL;
2263 unsigned int remain, used = 0;
2268 DBG("id 0x%04x qr %d opcode %d qdcount %d arcount %d",
2269 hdr->id, hdr->qr, hdr->opcode,
2272 if (hdr->qr != 0 || qdcount != 1)
2275 memset(name, 0, size);
2277 ptr = buf + sizeof(struct domain_hdr);
2278 remain = len - sizeof(struct domain_hdr);
2280 while (remain > 0) {
2284 last_label = (char *) (ptr + 1);
2288 if (used + len + 1 > size)
2291 strncat(name, (char *) (ptr + 1), len);
2300 if (last_label && arcount && remain >= 9 && last_label[4] == 0 &&
2301 !memcmp(last_label + 5, opt_edns0_type, 2)) {
2302 uint16_t edns0_bufsize;
2304 edns0_bufsize = last_label[7] << 8 | last_label[8];
2306 DBG("EDNS0 buffer size %u", edns0_bufsize);
2308 /* This is an evil hack until full TCP support has been
2311 * Somtimes the EDNS0 request gets send with a too-small
2312 * buffer size. Since glibc doesn't seem to crash when it
2313 * gets a response biffer then it requested, just bump
2314 * the buffer size up to 4KiB.
2316 if (edns0_bufsize < 0x1000) {
2317 last_label[7] = 0x10;
2318 last_label[8] = 0x00;
2322 DBG("query %s", name);
2327 static gboolean tcp_listener_event(GIOChannel *channel, GIOCondition condition,
2330 unsigned char buf[768];
2332 struct request_data *req;
2333 struct server_data *server;
2334 int sk, client_sk, len, err;
2335 struct sockaddr_in6 client_addr;
2336 socklen_t client_addr_len = sizeof(client_addr);
2338 struct listener_data *ifdata = user_data;
2340 DBG("condition 0x%x", condition);
2342 if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
2343 if (ifdata->tcp_listener_watch > 0)
2344 g_source_remove(ifdata->tcp_listener_watch);
2345 ifdata->tcp_listener_watch = 0;
2347 connman_error("Error with TCP listener channel");
2352 sk = g_io_channel_unix_get_fd(channel);
2354 client_sk = accept(sk, (void *)&client_addr, &client_addr_len);
2355 if (client_sk < 0) {
2356 connman_error("Accept failure on TCP listener");
2357 ifdata->tcp_listener_watch = 0;
2361 len = recv(client_sk, buf, sizeof(buf), 0);
2365 DBG("Received %d bytes (id 0x%04x)", len, buf[2] | buf[3] << 8);
2367 err = parse_request(buf + 2, len - 2, query, sizeof(query));
2368 if (err < 0 || (g_slist_length(server_list) == 0)) {
2369 send_response(client_sk, buf, len, NULL, 0, IPPROTO_TCP);
2373 req = g_try_new0(struct request_data, 1);
2377 memcpy(&req->sa, &client_addr, client_addr_len);
2378 req->sa_len = client_addr_len;
2379 req->client_sk = client_sk;
2380 req->protocol = IPPROTO_TCP;
2383 if (request_id == 0x0000 || request_id == 0xffff)
2386 req->srcid = buf[2] | (buf[3] << 8);
2387 req->dstid = request_id;
2388 req->altid = request_id + 1;
2389 req->request_len = len;
2391 buf[2] = req->dstid & 0xff;
2392 buf[3] = req->dstid >> 8;
2395 req->ifdata = (struct listener_data *) ifdata;
2396 req->append_domain = FALSE;
2397 request_list = g_slist_append(request_list, req);
2399 for (list = server_list; list; list = list->next) {
2400 struct server_data *data = list->data;
2403 if (data->protocol != IPPROTO_UDP || data->enabled == FALSE)
2406 server = create_server(data->interface, NULL,
2407 data->server, IPPROTO_TCP);
2410 * If server is NULL, we're not connected yet.
2411 * Copy the relevant buffers and continue with
2412 * the next nameserver.
2413 * The request will actually be sent once we're
2414 * properly connected over TCP to this nameserver.
2416 if (server == NULL) {
2417 req->request = g_try_malloc0(req->request_len);
2418 if (req->request == NULL)
2421 memcpy(req->request, buf, req->request_len);
2423 req->name = g_try_malloc0(sizeof(query));
2424 if (req->name == NULL) {
2425 g_free(req->request);
2428 memcpy(req->name, query, sizeof(query));
2433 if (req->timeout > 0)
2434 g_source_remove(req->timeout);
2436 for (domains = data->domains; domains;
2437 domains = domains->next) {
2438 char *dom = domains->data;
2440 DBG("Adding domain %s to %s", dom, server->server);
2442 server->domains = g_list_append(server->domains,
2446 req->timeout = g_timeout_add_seconds(30, request_timeout, req);
2447 if (ns_resolv(server, req, buf, query) > 0) {
2448 if (req->timeout > 0) {
2449 g_source_remove(req->timeout);
2458 static gboolean udp_listener_event(GIOChannel *channel, GIOCondition condition,
2461 unsigned char buf[768];
2463 struct request_data *req;
2464 struct sockaddr_in6 client_addr;
2465 socklen_t client_addr_len = sizeof(client_addr);
2467 struct listener_data *ifdata = user_data;
2469 if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
2470 connman_error("Error with UDP listener channel");
2471 ifdata->udp_listener_watch = 0;
2475 sk = g_io_channel_unix_get_fd(channel);
2477 memset(&client_addr, 0, client_addr_len);
2478 len = recvfrom(sk, buf, sizeof(buf), 0, (void *)&client_addr,
2483 DBG("Received %d bytes (id 0x%04x)", len, buf[0] | buf[1] << 8);
2485 err = parse_request(buf, len, query, sizeof(query));
2486 if (err < 0 || (g_slist_length(server_list) == 0)) {
2487 send_response(sk, buf, len, (void *)&client_addr,
2488 client_addr_len, IPPROTO_UDP);
2492 req = g_try_new0(struct request_data, 1);
2496 memcpy(&req->sa, &client_addr, client_addr_len);
2497 req->sa_len = client_addr_len;
2499 req->protocol = IPPROTO_UDP;
2502 if (request_id == 0x0000 || request_id == 0xffff)
2505 req->srcid = buf[0] | (buf[1] << 8);
2506 req->dstid = request_id;
2507 req->altid = request_id + 1;
2508 req->request_len = len;
2510 buf[0] = req->dstid & 0xff;
2511 buf[1] = req->dstid >> 8;
2514 req->ifdata = (struct listener_data *) ifdata;
2515 req->timeout = g_timeout_add_seconds(5, request_timeout, req);
2516 req->append_domain = FALSE;
2517 request_list = g_slist_append(request_list, req);
2519 return resolv(req, buf, query);
2522 static int create_dns_listener(int protocol, struct listener_data *ifdata)
2524 GIOChannel *channel;
2528 struct sockaddr_in6 sin6;
2529 struct sockaddr_in sin;
2532 int sk, type, v6only = 0;
2533 int family = AF_INET6;
2536 DBG("interface %s", ifdata->ifname);
2541 type = SOCK_DGRAM | SOCK_CLOEXEC;
2546 type = SOCK_STREAM | SOCK_CLOEXEC;
2553 sk = socket(family, type, protocol);
2554 if (sk < 0 && family == AF_INET6 && errno == EAFNOSUPPORT) {
2555 connman_error("No IPv6 support; DNS proxy listening only on Legacy IP");
2557 sk = socket(family, type, protocol);
2560 connman_error("Failed to create %s listener socket", proto);
2564 if (setsockopt(sk, SOL_SOCKET, SO_BINDTODEVICE,
2566 strlen(ifdata->ifname) + 1) < 0) {
2567 connman_error("Failed to bind %s listener interface", proto);
2571 /* Ensure it accepts Legacy IP connections too */
2572 if (family == AF_INET6 &&
2573 setsockopt(sk, SOL_IPV6, IPV6_V6ONLY,
2574 &v6only, sizeof(v6only)) < 0) {
2575 connman_error("Failed to clear V6ONLY on %s listener socket",
2581 if (family == AF_INET) {
2582 memset(&s.sin, 0, sizeof(s.sin));
2583 s.sin.sin_family = AF_INET;
2584 s.sin.sin_port = htons(53);
2585 s.sin.sin_addr.s_addr = htonl(INADDR_ANY);
2586 slen = sizeof(s.sin);
2588 memset(&s.sin6, 0, sizeof(s.sin6));
2589 s.sin6.sin6_family = AF_INET6;
2590 s.sin6.sin6_port = htons(53);
2591 s.sin6.sin6_addr = in6addr_any;
2592 slen = sizeof(s.sin6);
2595 if (bind(sk, &s.sa, slen) < 0) {
2596 connman_error("Failed to bind %s listener socket", proto);
2601 if (protocol == IPPROTO_TCP && listen(sk, 10) < 0) {
2602 connman_error("Failed to listen on TCP socket");
2607 channel = g_io_channel_unix_new(sk);
2608 if (channel == NULL) {
2609 connman_error("Failed to create %s listener channel", proto);
2614 g_io_channel_set_close_on_unref(channel, TRUE);
2616 if (protocol == IPPROTO_TCP) {
2617 ifdata->tcp_listener_channel = channel;
2618 ifdata->tcp_listener_watch = g_io_add_watch(channel,
2619 G_IO_IN, tcp_listener_event, (gpointer) ifdata);
2621 ifdata->udp_listener_channel = channel;
2622 ifdata->udp_listener_watch = g_io_add_watch(channel,
2623 G_IO_IN, udp_listener_event, (gpointer) ifdata);
2629 static void destroy_udp_listener(struct listener_data *ifdata)
2631 DBG("interface %s", ifdata->ifname);
2633 if (ifdata->udp_listener_watch > 0)
2634 g_source_remove(ifdata->udp_listener_watch);
2636 g_io_channel_unref(ifdata->udp_listener_channel);
2639 static void destroy_tcp_listener(struct listener_data *ifdata)
2641 DBG("interface %s", ifdata->ifname);
2643 if (ifdata->tcp_listener_watch > 0)
2644 g_source_remove(ifdata->tcp_listener_watch);
2646 g_io_channel_unref(ifdata->tcp_listener_channel);
2649 static int create_listener(struct listener_data *ifdata)
2653 err = create_dns_listener(IPPROTO_UDP, ifdata);
2657 err = create_dns_listener(IPPROTO_TCP, ifdata);
2659 destroy_udp_listener(ifdata);
2663 if (g_strcmp0(ifdata->ifname, "lo") == 0)
2664 __connman_resolvfile_append("lo", NULL, "127.0.0.1");
2669 static void destroy_request_data(struct request_data *req)
2671 if (req->timeout > 0)
2672 g_source_remove(req->timeout);
2675 g_free(req->request);
2680 static void destroy_listener(struct listener_data *ifdata)
2684 if (g_strcmp0(ifdata->ifname, "lo") == 0)
2685 __connman_resolvfile_remove("lo", NULL, "127.0.0.1");
2687 for (list = request_pending_list; list; list = list->next) {
2688 struct request_data *req = list->data;
2690 DBG("Dropping pending request (id 0x%04x -> 0x%04x)",
2691 req->srcid, req->dstid);
2692 destroy_request_data(req);
2696 g_slist_free(request_pending_list);
2697 request_pending_list = NULL;
2699 for (list = request_list; list; list = list->next) {
2700 struct request_data *req = list->data;
2702 DBG("Dropping request (id 0x%04x -> 0x%04x)",
2703 req->srcid, req->dstid);
2704 destroy_request_data(req);
2708 g_slist_free(request_list);
2709 request_list = NULL;
2711 destroy_tcp_listener(ifdata);
2712 destroy_udp_listener(ifdata);
2715 int __connman_dnsproxy_add_listener(const char *interface)
2717 struct listener_data *ifdata;
2720 DBG("interface %s", interface);
2722 if (g_hash_table_lookup(listener_table, interface) != NULL)
2725 ifdata = g_try_new0(struct listener_data, 1);
2729 ifdata->ifname = g_strdup(interface);
2730 ifdata->udp_listener_channel = NULL;
2731 ifdata->udp_listener_watch = 0;
2732 ifdata->tcp_listener_channel = NULL;
2733 ifdata->tcp_listener_watch = 0;
2735 err = create_listener(ifdata);
2737 connman_error("Couldn't create listener for %s err %d",
2739 g_free(ifdata->ifname);
2743 g_hash_table_insert(listener_table, ifdata->ifname, ifdata);
2747 void __connman_dnsproxy_remove_listener(const char *interface)
2749 struct listener_data *ifdata;
2751 DBG("interface %s", interface);
2753 ifdata = g_hash_table_lookup(listener_table, interface);
2757 destroy_listener(ifdata);
2759 g_hash_table_remove(listener_table, interface);
2762 static void remove_listener(gpointer key, gpointer value, gpointer user_data)
2764 const char *interface = key;
2765 struct listener_data *ifdata = value;
2767 DBG("interface %s", interface);
2769 destroy_listener(ifdata);
2772 int __connman_dnsproxy_init(void)
2778 listener_table = g_hash_table_new_full(g_str_hash, g_str_equal,
2780 err = __connman_dnsproxy_add_listener("lo");
2784 err = connman_notifier_register(&dnsproxy_notifier);
2791 __connman_dnsproxy_remove_listener("lo");
2792 g_hash_table_destroy(listener_table);
2797 void __connman_dnsproxy_cleanup(void)
2801 connman_notifier_unregister(&dnsproxy_notifier);
2803 g_hash_table_foreach(listener_table, remove_listener, NULL);
2805 g_hash_table_destroy(listener_table);