5 * Copyright (C) 2007-2012 Intel Corporation. All rights reserved.
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License version 2 as
9 * published by the Free Software Foundation.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
31 #include <arpa/inet.h>
32 #include <netinet/in.h>
33 #include <sys/types.h>
34 #include <sys/socket.h>
37 #include <gweb/gresolv.h>
43 #if __BYTE_ORDER == __LITTLE_ENDIAN
58 } __attribute__ ((packed));
59 #elif __BYTE_ORDER == __BIG_ENDIAN
74 } __attribute__ ((packed));
76 #error "Unknown byte order"
79 struct partial_reply {
95 struct partial_reply *incoming_reply;
100 struct sockaddr_in6 __sin6; /* Only for the length */
118 struct listener_data *ifdata;
119 gboolean append_domain;
122 struct listener_data {
124 GIOChannel *udp_listener_channel;
125 guint udp_listener_watch;
126 GIOChannel *tcp_listener_channel;
127 guint tcp_listener_watch;
137 unsigned int data_len;
138 unsigned char *data; /* contains DNS header + body */
145 struct cache_data *ipv4;
146 struct cache_data *ipv6;
149 struct domain_question {
152 } __attribute__ ((packed));
159 } __attribute__ ((packed));
162 * We limit how long the cached DNS entry stays in the cache.
163 * By default the TTL (time-to-live) of the DNS response is used
164 * when setting the cache entry life time. The value is in seconds.
166 #define MAX_CACHE_TTL (60 * 30)
168 * Also limit the other end, cache at least for 30 seconds.
170 #define MIN_CACHE_TTL (30)
173 * We limit the cache size to some sane value so that cached data does
174 * not occupy too much memory. Each cached entry occupies on average
175 * about 100 bytes memory (depending on DNS name length).
176 * Example: caching www.connman.net uses 97 bytes memory.
177 * The value is the max amount of cached DNS responses (count).
179 #define MAX_CACHE_SIZE 256
181 static int cache_size;
182 static GHashTable *cache;
183 static int cache_refcount;
184 static GSList *server_list = NULL;
185 static GSList *request_list = NULL;
186 static GHashTable *listener_table = NULL;
187 static time_t next_refresh;
189 static guint16 get_id()
194 static int protocol_offset(int protocol)
210 * There is a power and efficiency benefit to have entries
211 * in our cache expire at the same time. To this extend,
212 * we round down the cache valid time to common boundaries.
214 static time_t round_down_ttl(time_t end_time, int ttl)
219 /* Less than 5 minutes, round to 10 second boundary */
221 end_time = end_time / 10;
222 end_time = end_time * 10;
223 } else { /* 5 or more minutes, round to 30 seconds */
224 end_time = end_time / 30;
225 end_time = end_time * 30;
230 static struct request_data *find_request(guint16 id)
234 for (list = request_list; list; list = list->next) {
235 struct request_data *req = list->data;
237 if (req->dstid == id || req->altid == id)
244 static struct server_data *find_server(const char *interface,
250 DBG("interface %s server %s", interface, server);
252 for (list = server_list; list; list = list->next) {
253 struct server_data *data = list->data;
255 if (interface == NULL && data->interface == NULL &&
256 g_str_equal(data->server, server) == TRUE &&
257 data->protocol == protocol)
260 if (interface == NULL ||
261 data->interface == NULL || data->server == NULL)
264 if (g_str_equal(data->interface, interface) == TRUE &&
265 g_str_equal(data->server, server) == TRUE &&
266 data->protocol == protocol)
273 /* we can keep using the same resolve's */
274 static GResolv *ipv4_resolve;
275 static GResolv *ipv6_resolve;
277 static void dummy_resolve_func(GResolvResultStatus status,
278 char **results, gpointer user_data)
283 * Refresh a DNS entry, but also age the hit count a bit */
284 static void refresh_dns_entry(struct cache_entry *entry, char *name)
288 if (ipv4_resolve == NULL) {
289 ipv4_resolve = g_resolv_new(0);
290 g_resolv_set_address_family(ipv4_resolve, AF_INET);
291 g_resolv_add_nameserver(ipv4_resolve, "127.0.0.1", 53, 0);
294 if (ipv6_resolve == NULL) {
295 ipv6_resolve = g_resolv_new(0);
296 g_resolv_set_address_family(ipv6_resolve, AF_INET6);
297 g_resolv_add_nameserver(ipv6_resolve, "127.0.0.1", 53, 0);
300 if (entry->ipv4 == NULL) {
301 DBG("Refresing A record for %s", name);
302 g_resolv_lookup_hostname(ipv4_resolve, name,
303 dummy_resolve_func, NULL);
307 if (entry->ipv6 == NULL) {
308 DBG("Refresing AAAA record for %s", name);
309 g_resolv_lookup_hostname(ipv6_resolve, name,
310 dummy_resolve_func, NULL);
319 static int dns_name_length(unsigned char *buf)
321 if ((buf[0] & NS_CMPRSFLGS) == NS_CMPRSFLGS) /* compressed name */
323 return strlen((char *)buf);
326 static void update_cached_ttl(unsigned char *buf, int len, int new_ttl)
333 /* skip the header */
337 /* skip the query, which is a name and 2 16 bit words */
338 l = dns_name_length(c);
344 /* now we get the answer records */
348 l = dns_name_length(c);
353 /* then type + class, 2 bytes each */
359 /* now the 4 byte TTL field */
367 /* now the 2 byte rdlen field */
370 len -= ntohs(*w) + 2;
374 static void send_cached_response(int sk, unsigned char *buf, int len,
375 const struct sockaddr *to, socklen_t tolen,
376 int protocol, int id, uint16_t answers, int ttl)
378 struct domain_hdr *hdr;
379 unsigned char *ptr = buf;
380 int err, offset, dns_len, adj_len = len - 2;
383 * The cached packet contains always the TCP offset (two bytes)
384 * so skip them for UDP.
395 dns_len = ptr[0] * 256 + ptr[1];
404 hdr = (void *) (ptr + offset);
409 hdr->ancount = htons(answers);
413 /* if this is a negative reply, we are authorative */
417 update_cached_ttl((unsigned char *)hdr, adj_len, ttl);
419 DBG("sk %d id 0x%04x answers %d ptr %p length %d dns %d",
420 sk, hdr->id, answers, ptr, len, dns_len);
422 err = sendto(sk, ptr, len, MSG_NOSIGNAL, to, tolen);
424 connman_error("Cannot send cached DNS response: %s",
429 if (err != len || (dns_len != (len - 2) && protocol == IPPROTO_TCP) ||
430 (dns_len != len && protocol == IPPROTO_UDP))
431 DBG("Packet length mismatch, sent %d wanted %d dns %d",
435 static void send_response(int sk, unsigned char *buf, int len,
436 const struct sockaddr *to, socklen_t tolen,
439 struct domain_hdr *hdr;
440 int err, offset = protocol_offset(protocol);
450 hdr = (void *) (buf + offset);
452 DBG("id 0x%04x qr %d opcode %d", hdr->id, hdr->qr, hdr->opcode);
461 err = sendto(sk, buf, len, MSG_NOSIGNAL, to, tolen);
463 connman_error("Failed to send DNS response to %d: %s",
464 sk, strerror(errno));
469 static gboolean request_timeout(gpointer user_data)
471 struct request_data *req = user_data;
472 struct listener_data *ifdata;
474 DBG("id 0x%04x", req->srcid);
479 ifdata = req->ifdata;
481 request_list = g_slist_remove(request_list, req);
484 if (req->resplen > 0 && req->resp != NULL) {
487 sk = g_io_channel_unix_get_fd(ifdata->udp_listener_channel);
489 err = sendto(sk, req->resp, req->resplen, MSG_NOSIGNAL,
490 &req->sa, req->sa_len);
493 } else if (req->request && req->numserv == 0) {
494 struct domain_hdr *hdr;
496 if (req->protocol == IPPROTO_TCP) {
497 hdr = (void *) (req->request + 2);
498 hdr->id = req->srcid;
499 send_response(req->client_sk, req->request,
500 req->request_len, NULL, 0, IPPROTO_TCP);
502 } else if (req->protocol == IPPROTO_UDP) {
505 hdr = (void *) (req->request);
506 hdr->id = req->srcid;
507 sk = g_io_channel_unix_get_fd(
508 ifdata->udp_listener_channel);
509 send_response(sk, req->request, req->request_len,
510 &req->sa, req->sa_len, IPPROTO_UDP);
520 static int append_query(unsigned char *buf, unsigned int size,
521 const char *query, const char *domain)
523 unsigned char *ptr = buf;
526 DBG("query %s domain %s", query, domain);
528 while (query != NULL) {
531 tmp = strchr(query, '.');
537 memcpy(ptr + 1, query, len);
543 memcpy(ptr + 1, query, tmp - query);
544 ptr += tmp - query + 1;
549 while (domain != NULL) {
552 tmp = strchr(domain, '.');
554 len = strlen(domain);
558 memcpy(ptr + 1, domain, len);
564 memcpy(ptr + 1, domain, tmp - domain);
565 ptr += tmp - domain + 1;
575 static gboolean cache_check_is_valid(struct cache_data *data,
581 if (data->cache_until < current_time)
588 * remove stale cached entries so that they can be refreshed
590 static void cache_enforce_validity(struct cache_entry *entry)
592 time_t current_time = time(NULL);
594 if (cache_check_is_valid(entry->ipv4, current_time) == FALSE
596 DBG("cache timeout \"%s\" type A", entry->key);
597 g_free(entry->ipv4->data);
603 if (cache_check_is_valid(entry->ipv6, current_time) == FALSE
605 DBG("cache timeout \"%s\" type AAAA", entry->key);
606 g_free(entry->ipv6->data);
612 static uint16_t cache_check_validity(char *question, uint16_t type,
613 struct cache_entry *entry)
615 time_t current_time = time(NULL);
616 int want_refresh = 0;
619 * if we have a popular entry, we want a refresh instead of
620 * total destruction of the entry.
625 cache_enforce_validity(entry);
629 if (cache_check_is_valid(entry->ipv4, current_time) == FALSE) {
630 DBG("cache %s \"%s\" type A", entry->ipv4 ?
631 "timeout" : "entry missing", question);
634 entry->want_refresh = 1;
637 * We do not remove cache entry if there is still
638 * valid IPv6 entry found in the cache.
640 if (cache_check_is_valid(entry->ipv6, current_time)
641 == FALSE && want_refresh == FALSE) {
642 g_hash_table_remove(cache, question);
649 if (cache_check_is_valid(entry->ipv6, current_time) == FALSE) {
650 DBG("cache %s \"%s\" type AAAA", entry->ipv6 ?
651 "timeout" : "entry missing", question);
654 entry->want_refresh = 1;
656 if (cache_check_is_valid(entry->ipv4, current_time)
657 == FALSE && want_refresh == FALSE) {
658 g_hash_table_remove(cache, question);
668 static struct cache_entry *cache_check(gpointer request, int *qtype, int proto)
671 struct cache_entry *entry;
672 struct domain_question *q;
674 int offset, proto_offset;
679 proto_offset = protocol_offset(proto);
680 if (proto_offset < 0)
683 question = request + proto_offset + 12;
685 offset = strlen(question) + 1;
686 q = (void *) (question + offset);
687 type = ntohs(q->type);
689 /* We only cache either A (1) or AAAA (28) requests */
690 if (type != 1 && type != 28)
693 entry = g_hash_table_lookup(cache, question);
697 type = cache_check_validity(question, type, entry);
706 * Get a label/name from DNS resource record. The function decompresses the
707 * label if necessary. The function does not convert the name to presentation
708 * form. This means that the result string will contain label lengths instead
709 * of dots between labels. We intentionally do not want to convert to dotted
710 * format so that we can cache the wire format string directly.
712 static int get_name(int counter,
713 unsigned char *pkt, unsigned char *start, unsigned char *max,
714 unsigned char *output, int output_max, int *output_len,
715 unsigned char **end, char *name, int *name_len)
719 /* Limit recursion to 10 (this means up to 10 labels in domain name) */
725 if ((*p & NS_CMPRSFLGS) == NS_CMPRSFLGS) {
726 uint16_t offset = (*p & 0x3F) * 256 + *(p + 1);
728 if (offset >= max - pkt)
734 return get_name(counter + 1, pkt, pkt + offset, max,
735 output, output_max, output_len, end,
738 unsigned label_len = *p;
740 if (pkt + label_len > max)
743 if (*output_len > output_max)
747 * We need the original name in order to check
748 * if this answer is the correct one.
750 name[(*name_len)++] = label_len;
751 memcpy(name + *name_len, p + 1, label_len + 1);
752 *name_len += label_len;
754 /* We compress the result */
755 output[0] = NS_CMPRSFLGS;
772 static int parse_rr(unsigned char *buf, unsigned char *start,
774 unsigned char *response, unsigned int *response_size,
775 uint16_t *type, uint16_t *class, int *ttl, int *rdlen,
779 struct domain_rr *rr;
781 int name_len = 0, output_len = 0, max_rsp = *response_size;
783 err = get_name(0, buf, start, max, response, max_rsp,
784 &output_len, end, name, &name_len);
790 if ((unsigned int) offset > *response_size)
793 rr = (void *) (*end);
798 *type = ntohs(rr->type);
799 *class = ntohs(rr->class);
800 *ttl = ntohl(rr->ttl);
801 *rdlen = ntohs(rr->rdlen);
806 memcpy(response + offset, *end, sizeof(struct domain_rr));
808 offset += sizeof(struct domain_rr);
809 *end += sizeof(struct domain_rr);
811 if ((unsigned int) (offset + *rdlen) > *response_size)
814 memcpy(response + offset, *end, *rdlen);
818 *response_size = offset + *rdlen;
823 static gboolean check_alias(GSList *aliases, char *name)
827 if (aliases != NULL) {
828 for (list = aliases; list; list = list->next) {
829 int len = strlen((char *)list->data);
830 if (strncmp((char *)list->data, name, len) == 0)
838 static int parse_response(unsigned char *buf, int buflen,
839 char *question, int qlen,
840 uint16_t *type, uint16_t *class, int *ttl,
841 unsigned char *response, unsigned int *response_len,
844 struct domain_hdr *hdr = (void *) buf;
845 struct domain_question *q;
847 uint16_t qdcount = ntohs(hdr->qdcount);
848 uint16_t ancount = ntohs(hdr->ancount);
850 uint16_t qtype, qclass;
851 unsigned char *next = NULL;
852 unsigned int maxlen = *response_len;
853 GSList *aliases = NULL, *list;
854 char name[NS_MAXDNAME + 1];
859 DBG("qr %d qdcount %d", hdr->qr, qdcount);
861 /* We currently only cache responses where question count is 1 */
862 if (hdr->qr != 1 || qdcount != 1)
865 ptr = buf + sizeof(struct domain_hdr);
867 strncpy(question, (char *) ptr, qlen);
868 qlen = strlen(question);
869 ptr += qlen + 1; /* skip \0 */
872 qtype = ntohs(q->type);
874 /* We cache only A and AAAA records */
875 if (qtype != 1 && qtype != 28)
878 qclass = ntohs(q->class);
880 ptr += 2 + 2; /* ptr points now to answers */
887 * We have a bunch of answers (like A, AAAA, CNAME etc) to
888 * A or AAAA question. We traverse the answers and parse the
889 * resource records. Only A and AAAA records are cached, all
890 * the other records in answers are skipped.
892 for (i = 0; i < ancount; i++) {
894 * Get one address at a time to this buffer.
895 * The max size of the answer is
896 * 2 (pointer) + 2 (type) + 2 (class) +
897 * 4 (ttl) + 2 (rdlen) + addr (16 or 4) = 28
898 * for A or AAAA record.
899 * For CNAME the size can be bigger.
901 unsigned char rsp[NS_MAXCDNAME];
902 unsigned int rsp_len = sizeof(rsp) - 1;
905 memset(rsp, 0, sizeof(rsp));
907 ret = parse_rr(buf, ptr, buf + buflen, rsp, &rsp_len,
908 type, class, ttl, &rdlen, &next, name);
915 * Now rsp contains compressed or uncompressed resource
916 * record. Next we check if this record answers the question.
917 * The name var contains the uncompressed label.
918 * One tricky bit is the CNAME records as they alias
919 * the name we might be interested in.
923 * Go to next answer if the class is not the one we are
926 if (*class != qclass) {
933 * Try to resolve aliases also, type is CNAME(5).
934 * This is important as otherwise the aliased names would not
935 * be cached at all as the cache would not contain the aliased
938 * If any CNAME is found in DNS packet, then we cache the alias
939 * IP address instead of the question (as the server
940 * said that question has only an alias).
941 * This means in practice that if e.g., ipv6.google.com is
942 * queried, DNS server returns CNAME of that name which is
943 * ipv6.l.google.com. We then cache the address of the CNAME
944 * but return the question name to client. So the alias
945 * status of the name is not saved in cache and thus not
946 * returned to the client. We do not return DNS packets from
947 * cache to client saying that ipv6.google.com is an alias to
948 * ipv6.l.google.com but we return instead a DNS packet that
949 * says ipv6.google.com has address xxx which is in fact the
950 * address of ipv6.l.google.com. For caching purposes this
951 * should not cause any issues.
953 if (*type == 5 && strncmp(question, name, qlen) == 0) {
955 * So now the alias answered the question. This is
956 * not very useful from caching point of view as
957 * the following A or AAAA records will not match the
958 * question. We need to find the real A/AAAA record
959 * of the alias and cache that.
961 unsigned char *end = NULL;
962 int name_len = 0, output_len;
964 memset(rsp, 0, sizeof(rsp));
965 rsp_len = sizeof(rsp) - 1;
968 * Alias is in rdata part of the message,
969 * and next-rdlen points to it. So we need to get
970 * the real name of the alias.
972 ret = get_name(0, buf, next - rdlen, buf + buflen,
973 rsp, rsp_len, &output_len, &end,
976 /* just ignore the error at this point */
983 * We should now have the alias of the entry we might
984 * want to cache. Just remember it for a while.
985 * We check the alias list when we have parsed the
988 aliases = g_slist_prepend(aliases, g_strdup(name));
995 if (*type == qtype) {
997 * We found correct type (A or AAAA)
999 if (check_alias(aliases, name) == TRUE ||
1000 (aliases == NULL && strncmp(question, name,
1003 * We found an alias or the name of the rr
1004 * matches the question. If so, we append
1005 * the compressed label to the cache.
1006 * The end result is a response buffer that
1007 * will contain one or more cached and
1008 * compressed resource records.
1010 if (*response_len + rsp_len > maxlen) {
1014 memcpy(response + *response_len, rsp, rsp_len);
1015 *response_len += rsp_len;
1026 for (list = aliases; list; list = list->next)
1028 g_slist_free(aliases);
1033 struct cache_timeout {
1034 time_t current_time;
1039 static gboolean cache_check_entry(gpointer key, gpointer value,
1042 struct cache_timeout *data = user_data;
1043 struct cache_entry *entry = value;
1046 /* Scale the number of hits by half as part of cache aging */
1051 * If either IPv4 or IPv6 cached entry has expired, we
1052 * remove both from the cache.
1055 if (entry->ipv4 != NULL && entry->ipv4->timeout > 0) {
1056 max_timeout = entry->ipv4->cache_until;
1057 if (max_timeout > data->max_timeout)
1058 data->max_timeout = max_timeout;
1060 if (entry->ipv4->cache_until < data->current_time)
1064 if (entry->ipv6 != NULL && entry->ipv6->timeout > 0) {
1065 max_timeout = entry->ipv6->cache_until;
1066 if (max_timeout > data->max_timeout)
1067 data->max_timeout = max_timeout;
1069 if (entry->ipv6->cache_until < data->current_time)
1074 * if we're asked to try harder, also remove entries that have
1077 if (data->try_harder && entry->hits < 4)
1083 static void cache_cleanup(void)
1085 static int max_timeout;
1086 struct cache_timeout data;
1089 data.current_time = time(NULL);
1090 data.max_timeout = 0;
1091 data.try_harder = 0;
1094 * In the first pass, we only remove entries that have timed out.
1095 * We use a cache of the first time to expire to do this only
1096 * when it makes sense.
1098 if (max_timeout <= data.current_time) {
1099 count = g_hash_table_foreach_remove(cache, cache_check_entry,
1102 DBG("removed %d in the first pass", count);
1105 * In the second pass, if the first pass turned up blank,
1106 * we also expire entries with a low hit count,
1107 * while aging the hit count at the same time.
1109 data.try_harder = 1;
1111 count = g_hash_table_foreach_remove(cache, cache_check_entry,
1116 * If we could not remove anything, then remember
1117 * what is the max timeout and do nothing if we
1118 * have not yet reached it. This will prevent
1119 * constant traversal of the cache if it is full.
1121 max_timeout = data.max_timeout;
1126 static gboolean cache_invalidate_entry(gpointer key, gpointer value,
1129 struct cache_entry *entry = value;
1131 /* first, delete any expired elements */
1132 cache_enforce_validity(entry);
1134 /* if anything is not expired, mark the entry for refresh */
1135 if (entry->hits > 0 && (entry->ipv4 || entry->ipv6))
1136 entry->want_refresh = 1;
1138 /* delete the cached data */
1140 g_free(entry->ipv4->data);
1141 g_free(entry->ipv4);
1146 g_free(entry->ipv6->data);
1147 g_free(entry->ipv6);
1151 /* keep the entry if we want it refreshed, delete it otherwise */
1152 if (entry->want_refresh)
1159 * cache_invalidate is called from places where the DNS landscape
1160 * has changed, say because connections are added or we entered a VPN.
1161 * The logic is to wipe all cache data, but mark all non-expired
1162 * parts of the cache for refresh rather than deleting the whole cache.
1164 static void cache_invalidate(void)
1166 DBG("Invalidating the DNS cache %p", cache);
1171 g_hash_table_foreach_remove(cache, cache_invalidate_entry, NULL);
1174 static void cache_refresh_entry(struct cache_entry *entry)
1177 cache_enforce_validity(entry);
1179 if (entry->hits > 2 && entry->ipv4 == NULL)
1180 entry->want_refresh = 1;
1181 if (entry->hits > 2 && entry->ipv6 == NULL)
1182 entry->want_refresh = 1;
1184 if (entry->want_refresh) {
1186 char dns_name[NS_MAXDNAME + 1];
1187 entry->want_refresh = 0;
1189 /* turn a DNS name into a hostname with dots */
1190 strncpy(dns_name, entry->key, NS_MAXDNAME);
1198 DBG("Refreshing %s\n", dns_name);
1199 /* then refresh the hostname */
1200 refresh_dns_entry(entry, &dns_name[1]);
1204 static void cache_refresh_iterator(gpointer key, gpointer value,
1207 struct cache_entry *entry = value;
1209 cache_refresh_entry(entry);
1212 static void cache_refresh(void)
1217 g_hash_table_foreach(cache, cache_refresh_iterator, NULL);
1220 static int reply_query_type(unsigned char *msg, int len)
1227 /* skip the header */
1228 c = msg + sizeof(struct domain_hdr);
1229 len -= sizeof(struct domain_hdr);
1234 /* now the query, which is a name and 2 16 bit words */
1235 l = dns_name_length(c) + 1;
1243 static int cache_update(struct server_data *srv, unsigned char *msg,
1244 unsigned int msg_len)
1246 int offset = protocol_offset(srv->protocol);
1247 int err, qlen, ttl = 0;
1248 uint16_t answers = 0, type = 0, class = 0;
1249 struct domain_question *q;
1250 struct cache_entry *entry;
1251 struct cache_data *data;
1252 char question[NS_MAXDNAME + 1];
1253 unsigned char response[NS_MAXDNAME + 1];
1255 unsigned int rsplen;
1256 gboolean new_entry = TRUE;
1257 time_t current_time;
1259 if (cache_size >= MAX_CACHE_SIZE) {
1261 if (cache_size >= MAX_CACHE_SIZE)
1265 current_time = time(NULL);
1267 /* don't do a cache refresh more than twice a minute */
1268 if (next_refresh < current_time) {
1270 next_refresh = current_time + 30;
1274 /* Continue only if response code is 0 (=ok) */
1281 rsplen = sizeof(response) - 1;
1282 question[sizeof(question) - 1] = '\0';
1284 err = parse_response(msg + offset, msg_len - offset,
1285 question, sizeof(question) - 1,
1286 &type, &class, &ttl,
1287 response, &rsplen, &answers);
1290 * special case: if we do a ipv6 lookup and get no result
1291 * for a record that's already in our ipv4 cache.. we want
1292 * to cache the negative response.
1294 if ((err == -ENOMSG || err == -ENOBUFS) &&
1295 reply_query_type(msg + offset,
1296 msg_len - offset) == 28) {
1297 entry = g_hash_table_lookup(cache, question);
1298 if (entry && entry->ipv4 && entry->ipv6 == NULL) {
1299 int cache_offset = 0;
1301 data = g_try_new(struct cache_data, 1);
1304 data->inserted = entry->ipv4->inserted;
1306 data->answers = msg[5];
1307 data->timeout = entry->ipv4->timeout;
1308 if (srv->protocol == IPPROTO_UDP)
1310 data->data_len = msg_len + cache_offset;
1311 data->data = ptr = g_malloc(data->data_len);
1312 ptr[0] = (data->data_len - 2) / 256;
1313 ptr[1] = (data->data_len - 2) - ptr[0] * 256;
1314 if (srv->protocol == IPPROTO_UDP)
1316 data->valid_until = entry->ipv4->valid_until;
1317 data->cache_until = entry->ipv4->cache_until;
1318 memcpy(ptr, msg, msg_len);
1321 * we will get a "hit" when we serve the response
1325 if (entry->hits < 0)
1331 if (err < 0 || ttl == 0)
1334 qlen = strlen(question);
1337 * If the cache contains already data, check if the
1338 * type of the cached data is the same and do not add
1339 * to cache if data is already there.
1340 * This is needed so that we can cache both A and AAAA
1341 * records for the same name.
1343 entry = g_hash_table_lookup(cache, question);
1344 if (entry == NULL) {
1345 entry = g_try_new(struct cache_entry, 1);
1349 data = g_try_new(struct cache_data, 1);
1355 entry->key = g_strdup(question);
1356 entry->ipv4 = entry->ipv6 = NULL;
1357 entry->want_refresh = 0;
1365 if (type == 1 && entry->ipv4 != NULL)
1368 if (type == 28 && entry->ipv6 != NULL)
1371 data = g_try_new(struct cache_data, 1);
1381 * compensate for the hit we'll get for serving
1382 * the response out of the cache
1385 if (entry->hits < 0)
1391 if (ttl < MIN_CACHE_TTL)
1392 ttl = MIN_CACHE_TTL;
1394 data->inserted = current_time;
1396 data->answers = answers;
1397 data->timeout = ttl;
1399 * The "2" in start of the length is the TCP offset. We allocate it
1400 * here even for UDP packet because it simplifies the sending
1403 data->data_len = 2 + 12 + qlen + 1 + 2 + 2 + rsplen;
1404 data->data = ptr = g_malloc(data->data_len);
1405 data->valid_until = current_time + ttl;
1408 * Restrict the cached DNS record TTL to some sane value
1409 * in order to prevent data staying in the cache too long.
1411 if (ttl > MAX_CACHE_TTL)
1412 ttl = MAX_CACHE_TTL;
1414 data->cache_until = round_down_ttl(current_time + ttl, ttl);
1416 if (data->data == NULL) {
1424 * We cache the two extra bytes at the start of the message
1425 * in a TCP packet. When sending UDP packet, we skip the first
1426 * two bytes. This way we do not need to know the format
1427 * (UDP/TCP) of the cached message.
1429 ptr[0] = (data->data_len - 2) / 256;
1430 ptr[1] = (data->data_len - 2) - ptr[0] * 256;
1431 if (srv->protocol == IPPROTO_UDP)
1434 memcpy(ptr, msg, offset + 12);
1435 memcpy(ptr + offset + 12, question, qlen + 1); /* copy also the \0 */
1437 q = (void *) (ptr + offset + 12 + qlen + 1);
1438 q->type = htons(type);
1439 q->class = htons(class);
1440 memcpy(ptr + offset + 12 + qlen + 1 + sizeof(struct domain_question),
1443 if (new_entry == TRUE) {
1444 g_hash_table_replace(cache, entry->key, entry);
1448 DBG("cache %d %squestion \"%s\" type %d ttl %d size %zd packet %u "
1450 cache_size, new_entry ? "new " : "old ",
1451 question, type, ttl,
1452 sizeof(*entry) + sizeof(*data) + data->data_len + qlen,
1454 srv->protocol == IPPROTO_TCP ?
1455 (unsigned int)(data->data[0] * 256 + data->data[1]) :
1461 static int ns_resolv(struct server_data *server, struct request_data *req,
1462 gpointer request, gpointer name)
1465 int sk, err, type = 0;
1466 char *dot, *lookup = (char *) name;
1467 struct cache_entry *entry;
1469 entry = cache_check(request, &type, req->protocol);
1470 if (entry != NULL) {
1472 struct cache_data *data;
1474 DBG("cache hit %s type %s", lookup, type == 1 ? "A" : "AAAA");
1481 ttl_left = data->valid_until - time(NULL);
1485 if (data != NULL && req->protocol == IPPROTO_TCP) {
1486 send_cached_response(req->client_sk, data->data,
1487 data->data_len, NULL, 0, IPPROTO_TCP,
1488 req->srcid, data->answers, ttl_left);
1492 if (data != NULL && req->protocol == IPPROTO_UDP) {
1494 sk = g_io_channel_unix_get_fd(
1495 req->ifdata->udp_listener_channel);
1497 send_cached_response(sk, data->data,
1498 data->data_len, &req->sa, req->sa_len,
1499 IPPROTO_UDP, req->srcid, data->answers,
1505 sk = g_io_channel_unix_get_fd(server->channel);
1507 err = send(sk, request, req->request_len, MSG_NOSIGNAL);
1513 /* If we have more than one dot, we don't add domains */
1514 dot = strchr(lookup, '.');
1515 if (dot != NULL && dot != lookup + strlen(lookup) - 1)
1518 if (server->domains != NULL && server->domains->data != NULL)
1519 req->append_domain = TRUE;
1521 for (list = server->domains; list; list = list->next) {
1523 unsigned char alt[1024];
1524 struct domain_hdr *hdr = (void *) &alt;
1525 int altlen, domlen, offset;
1527 domain = list->data;
1532 offset = protocol_offset(server->protocol);
1536 domlen = strlen(domain) + 1;
1540 alt[offset] = req->altid & 0xff;
1541 alt[offset + 1] = req->altid >> 8;
1543 memcpy(alt + offset + 2, request + offset + 2, 10);
1544 hdr->qdcount = htons(1);
1546 altlen = append_query(alt + offset + 12, sizeof(alt) - 12,
1553 memcpy(alt + offset + altlen,
1554 request + offset + altlen - domlen,
1555 req->request_len - altlen - offset + domlen);
1557 if (server->protocol == IPPROTO_TCP) {
1558 int req_len = req->request_len + domlen - 2;
1560 alt[0] = (req_len >> 8) & 0xff;
1561 alt[1] = req_len & 0xff;
1564 err = send(sk, alt, req->request_len + domlen, MSG_NOSIGNAL);
1574 static void destroy_request_data(struct request_data *req)
1576 if (req->timeout > 0)
1577 g_source_remove(req->timeout);
1580 g_free(req->request);
1585 static int forward_dns_reply(unsigned char *reply, int reply_len, int protocol,
1586 struct server_data *data)
1588 struct domain_hdr *hdr;
1589 struct request_data *req;
1590 int dns_id, sk, err, offset = protocol_offset(protocol);
1591 struct listener_data *ifdata;
1596 hdr = (void *)(reply + offset);
1597 dns_id = reply[offset] | reply[offset + 1] << 8;
1599 DBG("Received %d bytes (id 0x%04x)", reply_len, dns_id);
1601 req = find_request(dns_id);
1605 DBG("id 0x%04x rcode %d", hdr->id, hdr->rcode);
1607 ifdata = req->ifdata;
1609 reply[offset] = req->srcid & 0xff;
1610 reply[offset + 1] = req->srcid >> 8;
1614 if (hdr->rcode == 0 || req->resp == NULL) {
1617 * If the domain name was append
1618 * remove it before forwarding the reply.
1620 if (req->append_domain == TRUE) {
1623 unsigned int domain_len;
1626 * ptr points to the first char of the hostname.
1627 * ->hostname.domain.net
1629 ptr = reply + offset + sizeof(struct domain_hdr);
1631 domain_len = strlen((const char *)ptr + host_len + 1);
1634 * Remove the domain name and replace it by the end
1635 * of reply. Check if the domain is really there
1636 * before trying to copy the data. The domain_len can
1637 * be 0 because if the original query did not contain
1638 * a domain name, then we are sending two packets,
1639 * first without the domain name and the second packet
1640 * with domain name. The append_domain is set to true
1641 * even if we sent the first packet without domain
1642 * name. In this case we end up in this branch.
1644 if (domain_len > 0) {
1646 * Note that we must use memmove() here,
1647 * because the memory areas can overlap.
1649 memmove(ptr + host_len + 1,
1650 ptr + host_len + domain_len + 1,
1651 reply_len - (ptr - reply + domain_len));
1653 reply_len = reply_len - domain_len;
1660 req->resp = g_try_malloc(reply_len);
1661 if (req->resp == NULL)
1664 memcpy(req->resp, reply, reply_len);
1665 req->resplen = reply_len;
1667 cache_update(data, reply, reply_len);
1670 if (hdr->rcode > 0 && req->numresp < req->numserv)
1673 request_list = g_slist_remove(request_list, req);
1675 if (protocol == IPPROTO_UDP) {
1676 sk = g_io_channel_unix_get_fd(ifdata->udp_listener_channel);
1677 err = sendto(sk, req->resp, req->resplen, 0,
1678 &req->sa, req->sa_len);
1680 sk = req->client_sk;
1681 err = send(sk, req->resp, req->resplen, MSG_NOSIGNAL);
1686 DBG("Cannot send msg, sk %d proto %d errno %d/%s", sk,
1687 protocol, errno, strerror(errno));
1689 DBG("proto %d sent %d bytes to %d", protocol, err, sk);
1691 destroy_request_data(req);
1696 static void cache_element_destroy(gpointer value)
1698 struct cache_entry *entry = value;
1703 if (entry->ipv4 != NULL) {
1704 g_free(entry->ipv4->data);
1705 g_free(entry->ipv4);
1708 if (entry->ipv6 != NULL) {
1709 g_free(entry->ipv6->data);
1710 g_free(entry->ipv6);
1716 if (--cache_size < 0)
1720 static gboolean try_remove_cache(gpointer user_data)
1722 if (__sync_fetch_and_sub(&cache_refcount, 1) == 1) {
1723 DBG("No cache users, removing it.");
1725 g_hash_table_destroy(cache);
1732 static void destroy_server(struct server_data *server)
1736 DBG("interface %s server %s sock %d", server->interface, server->server,
1737 g_io_channel_unix_get_fd(server->channel));
1739 server_list = g_slist_remove(server_list, server);
1741 if (server->watch > 0)
1742 g_source_remove(server->watch);
1744 if (server->timeout > 0)
1745 g_source_remove(server->timeout);
1747 g_io_channel_unref(server->channel);
1749 if (server->protocol == IPPROTO_UDP)
1750 DBG("Removing DNS server %s", server->server);
1752 g_free(server->incoming_reply);
1753 g_free(server->server);
1754 for (list = server->domains; list; list = list->next) {
1755 char *domain = list->data;
1757 server->domains = g_list_remove(server->domains, domain);
1760 g_free(server->interface);
1763 * We do not remove cache right away but delay it few seconds.
1764 * The idea is that when IPv6 DNS server is added via RDNSS, it has a
1765 * lifetime. When the lifetime expires we decrease the refcount so it
1766 * is possible that the cache is then removed. Because a new DNS server
1767 * is usually created almost immediately we would then loose the cache
1768 * without any good reason. The small delay allows the new RDNSS to
1769 * create a new DNS server instance and the refcount does not go to 0.
1771 g_timeout_add_seconds(3, try_remove_cache, NULL);
1776 static gboolean udp_server_event(GIOChannel *channel, GIOCondition condition,
1779 unsigned char buf[4096];
1781 struct server_data *data = user_data;
1783 if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
1784 connman_error("Error with UDP server %s", data->server);
1789 sk = g_io_channel_unix_get_fd(channel);
1791 len = recv(sk, buf, sizeof(buf), 0);
1795 err = forward_dns_reply(buf, len, IPPROTO_UDP, data);
1802 static gboolean tcp_server_event(GIOChannel *channel, GIOCondition condition,
1806 struct server_data *server = user_data;
1808 sk = g_io_channel_unix_get_fd(channel);
1812 if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
1815 DBG("TCP server channel closed, sk %d", sk);
1818 * Discard any partial response which is buffered; better
1819 * to get a proper response from a working server.
1821 g_free(server->incoming_reply);
1822 server->incoming_reply = NULL;
1824 for (list = request_list; list; list = list->next) {
1825 struct request_data *req = list->data;
1826 struct domain_hdr *hdr;
1828 if (req->protocol == IPPROTO_UDP)
1831 if (req->request == NULL)
1835 * If we're not waiting for any further response
1836 * from another name server, then we send an error
1837 * response to the client.
1839 if (req->numserv && --(req->numserv))
1842 hdr = (void *) (req->request + 2);
1843 hdr->id = req->srcid;
1844 send_response(req->client_sk, req->request,
1845 req->request_len, NULL, 0, IPPROTO_TCP);
1847 request_list = g_slist_remove(request_list, req);
1850 destroy_server(server);
1855 if ((condition & G_IO_OUT) && !server->connected) {
1858 int no_request_sent = TRUE;
1859 struct server_data *udp_server;
1861 udp_server = find_server(server->interface, server->server,
1863 if (udp_server != NULL) {
1864 for (domains = udp_server->domains; domains;
1865 domains = domains->next) {
1866 char *dom = domains->data;
1868 DBG("Adding domain %s to %s",
1869 dom, server->server);
1871 server->domains = g_list_append(server->domains,
1876 server->connected = TRUE;
1877 server_list = g_slist_append(server_list, server);
1879 if (server->timeout > 0) {
1880 g_source_remove(server->timeout);
1881 server->timeout = 0;
1884 for (list = request_list; list; ) {
1885 struct request_data *req = list->data;
1888 if (req->protocol == IPPROTO_UDP) {
1893 DBG("Sending req %s over TCP", (char *)req->name);
1895 status = ns_resolv(server, req,
1896 req->request, req->name);
1899 * A cached result was sent,
1900 * so the request can be released
1903 request_list = g_slist_remove(request_list, req);
1904 destroy_request_data(req);
1913 no_request_sent = FALSE;
1915 if (req->timeout > 0)
1916 g_source_remove(req->timeout);
1918 req->timeout = g_timeout_add_seconds(30,
1919 request_timeout, req);
1923 if (no_request_sent == TRUE) {
1924 destroy_server(server);
1928 } else if (condition & G_IO_IN) {
1929 struct partial_reply *reply = server->incoming_reply;
1933 unsigned char reply_len_buf[2];
1936 bytes_recv = recv(sk, reply_len_buf, 2, MSG_PEEK);
1939 } else if (bytes_recv < 0) {
1940 if (errno == EAGAIN || errno == EWOULDBLOCK)
1943 connman_error("DNS proxy error %s",
1946 } else if (bytes_recv < 2)
1949 reply_len = reply_len_buf[1] | reply_len_buf[0] << 8;
1952 DBG("TCP reply %d bytes from %d", reply_len, sk);
1954 reply = g_try_malloc(sizeof(*reply) + reply_len + 2);
1958 reply->len = reply_len;
1959 reply->received = 0;
1961 server->incoming_reply = reply;
1964 while (reply->received < reply->len) {
1965 bytes_recv = recv(sk, reply->buf + reply->received,
1966 reply->len - reply->received, 0);
1968 connman_error("DNS proxy TCP disconnect");
1970 } else if (bytes_recv < 0) {
1971 if (errno == EAGAIN || errno == EWOULDBLOCK)
1974 connman_error("DNS proxy error %s",
1978 reply->received += bytes_recv;
1981 forward_dns_reply(reply->buf, reply->received, IPPROTO_TCP,
1985 server->incoming_reply = NULL;
1987 destroy_server(server);
1995 static gboolean tcp_idle_timeout(gpointer user_data)
1997 struct server_data *server = user_data;
2004 destroy_server(server);
2009 static struct server_data *create_server(const char *interface,
2010 const char *domain, const char *server,
2013 struct addrinfo hints, *rp;
2014 struct server_data *data;
2017 DBG("interface %s server %s", interface, server);
2019 memset(&hints, 0, sizeof(hints));
2023 hints.ai_socktype = SOCK_DGRAM;
2027 hints.ai_socktype = SOCK_STREAM;
2033 hints.ai_family = AF_UNSPEC;
2034 hints.ai_flags = AI_PASSIVE | AI_NUMERICSERV | AI_NUMERICHOST;
2036 ret = getaddrinfo(server, "53", &hints, &rp);
2038 connman_error("Failed to parse server %s address: %s\n",
2039 server, gai_strerror(ret));
2042 /* Do not blindly copy this code elsewhere; it doesn't loop over the
2043 results using ->ai_next as it should. That's OK in *this* case
2044 because it was a numeric lookup; we *know* there's only one. */
2046 sk = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
2048 connman_error("Failed to create server %s socket", server);
2055 if (interface != NULL) {
2056 if (setsockopt(sk, SOL_SOCKET, SO_BINDTODEVICE,
2057 interface, strlen(interface) + 1) < 0) {
2058 connman_error("Failed to bind server %s "
2067 data = g_try_new0(struct server_data, 1);
2069 connman_error("Failed to allocate server %s data", server);
2075 data->channel = g_io_channel_unix_new(sk);
2076 if (data->channel == NULL) {
2077 connman_error("Failed to create server %s channel", server);
2084 g_io_channel_set_close_on_unref(data->channel, TRUE);
2086 if (protocol == IPPROTO_TCP) {
2087 g_io_channel_set_flags(data->channel, G_IO_FLAG_NONBLOCK, NULL);
2088 data->watch = g_io_add_watch(data->channel,
2089 G_IO_OUT | G_IO_IN | G_IO_HUP | G_IO_NVAL | G_IO_ERR,
2090 tcp_server_event, data);
2091 data->timeout = g_timeout_add_seconds(30, tcp_idle_timeout,
2094 data->watch = g_io_add_watch(data->channel,
2095 G_IO_IN | G_IO_NVAL | G_IO_ERR | G_IO_HUP,
2096 udp_server_event, data);
2098 data->interface = g_strdup(interface);
2100 data->domains = g_list_append(data->domains, g_strdup(domain));
2101 data->server = g_strdup(server);
2102 data->protocol = protocol;
2104 ret = connect(sk, rp->ai_addr, rp->ai_addrlen);
2107 if ((protocol == IPPROTO_TCP && errno != EINPROGRESS) ||
2108 protocol == IPPROTO_UDP) {
2111 connman_error("Failed to connect to server %s", server);
2112 if (data->watch > 0)
2113 g_source_remove(data->watch);
2114 if (data->timeout > 0)
2115 g_source_remove(data->timeout);
2117 g_io_channel_unref(data->channel);
2120 g_free(data->server);
2121 g_free(data->interface);
2122 for (list = data->domains; list; list = list->next) {
2123 char *domain = list->data;
2125 data->domains = g_list_remove(data->domains,
2134 if (__sync_fetch_and_add(&cache_refcount, 1) == 0)
2135 cache = g_hash_table_new_full(g_str_hash,
2138 cache_element_destroy);
2140 if (protocol == IPPROTO_UDP) {
2141 /* Enable new servers by default */
2142 data->enabled = TRUE;
2143 DBG("Adding DNS server %s", data->server);
2145 server_list = g_slist_append(server_list, data);
2151 static gboolean resolv(struct request_data *req,
2152 gpointer request, gpointer name)
2156 for (list = server_list; list; list = list->next) {
2157 struct server_data *data = list->data;
2159 DBG("server %s enabled %d", data->server, data->enabled);
2161 if (data->enabled == FALSE)
2164 if (data->watch == 0 && data->protocol == IPPROTO_UDP)
2165 data->watch = g_io_add_watch(data->channel,
2166 G_IO_IN | G_IO_NVAL | G_IO_ERR | G_IO_HUP,
2167 udp_server_event, data);
2169 if (ns_resolv(data, req, request, name) > 0)
2176 static void append_domain(const char *interface, const char *domain)
2180 DBG("interface %s domain %s", interface, domain);
2185 for (list = server_list; list; list = list->next) {
2186 struct server_data *data = list->data;
2189 gboolean dom_found = FALSE;
2191 if (data->interface == NULL)
2194 if (g_str_equal(data->interface, interface) == FALSE)
2197 for (dom_list = data->domains; dom_list;
2198 dom_list = dom_list->next) {
2199 dom = dom_list->data;
2201 if (g_str_equal(dom, domain)) {
2207 if (dom_found == FALSE) {
2209 g_list_append(data->domains, g_strdup(domain));
2214 int __connman_dnsproxy_append(const char *interface, const char *domain,
2217 struct server_data *data;
2219 DBG("interface %s server %s", interface, server);
2221 if (server == NULL && domain == NULL)
2224 if (server == NULL) {
2225 append_domain(interface, domain);
2230 if (g_str_equal(server, "127.0.0.1") == TRUE)
2233 data = find_server(interface, server, IPPROTO_UDP);
2235 append_domain(interface, domain);
2239 data = create_server(interface, domain, server, IPPROTO_UDP);
2246 static void remove_server(const char *interface, const char *domain,
2247 const char *server, int protocol)
2249 struct server_data *data;
2251 data = find_server(interface, server, protocol);
2255 destroy_server(data);
2258 int __connman_dnsproxy_remove(const char *interface, const char *domain,
2261 DBG("interface %s server %s", interface, server);
2266 if (g_str_equal(server, "127.0.0.1") == TRUE)
2269 remove_server(interface, domain, server, IPPROTO_UDP);
2270 remove_server(interface, domain, server, IPPROTO_TCP);
2275 void __connman_dnsproxy_flush(void)
2279 list = request_list;
2281 struct request_data *req = list->data;
2285 if (resolv(req, req->request, req->name) == TRUE) {
2287 * A cached result was sent,
2288 * so the request can be released
2291 g_slist_remove(request_list, req);
2292 destroy_request_data(req);
2296 if (req->timeout > 0)
2297 g_source_remove(req->timeout);
2298 req->timeout = g_timeout_add_seconds(5, request_timeout, req);
2302 static void dnsproxy_offline_mode(connman_bool_t enabled)
2306 DBG("enabled %d", enabled);
2308 for (list = server_list; list; list = list->next) {
2309 struct server_data *data = list->data;
2311 if (enabled == FALSE) {
2312 DBG("Enabling DNS server %s", data->server);
2313 data->enabled = TRUE;
2317 DBG("Disabling DNS server %s", data->server);
2318 data->enabled = FALSE;
2324 static void dnsproxy_default_changed(struct connman_service *service)
2329 DBG("service %p", service);
2331 /* DNS has changed, invalidate the cache */
2334 if (service == NULL) {
2335 /* When no services are active, then disable DNS proxying */
2336 dnsproxy_offline_mode(TRUE);
2340 interface = connman_service_get_interface(service);
2341 if (interface == NULL)
2344 for (list = server_list; list; list = list->next) {
2345 struct server_data *data = list->data;
2347 if (g_strcmp0(data->interface, interface) == 0) {
2348 DBG("Enabling DNS server %s", data->server);
2349 data->enabled = TRUE;
2351 DBG("Disabling DNS server %s", data->server);
2352 data->enabled = FALSE;
2360 static struct connman_notifier dnsproxy_notifier = {
2362 .default_changed = dnsproxy_default_changed,
2363 .offline_mode = dnsproxy_offline_mode,
2366 static unsigned char opt_edns0_type[2] = { 0x00, 0x29 };
2368 static int parse_request(unsigned char *buf, int len,
2369 char *name, unsigned int size)
2371 struct domain_hdr *hdr = (void *) buf;
2372 uint16_t qdcount = ntohs(hdr->qdcount);
2373 uint16_t arcount = ntohs(hdr->arcount);
2375 char *last_label = NULL;
2376 unsigned int remain, used = 0;
2381 DBG("id 0x%04x qr %d opcode %d qdcount %d arcount %d",
2382 hdr->id, hdr->qr, hdr->opcode,
2385 if (hdr->qr != 0 || qdcount != 1)
2390 ptr = buf + sizeof(struct domain_hdr);
2391 remain = len - sizeof(struct domain_hdr);
2393 while (remain > 0) {
2397 last_label = (char *) (ptr + 1);
2401 if (used + len + 1 > size)
2404 strncat(name, (char *) (ptr + 1), len);
2413 if (last_label && arcount && remain >= 9 && last_label[4] == 0 &&
2414 !memcmp(last_label + 5, opt_edns0_type, 2)) {
2415 uint16_t edns0_bufsize;
2417 edns0_bufsize = last_label[7] << 8 | last_label[8];
2419 DBG("EDNS0 buffer size %u", edns0_bufsize);
2421 /* This is an evil hack until full TCP support has been
2424 * Somtimes the EDNS0 request gets send with a too-small
2425 * buffer size. Since glibc doesn't seem to crash when it
2426 * gets a response biffer then it requested, just bump
2427 * the buffer size up to 4KiB.
2429 if (edns0_bufsize < 0x1000) {
2430 last_label[7] = 0x10;
2431 last_label[8] = 0x00;
2435 DBG("query %s", name);
2440 static gboolean tcp_listener_event(GIOChannel *channel, GIOCondition condition,
2443 unsigned char buf[768];
2445 struct request_data *req;
2446 int sk, client_sk, len, err;
2447 struct sockaddr_in6 client_addr;
2448 socklen_t client_addr_len = sizeof(client_addr);
2450 struct listener_data *ifdata = user_data;
2451 int waiting_for_connect = FALSE;
2453 DBG("condition 0x%x", condition);
2455 if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
2456 if (ifdata->tcp_listener_watch > 0)
2457 g_source_remove(ifdata->tcp_listener_watch);
2458 ifdata->tcp_listener_watch = 0;
2460 connman_error("Error with TCP listener channel");
2465 sk = g_io_channel_unix_get_fd(channel);
2467 client_sk = accept(sk, (void *)&client_addr, &client_addr_len);
2468 if (client_sk < 0) {
2469 connman_error("Accept failure on TCP listener");
2470 ifdata->tcp_listener_watch = 0;
2474 len = recv(client_sk, buf, sizeof(buf), 0);
2478 DBG("Received %d bytes (id 0x%04x) from %d", len,
2479 buf[2] | buf[3] << 8, client_sk);
2481 err = parse_request(buf + 2, len - 2, query, sizeof(query));
2482 if (err < 0 || (g_slist_length(server_list) == 0)) {
2483 send_response(client_sk, buf, len, NULL, 0, IPPROTO_TCP);
2487 req = g_try_new0(struct request_data, 1);
2491 memcpy(&req->sa, &client_addr, client_addr_len);
2492 req->sa_len = client_addr_len;
2493 req->client_sk = client_sk;
2494 req->protocol = IPPROTO_TCP;
2496 req->srcid = buf[2] | (buf[3] << 8);
2497 req->dstid = get_id();
2498 req->altid = get_id();
2499 req->request_len = len;
2501 buf[2] = req->dstid & 0xff;
2502 buf[3] = req->dstid >> 8;
2505 req->ifdata = (struct listener_data *) ifdata;
2506 req->append_domain = FALSE;
2508 for (list = server_list; list; list = list->next) {
2509 struct server_data *data = list->data;
2511 if (data->protocol != IPPROTO_UDP || data->enabled == FALSE)
2514 if(create_server(data->interface, NULL,
2515 data->server, IPPROTO_TCP) == NULL)
2518 waiting_for_connect = TRUE;
2521 if (waiting_for_connect == FALSE) {
2522 /* No server is waiting for connect */
2523 send_response(client_sk, buf, len, NULL, 0, IPPROTO_TCP);
2529 * The server is not connected yet.
2530 * Copy the relevant buffers.
2531 * The request will actually be sent once we're
2532 * properly connected over TCP to the nameserver.
2534 req->request = g_try_malloc0(req->request_len);
2535 if (req->request == NULL) {
2536 send_response(client_sk, buf, len, NULL, 0, IPPROTO_TCP);
2540 memcpy(req->request, buf, req->request_len);
2542 req->name = g_try_malloc0(sizeof(query));
2543 if (req->name == NULL) {
2544 send_response(client_sk, buf, len, NULL, 0, IPPROTO_TCP);
2545 g_free(req->request);
2549 memcpy(req->name, query, sizeof(query));
2551 req->timeout = g_timeout_add_seconds(30, request_timeout, req);
2553 request_list = g_slist_append(request_list, req);
2558 static gboolean udp_listener_event(GIOChannel *channel, GIOCondition condition,
2561 unsigned char buf[768];
2563 struct request_data *req;
2564 struct sockaddr_in6 client_addr;
2565 socklen_t client_addr_len = sizeof(client_addr);
2567 struct listener_data *ifdata = user_data;
2569 if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
2570 connman_error("Error with UDP listener channel");
2571 ifdata->udp_listener_watch = 0;
2575 sk = g_io_channel_unix_get_fd(channel);
2577 memset(&client_addr, 0, client_addr_len);
2578 len = recvfrom(sk, buf, sizeof(buf), 0, (void *)&client_addr,
2583 DBG("Received %d bytes (id 0x%04x)", len, buf[0] | buf[1] << 8);
2585 err = parse_request(buf, len, query, sizeof(query));
2586 if (err < 0 || (g_slist_length(server_list) == 0)) {
2587 send_response(sk, buf, len, (void *)&client_addr,
2588 client_addr_len, IPPROTO_UDP);
2592 req = g_try_new0(struct request_data, 1);
2596 memcpy(&req->sa, &client_addr, client_addr_len);
2597 req->sa_len = client_addr_len;
2599 req->protocol = IPPROTO_UDP;
2601 req->srcid = buf[0] | (buf[1] << 8);
2602 req->dstid = get_id();
2603 req->altid = get_id();
2604 req->request_len = len;
2606 buf[0] = req->dstid & 0xff;
2607 buf[1] = req->dstid >> 8;
2610 req->ifdata = (struct listener_data *) ifdata;
2611 req->append_domain = FALSE;
2613 if (resolv(req, buf, query) == TRUE) {
2614 /* a cached result was sent, so the request can be released */
2619 req->timeout = g_timeout_add_seconds(5, request_timeout, req);
2620 request_list = g_slist_append(request_list, req);
2625 static int create_dns_listener(int protocol, struct listener_data *ifdata)
2627 GIOChannel *channel;
2631 struct sockaddr_in6 sin6;
2632 struct sockaddr_in sin;
2635 int sk, type, v6only = 0;
2636 int family = AF_INET6;
2639 DBG("interface %s", ifdata->ifname);
2644 type = SOCK_DGRAM | SOCK_CLOEXEC;
2649 type = SOCK_STREAM | SOCK_CLOEXEC;
2656 sk = socket(family, type, protocol);
2657 if (sk < 0 && family == AF_INET6 && errno == EAFNOSUPPORT) {
2658 connman_error("No IPv6 support; DNS proxy listening only on Legacy IP");
2660 sk = socket(family, type, protocol);
2663 connman_error("Failed to create %s listener socket", proto);
2667 if (setsockopt(sk, SOL_SOCKET, SO_BINDTODEVICE,
2669 strlen(ifdata->ifname) + 1) < 0) {
2670 connman_error("Failed to bind %s listener interface", proto);
2674 /* Ensure it accepts Legacy IP connections too */
2675 if (family == AF_INET6 &&
2676 setsockopt(sk, SOL_IPV6, IPV6_V6ONLY,
2677 &v6only, sizeof(v6only)) < 0) {
2678 connman_error("Failed to clear V6ONLY on %s listener socket",
2684 if (family == AF_INET) {
2685 memset(&s.sin, 0, sizeof(s.sin));
2686 s.sin.sin_family = AF_INET;
2687 s.sin.sin_port = htons(53);
2688 s.sin.sin_addr.s_addr = htonl(INADDR_ANY);
2689 slen = sizeof(s.sin);
2691 memset(&s.sin6, 0, sizeof(s.sin6));
2692 s.sin6.sin6_family = AF_INET6;
2693 s.sin6.sin6_port = htons(53);
2694 s.sin6.sin6_addr = in6addr_any;
2695 slen = sizeof(s.sin6);
2698 if (bind(sk, &s.sa, slen) < 0) {
2699 connman_error("Failed to bind %s listener socket", proto);
2704 if (protocol == IPPROTO_TCP && listen(sk, 10) < 0) {
2705 connman_error("Failed to listen on TCP socket");
2710 channel = g_io_channel_unix_new(sk);
2711 if (channel == NULL) {
2712 connman_error("Failed to create %s listener channel", proto);
2717 g_io_channel_set_close_on_unref(channel, TRUE);
2719 if (protocol == IPPROTO_TCP) {
2720 ifdata->tcp_listener_channel = channel;
2721 ifdata->tcp_listener_watch = g_io_add_watch(channel,
2722 G_IO_IN, tcp_listener_event, (gpointer) ifdata);
2724 ifdata->udp_listener_channel = channel;
2725 ifdata->udp_listener_watch = g_io_add_watch(channel,
2726 G_IO_IN, udp_listener_event, (gpointer) ifdata);
2732 static void destroy_udp_listener(struct listener_data *ifdata)
2734 DBG("interface %s", ifdata->ifname);
2736 if (ifdata->udp_listener_watch > 0)
2737 g_source_remove(ifdata->udp_listener_watch);
2739 g_io_channel_unref(ifdata->udp_listener_channel);
2742 static void destroy_tcp_listener(struct listener_data *ifdata)
2744 DBG("interface %s", ifdata->ifname);
2746 if (ifdata->tcp_listener_watch > 0)
2747 g_source_remove(ifdata->tcp_listener_watch);
2749 g_io_channel_unref(ifdata->tcp_listener_channel);
2752 static int create_listener(struct listener_data *ifdata)
2756 err = create_dns_listener(IPPROTO_UDP, ifdata);
2760 err = create_dns_listener(IPPROTO_TCP, ifdata);
2762 destroy_udp_listener(ifdata);
2766 if (g_strcmp0(ifdata->ifname, "lo") == 0)
2767 __connman_resolvfile_append("lo", NULL, "127.0.0.1");
2772 static void destroy_listener(struct listener_data *ifdata)
2776 if (g_strcmp0(ifdata->ifname, "lo") == 0)
2777 __connman_resolvfile_remove("lo", NULL, "127.0.0.1");
2779 for (list = request_list; list; list = list->next) {
2780 struct request_data *req = list->data;
2782 DBG("Dropping request (id 0x%04x -> 0x%04x)",
2783 req->srcid, req->dstid);
2784 destroy_request_data(req);
2788 g_slist_free(request_list);
2789 request_list = NULL;
2791 destroy_tcp_listener(ifdata);
2792 destroy_udp_listener(ifdata);
2795 int __connman_dnsproxy_add_listener(const char *interface)
2797 struct listener_data *ifdata;
2800 DBG("interface %s", interface);
2802 if (g_hash_table_lookup(listener_table, interface) != NULL)
2805 ifdata = g_try_new0(struct listener_data, 1);
2809 ifdata->ifname = g_strdup(interface);
2810 ifdata->udp_listener_channel = NULL;
2811 ifdata->udp_listener_watch = 0;
2812 ifdata->tcp_listener_channel = NULL;
2813 ifdata->tcp_listener_watch = 0;
2815 err = create_listener(ifdata);
2817 connman_error("Couldn't create listener for %s err %d",
2819 g_free(ifdata->ifname);
2823 g_hash_table_insert(listener_table, ifdata->ifname, ifdata);
2827 void __connman_dnsproxy_remove_listener(const char *interface)
2829 struct listener_data *ifdata;
2831 DBG("interface %s", interface);
2833 ifdata = g_hash_table_lookup(listener_table, interface);
2837 destroy_listener(ifdata);
2839 g_hash_table_remove(listener_table, interface);
2842 static void remove_listener(gpointer key, gpointer value, gpointer user_data)
2844 const char *interface = key;
2845 struct listener_data *ifdata = value;
2847 DBG("interface %s", interface);
2849 destroy_listener(ifdata);
2852 int __connman_dnsproxy_init(void)
2858 srandom(time(NULL));
2860 listener_table = g_hash_table_new_full(g_str_hash, g_str_equal,
2862 err = __connman_dnsproxy_add_listener("lo");
2866 err = connman_notifier_register(&dnsproxy_notifier);
2873 __connman_dnsproxy_remove_listener("lo");
2874 g_hash_table_destroy(listener_table);
2879 void __connman_dnsproxy_cleanup(void)
2883 connman_notifier_unregister(&dnsproxy_notifier);
2885 g_hash_table_foreach(listener_table, remove_listener, NULL);
2887 g_hash_table_destroy(listener_table);