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 int reply_query_type(unsigned char *msg, int len)
1038 /* skip the header */
1039 c = msg + sizeof(struct domain_hdr);
1040 len -= sizeof(struct domain_hdr);
1045 /* now the query, which is a name and 2 16 bit words */
1046 l = dns_name_length(c) + 1;
1054 static int cache_update(struct server_data *srv, unsigned char *msg,
1055 unsigned int msg_len)
1057 int offset = protocol_offset(srv->protocol);
1058 int err, qlen, ttl = 0;
1059 uint16_t answers = 0, type = 0, class = 0;
1060 struct domain_question *q;
1061 struct cache_entry *entry;
1062 struct cache_data *data;
1063 char question[NS_MAXDNAME + 1];
1064 unsigned char response[NS_MAXDNAME + 1];
1066 unsigned int rsplen;
1067 gboolean new_entry = TRUE;
1068 time_t current_time;
1070 if (cache_size >= MAX_CACHE_SIZE) {
1072 if (cache_size >= MAX_CACHE_SIZE)
1076 /* Continue only if response code is 0 (=ok) */
1083 rsplen = sizeof(response) - 1;
1084 question[sizeof(question) - 1] = '\0';
1086 err = parse_response(msg + offset, msg_len - offset,
1087 question, sizeof(question) - 1,
1088 &type, &class, &ttl,
1089 response, &rsplen, &answers);
1092 * special case: if we do a ipv6 lookup and get no result
1093 * for a record that's already in our ipv4 cache.. we want
1094 * to cache the negative response.
1096 if ((err == -ENOMSG || err == -ENOBUFS) &&
1097 reply_query_type(msg, msg_len) == 28) {
1098 entry = g_hash_table_lookup(cache, question);
1099 if (entry && entry->ipv4 && entry->ipv6 == NULL) {
1100 data = g_try_new(struct cache_data, 1);
1103 data->inserted = entry->ipv4->inserted;
1105 data->answers = msg[5];
1106 data->timeout = entry->ipv4->timeout;
1107 data->data_len = msg_len;
1108 data->data = ptr = g_malloc(msg_len);
1109 data->valid_until = entry->ipv4->valid_until;
1110 data->cache_until = entry->ipv4->cache_until;
1111 memcpy(data->data, msg, msg_len);
1114 * we will get a "hit" when we serve the response
1118 if (entry->hits < 0)
1124 if (err < 0 || ttl == 0)
1127 qlen = strlen(question);
1128 current_time = time(0);
1131 * If the cache contains already data, check if the
1132 * type of the cached data is the same and do not add
1133 * to cache if data is already there.
1134 * This is needed so that we can cache both A and AAAA
1135 * records for the same name.
1137 entry = g_hash_table_lookup(cache, question);
1138 if (entry == NULL) {
1139 entry = g_try_new(struct cache_entry, 1);
1143 data = g_try_new(struct cache_data, 1);
1149 entry->key = g_strdup(question);
1150 entry->ipv4 = entry->ipv6 = NULL;
1158 if (type == 1 && entry->ipv4 != NULL)
1161 if (type == 28 && entry->ipv6 != NULL)
1164 data = g_try_new(struct cache_data, 1);
1174 * compensate for the hit we'll get for serving
1175 * the response out of the cache
1178 if (entry->hits < 0)
1184 if (ttl < MIN_CACHE_TTL)
1185 ttl = MIN_CACHE_TTL;
1187 data->inserted = current_time;
1189 data->answers = answers;
1190 data->timeout = ttl;
1191 data->data_len = 12 + qlen + 1 + 2 + 2 + rsplen;
1192 data->data = ptr = g_malloc(data->data_len);
1193 data->valid_until = current_time + ttl;
1196 * Restrict the cached DNS record TTL to some sane value
1197 * in order to prevent data staying in the cache too long.
1199 if (ttl > MAX_CACHE_TTL)
1200 ttl = MAX_CACHE_TTL;
1202 data->cache_until = round_down_ttl(current_time + ttl, ttl);
1204 if (data->data == NULL) {
1211 memcpy(ptr, msg, 12);
1212 memcpy(ptr + 12, question, qlen + 1); /* copy also the \0 */
1214 q = (void *) (ptr + 12 + qlen + 1);
1215 q->type = htons(type);
1216 q->class = htons(class);
1217 memcpy(ptr + 12 + qlen + 1 + sizeof(struct domain_question),
1220 if (new_entry == TRUE) {
1221 g_hash_table_replace(cache, entry->key, entry);
1225 DBG("cache %d %squestion \"%s\" type %d ttl %d size %zd",
1226 cache_size, new_entry ? "new " : "old ",
1227 question, type, ttl,
1228 sizeof(*entry) + sizeof(*data) + data->data_len + qlen);
1233 static int ns_resolv(struct server_data *server, struct request_data *req,
1234 gpointer request, gpointer name)
1237 int sk, err, type = 0;
1238 char *dot, *lookup = (char *) name;
1239 struct cache_entry *entry;
1241 entry = cache_check(request, &type);
1242 if (entry != NULL) {
1244 struct cache_data *data;
1246 DBG("cache hit %s type %s", lookup, type == 1 ? "A" : "AAAA");
1253 ttl_left = data->valid_until - time(0);
1257 if (data != NULL && req->protocol == IPPROTO_TCP) {
1258 send_cached_response(req->client_sk, data->data,
1259 data->data_len, NULL, 0, IPPROTO_TCP,
1260 req->srcid, data->answers, ttl_left);
1264 if (data != NULL && req->protocol == IPPROTO_UDP) {
1266 sk = g_io_channel_unix_get_fd(
1267 req->ifdata->udp_listener_channel);
1269 send_cached_response(sk, data->data,
1270 data->data_len, &req->sa, req->sa_len,
1271 IPPROTO_UDP, req->srcid, data->answers,
1277 sk = g_io_channel_unix_get_fd(server->channel);
1279 err = send(sk, request, req->request_len, 0);
1283 /* If we have more than one dot, we don't add domains */
1284 dot = strchr(lookup, '.');
1285 if (dot != NULL && dot != lookup + strlen(lookup) - 1)
1288 if (server->domains != NULL && server->domains->data != NULL)
1289 req->append_domain = TRUE;
1291 for (list = server->domains; list; list = list->next) {
1293 unsigned char alt[1024];
1294 struct domain_hdr *hdr = (void *) &alt;
1295 int altlen, domlen, offset;
1297 domain = list->data;
1302 offset = protocol_offset(server->protocol);
1306 domlen = strlen(domain) + 1;
1310 alt[offset] = req->altid & 0xff;
1311 alt[offset + 1] = req->altid >> 8;
1313 memcpy(alt + offset + 2, request + offset + 2, 10);
1314 hdr->qdcount = htons(1);
1316 altlen = append_query(alt + offset + 12, sizeof(alt) - 12,
1323 memcpy(alt + offset + altlen,
1324 request + offset + altlen - domlen,
1325 req->request_len - altlen - offset + domlen);
1327 if (server->protocol == IPPROTO_TCP) {
1328 int req_len = req->request_len + domlen - 2;
1330 alt[0] = (req_len >> 8) & 0xff;
1331 alt[1] = req_len & 0xff;
1334 err = send(sk, alt, req->request_len + domlen, 0);
1344 static int forward_dns_reply(unsigned char *reply, int reply_len, int protocol,
1345 struct server_data *data)
1347 struct domain_hdr *hdr;
1348 struct request_data *req;
1349 int dns_id, sk, err, offset = protocol_offset(protocol);
1350 struct listener_data *ifdata;
1355 hdr = (void *)(reply + offset);
1356 dns_id = reply[offset] | reply[offset + 1] << 8;
1358 DBG("Received %d bytes (id 0x%04x)", reply_len, dns_id);
1360 req = find_request(dns_id);
1364 DBG("id 0x%04x rcode %d", hdr->id, hdr->rcode);
1366 ifdata = req->ifdata;
1368 reply[offset] = req->srcid & 0xff;
1369 reply[offset + 1] = req->srcid >> 8;
1373 if (hdr->rcode == 0 || req->resp == NULL) {
1376 * If the domain name was append
1377 * remove it before forwarding the reply.
1379 if (req->append_domain == TRUE) {
1382 unsigned int domain_len;
1385 * ptr points to the first char of the hostname.
1386 * ->hostname.domain.net
1388 ptr = reply + offset + sizeof(struct domain_hdr);
1390 domain_len = strlen((const char *)ptr) - host_len - 1;
1393 * remove the domain name and replaced it by the end
1396 memmove(ptr + host_len + 1,
1397 ptr + host_len + domain_len + 1,
1398 reply_len - (ptr - reply + domain_len));
1400 reply_len = reply_len - domain_len;
1406 req->resp = g_try_malloc(reply_len);
1407 if (req->resp == NULL)
1410 memcpy(req->resp, reply, reply_len);
1411 req->resplen = reply_len;
1413 cache_update(data, reply, reply_len);
1416 if (hdr->rcode > 0 && req->numresp < req->numserv)
1419 if (req->timeout > 0)
1420 g_source_remove(req->timeout);
1422 request_list = g_slist_remove(request_list, req);
1424 if (protocol == IPPROTO_UDP) {
1425 sk = g_io_channel_unix_get_fd(ifdata->udp_listener_channel);
1426 err = sendto(sk, req->resp, req->resplen, 0,
1427 &req->sa, req->sa_len);
1429 sk = req->client_sk;
1430 err = send(sk, req->resp, req->resplen, 0);
1440 static void cache_element_destroy(gpointer value)
1442 struct cache_entry *entry = value;
1447 if (entry->ipv4 != NULL) {
1448 g_free(entry->ipv4->data);
1449 g_free(entry->ipv4);
1452 if (entry->ipv6 != NULL) {
1453 g_free(entry->ipv6->data);
1454 g_free(entry->ipv6);
1460 if (--cache_size < 0)
1464 static void destroy_server(struct server_data *server)
1468 DBG("interface %s server %s", server->interface, server->server);
1470 server_list = g_slist_remove(server_list, server);
1472 if (server->watch > 0)
1473 g_source_remove(server->watch);
1475 if (server->timeout > 0)
1476 g_source_remove(server->timeout);
1478 g_io_channel_unref(server->channel);
1480 if (server->protocol == IPPROTO_UDP)
1481 connman_info("Removing DNS server %s", server->server);
1483 g_free(server->incoming_reply);
1484 g_free(server->server);
1485 for (list = server->domains; list; list = list->next) {
1486 char *domain = list->data;
1488 server->domains = g_list_remove(server->domains, domain);
1491 g_free(server->interface);
1493 if (__sync_fetch_and_sub(&cache_refcount, 1) == 1)
1494 g_hash_table_destroy(cache);
1499 static gboolean udp_server_event(GIOChannel *channel, GIOCondition condition,
1502 unsigned char buf[4096];
1504 struct server_data *data = user_data;
1506 if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
1507 connman_error("Error with UDP server %s", data->server);
1512 sk = g_io_channel_unix_get_fd(channel);
1514 len = recv(sk, buf, sizeof(buf), 0);
1518 err = forward_dns_reply(buf, len, IPPROTO_UDP, data);
1525 static gboolean tcp_server_event(GIOChannel *channel, GIOCondition condition,
1529 struct server_data *server = user_data;
1531 sk = g_io_channel_unix_get_fd(channel);
1535 if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
1538 DBG("TCP server channel closed");
1541 * Discard any partial response which is buffered; better
1542 * to get a proper response from a working server.
1544 g_free(server->incoming_reply);
1545 server->incoming_reply = NULL;
1547 for (list = request_list; list; list = list->next) {
1548 struct request_data *req = list->data;
1549 struct domain_hdr *hdr;
1551 if (req->protocol == IPPROTO_UDP)
1554 if (req->request == NULL)
1558 * If we're not waiting for any further response
1559 * from another name server, then we send an error
1560 * response to the client.
1562 if (req->numserv && --(req->numserv))
1565 hdr = (void *) (req->request + 2);
1566 hdr->id = req->srcid;
1567 send_response(req->client_sk, req->request,
1568 req->request_len, NULL, 0, IPPROTO_TCP);
1570 request_list = g_slist_remove(request_list, req);
1573 destroy_server(server);
1578 if ((condition & G_IO_OUT) && !server->connected) {
1581 struct server_data *udp_server;
1583 udp_server = find_server(server->interface, server->server,
1585 if (udp_server != NULL) {
1586 for (domains = udp_server->domains; domains;
1587 domains = domains->next) {
1588 char *dom = domains->data;
1590 DBG("Adding domain %s to %s",
1591 dom, server->server);
1593 server->domains = g_list_append(server->domains,
1598 server->connected = TRUE;
1599 server_list = g_slist_append(server_list, server);
1601 if (server->timeout > 0) {
1602 g_source_remove(server->timeout);
1603 server->timeout = 0;
1606 for (list = request_list; list; list = list->next) {
1607 struct request_data *req = list->data;
1609 if (req->protocol == IPPROTO_UDP)
1612 DBG("Sending req %s over TCP", (char *)req->name);
1614 if (req->timeout > 0)
1615 g_source_remove(req->timeout);
1617 req->timeout = g_timeout_add_seconds(30,
1618 request_timeout, req);
1619 if (ns_resolv(server, req, req->request,
1621 /* We sent cached result so no need for timeout
1624 if (req->timeout > 0) {
1625 g_source_remove(req->timeout);
1631 } else if (condition & G_IO_IN) {
1632 struct partial_reply *reply = server->incoming_reply;
1636 unsigned char reply_len_buf[2];
1639 bytes_recv = recv(sk, reply_len_buf, 2, MSG_PEEK);
1642 } else if (bytes_recv < 0) {
1643 if (errno == EAGAIN || errno == EWOULDBLOCK)
1646 connman_error("DNS proxy error %s",
1649 } else if (bytes_recv < 2)
1652 reply_len = reply_len_buf[1] | reply_len_buf[0] << 8;
1655 DBG("TCP reply %d bytes", reply_len);
1657 reply = g_try_malloc(sizeof(*reply) + reply_len + 2);
1661 reply->len = reply_len;
1662 reply->received = 0;
1664 server->incoming_reply = reply;
1667 while (reply->received < reply->len) {
1668 bytes_recv = recv(sk, reply->buf + reply->received,
1669 reply->len - reply->received, 0);
1671 connman_error("DNS proxy TCP disconnect");
1673 } else if (bytes_recv < 0) {
1674 if (errno == EAGAIN || errno == EWOULDBLOCK)
1677 connman_error("DNS proxy error %s",
1681 reply->received += bytes_recv;
1684 forward_dns_reply(reply->buf, reply->received, IPPROTO_TCP,
1688 server->incoming_reply = NULL;
1690 destroy_server(server);
1698 static gboolean tcp_idle_timeout(gpointer user_data)
1700 struct server_data *server = user_data;
1707 destroy_server(server);
1712 static struct server_data *create_server(const char *interface,
1713 const char *domain, const char *server,
1716 struct addrinfo hints, *rp;
1717 struct server_data *data;
1720 DBG("interface %s server %s", interface, server);
1722 memset(&hints, 0, sizeof(hints));
1726 hints.ai_socktype = SOCK_DGRAM;
1730 hints.ai_socktype = SOCK_STREAM;
1736 hints.ai_family = AF_UNSPEC;
1737 hints.ai_flags = AI_PASSIVE | AI_NUMERICSERV | AI_NUMERICHOST;
1739 ret = getaddrinfo(server, "53", &hints, &rp);
1741 connman_error("Failed to parse server %s address: %s\n",
1742 server, gai_strerror(ret));
1745 /* Do not blindly copy this code elsewhere; it doesn't loop over the
1746 results using ->ai_next as it should. That's OK in *this* case
1747 because it was a numeric lookup; we *know* there's only one. */
1749 sk = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
1751 connman_error("Failed to create server %s socket", server);
1756 if (interface != NULL) {
1757 if (setsockopt(sk, SOL_SOCKET, SO_BINDTODEVICE,
1758 interface, strlen(interface) + 1) < 0) {
1759 connman_error("Failed to bind server %s "
1768 data = g_try_new0(struct server_data, 1);
1770 connman_error("Failed to allocate server %s data", server);
1776 data->channel = g_io_channel_unix_new(sk);
1777 if (data->channel == NULL) {
1778 connman_error("Failed to create server %s channel", server);
1785 g_io_channel_set_close_on_unref(data->channel, TRUE);
1787 if (protocol == IPPROTO_TCP) {
1788 g_io_channel_set_flags(data->channel, G_IO_FLAG_NONBLOCK, NULL);
1789 data->watch = g_io_add_watch(data->channel,
1790 G_IO_OUT | G_IO_IN | G_IO_HUP | G_IO_NVAL | G_IO_ERR,
1791 tcp_server_event, data);
1792 data->timeout = g_timeout_add_seconds(30, tcp_idle_timeout,
1795 data->watch = g_io_add_watch(data->channel,
1796 G_IO_IN | G_IO_NVAL | G_IO_ERR | G_IO_HUP,
1797 udp_server_event, data);
1799 data->interface = g_strdup(interface);
1801 data->domains = g_list_append(data->domains, g_strdup(domain));
1802 data->server = g_strdup(server);
1803 data->protocol = protocol;
1805 ret = connect(sk, rp->ai_addr, rp->ai_addrlen);
1808 if ((protocol == IPPROTO_TCP && errno != EINPROGRESS) ||
1809 protocol == IPPROTO_UDP) {
1812 connman_error("Failed to connect to server %s", server);
1813 if (data->watch > 0)
1814 g_source_remove(data->watch);
1815 if (data->timeout > 0)
1816 g_source_remove(data->timeout);
1818 g_io_channel_unref(data->channel);
1821 g_free(data->server);
1822 g_free(data->interface);
1823 for (list = data->domains; list; list = list->next) {
1824 char *domain = list->data;
1826 data->domains = g_list_remove(data->domains,
1835 if (__sync_fetch_and_add(&cache_refcount, 1) == 0)
1836 cache = g_hash_table_new_full(g_str_hash,
1839 cache_element_destroy);
1841 if (protocol == IPPROTO_UDP) {
1842 /* Enable new servers by default */
1843 data->enabled = TRUE;
1844 connman_info("Adding DNS server %s", data->server);
1846 server_list = g_slist_append(server_list, data);
1854 static gboolean resolv(struct request_data *req,
1855 gpointer request, gpointer name)
1860 for (list = server_list; list; list = list->next) {
1861 struct server_data *data = list->data;
1863 DBG("server %s enabled %d", data->server, data->enabled);
1865 if (data->enabled == FALSE)
1868 if (data->watch == 0 && data->protocol == IPPROTO_UDP)
1869 data->watch = g_io_add_watch(data->channel,
1870 G_IO_IN | G_IO_NVAL | G_IO_ERR | G_IO_HUP,
1871 udp_server_event, data);
1873 status = ns_resolv(data, req, request, name);
1878 if (req->timeout > 0) {
1879 g_source_remove(req->timeout);
1888 static void append_domain(const char *interface, const char *domain)
1892 DBG("interface %s domain %s", interface, domain);
1897 for (list = server_list; list; list = list->next) {
1898 struct server_data *data = list->data;
1901 gboolean dom_found = FALSE;
1903 if (data->interface == NULL)
1906 if (g_str_equal(data->interface, interface) == FALSE)
1909 for (dom_list = data->domains; dom_list;
1910 dom_list = dom_list->next) {
1911 dom = dom_list->data;
1913 if (g_str_equal(dom, domain)) {
1919 if (dom_found == FALSE) {
1921 g_list_append(data->domains, g_strdup(domain));
1926 int __connman_dnsproxy_append(const char *interface, const char *domain,
1929 struct server_data *data;
1931 DBG("interface %s server %s", interface, server);
1933 if (server == NULL && domain == NULL)
1936 if (server == NULL) {
1937 append_domain(interface, domain);
1942 if (g_str_equal(server, "127.0.0.1") == TRUE)
1945 data = find_server(interface, server, IPPROTO_UDP);
1947 append_domain(interface, domain);
1951 data = create_server(interface, domain, server, IPPROTO_UDP);
1958 static void remove_server(const char *interface, const char *domain,
1959 const char *server, int protocol)
1961 struct server_data *data;
1963 data = find_server(interface, server, protocol);
1967 destroy_server(data);
1970 int __connman_dnsproxy_remove(const char *interface, const char *domain,
1973 DBG("interface %s server %s", interface, server);
1978 if (g_str_equal(server, "127.0.0.1") == TRUE)
1981 remove_server(interface, domain, server, IPPROTO_UDP);
1982 remove_server(interface, domain, server, IPPROTO_TCP);
1987 void __connman_dnsproxy_flush(void)
1991 list = request_pending_list;
1993 struct request_data *req = list->data;
1997 request_pending_list =
1998 g_slist_remove(request_pending_list, req);
1999 resolv(req, req->request, req->name);
2000 g_free(req->request);
2005 static void dnsproxy_offline_mode(connman_bool_t enabled)
2009 DBG("enabled %d", enabled);
2011 for (list = server_list; list; list = list->next) {
2012 struct server_data *data = list->data;
2014 if (enabled == FALSE) {
2015 connman_info("Enabling DNS server %s", data->server);
2016 data->enabled = TRUE;
2018 connman_info("Disabling DNS server %s", data->server);
2019 data->enabled = FALSE;
2024 static void dnsproxy_default_changed(struct connman_service *service)
2029 DBG("service %p", service);
2031 if (service == NULL) {
2032 /* When no services are active, then disable DNS proxying */
2033 dnsproxy_offline_mode(TRUE);
2037 interface = connman_service_get_interface(service);
2038 if (interface == NULL)
2041 for (list = server_list; list; list = list->next) {
2042 struct server_data *data = list->data;
2044 if (g_strcmp0(data->interface, interface) == 0) {
2045 connman_info("Enabling DNS server %s", data->server);
2046 data->enabled = TRUE;
2048 connman_info("Disabling DNS server %s", data->server);
2049 data->enabled = FALSE;
2056 static struct connman_notifier dnsproxy_notifier = {
2058 .default_changed = dnsproxy_default_changed,
2059 .offline_mode = dnsproxy_offline_mode,
2062 static unsigned char opt_edns0_type[2] = { 0x00, 0x29 };
2064 static int parse_request(unsigned char *buf, int len,
2065 char *name, unsigned int size)
2067 struct domain_hdr *hdr = (void *) buf;
2068 uint16_t qdcount = ntohs(hdr->qdcount);
2069 uint16_t arcount = ntohs(hdr->arcount);
2071 char *last_label = NULL;
2072 unsigned int remain, used = 0;
2077 DBG("id 0x%04x qr %d opcode %d qdcount %d arcount %d",
2078 hdr->id, hdr->qr, hdr->opcode,
2081 if (hdr->qr != 0 || qdcount != 1)
2084 memset(name, 0, size);
2086 ptr = buf + sizeof(struct domain_hdr);
2087 remain = len - sizeof(struct domain_hdr);
2089 while (remain > 0) {
2093 last_label = (char *) (ptr + 1);
2097 if (used + len + 1 > size)
2100 strncat(name, (char *) (ptr + 1), len);
2109 if (last_label && arcount && remain >= 9 && last_label[4] == 0 &&
2110 !memcmp(last_label + 5, opt_edns0_type, 2)) {
2111 uint16_t edns0_bufsize;
2113 edns0_bufsize = last_label[7] << 8 | last_label[8];
2115 DBG("EDNS0 buffer size %u", edns0_bufsize);
2117 /* This is an evil hack until full TCP support has been
2120 * Somtimes the EDNS0 request gets send with a too-small
2121 * buffer size. Since glibc doesn't seem to crash when it
2122 * gets a response biffer then it requested, just bump
2123 * the buffer size up to 4KiB.
2125 if (edns0_bufsize < 0x1000) {
2126 last_label[7] = 0x10;
2127 last_label[8] = 0x00;
2131 DBG("query %s", name);
2136 static gboolean tcp_listener_event(GIOChannel *channel, GIOCondition condition,
2139 unsigned char buf[768];
2141 struct request_data *req;
2142 struct server_data *server;
2143 int sk, client_sk, len, err;
2144 struct sockaddr_in6 client_addr;
2145 socklen_t client_addr_len = sizeof(client_addr);
2147 struct listener_data *ifdata = user_data;
2149 DBG("condition 0x%x", condition);
2151 if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
2152 if (ifdata->tcp_listener_watch > 0)
2153 g_source_remove(ifdata->tcp_listener_watch);
2154 ifdata->tcp_listener_watch = 0;
2156 connman_error("Error with TCP listener channel");
2161 sk = g_io_channel_unix_get_fd(channel);
2163 client_sk = accept(sk, (void *)&client_addr, &client_addr_len);
2164 if (client_sk < 0) {
2165 connman_error("Accept failure on TCP listener");
2166 ifdata->tcp_listener_watch = 0;
2170 len = recv(client_sk, buf, sizeof(buf), 0);
2174 DBG("Received %d bytes (id 0x%04x)", len, buf[2] | buf[3] << 8);
2176 err = parse_request(buf + 2, len - 2, query, sizeof(query));
2177 if (err < 0 || (g_slist_length(server_list) == 0)) {
2178 send_response(client_sk, buf, len, NULL, 0, IPPROTO_TCP);
2182 req = g_try_new0(struct request_data, 1);
2186 memcpy(&req->sa, &client_addr, client_addr_len);
2187 req->sa_len = client_addr_len;
2188 req->client_sk = client_sk;
2189 req->protocol = IPPROTO_TCP;
2192 if (request_id == 0x0000 || request_id == 0xffff)
2195 req->srcid = buf[2] | (buf[3] << 8);
2196 req->dstid = request_id;
2197 req->altid = request_id + 1;
2198 req->request_len = len;
2200 buf[2] = req->dstid & 0xff;
2201 buf[3] = req->dstid >> 8;
2204 req->ifdata = (struct listener_data *) ifdata;
2205 req->append_domain = FALSE;
2206 request_list = g_slist_append(request_list, req);
2208 for (list = server_list; list; list = list->next) {
2209 struct server_data *data = list->data;
2212 if (data->protocol != IPPROTO_UDP || data->enabled == FALSE)
2215 server = create_server(data->interface, NULL,
2216 data->server, IPPROTO_TCP);
2219 * If server is NULL, we're not connected yet.
2220 * Copy the relevant buffers and continue with
2221 * the next nameserver.
2222 * The request will actually be sent once we're
2223 * properly connected over TCP to this nameserver.
2225 if (server == NULL) {
2226 req->request = g_try_malloc0(req->request_len);
2227 if (req->request == NULL)
2230 memcpy(req->request, buf, req->request_len);
2232 req->name = g_try_malloc0(sizeof(query));
2233 if (req->name == NULL) {
2234 g_free(req->request);
2237 memcpy(req->name, query, sizeof(query));
2242 if (req->timeout > 0)
2243 g_source_remove(req->timeout);
2245 for (domains = data->domains; domains;
2246 domains = domains->next) {
2247 char *dom = domains->data;
2249 DBG("Adding domain %s to %s", dom, server->server);
2251 server->domains = g_list_append(server->domains,
2255 req->timeout = g_timeout_add_seconds(30, request_timeout, req);
2256 if (ns_resolv(server, req, buf, query) > 0) {
2257 if (req->timeout > 0) {
2258 g_source_remove(req->timeout);
2267 static gboolean udp_listener_event(GIOChannel *channel, GIOCondition condition,
2270 unsigned char buf[768];
2272 struct request_data *req;
2273 struct sockaddr_in6 client_addr;
2274 socklen_t client_addr_len = sizeof(client_addr);
2276 struct listener_data *ifdata = user_data;
2278 if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
2279 connman_error("Error with UDP listener channel");
2280 ifdata->udp_listener_watch = 0;
2284 sk = g_io_channel_unix_get_fd(channel);
2286 memset(&client_addr, 0, client_addr_len);
2287 len = recvfrom(sk, buf, sizeof(buf), 0, (void *)&client_addr,
2292 DBG("Received %d bytes (id 0x%04x)", len, buf[0] | buf[1] << 8);
2294 err = parse_request(buf, len, query, sizeof(query));
2295 if (err < 0 || (g_slist_length(server_list) == 0)) {
2296 send_response(sk, buf, len, (void *)&client_addr,
2297 client_addr_len, IPPROTO_UDP);
2301 req = g_try_new0(struct request_data, 1);
2305 memcpy(&req->sa, &client_addr, client_addr_len);
2306 req->sa_len = client_addr_len;
2308 req->protocol = IPPROTO_UDP;
2311 if (request_id == 0x0000 || request_id == 0xffff)
2314 req->srcid = buf[0] | (buf[1] << 8);
2315 req->dstid = request_id;
2316 req->altid = request_id + 1;
2317 req->request_len = len;
2319 buf[0] = req->dstid & 0xff;
2320 buf[1] = req->dstid >> 8;
2323 req->ifdata = (struct listener_data *) ifdata;
2324 req->timeout = g_timeout_add_seconds(5, request_timeout, req);
2325 req->append_domain = FALSE;
2326 request_list = g_slist_append(request_list, req);
2328 return resolv(req, buf, query);
2331 static int create_dns_listener(int protocol, struct listener_data *ifdata)
2333 GIOChannel *channel;
2337 struct sockaddr_in6 sin6;
2338 struct sockaddr_in sin;
2341 int sk, type, v6only = 0;
2342 int family = AF_INET6;
2345 DBG("interface %s", ifdata->ifname);
2350 type = SOCK_DGRAM | SOCK_CLOEXEC;
2355 type = SOCK_STREAM | SOCK_CLOEXEC;
2362 sk = socket(family, type, protocol);
2363 if (sk < 0 && family == AF_INET6 && errno == EAFNOSUPPORT) {
2364 connman_error("No IPv6 support; DNS proxy listening only on Legacy IP");
2366 sk = socket(family, type, protocol);
2369 connman_error("Failed to create %s listener socket", proto);
2373 if (setsockopt(sk, SOL_SOCKET, SO_BINDTODEVICE,
2375 strlen(ifdata->ifname) + 1) < 0) {
2376 connman_error("Failed to bind %s listener interface", proto);
2380 /* Ensure it accepts Legacy IP connections too */
2381 if (family == AF_INET6 &&
2382 setsockopt(sk, SOL_IPV6, IPV6_V6ONLY,
2383 &v6only, sizeof(v6only)) < 0) {
2384 connman_error("Failed to clear V6ONLY on %s listener socket",
2390 if (family == AF_INET) {
2391 memset(&s.sin, 0, sizeof(s.sin));
2392 s.sin.sin_family = AF_INET;
2393 s.sin.sin_port = htons(53);
2394 s.sin.sin_addr.s_addr = htonl(INADDR_ANY);
2395 slen = sizeof(s.sin);
2397 memset(&s.sin6, 0, sizeof(s.sin6));
2398 s.sin6.sin6_family = AF_INET6;
2399 s.sin6.sin6_port = htons(53);
2400 s.sin6.sin6_addr = in6addr_any;
2401 slen = sizeof(s.sin6);
2404 if (bind(sk, &s.sa, slen) < 0) {
2405 connman_error("Failed to bind %s listener socket", proto);
2410 if (protocol == IPPROTO_TCP && listen(sk, 10) < 0) {
2411 connman_error("Failed to listen on TCP socket");
2416 channel = g_io_channel_unix_new(sk);
2417 if (channel == NULL) {
2418 connman_error("Failed to create %s listener channel", proto);
2423 g_io_channel_set_close_on_unref(channel, TRUE);
2425 if (protocol == IPPROTO_TCP) {
2426 ifdata->tcp_listener_channel = channel;
2427 ifdata->tcp_listener_watch = g_io_add_watch(channel,
2428 G_IO_IN, tcp_listener_event, (gpointer) ifdata);
2430 ifdata->udp_listener_channel = channel;
2431 ifdata->udp_listener_watch = g_io_add_watch(channel,
2432 G_IO_IN, udp_listener_event, (gpointer) ifdata);
2438 static void destroy_udp_listener(struct listener_data *ifdata)
2440 DBG("interface %s", ifdata->ifname);
2442 if (ifdata->udp_listener_watch > 0)
2443 g_source_remove(ifdata->udp_listener_watch);
2445 g_io_channel_unref(ifdata->udp_listener_channel);
2448 static void destroy_tcp_listener(struct listener_data *ifdata)
2450 DBG("interface %s", ifdata->ifname);
2452 if (ifdata->tcp_listener_watch > 0)
2453 g_source_remove(ifdata->tcp_listener_watch);
2455 g_io_channel_unref(ifdata->tcp_listener_channel);
2458 static int create_listener(struct listener_data *ifdata)
2462 err = create_dns_listener(IPPROTO_UDP, ifdata);
2466 err = create_dns_listener(IPPROTO_TCP, ifdata);
2468 destroy_udp_listener(ifdata);
2472 if (g_strcmp0(ifdata->ifname, "lo") == 0)
2473 __connman_resolvfile_append("lo", NULL, "127.0.0.1");
2478 static void destroy_listener(struct listener_data *ifdata)
2482 if (g_strcmp0(ifdata->ifname, "lo") == 0)
2483 __connman_resolvfile_remove("lo", NULL, "127.0.0.1");
2485 for (list = request_pending_list; list; list = list->next) {
2486 struct request_data *req = list->data;
2488 DBG("Dropping pending request (id 0x%04x -> 0x%04x)",
2489 req->srcid, req->dstid);
2492 g_free(req->request);
2498 g_slist_free(request_pending_list);
2499 request_pending_list = NULL;
2501 for (list = request_list; list; list = list->next) {
2502 struct request_data *req = list->data;
2504 DBG("Dropping request (id 0x%04x -> 0x%04x)",
2505 req->srcid, req->dstid);
2508 g_free(req->request);
2514 g_slist_free(request_list);
2515 request_list = NULL;
2517 destroy_tcp_listener(ifdata);
2518 destroy_udp_listener(ifdata);
2521 int __connman_dnsproxy_add_listener(const char *interface)
2523 struct listener_data *ifdata;
2526 DBG("interface %s", interface);
2528 if (g_hash_table_lookup(listener_table, interface) != NULL)
2531 ifdata = g_try_new0(struct listener_data, 1);
2535 ifdata->ifname = g_strdup(interface);
2536 ifdata->udp_listener_channel = NULL;
2537 ifdata->udp_listener_watch = 0;
2538 ifdata->tcp_listener_channel = NULL;
2539 ifdata->tcp_listener_watch = 0;
2541 err = create_listener(ifdata);
2543 connman_error("Couldn't create listener for %s err %d",
2545 g_free(ifdata->ifname);
2549 g_hash_table_insert(listener_table, ifdata->ifname, ifdata);
2553 void __connman_dnsproxy_remove_listener(const char *interface)
2555 struct listener_data *ifdata;
2557 DBG("interface %s", interface);
2559 ifdata = g_hash_table_lookup(listener_table, interface);
2563 destroy_listener(ifdata);
2565 g_hash_table_remove(listener_table, interface);
2568 static void remove_listener(gpointer key, gpointer value, gpointer user_data)
2570 __connman_dnsproxy_remove_listener(key);
2573 int __connman_dnsproxy_init(void)
2579 listener_table = g_hash_table_new_full(g_str_hash, g_str_equal,
2581 err = __connman_dnsproxy_add_listener("lo");
2585 err = connman_notifier_register(&dnsproxy_notifier);
2592 __connman_dnsproxy_remove_listener("lo");
2593 g_hash_table_destroy(listener_table);
2598 void __connman_dnsproxy_cleanup(void)
2602 connman_notifier_unregister(&dnsproxy_notifier);
2604 g_hash_table_foreach(listener_table, remove_listener, NULL);
2606 g_hash_table_destroy(listener_table);