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 {
943 static gboolean cache_check_entry(gpointer key, gpointer value,
946 struct cache_timeout *data = user_data;
947 struct cache_entry *entry = value;
951 * If either IPv4 or IPv6 cached entry has expired, we
952 * remove both from the cache.
955 if (entry->ipv4 != NULL && entry->ipv4->timeout > 0) {
956 max_timeout = entry->ipv4->cache_until;
957 if (max_timeout > data->max_timeout)
958 data->max_timeout = max_timeout;
960 if (entry->ipv4->cache_until < data->current_time)
964 if (entry->ipv6 != NULL && entry->ipv6->timeout > 0) {
965 max_timeout = entry->ipv6->cache_until;
966 if (max_timeout > data->max_timeout)
967 data->max_timeout = max_timeout;
969 if (entry->ipv6->cache_until < data->current_time)
976 static void cache_cleanup(void)
978 static int max_timeout;
979 struct cache_timeout data;
982 data.current_time = time(0);
983 data.max_timeout = 0;
985 if (max_timeout > data.current_time) {
986 DBG("waiting %ld secs before cleaning cache",
987 max_timeout - data.current_time);
991 count = g_hash_table_foreach_remove(cache, cache_check_entry,
993 DBG("removed %d", count);
997 * If we could not remove anything, then remember
998 * what is the max timeout and do nothing if we
999 * have not yet reached it. This will prevent
1000 * constant traversal of the cache if it is full.
1002 max_timeout = data.max_timeout;
1007 static int reply_query_type(unsigned char *msg, int len)
1014 /* skip the header */
1015 c = msg + sizeof(struct domain_hdr);
1016 len -= sizeof(struct domain_hdr);
1021 /* now the query, which is a name and 2 16 bit words */
1022 l = dns_name_length(c) + 1;
1030 static int cache_update(struct server_data *srv, unsigned char *msg,
1031 unsigned int msg_len)
1033 int offset = protocol_offset(srv->protocol);
1034 int err, qlen, ttl = 0;
1035 uint16_t answers = 0, type = 0, class = 0;
1036 struct domain_question *q;
1037 struct cache_entry *entry;
1038 struct cache_data *data;
1039 char question[NS_MAXDNAME + 1];
1040 unsigned char response[NS_MAXDNAME + 1];
1042 unsigned int rsplen;
1043 gboolean new_entry = TRUE;
1044 time_t current_time;
1046 if (cache_size >= MAX_CACHE_SIZE) {
1048 if (cache_size >= MAX_CACHE_SIZE)
1052 /* Continue only if response code is 0 (=ok) */
1059 rsplen = sizeof(response) - 1;
1060 question[sizeof(question) - 1] = '\0';
1062 err = parse_response(msg + offset, msg_len - offset,
1063 question, sizeof(question) - 1,
1064 &type, &class, &ttl,
1065 response, &rsplen, &answers);
1068 * special case: if we do a ipv6 lookup and get no result
1069 * for a record that's already in our ipv4 cache.. we want
1070 * to cache the negative response.
1072 if ((err == -ENOMSG || err == -ENOBUFS) &&
1073 reply_query_type(msg, msg_len) == 28) {
1074 entry = g_hash_table_lookup(cache, question);
1075 if (entry && entry->ipv4 && entry->ipv6 == NULL) {
1076 data = g_try_new(struct cache_data, 1);
1079 data->inserted = entry->ipv4->inserted;
1081 data->answers = msg[5];
1082 data->timeout = entry->ipv4->timeout;
1083 data->data_len = msg_len;
1084 data->data = ptr = g_malloc(msg_len);
1085 data->valid_until = entry->ipv4->valid_until;
1086 data->cache_until = entry->ipv4->cache_until;
1087 memcpy(data->data, msg, msg_len);
1090 * we will get a "hit" when we serve the response
1094 if (entry->hits < 0)
1100 if (err < 0 || ttl == 0)
1103 qlen = strlen(question);
1104 current_time = time(0);
1107 * If the cache contains already data, check if the
1108 * type of the cached data is the same and do not add
1109 * to cache if data is already there.
1110 * This is needed so that we can cache both A and AAAA
1111 * records for the same name.
1113 entry = g_hash_table_lookup(cache, question);
1114 if (entry == NULL) {
1115 entry = g_try_new(struct cache_entry, 1);
1119 data = g_try_new(struct cache_data, 1);
1125 entry->key = g_strdup(question);
1126 entry->ipv4 = entry->ipv6 = NULL;
1134 if (type == 1 && entry->ipv4 != NULL)
1137 if (type == 28 && entry->ipv6 != NULL)
1140 data = g_try_new(struct cache_data, 1);
1150 * compensate for the hit we'll get for serving
1151 * the response out of the cache
1154 if (entry->hits < 0)
1160 if (ttl < MIN_CACHE_TTL)
1161 ttl = MIN_CACHE_TTL;
1163 data->inserted = current_time;
1165 data->answers = answers;
1166 data->timeout = ttl;
1167 data->data_len = 12 + qlen + 1 + 2 + 2 + rsplen;
1168 data->data = ptr = g_malloc(data->data_len);
1169 data->valid_until = current_time + ttl;
1172 * Restrict the cached DNS record TTL to some sane value
1173 * in order to prevent data staying in the cache too long.
1175 if (ttl > MAX_CACHE_TTL)
1176 ttl = MAX_CACHE_TTL;
1178 data->cache_until = round_down_ttl(current_time + ttl, ttl);
1180 if (data->data == NULL) {
1187 memcpy(ptr, msg, 12);
1188 memcpy(ptr + 12, question, qlen + 1); /* copy also the \0 */
1190 q = (void *) (ptr + 12 + qlen + 1);
1191 q->type = htons(type);
1192 q->class = htons(class);
1193 memcpy(ptr + 12 + qlen + 1 + sizeof(struct domain_question),
1196 if (new_entry == TRUE) {
1197 g_hash_table_replace(cache, entry->key, entry);
1201 DBG("cache %d %squestion \"%s\" type %d ttl %d size %zd",
1202 cache_size, new_entry ? "new " : "old ",
1203 question, type, ttl,
1204 sizeof(*entry) + sizeof(*data) + data->data_len + qlen);
1209 static int ns_resolv(struct server_data *server, struct request_data *req,
1210 gpointer request, gpointer name)
1213 int sk, err, type = 0;
1214 char *dot, *lookup = (char *) name;
1215 struct cache_entry *entry;
1217 entry = cache_check(request, &type);
1218 if (entry != NULL) {
1220 struct cache_data *data;
1222 DBG("cache hit %s type %s", lookup, type == 1 ? "A" : "AAAA");
1229 ttl_left = data->valid_until - time(0);
1233 if (data != NULL && req->protocol == IPPROTO_TCP) {
1234 send_cached_response(req->client_sk, data->data,
1235 data->data_len, NULL, 0, IPPROTO_TCP,
1236 req->srcid, data->answers, ttl_left);
1240 if (data != NULL && req->protocol == IPPROTO_UDP) {
1242 sk = g_io_channel_unix_get_fd(
1243 req->ifdata->udp_listener_channel);
1245 send_cached_response(sk, data->data,
1246 data->data_len, &req->sa, req->sa_len,
1247 IPPROTO_UDP, req->srcid, data->answers,
1253 sk = g_io_channel_unix_get_fd(server->channel);
1255 err = send(sk, request, req->request_len, 0);
1259 /* If we have more than one dot, we don't add domains */
1260 dot = strchr(lookup, '.');
1261 if (dot != NULL && dot != lookup + strlen(lookup) - 1)
1264 if (server->domains != NULL && server->domains->data != NULL)
1265 req->append_domain = TRUE;
1267 for (list = server->domains; list; list = list->next) {
1269 unsigned char alt[1024];
1270 struct domain_hdr *hdr = (void *) &alt;
1271 int altlen, domlen, offset;
1273 domain = list->data;
1278 offset = protocol_offset(server->protocol);
1282 domlen = strlen(domain) + 1;
1286 alt[offset] = req->altid & 0xff;
1287 alt[offset + 1] = req->altid >> 8;
1289 memcpy(alt + offset + 2, request + offset + 2, 10);
1290 hdr->qdcount = htons(1);
1292 altlen = append_query(alt + offset + 12, sizeof(alt) - 12,
1299 memcpy(alt + offset + altlen,
1300 request + offset + altlen - domlen,
1301 req->request_len - altlen - offset + domlen);
1303 if (server->protocol == IPPROTO_TCP) {
1304 int req_len = req->request_len + domlen - 2;
1306 alt[0] = (req_len >> 8) & 0xff;
1307 alt[1] = req_len & 0xff;
1310 err = send(sk, alt, req->request_len + domlen, 0);
1320 static int forward_dns_reply(unsigned char *reply, int reply_len, int protocol,
1321 struct server_data *data)
1323 struct domain_hdr *hdr;
1324 struct request_data *req;
1325 int dns_id, sk, err, offset = protocol_offset(protocol);
1326 struct listener_data *ifdata;
1331 hdr = (void *)(reply + offset);
1332 dns_id = reply[offset] | reply[offset + 1] << 8;
1334 DBG("Received %d bytes (id 0x%04x)", reply_len, dns_id);
1336 req = find_request(dns_id);
1340 DBG("id 0x%04x rcode %d", hdr->id, hdr->rcode);
1342 ifdata = req->ifdata;
1344 reply[offset] = req->srcid & 0xff;
1345 reply[offset + 1] = req->srcid >> 8;
1349 if (hdr->rcode == 0 || req->resp == NULL) {
1352 * If the domain name was append
1353 * remove it before forwarding the reply.
1355 if (req->append_domain == TRUE) {
1358 unsigned int domain_len;
1361 * ptr points to the first char of the hostname.
1362 * ->hostname.domain.net
1364 ptr = reply + offset + sizeof(struct domain_hdr);
1366 domain_len = strlen((const char *)ptr) - host_len - 1;
1369 * remove the domain name and replaced it by the end
1372 memmove(ptr + host_len + 1,
1373 ptr + host_len + domain_len + 1,
1374 reply_len - (ptr - reply + domain_len));
1376 reply_len = reply_len - domain_len;
1382 req->resp = g_try_malloc(reply_len);
1383 if (req->resp == NULL)
1386 memcpy(req->resp, reply, reply_len);
1387 req->resplen = reply_len;
1389 cache_update(data, reply, reply_len);
1392 if (hdr->rcode > 0 && req->numresp < req->numserv)
1395 if (req->timeout > 0)
1396 g_source_remove(req->timeout);
1398 request_list = g_slist_remove(request_list, req);
1400 if (protocol == IPPROTO_UDP) {
1401 sk = g_io_channel_unix_get_fd(ifdata->udp_listener_channel);
1402 err = sendto(sk, req->resp, req->resplen, 0,
1403 &req->sa, req->sa_len);
1405 sk = req->client_sk;
1406 err = send(sk, req->resp, req->resplen, 0);
1416 static void cache_element_destroy(gpointer value)
1418 struct cache_entry *entry = value;
1423 if (entry->ipv4 != NULL) {
1424 g_free(entry->ipv4->data);
1425 g_free(entry->ipv4);
1428 if (entry->ipv6 != NULL) {
1429 g_free(entry->ipv6->data);
1430 g_free(entry->ipv6);
1436 if (--cache_size < 0)
1440 static void destroy_server(struct server_data *server)
1444 DBG("interface %s server %s", server->interface, server->server);
1446 server_list = g_slist_remove(server_list, server);
1448 if (server->watch > 0)
1449 g_source_remove(server->watch);
1451 if (server->timeout > 0)
1452 g_source_remove(server->timeout);
1454 g_io_channel_unref(server->channel);
1456 if (server->protocol == IPPROTO_UDP)
1457 connman_info("Removing DNS server %s", server->server);
1459 g_free(server->incoming_reply);
1460 g_free(server->server);
1461 for (list = server->domains; list; list = list->next) {
1462 char *domain = list->data;
1464 server->domains = g_list_remove(server->domains, domain);
1467 g_free(server->interface);
1469 if (__sync_fetch_and_sub(&cache_refcount, 1) == 1)
1470 g_hash_table_destroy(cache);
1475 static gboolean udp_server_event(GIOChannel *channel, GIOCondition condition,
1478 unsigned char buf[4096];
1480 struct server_data *data = user_data;
1482 if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
1483 connman_error("Error with UDP server %s", data->server);
1488 sk = g_io_channel_unix_get_fd(channel);
1490 len = recv(sk, buf, sizeof(buf), 0);
1494 err = forward_dns_reply(buf, len, IPPROTO_UDP, data);
1501 static gboolean tcp_server_event(GIOChannel *channel, GIOCondition condition,
1505 struct server_data *server = user_data;
1507 sk = g_io_channel_unix_get_fd(channel);
1511 if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
1514 DBG("TCP server channel closed");
1517 * Discard any partial response which is buffered; better
1518 * to get a proper response from a working server.
1520 g_free(server->incoming_reply);
1521 server->incoming_reply = NULL;
1523 for (list = request_list; list; list = list->next) {
1524 struct request_data *req = list->data;
1525 struct domain_hdr *hdr;
1527 if (req->protocol == IPPROTO_UDP)
1530 if (req->request == NULL)
1534 * If we're not waiting for any further response
1535 * from another name server, then we send an error
1536 * response to the client.
1538 if (req->numserv && --(req->numserv))
1541 hdr = (void *) (req->request + 2);
1542 hdr->id = req->srcid;
1543 send_response(req->client_sk, req->request,
1544 req->request_len, NULL, 0, IPPROTO_TCP);
1546 request_list = g_slist_remove(request_list, req);
1549 destroy_server(server);
1554 if ((condition & G_IO_OUT) && !server->connected) {
1557 struct server_data *udp_server;
1559 udp_server = find_server(server->interface, server->server,
1561 if (udp_server != NULL) {
1562 for (domains = udp_server->domains; domains;
1563 domains = domains->next) {
1564 char *dom = domains->data;
1566 DBG("Adding domain %s to %s",
1567 dom, server->server);
1569 server->domains = g_list_append(server->domains,
1574 server->connected = TRUE;
1575 server_list = g_slist_append(server_list, server);
1577 if (server->timeout > 0) {
1578 g_source_remove(server->timeout);
1579 server->timeout = 0;
1582 for (list = request_list; list; list = list->next) {
1583 struct request_data *req = list->data;
1585 if (req->protocol == IPPROTO_UDP)
1588 DBG("Sending req %s over TCP", (char *)req->name);
1590 if (req->timeout > 0)
1591 g_source_remove(req->timeout);
1593 req->timeout = g_timeout_add_seconds(30,
1594 request_timeout, req);
1595 if (ns_resolv(server, req, req->request,
1597 /* We sent cached result so no need for timeout
1600 if (req->timeout > 0) {
1601 g_source_remove(req->timeout);
1607 } else if (condition & G_IO_IN) {
1608 struct partial_reply *reply = server->incoming_reply;
1612 unsigned char reply_len_buf[2];
1615 bytes_recv = recv(sk, reply_len_buf, 2, MSG_PEEK);
1618 } else if (bytes_recv < 0) {
1619 if (errno == EAGAIN || errno == EWOULDBLOCK)
1622 connman_error("DNS proxy error %s",
1625 } else if (bytes_recv < 2)
1628 reply_len = reply_len_buf[1] | reply_len_buf[0] << 8;
1631 DBG("TCP reply %d bytes", reply_len);
1633 reply = g_try_malloc(sizeof(*reply) + reply_len + 2);
1637 reply->len = reply_len;
1638 reply->received = 0;
1640 server->incoming_reply = reply;
1643 while (reply->received < reply->len) {
1644 bytes_recv = recv(sk, reply->buf + reply->received,
1645 reply->len - reply->received, 0);
1647 connman_error("DNS proxy TCP disconnect");
1649 } else if (bytes_recv < 0) {
1650 if (errno == EAGAIN || errno == EWOULDBLOCK)
1653 connman_error("DNS proxy error %s",
1657 reply->received += bytes_recv;
1660 forward_dns_reply(reply->buf, reply->received, IPPROTO_TCP,
1664 server->incoming_reply = NULL;
1666 destroy_server(server);
1674 static gboolean tcp_idle_timeout(gpointer user_data)
1676 struct server_data *server = user_data;
1683 destroy_server(server);
1688 static struct server_data *create_server(const char *interface,
1689 const char *domain, const char *server,
1692 struct addrinfo hints, *rp;
1693 struct server_data *data;
1696 DBG("interface %s server %s", interface, server);
1698 memset(&hints, 0, sizeof(hints));
1702 hints.ai_socktype = SOCK_DGRAM;
1706 hints.ai_socktype = SOCK_STREAM;
1712 hints.ai_family = AF_UNSPEC;
1713 hints.ai_flags = AI_PASSIVE | AI_NUMERICSERV | AI_NUMERICHOST;
1715 ret = getaddrinfo(server, "53", &hints, &rp);
1717 connman_error("Failed to parse server %s address: %s\n",
1718 server, gai_strerror(ret));
1721 /* Do not blindly copy this code elsewhere; it doesn't loop over the
1722 results using ->ai_next as it should. That's OK in *this* case
1723 because it was a numeric lookup; we *know* there's only one. */
1725 sk = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
1727 connman_error("Failed to create server %s socket", server);
1732 if (interface != NULL) {
1733 if (setsockopt(sk, SOL_SOCKET, SO_BINDTODEVICE,
1734 interface, strlen(interface) + 1) < 0) {
1735 connman_error("Failed to bind server %s "
1744 data = g_try_new0(struct server_data, 1);
1746 connman_error("Failed to allocate server %s data", server);
1752 data->channel = g_io_channel_unix_new(sk);
1753 if (data->channel == NULL) {
1754 connman_error("Failed to create server %s channel", server);
1761 g_io_channel_set_close_on_unref(data->channel, TRUE);
1763 if (protocol == IPPROTO_TCP) {
1764 g_io_channel_set_flags(data->channel, G_IO_FLAG_NONBLOCK, NULL);
1765 data->watch = g_io_add_watch(data->channel,
1766 G_IO_OUT | G_IO_IN | G_IO_HUP | G_IO_NVAL | G_IO_ERR,
1767 tcp_server_event, data);
1768 data->timeout = g_timeout_add_seconds(30, tcp_idle_timeout,
1771 data->watch = g_io_add_watch(data->channel,
1772 G_IO_IN | G_IO_NVAL | G_IO_ERR | G_IO_HUP,
1773 udp_server_event, data);
1775 data->interface = g_strdup(interface);
1777 data->domains = g_list_append(data->domains, g_strdup(domain));
1778 data->server = g_strdup(server);
1779 data->protocol = protocol;
1781 ret = connect(sk, rp->ai_addr, rp->ai_addrlen);
1784 if ((protocol == IPPROTO_TCP && errno != EINPROGRESS) ||
1785 protocol == IPPROTO_UDP) {
1788 connman_error("Failed to connect to server %s", server);
1789 if (data->watch > 0)
1790 g_source_remove(data->watch);
1791 if (data->timeout > 0)
1792 g_source_remove(data->timeout);
1794 g_io_channel_unref(data->channel);
1797 g_free(data->server);
1798 g_free(data->interface);
1799 for (list = data->domains; list; list = list->next) {
1800 char *domain = list->data;
1802 data->domains = g_list_remove(data->domains,
1811 if (__sync_fetch_and_add(&cache_refcount, 1) == 0)
1812 cache = g_hash_table_new_full(g_str_hash,
1815 cache_element_destroy);
1817 if (protocol == IPPROTO_UDP) {
1818 /* Enable new servers by default */
1819 data->enabled = TRUE;
1820 connman_info("Adding DNS server %s", data->server);
1822 server_list = g_slist_append(server_list, data);
1830 static gboolean resolv(struct request_data *req,
1831 gpointer request, gpointer name)
1836 for (list = server_list; list; list = list->next) {
1837 struct server_data *data = list->data;
1839 DBG("server %s enabled %d", data->server, data->enabled);
1841 if (data->enabled == FALSE)
1844 if (data->watch == 0 && data->protocol == IPPROTO_UDP)
1845 data->watch = g_io_add_watch(data->channel,
1846 G_IO_IN | G_IO_NVAL | G_IO_ERR | G_IO_HUP,
1847 udp_server_event, data);
1849 status = ns_resolv(data, req, request, name);
1854 if (req->timeout > 0) {
1855 g_source_remove(req->timeout);
1864 static void append_domain(const char *interface, const char *domain)
1868 DBG("interface %s domain %s", interface, domain);
1873 for (list = server_list; list; list = list->next) {
1874 struct server_data *data = list->data;
1877 gboolean dom_found = FALSE;
1879 if (data->interface == NULL)
1882 if (g_str_equal(data->interface, interface) == FALSE)
1885 for (dom_list = data->domains; dom_list;
1886 dom_list = dom_list->next) {
1887 dom = dom_list->data;
1889 if (g_str_equal(dom, domain)) {
1895 if (dom_found == FALSE) {
1897 g_list_append(data->domains, g_strdup(domain));
1902 int __connman_dnsproxy_append(const char *interface, const char *domain,
1905 struct server_data *data;
1907 DBG("interface %s server %s", interface, server);
1909 if (server == NULL && domain == NULL)
1912 if (server == NULL) {
1913 append_domain(interface, domain);
1918 if (g_str_equal(server, "127.0.0.1") == TRUE)
1921 data = find_server(interface, server, IPPROTO_UDP);
1923 append_domain(interface, domain);
1927 data = create_server(interface, domain, server, IPPROTO_UDP);
1934 static void remove_server(const char *interface, const char *domain,
1935 const char *server, int protocol)
1937 struct server_data *data;
1939 data = find_server(interface, server, protocol);
1943 destroy_server(data);
1946 int __connman_dnsproxy_remove(const char *interface, const char *domain,
1949 DBG("interface %s server %s", interface, server);
1954 if (g_str_equal(server, "127.0.0.1") == TRUE)
1957 remove_server(interface, domain, server, IPPROTO_UDP);
1958 remove_server(interface, domain, server, IPPROTO_TCP);
1963 void __connman_dnsproxy_flush(void)
1967 list = request_pending_list;
1969 struct request_data *req = list->data;
1973 request_pending_list =
1974 g_slist_remove(request_pending_list, req);
1975 resolv(req, req->request, req->name);
1976 g_free(req->request);
1981 static void dnsproxy_offline_mode(connman_bool_t enabled)
1985 DBG("enabled %d", enabled);
1987 for (list = server_list; list; list = list->next) {
1988 struct server_data *data = list->data;
1990 if (enabled == FALSE) {
1991 connman_info("Enabling DNS server %s", data->server);
1992 data->enabled = TRUE;
1994 connman_info("Disabling DNS server %s", data->server);
1995 data->enabled = FALSE;
2000 static void dnsproxy_default_changed(struct connman_service *service)
2005 DBG("service %p", service);
2007 if (service == NULL) {
2008 /* When no services are active, then disable DNS proxying */
2009 dnsproxy_offline_mode(TRUE);
2013 interface = connman_service_get_interface(service);
2014 if (interface == NULL)
2017 for (list = server_list; list; list = list->next) {
2018 struct server_data *data = list->data;
2020 if (g_strcmp0(data->interface, interface) == 0) {
2021 connman_info("Enabling DNS server %s", data->server);
2022 data->enabled = TRUE;
2024 connman_info("Disabling DNS server %s", data->server);
2025 data->enabled = FALSE;
2032 static struct connman_notifier dnsproxy_notifier = {
2034 .default_changed = dnsproxy_default_changed,
2035 .offline_mode = dnsproxy_offline_mode,
2038 static unsigned char opt_edns0_type[2] = { 0x00, 0x29 };
2040 static int parse_request(unsigned char *buf, int len,
2041 char *name, unsigned int size)
2043 struct domain_hdr *hdr = (void *) buf;
2044 uint16_t qdcount = ntohs(hdr->qdcount);
2045 uint16_t arcount = ntohs(hdr->arcount);
2047 char *last_label = NULL;
2048 unsigned int remain, used = 0;
2053 DBG("id 0x%04x qr %d opcode %d qdcount %d arcount %d",
2054 hdr->id, hdr->qr, hdr->opcode,
2057 if (hdr->qr != 0 || qdcount != 1)
2060 memset(name, 0, size);
2062 ptr = buf + sizeof(struct domain_hdr);
2063 remain = len - sizeof(struct domain_hdr);
2065 while (remain > 0) {
2069 last_label = (char *) (ptr + 1);
2073 if (used + len + 1 > size)
2076 strncat(name, (char *) (ptr + 1), len);
2085 if (last_label && arcount && remain >= 9 && last_label[4] == 0 &&
2086 !memcmp(last_label + 5, opt_edns0_type, 2)) {
2087 uint16_t edns0_bufsize;
2089 edns0_bufsize = last_label[7] << 8 | last_label[8];
2091 DBG("EDNS0 buffer size %u", edns0_bufsize);
2093 /* This is an evil hack until full TCP support has been
2096 * Somtimes the EDNS0 request gets send with a too-small
2097 * buffer size. Since glibc doesn't seem to crash when it
2098 * gets a response biffer then it requested, just bump
2099 * the buffer size up to 4KiB.
2101 if (edns0_bufsize < 0x1000) {
2102 last_label[7] = 0x10;
2103 last_label[8] = 0x00;
2107 DBG("query %s", name);
2112 static gboolean tcp_listener_event(GIOChannel *channel, GIOCondition condition,
2115 unsigned char buf[768];
2117 struct request_data *req;
2118 struct server_data *server;
2119 int sk, client_sk, len, err;
2120 struct sockaddr_in6 client_addr;
2121 socklen_t client_addr_len = sizeof(client_addr);
2123 struct listener_data *ifdata = user_data;
2125 DBG("condition 0x%x", condition);
2127 if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
2128 if (ifdata->tcp_listener_watch > 0)
2129 g_source_remove(ifdata->tcp_listener_watch);
2130 ifdata->tcp_listener_watch = 0;
2132 connman_error("Error with TCP listener channel");
2137 sk = g_io_channel_unix_get_fd(channel);
2139 client_sk = accept(sk, (void *)&client_addr, &client_addr_len);
2140 if (client_sk < 0) {
2141 connman_error("Accept failure on TCP listener");
2142 ifdata->tcp_listener_watch = 0;
2146 len = recv(client_sk, buf, sizeof(buf), 0);
2150 DBG("Received %d bytes (id 0x%04x)", len, buf[2] | buf[3] << 8);
2152 err = parse_request(buf + 2, len - 2, query, sizeof(query));
2153 if (err < 0 || (g_slist_length(server_list) == 0)) {
2154 send_response(client_sk, buf, len, NULL, 0, IPPROTO_TCP);
2158 req = g_try_new0(struct request_data, 1);
2162 memcpy(&req->sa, &client_addr, client_addr_len);
2163 req->sa_len = client_addr_len;
2164 req->client_sk = client_sk;
2165 req->protocol = IPPROTO_TCP;
2168 if (request_id == 0x0000 || request_id == 0xffff)
2171 req->srcid = buf[2] | (buf[3] << 8);
2172 req->dstid = request_id;
2173 req->altid = request_id + 1;
2174 req->request_len = len;
2176 buf[2] = req->dstid & 0xff;
2177 buf[3] = req->dstid >> 8;
2180 req->ifdata = (struct listener_data *) ifdata;
2181 req->append_domain = FALSE;
2182 request_list = g_slist_append(request_list, req);
2184 for (list = server_list; list; list = list->next) {
2185 struct server_data *data = list->data;
2188 if (data->protocol != IPPROTO_UDP || data->enabled == FALSE)
2191 server = create_server(data->interface, NULL,
2192 data->server, IPPROTO_TCP);
2195 * If server is NULL, we're not connected yet.
2196 * Copy the relevant buffers and continue with
2197 * the next nameserver.
2198 * The request will actually be sent once we're
2199 * properly connected over TCP to this nameserver.
2201 if (server == NULL) {
2202 req->request = g_try_malloc0(req->request_len);
2203 if (req->request == NULL)
2206 memcpy(req->request, buf, req->request_len);
2208 req->name = g_try_malloc0(sizeof(query));
2209 if (req->name == NULL) {
2210 g_free(req->request);
2213 memcpy(req->name, query, sizeof(query));
2218 if (req->timeout > 0)
2219 g_source_remove(req->timeout);
2221 for (domains = data->domains; domains;
2222 domains = domains->next) {
2223 char *dom = domains->data;
2225 DBG("Adding domain %s to %s", dom, server->server);
2227 server->domains = g_list_append(server->domains,
2231 req->timeout = g_timeout_add_seconds(30, request_timeout, req);
2232 if (ns_resolv(server, req, buf, query) > 0) {
2233 if (req->timeout > 0) {
2234 g_source_remove(req->timeout);
2243 static gboolean udp_listener_event(GIOChannel *channel, GIOCondition condition,
2246 unsigned char buf[768];
2248 struct request_data *req;
2249 struct sockaddr_in6 client_addr;
2250 socklen_t client_addr_len = sizeof(client_addr);
2252 struct listener_data *ifdata = user_data;
2254 if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
2255 connman_error("Error with UDP listener channel");
2256 ifdata->udp_listener_watch = 0;
2260 sk = g_io_channel_unix_get_fd(channel);
2262 memset(&client_addr, 0, client_addr_len);
2263 len = recvfrom(sk, buf, sizeof(buf), 0, (void *)&client_addr,
2268 DBG("Received %d bytes (id 0x%04x)", len, buf[0] | buf[1] << 8);
2270 err = parse_request(buf, len, query, sizeof(query));
2271 if (err < 0 || (g_slist_length(server_list) == 0)) {
2272 send_response(sk, buf, len, (void *)&client_addr,
2273 client_addr_len, IPPROTO_UDP);
2277 req = g_try_new0(struct request_data, 1);
2281 memcpy(&req->sa, &client_addr, client_addr_len);
2282 req->sa_len = client_addr_len;
2284 req->protocol = IPPROTO_UDP;
2287 if (request_id == 0x0000 || request_id == 0xffff)
2290 req->srcid = buf[0] | (buf[1] << 8);
2291 req->dstid = request_id;
2292 req->altid = request_id + 1;
2293 req->request_len = len;
2295 buf[0] = req->dstid & 0xff;
2296 buf[1] = req->dstid >> 8;
2299 req->ifdata = (struct listener_data *) ifdata;
2300 req->timeout = g_timeout_add_seconds(5, request_timeout, req);
2301 req->append_domain = FALSE;
2302 request_list = g_slist_append(request_list, req);
2304 return resolv(req, buf, query);
2307 static int create_dns_listener(int protocol, struct listener_data *ifdata)
2309 GIOChannel *channel;
2313 struct sockaddr_in6 sin6;
2314 struct sockaddr_in sin;
2317 int sk, type, v6only = 0;
2318 int family = AF_INET6;
2321 DBG("interface %s", ifdata->ifname);
2326 type = SOCK_DGRAM | SOCK_CLOEXEC;
2331 type = SOCK_STREAM | SOCK_CLOEXEC;
2338 sk = socket(family, type, protocol);
2339 if (sk < 0 && family == AF_INET6 && errno == EAFNOSUPPORT) {
2340 connman_error("No IPv6 support; DNS proxy listening only on Legacy IP");
2342 sk = socket(family, type, protocol);
2345 connman_error("Failed to create %s listener socket", proto);
2349 if (setsockopt(sk, SOL_SOCKET, SO_BINDTODEVICE,
2351 strlen(ifdata->ifname) + 1) < 0) {
2352 connman_error("Failed to bind %s listener interface", proto);
2356 /* Ensure it accepts Legacy IP connections too */
2357 if (family == AF_INET6 &&
2358 setsockopt(sk, SOL_IPV6, IPV6_V6ONLY,
2359 &v6only, sizeof(v6only)) < 0) {
2360 connman_error("Failed to clear V6ONLY on %s listener socket",
2366 if (family == AF_INET) {
2367 memset(&s.sin, 0, sizeof(s.sin));
2368 s.sin.sin_family = AF_INET;
2369 s.sin.sin_port = htons(53);
2370 s.sin.sin_addr.s_addr = htonl(INADDR_ANY);
2371 slen = sizeof(s.sin);
2373 memset(&s.sin6, 0, sizeof(s.sin6));
2374 s.sin6.sin6_family = AF_INET6;
2375 s.sin6.sin6_port = htons(53);
2376 s.sin6.sin6_addr = in6addr_any;
2377 slen = sizeof(s.sin6);
2380 if (bind(sk, &s.sa, slen) < 0) {
2381 connman_error("Failed to bind %s listener socket", proto);
2386 if (protocol == IPPROTO_TCP && listen(sk, 10) < 0) {
2387 connman_error("Failed to listen on TCP socket");
2392 channel = g_io_channel_unix_new(sk);
2393 if (channel == NULL) {
2394 connman_error("Failed to create %s listener channel", proto);
2399 g_io_channel_set_close_on_unref(channel, TRUE);
2401 if (protocol == IPPROTO_TCP) {
2402 ifdata->tcp_listener_channel = channel;
2403 ifdata->tcp_listener_watch = g_io_add_watch(channel,
2404 G_IO_IN, tcp_listener_event, (gpointer) ifdata);
2406 ifdata->udp_listener_channel = channel;
2407 ifdata->udp_listener_watch = g_io_add_watch(channel,
2408 G_IO_IN, udp_listener_event, (gpointer) ifdata);
2414 static void destroy_udp_listener(struct listener_data *ifdata)
2416 DBG("interface %s", ifdata->ifname);
2418 if (ifdata->udp_listener_watch > 0)
2419 g_source_remove(ifdata->udp_listener_watch);
2421 g_io_channel_unref(ifdata->udp_listener_channel);
2424 static void destroy_tcp_listener(struct listener_data *ifdata)
2426 DBG("interface %s", ifdata->ifname);
2428 if (ifdata->tcp_listener_watch > 0)
2429 g_source_remove(ifdata->tcp_listener_watch);
2431 g_io_channel_unref(ifdata->tcp_listener_channel);
2434 static int create_listener(struct listener_data *ifdata)
2438 err = create_dns_listener(IPPROTO_UDP, ifdata);
2442 err = create_dns_listener(IPPROTO_TCP, ifdata);
2444 destroy_udp_listener(ifdata);
2448 if (g_strcmp0(ifdata->ifname, "lo") == 0)
2449 __connman_resolvfile_append("lo", NULL, "127.0.0.1");
2454 static void destroy_listener(struct listener_data *ifdata)
2458 if (g_strcmp0(ifdata->ifname, "lo") == 0)
2459 __connman_resolvfile_remove("lo", NULL, "127.0.0.1");
2461 for (list = request_pending_list; list; list = list->next) {
2462 struct request_data *req = list->data;
2464 DBG("Dropping pending request (id 0x%04x -> 0x%04x)",
2465 req->srcid, req->dstid);
2468 g_free(req->request);
2474 g_slist_free(request_pending_list);
2475 request_pending_list = NULL;
2477 for (list = request_list; list; list = list->next) {
2478 struct request_data *req = list->data;
2480 DBG("Dropping request (id 0x%04x -> 0x%04x)",
2481 req->srcid, req->dstid);
2484 g_free(req->request);
2490 g_slist_free(request_list);
2491 request_list = NULL;
2493 destroy_tcp_listener(ifdata);
2494 destroy_udp_listener(ifdata);
2497 int __connman_dnsproxy_add_listener(const char *interface)
2499 struct listener_data *ifdata;
2502 DBG("interface %s", interface);
2504 if (g_hash_table_lookup(listener_table, interface) != NULL)
2507 ifdata = g_try_new0(struct listener_data, 1);
2511 ifdata->ifname = g_strdup(interface);
2512 ifdata->udp_listener_channel = NULL;
2513 ifdata->udp_listener_watch = 0;
2514 ifdata->tcp_listener_channel = NULL;
2515 ifdata->tcp_listener_watch = 0;
2517 err = create_listener(ifdata);
2519 connman_error("Couldn't create listener for %s err %d",
2521 g_free(ifdata->ifname);
2525 g_hash_table_insert(listener_table, ifdata->ifname, ifdata);
2529 void __connman_dnsproxy_remove_listener(const char *interface)
2531 struct listener_data *ifdata;
2533 DBG("interface %s", interface);
2535 ifdata = g_hash_table_lookup(listener_table, interface);
2539 destroy_listener(ifdata);
2541 g_hash_table_remove(listener_table, interface);
2544 static void remove_listener(gpointer key, gpointer value, gpointer user_data)
2546 __connman_dnsproxy_remove_listener(key);
2549 int __connman_dnsproxy_init(void)
2555 listener_table = g_hash_table_new_full(g_str_hash, g_str_equal,
2557 err = __connman_dnsproxy_add_listener("lo");
2561 err = connman_notifier_register(&dnsproxy_notifier);
2568 __connman_dnsproxy_remove_listener("lo");
2569 g_hash_table_destroy(listener_table);
2574 void __connman_dnsproxy_cleanup(void)
2578 connman_notifier_unregister(&dnsproxy_notifier);
2580 g_hash_table_foreach(listener_table, remove_listener, NULL);
2582 g_hash_table_destroy(listener_table);