5 * Copyright (C) 2007-2010 Intel Corporation. All rights reserved.
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License version 2 as
9 * published by the Free Software Foundation.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
30 #include <arpa/inet.h>
31 #include <netinet/in.h>
32 #include <sys/types.h>
33 #include <sys/socket.h>
41 #if __BYTE_ORDER == __LITTLE_ENDIAN
56 } __attribute__ ((packed));
57 #elif __BYTE_ORDER == __BIG_ENDIAN
72 } __attribute__ ((packed));
74 #error "Unknown byte order"
77 struct partial_reply {
93 struct partial_reply *incoming_reply;
98 struct sockaddr_in6 __sin6; /* Only for the length */
116 struct listener_data *ifdata;
117 gboolean append_domain;
120 struct listener_data {
122 GIOChannel *udp_listener_channel;
123 guint udp_listener_watch;
124 GIOChannel *tcp_listener_channel;
125 guint tcp_listener_watch;
135 unsigned int data_len;
136 unsigned char *data; /* contains DNS header + body */
142 struct cache_data *ipv4;
143 struct cache_data *ipv6;
146 struct domain_question {
149 } __attribute__ ((packed));
156 } __attribute__ ((packed));
159 * We limit how long the cached DNS entry stays in the cache.
160 * By default the TTL (time-to-live) of the DNS response is used
161 * when setting the cache entry life time. The value is in seconds.
163 #define MAX_CACHE_TTL (60 * 30)
165 * Also limit the other end, cache at least for 30 seconds.
167 #define MIN_CACHE_TTL (30)
170 * We limit the cache size to some sane value so that cached data does
171 * not occupy too much memory. Each cached entry occupies on average
172 * about 100 bytes memory (depending on DNS name length).
173 * Example: caching www.connman.net uses 97 bytes memory.
174 * The value is the max amount of cached DNS responses (count).
176 #define MAX_CACHE_SIZE 256
178 static int cache_size;
179 static GHashTable *cache;
180 static int cache_refcount;
181 static GSList *server_list = NULL;
182 static GSList *request_list = NULL;
183 static GSList *request_pending_list = NULL;
184 static guint16 request_id = 0x0000;
185 static GHashTable *listener_table = NULL;
187 static int protocol_offset(int protocol)
203 * There is a power and efficiency benefit to have entries
204 * in our cache expire at the same time. To this extend,
205 * we round down the cache valid time to common boundaries.
207 static time_t round_down_ttl(time_t end_time, int ttl)
212 /* Less than 5 minutes, round to 10 second boundary */
214 end_time = end_time / 10;
215 end_time = end_time * 10;
216 } else { /* 5 or more minutes, round to 30 seconds */
217 end_time = end_time / 30;
218 end_time = end_time * 30;
223 static struct request_data *find_request(guint16 id)
227 for (list = request_list; list; list = list->next) {
228 struct request_data *req = list->data;
230 if (req->dstid == id || req->altid == id)
237 static struct server_data *find_server(const char *interface,
243 DBG("interface %s server %s", interface, server);
245 for (list = server_list; list; list = list->next) {
246 struct server_data *data = list->data;
248 if (interface == NULL && data->interface == NULL &&
249 g_str_equal(data->server, server) == TRUE &&
250 data->protocol == protocol)
253 if (interface == NULL ||
254 data->interface == NULL || data->server == NULL)
257 if (g_str_equal(data->interface, interface) == TRUE &&
258 g_str_equal(data->server, server) == TRUE &&
259 data->protocol == protocol)
266 static int dns_name_length(unsigned char *buf)
268 if ((buf[0] & NS_CMPRSFLGS) == NS_CMPRSFLGS) /* compressed name */
270 return strlen((char *)buf);
273 static void update_cached_ttl(unsigned char *buf, int len, int new_ttl)
280 /* skip the header */
284 /* skip the query, which is a name and 2 16 bit words */
285 l = dns_name_length(c);
291 /* now we get the answer records */
295 l = dns_name_length(c);
300 /* then type + class, 2 bytes each */
306 /* now the 4 byte TTL field */
314 /* now the 2 byte rdlen field */
317 len -= ntohs(*w) + 2;
323 static void send_cached_response(int sk, unsigned char *buf, int len,
324 const struct sockaddr *to, socklen_t tolen,
325 int protocol, int id, uint16_t answers, int ttl)
327 struct domain_hdr *hdr;
328 int err, offset = protocol_offset(protocol);
336 hdr = (void *) (buf + offset);
341 hdr->ancount = htons(answers);
345 /* if this is a negative reply, we are authorative */
349 update_cached_ttl(buf, len, ttl);
351 DBG("id 0x%04x answers %d", hdr->id, answers);
353 err = sendto(sk, buf, len, 0, to, tolen);
355 connman_error("Cannot send cached DNS response: %s",
361 static void send_response(int sk, unsigned char *buf, int len,
362 const struct sockaddr *to, socklen_t tolen,
365 struct domain_hdr *hdr;
366 int err, offset = protocol_offset(protocol);
376 hdr = (void *) (buf + offset);
378 DBG("id 0x%04x qr %d opcode %d", hdr->id, hdr->qr, hdr->opcode);
387 err = sendto(sk, buf, len, 0, to, tolen);
389 connman_error("Failed to send DNS response: %s",
395 static gboolean request_timeout(gpointer user_data)
397 struct request_data *req = user_data;
398 struct listener_data *ifdata;
400 DBG("id 0x%04x", req->srcid);
405 ifdata = req->ifdata;
407 request_list = g_slist_remove(request_list, req);
410 if (req->resplen > 0 && req->resp != NULL) {
413 sk = g_io_channel_unix_get_fd(ifdata->udp_listener_channel);
415 err = sendto(sk, req->resp, req->resplen, 0,
416 &req->sa, req->sa_len);
419 } else if (req->request && req->numserv == 0) {
420 struct domain_hdr *hdr;
422 if (req->protocol == IPPROTO_TCP) {
423 hdr = (void *) (req->request + 2);
424 hdr->id = req->srcid;
425 send_response(req->client_sk, req->request,
426 req->request_len, NULL, 0, IPPROTO_TCP);
428 } else if (req->protocol == IPPROTO_UDP) {
431 hdr = (void *) (req->request);
432 hdr->id = req->srcid;
433 sk = g_io_channel_unix_get_fd(
434 ifdata->udp_listener_channel);
435 send_response(sk, req->request, req->request_len,
436 &req->sa, req->sa_len, IPPROTO_UDP);
446 static int append_query(unsigned char *buf, unsigned int size,
447 const char *query, const char *domain)
449 unsigned char *ptr = buf;
453 DBG("query %s domain %s", query, domain);
455 offset = (char *) query;
456 while (offset != NULL) {
459 tmp = strchr(offset, '.');
461 len = strlen(offset);
465 memcpy(ptr + 1, offset, len);
471 memcpy(ptr + 1, offset, tmp - offset);
472 ptr += tmp - offset + 1;
477 offset = (char *) domain;
478 while (offset != NULL) {
481 tmp = strchr(offset, '.');
483 len = strlen(offset);
487 memcpy(ptr + 1, offset, len);
493 memcpy(ptr + 1, offset, tmp - offset);
494 ptr += tmp - offset + 1;
504 static gboolean cache_check_is_valid(struct cache_data *data,
510 if (data->cache_until < current_time)
517 * remove stale cached entries so that they can be refreshed
519 static void cache_enforce_validity(struct cache_entry *entry)
521 time_t current_time = time(0);
523 if (cache_check_is_valid(entry->ipv4, current_time) == FALSE
525 DBG("cache timeout \"%s\" type A", entry->key);
526 g_free(entry->ipv4->data);
532 if (cache_check_is_valid(entry->ipv6, current_time) == FALSE
534 DBG("cache timeout \"%s\" type AAAA", entry->key);
535 g_free(entry->ipv6->data);
542 static uint16_t cache_check_validity(char *question, uint16_t type,
543 struct cache_entry *entry)
545 time_t current_time = time(0);
547 cache_enforce_validity(entry);
551 if (cache_check_is_valid(entry->ipv4, current_time) == FALSE) {
552 DBG("cache %s \"%s\" type A", entry->ipv4 ?
553 "timeout" : "entry missing", question);
556 * We do not remove cache entry if there is still
557 * valid IPv6 entry found in the cache.
559 if (cache_check_is_valid(entry->ipv6, current_time) == FALSE)
560 g_hash_table_remove(cache, question);
567 if (cache_check_is_valid(entry->ipv6, current_time) == FALSE) {
568 DBG("cache %s \"%s\" type AAAA", entry->ipv6 ?
569 "timeout" : "entry missing", question);
571 if (cache_check_is_valid(entry->ipv4, current_time) == FALSE)
572 g_hash_table_remove(cache, question);
582 static struct cache_entry *cache_check(gpointer request, int *qtype)
584 char *question = request + 12;
585 struct cache_entry *entry;
586 struct domain_question *q;
590 offset = strlen(question) + 1;
591 q = (void *) (question + offset);
592 type = ntohs(q->type);
594 /* We only cache either A (1) or AAAA (28) requests */
595 if (type != 1 && type != 28)
598 entry = g_hash_table_lookup(cache, question);
602 type = cache_check_validity(question, type, entry);
611 * Get a label/name from DNS resource record. The function decompresses the
612 * label if necessary. The function does not convert the name to presentation
613 * form. This means that the result string will contain label lengths instead
614 * of dots between labels. We intentionally do not want to convert to dotted
615 * format so that we can cache the wire format string directly.
617 static int get_name(int counter,
618 unsigned char *pkt, unsigned char *start, unsigned char *max,
619 unsigned char *output, int output_max, int *output_len,
620 unsigned char **end, char *name, int *name_len)
624 /* Limit recursion to 10 (this means up to 10 labels in domain name) */
630 if ((*p & NS_CMPRSFLGS) == NS_CMPRSFLGS) {
631 uint16_t offset = (*p & 0x3F) * 256 + *(p + 1);
633 if (offset >= max - pkt)
639 return get_name(counter + 1, pkt, pkt + offset, max,
640 output, output_max, output_len, end,
643 unsigned label_len = *p;
645 if (pkt + label_len > max)
648 if (*output_len > output_max)
652 * We need the original name in order to check
653 * if this answer is the correct one.
655 name[(*name_len)++] = label_len;
656 memcpy(name + *name_len, p + 1, label_len + 1);
657 *name_len += label_len;
659 /* We compress the result */
660 output[0] = NS_CMPRSFLGS;
677 static int parse_rr(unsigned char *buf, unsigned char *start,
679 unsigned char *response, unsigned int *response_size,
680 uint16_t *type, uint16_t *class, int *ttl, int *rdlen,
684 struct domain_rr *rr;
686 int name_len = 0, output_len = 0, max_rsp = *response_size;
688 err = get_name(0, buf, start, max, response, max_rsp,
689 &output_len, end, name, &name_len);
695 if ((unsigned int) offset > *response_size)
698 rr = (void *) (*end);
703 *type = ntohs(rr->type);
704 *class = ntohs(rr->class);
705 *ttl = ntohl(rr->ttl);
706 *rdlen = ntohs(rr->rdlen);
711 memcpy(response + offset, *end, sizeof(struct domain_rr));
713 offset += sizeof(struct domain_rr);
714 *end += sizeof(struct domain_rr);
716 if ((unsigned int) (offset + *rdlen) > *response_size)
719 memcpy(response + offset, *end, *rdlen);
723 *response_size = offset + *rdlen;
728 static gboolean check_alias(GSList *aliases, char *name)
732 if (aliases != NULL) {
733 for (list = aliases; list; list = list->next) {
734 int len = strlen((char *)list->data);
735 if (strncmp((char *)list->data, name, len) == 0)
743 static int parse_response(unsigned char *buf, int buflen,
744 char *question, int qlen,
745 uint16_t *type, uint16_t *class, int *ttl,
746 unsigned char *response, unsigned int *response_len,
749 struct domain_hdr *hdr = (void *) buf;
750 struct domain_question *q;
752 uint16_t qdcount = ntohs(hdr->qdcount);
753 uint16_t ancount = ntohs(hdr->ancount);
755 uint16_t qtype, qclass;
756 unsigned char *next = NULL;
757 unsigned int maxlen = *response_len;
758 GSList *aliases = NULL, *list;
759 char name[NS_MAXDNAME + 1];
764 DBG("qr %d qdcount %d", hdr->qr, qdcount);
766 /* We currently only cache responses where question count is 1 */
767 if (hdr->qr != 1 || qdcount != 1)
770 ptr = buf + sizeof(struct domain_hdr);
772 strncpy(question, (char *) ptr, qlen);
773 qlen = strlen(question);
774 ptr += qlen + 1; /* skip \0 */
777 qtype = ntohs(q->type);
779 /* We cache only A and AAAA records */
780 if (qtype != 1 && qtype != 28)
783 qclass = ntohs(q->class);
785 ptr += 2 + 2; /* ptr points now to answers */
792 * We have a bunch of answers (like A, AAAA, CNAME etc) to
793 * A or AAAA question. We traverse the answers and parse the
794 * resource records. Only A and AAAA records are cached, all
795 * the other records in answers are skipped.
797 for (i = 0; i < ancount; i++) {
799 * Get one address at a time to this buffer.
800 * The max size of the answer is
801 * 2 (pointer) + 2 (type) + 2 (class) +
802 * 4 (ttl) + 2 (rdlen) + addr (16 or 4) = 28
803 * for A or AAAA record.
804 * For CNAME the size can be bigger.
806 unsigned char rsp[NS_MAXCDNAME];
807 unsigned int rsp_len = sizeof(rsp) - 1;
810 memset(rsp, 0, sizeof(rsp));
812 ret = parse_rr(buf, ptr, buf + buflen, rsp, &rsp_len,
813 type, class, ttl, &rdlen, &next, name);
820 * Now rsp contains compressed or uncompressed resource
821 * record. Next we check if this record answers the question.
822 * The name var contains the uncompressed label.
823 * One tricky bit is the CNAME records as they alias
824 * the name we might be interested in.
828 * Go to next answer if the class is not the one we are
831 if (*class != qclass) {
838 * Try to resolve aliases also, type is CNAME(5).
839 * This is important as otherwise the aliased names would not
840 * be cached at all as the cache would not contain the aliased
843 * If any CNAME is found in DNS packet, then we cache the alias
844 * IP address instead of the question (as the server
845 * said that question has only an alias).
846 * This means in practice that if e.g., ipv6.google.com is
847 * queried, DNS server returns CNAME of that name which is
848 * ipv6.l.google.com. We then cache the address of the CNAME
849 * but return the question name to client. So the alias
850 * status of the name is not saved in cache and thus not
851 * returned to the client. We do not return DNS packets from
852 * cache to client saying that ipv6.google.com is an alias to
853 * ipv6.l.google.com but we return instead a DNS packet that
854 * says ipv6.google.com has address xxx which is in fact the
855 * address of ipv6.l.google.com. For caching purposes this
856 * should not cause any issues.
858 if (*type == 5 && strncmp(question, name, qlen) == 0) {
860 * So now the alias answered the question. This is
861 * not very useful from caching point of view as
862 * the following A or AAAA records will not match the
863 * question. We need to find the real A/AAAA record
864 * of the alias and cache that.
866 unsigned char *end = NULL;
867 int name_len = 0, output_len;
869 memset(rsp, 0, sizeof(rsp));
870 rsp_len = sizeof(rsp) - 1;
873 * Alias is in rdata part of the message,
874 * and next-rdlen points to it. So we need to get
875 * the real name of the alias.
877 ret = get_name(0, buf, next - rdlen, buf + buflen,
878 rsp, rsp_len, &output_len, &end,
881 /* just ignore the error at this point */
888 * We should now have the alias of the entry we might
889 * want to cache. Just remember it for a while.
890 * We check the alias list when we have parsed the
893 aliases = g_slist_prepend(aliases, g_strdup(name));
900 if (*type == qtype) {
902 * We found correct type (A or AAAA)
904 if (check_alias(aliases, name) == TRUE ||
905 (aliases == NULL && strncmp(question, name,
908 * We found an alias or the name of the rr
909 * matches the question. If so, we append
910 * the compressed label to the cache.
911 * The end result is a response buffer that
912 * will contain one or more cached and
913 * compressed resource records.
915 if (*response_len + rsp_len > maxlen) {
919 memcpy(response + *response_len, rsp, rsp_len);
920 *response_len += rsp_len;
931 for (list = aliases; list; list = list->next)
933 g_slist_free(aliases);
938 struct cache_timeout {
944 static gboolean cache_check_entry(gpointer key, gpointer value,
947 struct cache_timeout *data = user_data;
948 struct cache_entry *entry = value;
951 /* Scale the number of hits by half as part of cache aging */
956 * If either IPv4 or IPv6 cached entry has expired, we
957 * remove both from the cache.
960 if (entry->ipv4 != NULL && entry->ipv4->timeout > 0) {
961 max_timeout = entry->ipv4->cache_until;
962 if (max_timeout > data->max_timeout)
963 data->max_timeout = max_timeout;
965 if (entry->ipv4->cache_until < data->current_time)
969 if (entry->ipv6 != NULL && entry->ipv6->timeout > 0) {
970 max_timeout = entry->ipv6->cache_until;
971 if (max_timeout > data->max_timeout)
972 data->max_timeout = max_timeout;
974 if (entry->ipv6->cache_until < data->current_time)
979 * if we're asked to try harder, also remove entries that have
982 if (data->try_harder && entry->hits < 4)
988 static void cache_cleanup(void)
990 static int max_timeout;
991 struct cache_timeout data;
994 data.current_time = time(0);
995 data.max_timeout = 0;
999 * In the first pass, we only remove entries that have timed out.
1000 * We use a cache of the first time to expire to do this only
1001 * when it makes sense.
1003 if (max_timeout <= data.current_time) {
1004 count = g_hash_table_foreach_remove(cache, cache_check_entry,
1007 DBG("removed %d in the first pass", count);
1010 * In the second pass, if the first pass turned up blank,
1011 * we also expire entries with a low hit count,
1012 * while aging the hit count at the same time.
1014 data.try_harder = 1;
1016 count = g_hash_table_foreach_remove(cache, cache_check_entry,
1021 * If we could not remove anything, then remember
1022 * what is the max timeout and do nothing if we
1023 * have not yet reached it. This will prevent
1024 * constant traversal of the cache if it is full.
1026 max_timeout = data.max_timeout;
1031 static gboolean cache_invalidate_entry(gpointer key, gpointer value,
1034 struct cache_entry *entry = value;
1036 /* first, delete any expired elements */
1037 cache_enforce_validity(entry);
1039 /* delete the cached data */
1041 g_free(entry->ipv4->data);
1042 g_free(entry->ipv4);
1047 g_free(entry->ipv6->data);
1048 g_free(entry->ipv6);
1056 * cache_invalidate is called from places where the DNS landscape
1057 * has changed, say because connections are added or we entered a VPN.
1058 * The logic is to wipe all cache data, but mark all non-expired
1059 * parts of the cache for refresh rather than deleting the whole cache.
1061 static void cache_invalidate(void)
1063 DBG("Invalidating the DNS cache");
1064 g_hash_table_foreach_remove(cache, cache_invalidate_entry,
1069 static int reply_query_type(unsigned char *msg, int len)
1076 /* skip the header */
1077 c = msg + sizeof(struct domain_hdr);
1078 len -= sizeof(struct domain_hdr);
1083 /* now the query, which is a name and 2 16 bit words */
1084 l = dns_name_length(c) + 1;
1092 static int cache_update(struct server_data *srv, unsigned char *msg,
1093 unsigned int msg_len)
1095 int offset = protocol_offset(srv->protocol);
1096 int err, qlen, ttl = 0;
1097 uint16_t answers = 0, type = 0, class = 0;
1098 struct domain_question *q;
1099 struct cache_entry *entry;
1100 struct cache_data *data;
1101 char question[NS_MAXDNAME + 1];
1102 unsigned char response[NS_MAXDNAME + 1];
1104 unsigned int rsplen;
1105 gboolean new_entry = TRUE;
1106 time_t current_time;
1108 if (cache_size >= MAX_CACHE_SIZE) {
1110 if (cache_size >= MAX_CACHE_SIZE)
1114 /* Continue only if response code is 0 (=ok) */
1121 rsplen = sizeof(response) - 1;
1122 question[sizeof(question) - 1] = '\0';
1124 err = parse_response(msg + offset, msg_len - offset,
1125 question, sizeof(question) - 1,
1126 &type, &class, &ttl,
1127 response, &rsplen, &answers);
1130 * special case: if we do a ipv6 lookup and get no result
1131 * for a record that's already in our ipv4 cache.. we want
1132 * to cache the negative response.
1134 if ((err == -ENOMSG || err == -ENOBUFS) &&
1135 reply_query_type(msg, msg_len) == 28) {
1136 entry = g_hash_table_lookup(cache, question);
1137 if (entry && entry->ipv4 && entry->ipv6 == NULL) {
1138 data = g_try_new(struct cache_data, 1);
1141 data->inserted = entry->ipv4->inserted;
1143 data->answers = msg[5];
1144 data->timeout = entry->ipv4->timeout;
1145 data->data_len = msg_len;
1146 data->data = ptr = g_malloc(msg_len);
1147 data->valid_until = entry->ipv4->valid_until;
1148 data->cache_until = entry->ipv4->cache_until;
1149 memcpy(data->data, msg, msg_len);
1152 * we will get a "hit" when we serve the response
1156 if (entry->hits < 0)
1162 if (err < 0 || ttl == 0)
1165 qlen = strlen(question);
1166 current_time = time(0);
1169 * If the cache contains already data, check if the
1170 * type of the cached data is the same and do not add
1171 * to cache if data is already there.
1172 * This is needed so that we can cache both A and AAAA
1173 * records for the same name.
1175 entry = g_hash_table_lookup(cache, question);
1176 if (entry == NULL) {
1177 entry = g_try_new(struct cache_entry, 1);
1181 data = g_try_new(struct cache_data, 1);
1187 entry->key = g_strdup(question);
1188 entry->ipv4 = entry->ipv6 = NULL;
1196 if (type == 1 && entry->ipv4 != NULL)
1199 if (type == 28 && entry->ipv6 != NULL)
1202 data = g_try_new(struct cache_data, 1);
1212 * compensate for the hit we'll get for serving
1213 * the response out of the cache
1216 if (entry->hits < 0)
1222 if (ttl < MIN_CACHE_TTL)
1223 ttl = MIN_CACHE_TTL;
1225 data->inserted = current_time;
1227 data->answers = answers;
1228 data->timeout = ttl;
1229 data->data_len = 12 + qlen + 1 + 2 + 2 + rsplen;
1230 data->data = ptr = g_malloc(data->data_len);
1231 data->valid_until = current_time + ttl;
1234 * Restrict the cached DNS record TTL to some sane value
1235 * in order to prevent data staying in the cache too long.
1237 if (ttl > MAX_CACHE_TTL)
1238 ttl = MAX_CACHE_TTL;
1240 data->cache_until = round_down_ttl(current_time + ttl, ttl);
1242 if (data->data == NULL) {
1249 memcpy(ptr, msg, 12);
1250 memcpy(ptr + 12, question, qlen + 1); /* copy also the \0 */
1252 q = (void *) (ptr + 12 + qlen + 1);
1253 q->type = htons(type);
1254 q->class = htons(class);
1255 memcpy(ptr + 12 + qlen + 1 + sizeof(struct domain_question),
1258 if (new_entry == TRUE) {
1259 g_hash_table_replace(cache, entry->key, entry);
1263 DBG("cache %d %squestion \"%s\" type %d ttl %d size %zd",
1264 cache_size, new_entry ? "new " : "old ",
1265 question, type, ttl,
1266 sizeof(*entry) + sizeof(*data) + data->data_len + qlen);
1271 static int ns_resolv(struct server_data *server, struct request_data *req,
1272 gpointer request, gpointer name)
1275 int sk, err, type = 0;
1276 char *dot, *lookup = (char *) name;
1277 struct cache_entry *entry;
1279 entry = cache_check(request, &type);
1280 if (entry != NULL) {
1282 struct cache_data *data;
1284 DBG("cache hit %s type %s", lookup, type == 1 ? "A" : "AAAA");
1291 ttl_left = data->valid_until - time(0);
1295 if (data != NULL && req->protocol == IPPROTO_TCP) {
1296 send_cached_response(req->client_sk, data->data,
1297 data->data_len, NULL, 0, IPPROTO_TCP,
1298 req->srcid, data->answers, ttl_left);
1302 if (data != NULL && req->protocol == IPPROTO_UDP) {
1304 sk = g_io_channel_unix_get_fd(
1305 req->ifdata->udp_listener_channel);
1307 send_cached_response(sk, data->data,
1308 data->data_len, &req->sa, req->sa_len,
1309 IPPROTO_UDP, req->srcid, data->answers,
1315 sk = g_io_channel_unix_get_fd(server->channel);
1317 err = send(sk, request, req->request_len, 0);
1321 /* If we have more than one dot, we don't add domains */
1322 dot = strchr(lookup, '.');
1323 if (dot != NULL && dot != lookup + strlen(lookup) - 1)
1326 if (server->domains != NULL && server->domains->data != NULL)
1327 req->append_domain = TRUE;
1329 for (list = server->domains; list; list = list->next) {
1331 unsigned char alt[1024];
1332 struct domain_hdr *hdr = (void *) &alt;
1333 int altlen, domlen, offset;
1335 domain = list->data;
1340 offset = protocol_offset(server->protocol);
1344 domlen = strlen(domain) + 1;
1348 alt[offset] = req->altid & 0xff;
1349 alt[offset + 1] = req->altid >> 8;
1351 memcpy(alt + offset + 2, request + offset + 2, 10);
1352 hdr->qdcount = htons(1);
1354 altlen = append_query(alt + offset + 12, sizeof(alt) - 12,
1361 memcpy(alt + offset + altlen,
1362 request + offset + altlen - domlen,
1363 req->request_len - altlen - offset + domlen);
1365 if (server->protocol == IPPROTO_TCP) {
1366 int req_len = req->request_len + domlen - 2;
1368 alt[0] = (req_len >> 8) & 0xff;
1369 alt[1] = req_len & 0xff;
1372 err = send(sk, alt, req->request_len + domlen, 0);
1382 static int forward_dns_reply(unsigned char *reply, int reply_len, int protocol,
1383 struct server_data *data)
1385 struct domain_hdr *hdr;
1386 struct request_data *req;
1387 int dns_id, sk, err, offset = protocol_offset(protocol);
1388 struct listener_data *ifdata;
1393 hdr = (void *)(reply + offset);
1394 dns_id = reply[offset] | reply[offset + 1] << 8;
1396 DBG("Received %d bytes (id 0x%04x)", reply_len, dns_id);
1398 req = find_request(dns_id);
1402 DBG("id 0x%04x rcode %d", hdr->id, hdr->rcode);
1404 ifdata = req->ifdata;
1406 reply[offset] = req->srcid & 0xff;
1407 reply[offset + 1] = req->srcid >> 8;
1411 if (hdr->rcode == 0 || req->resp == NULL) {
1414 * If the domain name was append
1415 * remove it before forwarding the reply.
1417 if (req->append_domain == TRUE) {
1420 unsigned int domain_len;
1423 * ptr points to the first char of the hostname.
1424 * ->hostname.domain.net
1426 ptr = reply + offset + sizeof(struct domain_hdr);
1428 domain_len = strlen((const char *)ptr) - host_len - 1;
1431 * remove the domain name and replaced it by the end
1434 memmove(ptr + host_len + 1,
1435 ptr + host_len + domain_len + 1,
1436 reply_len - (ptr - reply + domain_len));
1438 reply_len = reply_len - domain_len;
1444 req->resp = g_try_malloc(reply_len);
1445 if (req->resp == NULL)
1448 memcpy(req->resp, reply, reply_len);
1449 req->resplen = reply_len;
1451 cache_update(data, reply, reply_len);
1454 if (hdr->rcode > 0 && req->numresp < req->numserv)
1457 if (req->timeout > 0)
1458 g_source_remove(req->timeout);
1460 request_list = g_slist_remove(request_list, req);
1462 if (protocol == IPPROTO_UDP) {
1463 sk = g_io_channel_unix_get_fd(ifdata->udp_listener_channel);
1464 err = sendto(sk, req->resp, req->resplen, 0,
1465 &req->sa, req->sa_len);
1467 sk = req->client_sk;
1468 err = send(sk, req->resp, req->resplen, 0);
1478 static void cache_element_destroy(gpointer value)
1480 struct cache_entry *entry = value;
1485 if (entry->ipv4 != NULL) {
1486 g_free(entry->ipv4->data);
1487 g_free(entry->ipv4);
1490 if (entry->ipv6 != NULL) {
1491 g_free(entry->ipv6->data);
1492 g_free(entry->ipv6);
1498 if (--cache_size < 0)
1502 static void destroy_server(struct server_data *server)
1506 DBG("interface %s server %s", server->interface, server->server);
1508 server_list = g_slist_remove(server_list, server);
1510 if (server->watch > 0)
1511 g_source_remove(server->watch);
1513 if (server->timeout > 0)
1514 g_source_remove(server->timeout);
1516 g_io_channel_unref(server->channel);
1518 if (server->protocol == IPPROTO_UDP)
1519 connman_info("Removing DNS server %s", server->server);
1521 g_free(server->incoming_reply);
1522 g_free(server->server);
1523 for (list = server->domains; list; list = list->next) {
1524 char *domain = list->data;
1526 server->domains = g_list_remove(server->domains, domain);
1529 g_free(server->interface);
1531 if (__sync_fetch_and_sub(&cache_refcount, 1) == 1)
1532 g_hash_table_destroy(cache);
1537 static gboolean udp_server_event(GIOChannel *channel, GIOCondition condition,
1540 unsigned char buf[4096];
1542 struct server_data *data = user_data;
1544 if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
1545 connman_error("Error with UDP server %s", data->server);
1550 sk = g_io_channel_unix_get_fd(channel);
1552 len = recv(sk, buf, sizeof(buf), 0);
1556 err = forward_dns_reply(buf, len, IPPROTO_UDP, data);
1563 static gboolean tcp_server_event(GIOChannel *channel, GIOCondition condition,
1567 struct server_data *server = user_data;
1569 sk = g_io_channel_unix_get_fd(channel);
1573 if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
1576 DBG("TCP server channel closed");
1579 * Discard any partial response which is buffered; better
1580 * to get a proper response from a working server.
1582 g_free(server->incoming_reply);
1583 server->incoming_reply = NULL;
1585 for (list = request_list; list; list = list->next) {
1586 struct request_data *req = list->data;
1587 struct domain_hdr *hdr;
1589 if (req->protocol == IPPROTO_UDP)
1592 if (req->request == NULL)
1596 * If we're not waiting for any further response
1597 * from another name server, then we send an error
1598 * response to the client.
1600 if (req->numserv && --(req->numserv))
1603 hdr = (void *) (req->request + 2);
1604 hdr->id = req->srcid;
1605 send_response(req->client_sk, req->request,
1606 req->request_len, NULL, 0, IPPROTO_TCP);
1608 request_list = g_slist_remove(request_list, req);
1611 destroy_server(server);
1616 if ((condition & G_IO_OUT) && !server->connected) {
1619 struct server_data *udp_server;
1621 udp_server = find_server(server->interface, server->server,
1623 if (udp_server != NULL) {
1624 for (domains = udp_server->domains; domains;
1625 domains = domains->next) {
1626 char *dom = domains->data;
1628 DBG("Adding domain %s to %s",
1629 dom, server->server);
1631 server->domains = g_list_append(server->domains,
1636 server->connected = TRUE;
1637 server_list = g_slist_append(server_list, server);
1639 if (server->timeout > 0) {
1640 g_source_remove(server->timeout);
1641 server->timeout = 0;
1644 for (list = request_list; list; list = list->next) {
1645 struct request_data *req = list->data;
1647 if (req->protocol == IPPROTO_UDP)
1650 DBG("Sending req %s over TCP", (char *)req->name);
1652 if (req->timeout > 0)
1653 g_source_remove(req->timeout);
1655 req->timeout = g_timeout_add_seconds(30,
1656 request_timeout, req);
1657 if (ns_resolv(server, req, req->request,
1659 /* We sent cached result so no need for timeout
1662 if (req->timeout > 0) {
1663 g_source_remove(req->timeout);
1669 } else if (condition & G_IO_IN) {
1670 struct partial_reply *reply = server->incoming_reply;
1674 unsigned char reply_len_buf[2];
1677 bytes_recv = recv(sk, reply_len_buf, 2, MSG_PEEK);
1680 } else if (bytes_recv < 0) {
1681 if (errno == EAGAIN || errno == EWOULDBLOCK)
1684 connman_error("DNS proxy error %s",
1687 } else if (bytes_recv < 2)
1690 reply_len = reply_len_buf[1] | reply_len_buf[0] << 8;
1693 DBG("TCP reply %d bytes", reply_len);
1695 reply = g_try_malloc(sizeof(*reply) + reply_len + 2);
1699 reply->len = reply_len;
1700 reply->received = 0;
1702 server->incoming_reply = reply;
1705 while (reply->received < reply->len) {
1706 bytes_recv = recv(sk, reply->buf + reply->received,
1707 reply->len - reply->received, 0);
1709 connman_error("DNS proxy TCP disconnect");
1711 } else if (bytes_recv < 0) {
1712 if (errno == EAGAIN || errno == EWOULDBLOCK)
1715 connman_error("DNS proxy error %s",
1719 reply->received += bytes_recv;
1722 forward_dns_reply(reply->buf, reply->received, IPPROTO_TCP,
1726 server->incoming_reply = NULL;
1728 destroy_server(server);
1736 static gboolean tcp_idle_timeout(gpointer user_data)
1738 struct server_data *server = user_data;
1745 destroy_server(server);
1750 static struct server_data *create_server(const char *interface,
1751 const char *domain, const char *server,
1754 struct addrinfo hints, *rp;
1755 struct server_data *data;
1758 DBG("interface %s server %s", interface, server);
1760 memset(&hints, 0, sizeof(hints));
1764 hints.ai_socktype = SOCK_DGRAM;
1768 hints.ai_socktype = SOCK_STREAM;
1774 hints.ai_family = AF_UNSPEC;
1775 hints.ai_flags = AI_PASSIVE | AI_NUMERICSERV | AI_NUMERICHOST;
1777 ret = getaddrinfo(server, "53", &hints, &rp);
1779 connman_error("Failed to parse server %s address: %s\n",
1780 server, gai_strerror(ret));
1783 /* Do not blindly copy this code elsewhere; it doesn't loop over the
1784 results using ->ai_next as it should. That's OK in *this* case
1785 because it was a numeric lookup; we *know* there's only one. */
1787 sk = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
1789 connman_error("Failed to create server %s socket", server);
1794 if (interface != NULL) {
1795 if (setsockopt(sk, SOL_SOCKET, SO_BINDTODEVICE,
1796 interface, strlen(interface) + 1) < 0) {
1797 connman_error("Failed to bind server %s "
1806 data = g_try_new0(struct server_data, 1);
1808 connman_error("Failed to allocate server %s data", server);
1814 data->channel = g_io_channel_unix_new(sk);
1815 if (data->channel == NULL) {
1816 connman_error("Failed to create server %s channel", server);
1823 g_io_channel_set_close_on_unref(data->channel, TRUE);
1825 if (protocol == IPPROTO_TCP) {
1826 g_io_channel_set_flags(data->channel, G_IO_FLAG_NONBLOCK, NULL);
1827 data->watch = g_io_add_watch(data->channel,
1828 G_IO_OUT | G_IO_IN | G_IO_HUP | G_IO_NVAL | G_IO_ERR,
1829 tcp_server_event, data);
1830 data->timeout = g_timeout_add_seconds(30, tcp_idle_timeout,
1833 data->watch = g_io_add_watch(data->channel,
1834 G_IO_IN | G_IO_NVAL | G_IO_ERR | G_IO_HUP,
1835 udp_server_event, data);
1837 data->interface = g_strdup(interface);
1839 data->domains = g_list_append(data->domains, g_strdup(domain));
1840 data->server = g_strdup(server);
1841 data->protocol = protocol;
1843 ret = connect(sk, rp->ai_addr, rp->ai_addrlen);
1846 if ((protocol == IPPROTO_TCP && errno != EINPROGRESS) ||
1847 protocol == IPPROTO_UDP) {
1850 connman_error("Failed to connect to server %s", server);
1851 if (data->watch > 0)
1852 g_source_remove(data->watch);
1853 if (data->timeout > 0)
1854 g_source_remove(data->timeout);
1856 g_io_channel_unref(data->channel);
1859 g_free(data->server);
1860 g_free(data->interface);
1861 for (list = data->domains; list; list = list->next) {
1862 char *domain = list->data;
1864 data->domains = g_list_remove(data->domains,
1873 if (__sync_fetch_and_add(&cache_refcount, 1) == 0)
1874 cache = g_hash_table_new_full(g_str_hash,
1877 cache_element_destroy);
1879 if (protocol == IPPROTO_UDP) {
1880 /* Enable new servers by default */
1881 data->enabled = TRUE;
1882 connman_info("Adding DNS server %s", data->server);
1884 server_list = g_slist_append(server_list, data);
1892 static gboolean resolv(struct request_data *req,
1893 gpointer request, gpointer name)
1898 for (list = server_list; list; list = list->next) {
1899 struct server_data *data = list->data;
1901 DBG("server %s enabled %d", data->server, data->enabled);
1903 if (data->enabled == FALSE)
1906 if (data->watch == 0 && data->protocol == IPPROTO_UDP)
1907 data->watch = g_io_add_watch(data->channel,
1908 G_IO_IN | G_IO_NVAL | G_IO_ERR | G_IO_HUP,
1909 udp_server_event, data);
1911 status = ns_resolv(data, req, request, name);
1916 if (req->timeout > 0) {
1917 g_source_remove(req->timeout);
1926 static void append_domain(const char *interface, const char *domain)
1930 DBG("interface %s domain %s", interface, domain);
1935 for (list = server_list; list; list = list->next) {
1936 struct server_data *data = list->data;
1939 gboolean dom_found = FALSE;
1941 if (data->interface == NULL)
1944 if (g_str_equal(data->interface, interface) == FALSE)
1947 for (dom_list = data->domains; dom_list;
1948 dom_list = dom_list->next) {
1949 dom = dom_list->data;
1951 if (g_str_equal(dom, domain)) {
1957 if (dom_found == FALSE) {
1959 g_list_append(data->domains, g_strdup(domain));
1964 int __connman_dnsproxy_append(const char *interface, const char *domain,
1967 struct server_data *data;
1969 DBG("interface %s server %s", interface, server);
1971 if (server == NULL && domain == NULL)
1974 if (server == NULL) {
1975 append_domain(interface, domain);
1980 if (g_str_equal(server, "127.0.0.1") == TRUE)
1983 data = find_server(interface, server, IPPROTO_UDP);
1985 append_domain(interface, domain);
1989 data = create_server(interface, domain, server, IPPROTO_UDP);
1996 static void remove_server(const char *interface, const char *domain,
1997 const char *server, int protocol)
1999 struct server_data *data;
2001 data = find_server(interface, server, protocol);
2005 destroy_server(data);
2008 int __connman_dnsproxy_remove(const char *interface, const char *domain,
2011 DBG("interface %s server %s", interface, server);
2016 if (g_str_equal(server, "127.0.0.1") == TRUE)
2019 remove_server(interface, domain, server, IPPROTO_UDP);
2020 remove_server(interface, domain, server, IPPROTO_TCP);
2025 void __connman_dnsproxy_flush(void)
2029 list = request_pending_list;
2031 struct request_data *req = list->data;
2035 request_pending_list =
2036 g_slist_remove(request_pending_list, req);
2037 resolv(req, req->request, req->name);
2038 g_free(req->request);
2043 static void dnsproxy_offline_mode(connman_bool_t enabled)
2047 DBG("enabled %d", enabled);
2049 for (list = server_list; list; list = list->next) {
2050 struct server_data *data = list->data;
2052 if (enabled == FALSE) {
2053 connman_info("Enabling DNS server %s", data->server);
2054 data->enabled = TRUE;
2057 connman_info("Disabling DNS server %s", data->server);
2058 data->enabled = FALSE;
2064 static void dnsproxy_default_changed(struct connman_service *service)
2069 DBG("service %p", service);
2071 /* DNS has changed, invalidate the cache */
2074 if (service == NULL) {
2075 /* When no services are active, then disable DNS proxying */
2076 dnsproxy_offline_mode(TRUE);
2080 interface = connman_service_get_interface(service);
2081 if (interface == NULL)
2084 for (list = server_list; list; list = list->next) {
2085 struct server_data *data = list->data;
2087 if (g_strcmp0(data->interface, interface) == 0) {
2088 connman_info("Enabling DNS server %s", data->server);
2089 data->enabled = TRUE;
2091 connman_info("Disabling DNS server %s", data->server);
2092 data->enabled = FALSE;
2099 static struct connman_notifier dnsproxy_notifier = {
2101 .default_changed = dnsproxy_default_changed,
2102 .offline_mode = dnsproxy_offline_mode,
2105 static unsigned char opt_edns0_type[2] = { 0x00, 0x29 };
2107 static int parse_request(unsigned char *buf, int len,
2108 char *name, unsigned int size)
2110 struct domain_hdr *hdr = (void *) buf;
2111 uint16_t qdcount = ntohs(hdr->qdcount);
2112 uint16_t arcount = ntohs(hdr->arcount);
2114 char *last_label = NULL;
2115 unsigned int remain, used = 0;
2120 DBG("id 0x%04x qr %d opcode %d qdcount %d arcount %d",
2121 hdr->id, hdr->qr, hdr->opcode,
2124 if (hdr->qr != 0 || qdcount != 1)
2127 memset(name, 0, size);
2129 ptr = buf + sizeof(struct domain_hdr);
2130 remain = len - sizeof(struct domain_hdr);
2132 while (remain > 0) {
2136 last_label = (char *) (ptr + 1);
2140 if (used + len + 1 > size)
2143 strncat(name, (char *) (ptr + 1), len);
2152 if (last_label && arcount && remain >= 9 && last_label[4] == 0 &&
2153 !memcmp(last_label + 5, opt_edns0_type, 2)) {
2154 uint16_t edns0_bufsize;
2156 edns0_bufsize = last_label[7] << 8 | last_label[8];
2158 DBG("EDNS0 buffer size %u", edns0_bufsize);
2160 /* This is an evil hack until full TCP support has been
2163 * Somtimes the EDNS0 request gets send with a too-small
2164 * buffer size. Since glibc doesn't seem to crash when it
2165 * gets a response biffer then it requested, just bump
2166 * the buffer size up to 4KiB.
2168 if (edns0_bufsize < 0x1000) {
2169 last_label[7] = 0x10;
2170 last_label[8] = 0x00;
2174 DBG("query %s", name);
2179 static gboolean tcp_listener_event(GIOChannel *channel, GIOCondition condition,
2182 unsigned char buf[768];
2184 struct request_data *req;
2185 struct server_data *server;
2186 int sk, client_sk, len, err;
2187 struct sockaddr_in6 client_addr;
2188 socklen_t client_addr_len = sizeof(client_addr);
2190 struct listener_data *ifdata = user_data;
2192 DBG("condition 0x%x", condition);
2194 if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
2195 if (ifdata->tcp_listener_watch > 0)
2196 g_source_remove(ifdata->tcp_listener_watch);
2197 ifdata->tcp_listener_watch = 0;
2199 connman_error("Error with TCP listener channel");
2204 sk = g_io_channel_unix_get_fd(channel);
2206 client_sk = accept(sk, (void *)&client_addr, &client_addr_len);
2207 if (client_sk < 0) {
2208 connman_error("Accept failure on TCP listener");
2209 ifdata->tcp_listener_watch = 0;
2213 len = recv(client_sk, buf, sizeof(buf), 0);
2217 DBG("Received %d bytes (id 0x%04x)", len, buf[2] | buf[3] << 8);
2219 err = parse_request(buf + 2, len - 2, query, sizeof(query));
2220 if (err < 0 || (g_slist_length(server_list) == 0)) {
2221 send_response(client_sk, buf, len, NULL, 0, IPPROTO_TCP);
2225 req = g_try_new0(struct request_data, 1);
2229 memcpy(&req->sa, &client_addr, client_addr_len);
2230 req->sa_len = client_addr_len;
2231 req->client_sk = client_sk;
2232 req->protocol = IPPROTO_TCP;
2235 if (request_id == 0x0000 || request_id == 0xffff)
2238 req->srcid = buf[2] | (buf[3] << 8);
2239 req->dstid = request_id;
2240 req->altid = request_id + 1;
2241 req->request_len = len;
2243 buf[2] = req->dstid & 0xff;
2244 buf[3] = req->dstid >> 8;
2247 req->ifdata = (struct listener_data *) ifdata;
2248 req->append_domain = FALSE;
2249 request_list = g_slist_append(request_list, req);
2251 for (list = server_list; list; list = list->next) {
2252 struct server_data *data = list->data;
2255 if (data->protocol != IPPROTO_UDP || data->enabled == FALSE)
2258 server = create_server(data->interface, NULL,
2259 data->server, IPPROTO_TCP);
2262 * If server is NULL, we're not connected yet.
2263 * Copy the relevant buffers and continue with
2264 * the next nameserver.
2265 * The request will actually be sent once we're
2266 * properly connected over TCP to this nameserver.
2268 if (server == NULL) {
2269 req->request = g_try_malloc0(req->request_len);
2270 if (req->request == NULL)
2273 memcpy(req->request, buf, req->request_len);
2275 req->name = g_try_malloc0(sizeof(query));
2276 if (req->name == NULL) {
2277 g_free(req->request);
2280 memcpy(req->name, query, sizeof(query));
2285 if (req->timeout > 0)
2286 g_source_remove(req->timeout);
2288 for (domains = data->domains; domains;
2289 domains = domains->next) {
2290 char *dom = domains->data;
2292 DBG("Adding domain %s to %s", dom, server->server);
2294 server->domains = g_list_append(server->domains,
2298 req->timeout = g_timeout_add_seconds(30, request_timeout, req);
2299 if (ns_resolv(server, req, buf, query) > 0) {
2300 if (req->timeout > 0) {
2301 g_source_remove(req->timeout);
2310 static gboolean udp_listener_event(GIOChannel *channel, GIOCondition condition,
2313 unsigned char buf[768];
2315 struct request_data *req;
2316 struct sockaddr_in6 client_addr;
2317 socklen_t client_addr_len = sizeof(client_addr);
2319 struct listener_data *ifdata = user_data;
2321 if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
2322 connman_error("Error with UDP listener channel");
2323 ifdata->udp_listener_watch = 0;
2327 sk = g_io_channel_unix_get_fd(channel);
2329 memset(&client_addr, 0, client_addr_len);
2330 len = recvfrom(sk, buf, sizeof(buf), 0, (void *)&client_addr,
2335 DBG("Received %d bytes (id 0x%04x)", len, buf[0] | buf[1] << 8);
2337 err = parse_request(buf, len, query, sizeof(query));
2338 if (err < 0 || (g_slist_length(server_list) == 0)) {
2339 send_response(sk, buf, len, (void *)&client_addr,
2340 client_addr_len, IPPROTO_UDP);
2344 req = g_try_new0(struct request_data, 1);
2348 memcpy(&req->sa, &client_addr, client_addr_len);
2349 req->sa_len = client_addr_len;
2351 req->protocol = IPPROTO_UDP;
2354 if (request_id == 0x0000 || request_id == 0xffff)
2357 req->srcid = buf[0] | (buf[1] << 8);
2358 req->dstid = request_id;
2359 req->altid = request_id + 1;
2360 req->request_len = len;
2362 buf[0] = req->dstid & 0xff;
2363 buf[1] = req->dstid >> 8;
2366 req->ifdata = (struct listener_data *) ifdata;
2367 req->timeout = g_timeout_add_seconds(5, request_timeout, req);
2368 req->append_domain = FALSE;
2369 request_list = g_slist_append(request_list, req);
2371 return resolv(req, buf, query);
2374 static int create_dns_listener(int protocol, struct listener_data *ifdata)
2376 GIOChannel *channel;
2380 struct sockaddr_in6 sin6;
2381 struct sockaddr_in sin;
2384 int sk, type, v6only = 0;
2385 int family = AF_INET6;
2388 DBG("interface %s", ifdata->ifname);
2393 type = SOCK_DGRAM | SOCK_CLOEXEC;
2398 type = SOCK_STREAM | SOCK_CLOEXEC;
2405 sk = socket(family, type, protocol);
2406 if (sk < 0 && family == AF_INET6 && errno == EAFNOSUPPORT) {
2407 connman_error("No IPv6 support; DNS proxy listening only on Legacy IP");
2409 sk = socket(family, type, protocol);
2412 connman_error("Failed to create %s listener socket", proto);
2416 if (setsockopt(sk, SOL_SOCKET, SO_BINDTODEVICE,
2418 strlen(ifdata->ifname) + 1) < 0) {
2419 connman_error("Failed to bind %s listener interface", proto);
2423 /* Ensure it accepts Legacy IP connections too */
2424 if (family == AF_INET6 &&
2425 setsockopt(sk, SOL_IPV6, IPV6_V6ONLY,
2426 &v6only, sizeof(v6only)) < 0) {
2427 connman_error("Failed to clear V6ONLY on %s listener socket",
2433 if (family == AF_INET) {
2434 memset(&s.sin, 0, sizeof(s.sin));
2435 s.sin.sin_family = AF_INET;
2436 s.sin.sin_port = htons(53);
2437 s.sin.sin_addr.s_addr = htonl(INADDR_ANY);
2438 slen = sizeof(s.sin);
2440 memset(&s.sin6, 0, sizeof(s.sin6));
2441 s.sin6.sin6_family = AF_INET6;
2442 s.sin6.sin6_port = htons(53);
2443 s.sin6.sin6_addr = in6addr_any;
2444 slen = sizeof(s.sin6);
2447 if (bind(sk, &s.sa, slen) < 0) {
2448 connman_error("Failed to bind %s listener socket", proto);
2453 if (protocol == IPPROTO_TCP && listen(sk, 10) < 0) {
2454 connman_error("Failed to listen on TCP socket");
2459 channel = g_io_channel_unix_new(sk);
2460 if (channel == NULL) {
2461 connman_error("Failed to create %s listener channel", proto);
2466 g_io_channel_set_close_on_unref(channel, TRUE);
2468 if (protocol == IPPROTO_TCP) {
2469 ifdata->tcp_listener_channel = channel;
2470 ifdata->tcp_listener_watch = g_io_add_watch(channel,
2471 G_IO_IN, tcp_listener_event, (gpointer) ifdata);
2473 ifdata->udp_listener_channel = channel;
2474 ifdata->udp_listener_watch = g_io_add_watch(channel,
2475 G_IO_IN, udp_listener_event, (gpointer) ifdata);
2481 static void destroy_udp_listener(struct listener_data *ifdata)
2483 DBG("interface %s", ifdata->ifname);
2485 if (ifdata->udp_listener_watch > 0)
2486 g_source_remove(ifdata->udp_listener_watch);
2488 g_io_channel_unref(ifdata->udp_listener_channel);
2491 static void destroy_tcp_listener(struct listener_data *ifdata)
2493 DBG("interface %s", ifdata->ifname);
2495 if (ifdata->tcp_listener_watch > 0)
2496 g_source_remove(ifdata->tcp_listener_watch);
2498 g_io_channel_unref(ifdata->tcp_listener_channel);
2501 static int create_listener(struct listener_data *ifdata)
2505 err = create_dns_listener(IPPROTO_UDP, ifdata);
2509 err = create_dns_listener(IPPROTO_TCP, ifdata);
2511 destroy_udp_listener(ifdata);
2515 if (g_strcmp0(ifdata->ifname, "lo") == 0)
2516 __connman_resolvfile_append("lo", NULL, "127.0.0.1");
2521 static void destroy_listener(struct listener_data *ifdata)
2525 if (g_strcmp0(ifdata->ifname, "lo") == 0)
2526 __connman_resolvfile_remove("lo", NULL, "127.0.0.1");
2528 for (list = request_pending_list; list; list = list->next) {
2529 struct request_data *req = list->data;
2531 DBG("Dropping pending request (id 0x%04x -> 0x%04x)",
2532 req->srcid, req->dstid);
2535 g_free(req->request);
2541 g_slist_free(request_pending_list);
2542 request_pending_list = NULL;
2544 for (list = request_list; list; list = list->next) {
2545 struct request_data *req = list->data;
2547 DBG("Dropping request (id 0x%04x -> 0x%04x)",
2548 req->srcid, req->dstid);
2551 g_free(req->request);
2557 g_slist_free(request_list);
2558 request_list = NULL;
2560 destroy_tcp_listener(ifdata);
2561 destroy_udp_listener(ifdata);
2564 int __connman_dnsproxy_add_listener(const char *interface)
2566 struct listener_data *ifdata;
2569 DBG("interface %s", interface);
2571 if (g_hash_table_lookup(listener_table, interface) != NULL)
2574 ifdata = g_try_new0(struct listener_data, 1);
2578 ifdata->ifname = g_strdup(interface);
2579 ifdata->udp_listener_channel = NULL;
2580 ifdata->udp_listener_watch = 0;
2581 ifdata->tcp_listener_channel = NULL;
2582 ifdata->tcp_listener_watch = 0;
2584 err = create_listener(ifdata);
2586 connman_error("Couldn't create listener for %s err %d",
2588 g_free(ifdata->ifname);
2592 g_hash_table_insert(listener_table, ifdata->ifname, ifdata);
2596 void __connman_dnsproxy_remove_listener(const char *interface)
2598 struct listener_data *ifdata;
2600 DBG("interface %s", interface);
2602 ifdata = g_hash_table_lookup(listener_table, interface);
2606 destroy_listener(ifdata);
2608 g_hash_table_remove(listener_table, interface);
2611 static void remove_listener(gpointer key, gpointer value, gpointer user_data)
2613 __connman_dnsproxy_remove_listener(key);
2616 int __connman_dnsproxy_init(void)
2622 listener_table = g_hash_table_new_full(g_str_hash, g_str_equal,
2624 err = __connman_dnsproxy_add_listener("lo");
2628 err = connman_notifier_register(&dnsproxy_notifier);
2635 __connman_dnsproxy_remove_listener("lo");
2636 g_hash_table_destroy(listener_table);
2641 void __connman_dnsproxy_cleanup(void)
2645 connman_notifier_unregister(&dnsproxy_notifier);
2647 g_hash_table_foreach(listener_table, remove_listener, NULL);
2649 g_hash_table_destroy(listener_table);