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 */
141 struct cache_data *ipv4;
142 struct cache_data *ipv6;
145 struct domain_question {
148 } __attribute__ ((packed));
155 } __attribute__ ((packed));
158 * We limit how long the cached DNS entry stays in the cache.
159 * By default the TTL (time-to-live) of the DNS response is used
160 * when setting the cache entry life time. The value is in seconds.
162 #define MAX_CACHE_TTL (60 * 30)
164 * Also limit the other end, cache at least for 30 seconds.
166 #define MIN_CACHE_TTL (30)
169 * We limit the cache size to some sane value so that cached data does
170 * not occupy too much memory. Each cached entry occupies on average
171 * about 100 bytes memory (depending on DNS name length).
172 * Example: caching www.connman.net uses 97 bytes memory.
173 * The value is the max amount of cached DNS responses (count).
175 #define MAX_CACHE_SIZE 256
177 static int cache_size;
178 static GHashTable *cache;
179 static int cache_refcount;
180 static GSList *server_list = NULL;
181 static GSList *request_list = NULL;
182 static GSList *request_pending_list = NULL;
183 static guint16 request_id = 0x0000;
184 static GHashTable *listener_table = NULL;
186 static int protocol_offset(int protocol)
202 * There is a power and efficiency benefit to have entries
203 * in our cache expire at the same time. To this extend,
204 * we round down the cache valid time to common boundaries.
206 static time_t round_down_ttl(time_t end_time, int ttl)
211 /* Less than 5 minutes, round to 10 second boundary */
213 end_time = end_time / 10;
214 end_time = end_time * 10;
215 } else { /* 5 or more minutes, round to 30 seconds */
216 end_time = end_time / 30;
217 end_time = end_time * 30;
222 static struct request_data *find_request(guint16 id)
226 for (list = request_list; list; list = list->next) {
227 struct request_data *req = list->data;
229 if (req->dstid == id || req->altid == id)
236 static struct server_data *find_server(const char *interface,
242 DBG("interface %s server %s", interface, server);
244 for (list = server_list; list; list = list->next) {
245 struct server_data *data = list->data;
247 if (interface == NULL && data->interface == NULL &&
248 g_str_equal(data->server, server) == TRUE &&
249 data->protocol == protocol)
252 if (interface == NULL ||
253 data->interface == NULL || data->server == NULL)
256 if (g_str_equal(data->interface, interface) == TRUE &&
257 g_str_equal(data->server, server) == TRUE &&
258 data->protocol == protocol)
265 static int dns_name_length(unsigned char *buf)
267 if ((buf[0] & NS_CMPRSFLGS) == NS_CMPRSFLGS) /* compressed name */
269 return strlen((char *)buf);
272 static void update_cached_ttl(unsigned char *buf, int len, int new_ttl)
279 /* skip the header */
283 /* skip the query, which is a name and 2 16 bit words */
284 l = dns_name_length(c);
290 /* now we get the answer records */
294 l = dns_name_length(c);
299 /* then type + class, 2 bytes each */
305 /* now the 4 byte TTL field */
313 /* now the 2 byte rdlen field */
316 len -= ntohs(*w) + 2;
322 static void send_cached_response(int sk, unsigned char *buf, int len,
323 const struct sockaddr *to, socklen_t tolen,
324 int protocol, int id, uint16_t answers, int ttl)
326 struct domain_hdr *hdr;
327 int err, offset = protocol_offset(protocol);
335 hdr = (void *) (buf + offset);
340 hdr->ancount = htons(answers);
344 /* if this is a negative reply, we are authorative */
348 update_cached_ttl(buf, len, ttl);
350 DBG("id 0x%04x answers %d", hdr->id, answers);
352 err = sendto(sk, buf, len, 0, to, tolen);
354 connman_error("Cannot send cached DNS response: %s",
360 static void send_response(int sk, unsigned char *buf, int len,
361 const struct sockaddr *to, socklen_t tolen,
364 struct domain_hdr *hdr;
365 int err, offset = protocol_offset(protocol);
375 hdr = (void *) (buf + offset);
377 DBG("id 0x%04x qr %d opcode %d", hdr->id, hdr->qr, hdr->opcode);
386 err = sendto(sk, buf, len, 0, to, tolen);
388 connman_error("Failed to send DNS response: %s",
394 static gboolean request_timeout(gpointer user_data)
396 struct request_data *req = user_data;
397 struct listener_data *ifdata;
399 DBG("id 0x%04x", req->srcid);
404 ifdata = req->ifdata;
406 request_list = g_slist_remove(request_list, req);
409 if (req->resplen > 0 && req->resp != NULL) {
412 sk = g_io_channel_unix_get_fd(ifdata->udp_listener_channel);
414 err = sendto(sk, req->resp, req->resplen, 0,
415 &req->sa, req->sa_len);
418 } else if (req->request && req->numserv == 0) {
419 struct domain_hdr *hdr;
421 if (req->protocol == IPPROTO_TCP) {
422 hdr = (void *) (req->request + 2);
423 hdr->id = req->srcid;
424 send_response(req->client_sk, req->request,
425 req->request_len, NULL, 0, IPPROTO_TCP);
427 } else if (req->protocol == IPPROTO_UDP) {
430 hdr = (void *) (req->request);
431 hdr->id = req->srcid;
432 sk = g_io_channel_unix_get_fd(
433 ifdata->udp_listener_channel);
434 send_response(sk, req->request, req->request_len,
435 &req->sa, req->sa_len, IPPROTO_UDP);
445 static int append_query(unsigned char *buf, unsigned int size,
446 const char *query, const char *domain)
448 unsigned char *ptr = buf;
452 DBG("query %s domain %s", query, domain);
454 offset = (char *) query;
455 while (offset != NULL) {
458 tmp = strchr(offset, '.');
460 len = strlen(offset);
464 memcpy(ptr + 1, offset, len);
470 memcpy(ptr + 1, offset, tmp - offset);
471 ptr += tmp - offset + 1;
476 offset = (char *) domain;
477 while (offset != NULL) {
480 tmp = strchr(offset, '.');
482 len = strlen(offset);
486 memcpy(ptr + 1, offset, len);
492 memcpy(ptr + 1, offset, tmp - offset);
493 ptr += tmp - offset + 1;
503 static gboolean cache_check_is_valid(struct cache_data *data,
509 if (data->cache_until < current_time)
516 * remove stale cached entries so that they can be refreshed
518 static void cache_enforce_validity(struct cache_entry *entry)
520 time_t current_time = time(0);
522 if (cache_check_is_valid(entry->ipv4, current_time) == FALSE
524 DBG("cache timeout \"%s\" type A", entry->key);
525 g_free(entry->ipv4->data);
531 if (cache_check_is_valid(entry->ipv6, current_time) == FALSE
533 DBG("cache timeout \"%s\" type AAAA", entry->key);
534 g_free(entry->ipv6->data);
541 static uint16_t cache_check_validity(char *question, uint16_t type,
542 struct cache_entry *entry)
544 time_t current_time = time(0);
546 cache_enforce_validity(entry);
550 if (cache_check_is_valid(entry->ipv4, current_time) == FALSE) {
551 DBG("cache %s \"%s\" type A", entry->ipv4 ?
552 "timeout" : "entry missing", question);
555 * We do not remove cache entry if there is still
556 * valid IPv6 entry found in the cache.
558 if (cache_check_is_valid(entry->ipv6, current_time) == FALSE)
559 g_hash_table_remove(cache, question);
566 if (cache_check_is_valid(entry->ipv6, current_time) == FALSE) {
567 DBG("cache %s \"%s\" type AAAA", entry->ipv6 ?
568 "timeout" : "entry missing", question);
570 if (cache_check_is_valid(entry->ipv4, current_time) == FALSE)
571 g_hash_table_remove(cache, question);
581 static struct cache_entry *cache_check(gpointer request, int *qtype)
583 char *question = request + 12;
584 struct cache_entry *entry;
585 struct domain_question *q;
589 offset = strlen(question) + 1;
590 q = (void *) (question + offset);
591 type = ntohs(q->type);
593 /* We only cache either A (1) or AAAA (28) requests */
594 if (type != 1 && type != 28)
597 entry = g_hash_table_lookup(cache, question);
601 type = cache_check_validity(question, type, entry);
610 * Get a label/name from DNS resource record. The function decompresses the
611 * label if necessary. The function does not convert the name to presentation
612 * form. This means that the result string will contain label lengths instead
613 * of dots between labels. We intentionally do not want to convert to dotted
614 * format so that we can cache the wire format string directly.
616 static int get_name(int counter,
617 unsigned char *pkt, unsigned char *start, unsigned char *max,
618 unsigned char *output, int output_max, int *output_len,
619 unsigned char **end, char *name, int *name_len)
623 /* Limit recursion to 10 (this means up to 10 labels in domain name) */
629 if ((*p & NS_CMPRSFLGS) == NS_CMPRSFLGS) {
630 uint16_t offset = (*p & 0x3F) * 256 + *(p + 1);
632 if (offset >= max - pkt)
638 return get_name(counter + 1, pkt, pkt + offset, max,
639 output, output_max, output_len, end,
642 unsigned label_len = *p;
644 if (pkt + label_len > max)
647 if (*output_len > output_max)
651 * We need the original name in order to check
652 * if this answer is the correct one.
654 name[(*name_len)++] = label_len;
655 memcpy(name + *name_len, p + 1, label_len + 1);
656 *name_len += label_len;
658 /* We compress the result */
659 output[0] = NS_CMPRSFLGS;
676 static int parse_rr(unsigned char *buf, unsigned char *start,
678 unsigned char *response, unsigned int *response_size,
679 uint16_t *type, uint16_t *class, int *ttl, int *rdlen,
683 struct domain_rr *rr;
685 int name_len = 0, output_len = 0, max_rsp = *response_size;
687 err = get_name(0, buf, start, max, response, max_rsp,
688 &output_len, end, name, &name_len);
694 if ((unsigned int) offset > *response_size)
697 rr = (void *) (*end);
702 *type = ntohs(rr->type);
703 *class = ntohs(rr->class);
704 *ttl = ntohl(rr->ttl);
705 *rdlen = ntohs(rr->rdlen);
710 memcpy(response + offset, *end, sizeof(struct domain_rr));
712 offset += sizeof(struct domain_rr);
713 *end += sizeof(struct domain_rr);
715 if ((unsigned int) (offset + *rdlen) > *response_size)
718 memcpy(response + offset, *end, *rdlen);
722 *response_size = offset + *rdlen;
727 static gboolean check_alias(GSList *aliases, char *name)
731 if (aliases != NULL) {
732 for (list = aliases; list; list = list->next) {
733 int len = strlen((char *)list->data);
734 if (strncmp((char *)list->data, name, len) == 0)
742 static int parse_response(unsigned char *buf, int buflen,
743 char *question, int qlen,
744 uint16_t *type, uint16_t *class, int *ttl,
745 unsigned char *response, unsigned int *response_len,
748 struct domain_hdr *hdr = (void *) buf;
749 struct domain_question *q;
751 uint16_t qdcount = ntohs(hdr->qdcount);
752 uint16_t ancount = ntohs(hdr->ancount);
754 uint16_t qtype, qclass;
755 unsigned char *next = NULL;
756 unsigned int maxlen = *response_len;
757 GSList *aliases = NULL, *list;
758 char name[NS_MAXDNAME + 1];
763 DBG("qr %d qdcount %d", hdr->qr, qdcount);
765 /* We currently only cache responses where question count is 1 */
766 if (hdr->qr != 1 || qdcount != 1)
769 ptr = buf + sizeof(struct domain_hdr);
771 strncpy(question, (char *) ptr, qlen);
772 qlen = strlen(question);
773 ptr += qlen + 1; /* skip \0 */
776 qtype = ntohs(q->type);
778 /* We cache only A and AAAA records */
779 if (qtype != 1 && qtype != 28)
782 qclass = ntohs(q->class);
784 ptr += 2 + 2; /* ptr points now to answers */
791 * We have a bunch of answers (like A, AAAA, CNAME etc) to
792 * A or AAAA question. We traverse the answers and parse the
793 * resource records. Only A and AAAA records are cached, all
794 * the other records in answers are skipped.
796 for (i = 0; i < ancount; i++) {
798 * Get one address at a time to this buffer.
799 * The max size of the answer is
800 * 2 (pointer) + 2 (type) + 2 (class) +
801 * 4 (ttl) + 2 (rdlen) + addr (16 or 4) = 28
802 * for A or AAAA record.
803 * For CNAME the size can be bigger.
805 unsigned char rsp[NS_MAXCDNAME];
806 unsigned int rsp_len = sizeof(rsp) - 1;
809 memset(rsp, 0, sizeof(rsp));
811 ret = parse_rr(buf, ptr, buf + buflen, rsp, &rsp_len,
812 type, class, ttl, &rdlen, &next, name);
819 * Now rsp contains compressed or uncompressed resource
820 * record. Next we check if this record answers the question.
821 * The name var contains the uncompressed label.
822 * One tricky bit is the CNAME records as they alias
823 * the name we might be interested in.
827 * Go to next answer if the class is not the one we are
830 if (*class != qclass) {
837 * Try to resolve aliases also, type is CNAME(5).
838 * This is important as otherwise the aliased names would not
839 * be cached at all as the cache would not contain the aliased
842 * If any CNAME is found in DNS packet, then we cache the alias
843 * IP address instead of the question (as the server
844 * said that question has only an alias).
845 * This means in practice that if e.g., ipv6.google.com is
846 * queried, DNS server returns CNAME of that name which is
847 * ipv6.l.google.com. We then cache the address of the CNAME
848 * but return the question name to client. So the alias
849 * status of the name is not saved in cache and thus not
850 * returned to the client. We do not return DNS packets from
851 * cache to client saying that ipv6.google.com is an alias to
852 * ipv6.l.google.com but we return instead a DNS packet that
853 * says ipv6.google.com has address xxx which is in fact the
854 * address of ipv6.l.google.com. For caching purposes this
855 * should not cause any issues.
857 if (*type == 5 && strncmp(question, name, qlen) == 0) {
859 * So now the alias answered the question. This is
860 * not very useful from caching point of view as
861 * the following A or AAAA records will not match the
862 * question. We need to find the real A/AAAA record
863 * of the alias and cache that.
865 unsigned char *end = NULL;
866 int name_len = 0, output_len;
868 memset(rsp, 0, sizeof(rsp));
869 rsp_len = sizeof(rsp) - 1;
872 * Alias is in rdata part of the message,
873 * and next-rdlen points to it. So we need to get
874 * the real name of the alias.
876 ret = get_name(0, buf, next - rdlen, buf + buflen,
877 rsp, rsp_len, &output_len, &end,
880 /* just ignore the error at this point */
887 * We should now have the alias of the entry we might
888 * want to cache. Just remember it for a while.
889 * We check the alias list when we have parsed the
892 aliases = g_slist_prepend(aliases, g_strdup(name));
899 if (*type == qtype) {
901 * We found correct type (A or AAAA)
903 if (check_alias(aliases, name) == TRUE ||
904 (aliases == NULL && strncmp(question, name,
907 * We found an alias or the name of the rr
908 * matches the question. If so, we append
909 * the compressed label to the cache.
910 * The end result is a response buffer that
911 * will contain one or more cached and
912 * compressed resource records.
914 if (*response_len + rsp_len > maxlen) {
918 memcpy(response + *response_len, rsp, rsp_len);
919 *response_len += rsp_len;
930 for (list = aliases; list; list = list->next)
932 g_slist_free(aliases);
937 struct cache_timeout {
942 static gboolean cache_check_entry(gpointer key, gpointer value,
945 struct cache_timeout *data = user_data;
946 struct cache_entry *entry = value;
950 * If either IPv4 or IPv6 cached entry has expired, we
951 * remove both from the cache.
954 if (entry->ipv4 != NULL && entry->ipv4->timeout > 0) {
955 max_timeout = entry->ipv4->cache_until;
956 if (max_timeout > data->max_timeout)
957 data->max_timeout = max_timeout;
959 if (entry->ipv4->cache_until < data->current_time)
963 if (entry->ipv6 != NULL && entry->ipv6->timeout > 0) {
964 max_timeout = entry->ipv6->cache_until;
965 if (max_timeout > data->max_timeout)
966 data->max_timeout = max_timeout;
968 if (entry->ipv6->cache_until < data->current_time)
975 static void cache_cleanup(void)
977 static int max_timeout;
978 struct cache_timeout data;
981 data.current_time = time(0);
982 data.max_timeout = 0;
984 if (max_timeout > data.current_time) {
985 DBG("waiting %ld secs before cleaning cache",
986 max_timeout - data.current_time);
990 count = g_hash_table_foreach_remove(cache, cache_check_entry,
992 DBG("removed %d", count);
996 * If we could not remove anything, then remember
997 * what is the max timeout and do nothing if we
998 * have not yet reached it. This will prevent
999 * constant traversal of the cache if it is full.
1001 max_timeout = data.max_timeout;
1006 static int reply_query_type(unsigned char *msg, int len)
1013 /* skip the header */
1014 c = msg + sizeof(struct domain_hdr);
1015 len -= sizeof(struct domain_hdr);
1020 /* now the query, which is a name and 2 16 bit words */
1021 l = dns_name_length(c) + 1;
1029 static int cache_update(struct server_data *srv, unsigned char *msg,
1030 unsigned int msg_len)
1032 int offset = protocol_offset(srv->protocol);
1033 int err, qlen, ttl = 0;
1034 uint16_t answers = 0, type = 0, class = 0;
1035 struct domain_question *q;
1036 struct cache_entry *entry;
1037 struct cache_data *data;
1038 char question[NS_MAXDNAME + 1];
1039 unsigned char response[NS_MAXDNAME + 1];
1041 unsigned int rsplen;
1042 gboolean new_entry = TRUE;
1043 time_t current_time;
1045 if (cache_size >= MAX_CACHE_SIZE) {
1047 if (cache_size >= MAX_CACHE_SIZE)
1051 /* Continue only if response code is 0 (=ok) */
1058 rsplen = sizeof(response) - 1;
1059 question[sizeof(question) - 1] = '\0';
1061 err = parse_response(msg + offset, msg_len - offset,
1062 question, sizeof(question) - 1,
1063 &type, &class, &ttl,
1064 response, &rsplen, &answers);
1067 * special case: if we do a ipv6 lookup and get no result
1068 * for a record that's already in our ipv4 cache.. we want
1069 * to cache the negative response.
1071 if ((err == -ENOMSG || err == -ENOBUFS) &&
1072 reply_query_type(msg, msg_len) == 28) {
1073 entry = g_hash_table_lookup(cache, question);
1074 if (entry && entry->ipv4 && entry->ipv6 == NULL) {
1075 data = g_try_new(struct cache_data, 1);
1078 data->inserted = entry->ipv4->inserted;
1080 data->answers = msg[5];
1081 data->timeout = entry->ipv4->timeout;
1082 data->data_len = msg_len;
1083 data->data = ptr = g_malloc(msg_len);
1084 data->valid_until = entry->ipv4->valid_until;
1085 data->cache_until = entry->ipv4->cache_until;
1086 memcpy(data->data, msg, msg_len);
1092 if (err < 0 || ttl == 0)
1095 qlen = strlen(question);
1096 current_time = time(0);
1099 * If the cache contains already data, check if the
1100 * type of the cached data is the same and do not add
1101 * to cache if data is already there.
1102 * This is needed so that we can cache both A and AAAA
1103 * records for the same name.
1105 entry = g_hash_table_lookup(cache, question);
1106 if (entry == NULL) {
1107 entry = g_try_new(struct cache_entry, 1);
1111 data = g_try_new(struct cache_data, 1);
1117 entry->key = g_strdup(question);
1118 entry->ipv4 = entry->ipv6 = NULL;
1125 if (type == 1 && entry->ipv4 != NULL)
1128 if (type == 28 && entry->ipv6 != NULL)
1131 data = g_try_new(struct cache_data, 1);
1143 if (ttl < MIN_CACHE_TTL)
1144 ttl = MIN_CACHE_TTL;
1146 data->inserted = current_time;
1148 data->answers = answers;
1149 data->timeout = ttl;
1150 data->data_len = 12 + qlen + 1 + 2 + 2 + rsplen;
1151 data->data = ptr = g_malloc(data->data_len);
1152 data->valid_until = current_time + ttl;
1155 * Restrict the cached DNS record TTL to some sane value
1156 * in order to prevent data staying in the cache too long.
1158 if (ttl > MAX_CACHE_TTL)
1159 ttl = MAX_CACHE_TTL;
1161 data->cache_until = round_down_ttl(current_time + ttl, ttl);
1163 if (data->data == NULL) {
1170 memcpy(ptr, msg, 12);
1171 memcpy(ptr + 12, question, qlen + 1); /* copy also the \0 */
1173 q = (void *) (ptr + 12 + qlen + 1);
1174 q->type = htons(type);
1175 q->class = htons(class);
1176 memcpy(ptr + 12 + qlen + 1 + sizeof(struct domain_question),
1179 if (new_entry == TRUE) {
1180 g_hash_table_replace(cache, entry->key, entry);
1184 DBG("cache %d %squestion \"%s\" type %d ttl %d size %zd",
1185 cache_size, new_entry ? "new " : "old ",
1186 question, type, ttl,
1187 sizeof(*entry) + sizeof(*data) + data->data_len + qlen);
1192 static int ns_resolv(struct server_data *server, struct request_data *req,
1193 gpointer request, gpointer name)
1196 int sk, err, type = 0;
1197 char *dot, *lookup = (char *) name;
1198 struct cache_entry *entry;
1200 entry = cache_check(request, &type);
1201 if (entry != NULL) {
1203 struct cache_data *data;
1205 DBG("cache hit %s type %s", lookup, type == 1 ? "A" : "AAAA");
1212 ttl_left = data->valid_until - time(0);
1214 if (data != NULL && req->protocol == IPPROTO_TCP) {
1215 send_cached_response(req->client_sk, data->data,
1216 data->data_len, NULL, 0, IPPROTO_TCP,
1217 req->srcid, data->answers, ttl_left);
1221 if (data != NULL && req->protocol == IPPROTO_UDP) {
1223 sk = g_io_channel_unix_get_fd(
1224 req->ifdata->udp_listener_channel);
1226 send_cached_response(sk, data->data,
1227 data->data_len, &req->sa, req->sa_len,
1228 IPPROTO_UDP, req->srcid, data->answers,
1234 sk = g_io_channel_unix_get_fd(server->channel);
1236 err = send(sk, request, req->request_len, 0);
1240 /* If we have more than one dot, we don't add domains */
1241 dot = strchr(lookup, '.');
1242 if (dot != NULL && dot != lookup + strlen(lookup) - 1)
1245 if (server->domains != NULL && server->domains->data != NULL)
1246 req->append_domain = TRUE;
1248 for (list = server->domains; list; list = list->next) {
1250 unsigned char alt[1024];
1251 struct domain_hdr *hdr = (void *) &alt;
1252 int altlen, domlen, offset;
1254 domain = list->data;
1259 offset = protocol_offset(server->protocol);
1263 domlen = strlen(domain) + 1;
1267 alt[offset] = req->altid & 0xff;
1268 alt[offset + 1] = req->altid >> 8;
1270 memcpy(alt + offset + 2, request + offset + 2, 10);
1271 hdr->qdcount = htons(1);
1273 altlen = append_query(alt + offset + 12, sizeof(alt) - 12,
1280 memcpy(alt + offset + altlen,
1281 request + offset + altlen - domlen,
1282 req->request_len - altlen - offset + domlen);
1284 if (server->protocol == IPPROTO_TCP) {
1285 int req_len = req->request_len + domlen - 2;
1287 alt[0] = (req_len >> 8) & 0xff;
1288 alt[1] = req_len & 0xff;
1291 err = send(sk, alt, req->request_len + domlen, 0);
1301 static int forward_dns_reply(unsigned char *reply, int reply_len, int protocol,
1302 struct server_data *data)
1304 struct domain_hdr *hdr;
1305 struct request_data *req;
1306 int dns_id, sk, err, offset = protocol_offset(protocol);
1307 struct listener_data *ifdata;
1312 hdr = (void *)(reply + offset);
1313 dns_id = reply[offset] | reply[offset + 1] << 8;
1315 DBG("Received %d bytes (id 0x%04x)", reply_len, dns_id);
1317 req = find_request(dns_id);
1321 DBG("id 0x%04x rcode %d", hdr->id, hdr->rcode);
1323 ifdata = req->ifdata;
1325 reply[offset] = req->srcid & 0xff;
1326 reply[offset + 1] = req->srcid >> 8;
1330 if (hdr->rcode == 0 || req->resp == NULL) {
1333 * If the domain name was append
1334 * remove it before forwarding the reply.
1336 if (req->append_domain == TRUE) {
1339 unsigned int domain_len;
1342 * ptr points to the first char of the hostname.
1343 * ->hostname.domain.net
1345 ptr = reply + offset + sizeof(struct domain_hdr);
1347 domain_len = strlen((const char *)ptr) - host_len - 1;
1350 * remove the domain name and replaced it by the end
1353 memmove(ptr + host_len + 1,
1354 ptr + host_len + domain_len + 1,
1355 reply_len - (ptr - reply + domain_len));
1357 reply_len = reply_len - domain_len;
1363 req->resp = g_try_malloc(reply_len);
1364 if (req->resp == NULL)
1367 memcpy(req->resp, reply, reply_len);
1368 req->resplen = reply_len;
1370 cache_update(data, reply, reply_len);
1373 if (hdr->rcode > 0 && req->numresp < req->numserv)
1376 if (req->timeout > 0)
1377 g_source_remove(req->timeout);
1379 request_list = g_slist_remove(request_list, req);
1381 if (protocol == IPPROTO_UDP) {
1382 sk = g_io_channel_unix_get_fd(ifdata->udp_listener_channel);
1383 err = sendto(sk, req->resp, req->resplen, 0,
1384 &req->sa, req->sa_len);
1386 sk = req->client_sk;
1387 err = send(sk, req->resp, req->resplen, 0);
1397 static void cache_element_destroy(gpointer value)
1399 struct cache_entry *entry = value;
1404 if (entry->ipv4 != NULL) {
1405 g_free(entry->ipv4->data);
1406 g_free(entry->ipv4);
1409 if (entry->ipv6 != NULL) {
1410 g_free(entry->ipv6->data);
1411 g_free(entry->ipv6);
1417 if (--cache_size < 0)
1421 static void destroy_server(struct server_data *server)
1425 DBG("interface %s server %s", server->interface, server->server);
1427 server_list = g_slist_remove(server_list, server);
1429 if (server->watch > 0)
1430 g_source_remove(server->watch);
1432 if (server->timeout > 0)
1433 g_source_remove(server->timeout);
1435 g_io_channel_unref(server->channel);
1437 if (server->protocol == IPPROTO_UDP)
1438 connman_info("Removing DNS server %s", server->server);
1440 g_free(server->incoming_reply);
1441 g_free(server->server);
1442 for (list = server->domains; list; list = list->next) {
1443 char *domain = list->data;
1445 server->domains = g_list_remove(server->domains, domain);
1448 g_free(server->interface);
1450 if (__sync_fetch_and_sub(&cache_refcount, 1) == 1)
1451 g_hash_table_destroy(cache);
1456 static gboolean udp_server_event(GIOChannel *channel, GIOCondition condition,
1459 unsigned char buf[4096];
1461 struct server_data *data = user_data;
1463 if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
1464 connman_error("Error with UDP server %s", data->server);
1469 sk = g_io_channel_unix_get_fd(channel);
1471 len = recv(sk, buf, sizeof(buf), 0);
1475 err = forward_dns_reply(buf, len, IPPROTO_UDP, data);
1482 static gboolean tcp_server_event(GIOChannel *channel, GIOCondition condition,
1486 struct server_data *server = user_data;
1488 sk = g_io_channel_unix_get_fd(channel);
1492 if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
1495 DBG("TCP server channel closed");
1498 * Discard any partial response which is buffered; better
1499 * to get a proper response from a working server.
1501 g_free(server->incoming_reply);
1502 server->incoming_reply = NULL;
1504 for (list = request_list; list; list = list->next) {
1505 struct request_data *req = list->data;
1506 struct domain_hdr *hdr;
1508 if (req->protocol == IPPROTO_UDP)
1511 if (req->request == NULL)
1515 * If we're not waiting for any further response
1516 * from another name server, then we send an error
1517 * response to the client.
1519 if (req->numserv && --(req->numserv))
1522 hdr = (void *) (req->request + 2);
1523 hdr->id = req->srcid;
1524 send_response(req->client_sk, req->request,
1525 req->request_len, NULL, 0, IPPROTO_TCP);
1527 request_list = g_slist_remove(request_list, req);
1530 destroy_server(server);
1535 if ((condition & G_IO_OUT) && !server->connected) {
1538 struct server_data *udp_server;
1540 udp_server = find_server(server->interface, server->server,
1542 if (udp_server != NULL) {
1543 for (domains = udp_server->domains; domains;
1544 domains = domains->next) {
1545 char *dom = domains->data;
1547 DBG("Adding domain %s to %s",
1548 dom, server->server);
1550 server->domains = g_list_append(server->domains,
1555 server->connected = TRUE;
1556 server_list = g_slist_append(server_list, server);
1558 if (server->timeout > 0) {
1559 g_source_remove(server->timeout);
1560 server->timeout = 0;
1563 for (list = request_list; list; list = list->next) {
1564 struct request_data *req = list->data;
1566 if (req->protocol == IPPROTO_UDP)
1569 DBG("Sending req %s over TCP", (char *)req->name);
1571 if (req->timeout > 0)
1572 g_source_remove(req->timeout);
1574 req->timeout = g_timeout_add_seconds(30,
1575 request_timeout, req);
1576 if (ns_resolv(server, req, req->request,
1578 /* We sent cached result so no need for timeout
1581 if (req->timeout > 0) {
1582 g_source_remove(req->timeout);
1588 } else if (condition & G_IO_IN) {
1589 struct partial_reply *reply = server->incoming_reply;
1593 unsigned char reply_len_buf[2];
1596 bytes_recv = recv(sk, reply_len_buf, 2, MSG_PEEK);
1599 } else if (bytes_recv < 0) {
1600 if (errno == EAGAIN || errno == EWOULDBLOCK)
1603 connman_error("DNS proxy error %s",
1606 } else if (bytes_recv < 2)
1609 reply_len = reply_len_buf[1] | reply_len_buf[0] << 8;
1612 DBG("TCP reply %d bytes", reply_len);
1614 reply = g_try_malloc(sizeof(*reply) + reply_len + 2);
1618 reply->len = reply_len;
1619 reply->received = 0;
1621 server->incoming_reply = reply;
1624 while (reply->received < reply->len) {
1625 bytes_recv = recv(sk, reply->buf + reply->received,
1626 reply->len - reply->received, 0);
1628 connman_error("DNS proxy TCP disconnect");
1630 } else if (bytes_recv < 0) {
1631 if (errno == EAGAIN || errno == EWOULDBLOCK)
1634 connman_error("DNS proxy error %s",
1638 reply->received += bytes_recv;
1641 forward_dns_reply(reply->buf, reply->received, IPPROTO_TCP,
1645 server->incoming_reply = NULL;
1647 destroy_server(server);
1655 static gboolean tcp_idle_timeout(gpointer user_data)
1657 struct server_data *server = user_data;
1664 destroy_server(server);
1669 static struct server_data *create_server(const char *interface,
1670 const char *domain, const char *server,
1673 struct addrinfo hints, *rp;
1674 struct server_data *data;
1677 DBG("interface %s server %s", interface, server);
1679 memset(&hints, 0, sizeof(hints));
1683 hints.ai_socktype = SOCK_DGRAM;
1687 hints.ai_socktype = SOCK_STREAM;
1693 hints.ai_family = AF_UNSPEC;
1694 hints.ai_flags = AI_PASSIVE | AI_NUMERICSERV | AI_NUMERICHOST;
1696 ret = getaddrinfo(server, "53", &hints, &rp);
1698 connman_error("Failed to parse server %s address: %s\n",
1699 server, gai_strerror(ret));
1702 /* Do not blindly copy this code elsewhere; it doesn't loop over the
1703 results using ->ai_next as it should. That's OK in *this* case
1704 because it was a numeric lookup; we *know* there's only one. */
1706 sk = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
1708 connman_error("Failed to create server %s socket", server);
1713 if (interface != NULL) {
1714 if (setsockopt(sk, SOL_SOCKET, SO_BINDTODEVICE,
1715 interface, strlen(interface) + 1) < 0) {
1716 connman_error("Failed to bind server %s "
1725 data = g_try_new0(struct server_data, 1);
1727 connman_error("Failed to allocate server %s data", server);
1733 data->channel = g_io_channel_unix_new(sk);
1734 if (data->channel == NULL) {
1735 connman_error("Failed to create server %s channel", server);
1742 g_io_channel_set_close_on_unref(data->channel, TRUE);
1744 if (protocol == IPPROTO_TCP) {
1745 g_io_channel_set_flags(data->channel, G_IO_FLAG_NONBLOCK, NULL);
1746 data->watch = g_io_add_watch(data->channel,
1747 G_IO_OUT | G_IO_IN | G_IO_HUP | G_IO_NVAL | G_IO_ERR,
1748 tcp_server_event, data);
1749 data->timeout = g_timeout_add_seconds(30, tcp_idle_timeout,
1752 data->watch = g_io_add_watch(data->channel,
1753 G_IO_IN | G_IO_NVAL | G_IO_ERR | G_IO_HUP,
1754 udp_server_event, data);
1756 data->interface = g_strdup(interface);
1758 data->domains = g_list_append(data->domains, g_strdup(domain));
1759 data->server = g_strdup(server);
1760 data->protocol = protocol;
1762 ret = connect(sk, rp->ai_addr, rp->ai_addrlen);
1765 if ((protocol == IPPROTO_TCP && errno != EINPROGRESS) ||
1766 protocol == IPPROTO_UDP) {
1769 connman_error("Failed to connect to server %s", server);
1770 if (data->watch > 0)
1771 g_source_remove(data->watch);
1772 if (data->timeout > 0)
1773 g_source_remove(data->timeout);
1775 g_io_channel_unref(data->channel);
1778 g_free(data->server);
1779 g_free(data->interface);
1780 for (list = data->domains; list; list = list->next) {
1781 char *domain = list->data;
1783 data->domains = g_list_remove(data->domains,
1792 if (__sync_fetch_and_add(&cache_refcount, 1) == 0)
1793 cache = g_hash_table_new_full(g_str_hash,
1796 cache_element_destroy);
1798 if (protocol == IPPROTO_UDP) {
1799 /* Enable new servers by default */
1800 data->enabled = TRUE;
1801 connman_info("Adding DNS server %s", data->server);
1803 server_list = g_slist_append(server_list, data);
1811 static gboolean resolv(struct request_data *req,
1812 gpointer request, gpointer name)
1817 for (list = server_list; list; list = list->next) {
1818 struct server_data *data = list->data;
1820 DBG("server %s enabled %d", data->server, data->enabled);
1822 if (data->enabled == FALSE)
1825 if (data->watch == 0 && data->protocol == IPPROTO_UDP)
1826 data->watch = g_io_add_watch(data->channel,
1827 G_IO_IN | G_IO_NVAL | G_IO_ERR | G_IO_HUP,
1828 udp_server_event, data);
1830 status = ns_resolv(data, req, request, name);
1835 if (req->timeout > 0) {
1836 g_source_remove(req->timeout);
1845 static void append_domain(const char *interface, const char *domain)
1849 DBG("interface %s domain %s", interface, domain);
1854 for (list = server_list; list; list = list->next) {
1855 struct server_data *data = list->data;
1858 gboolean dom_found = FALSE;
1860 if (data->interface == NULL)
1863 if (g_str_equal(data->interface, interface) == FALSE)
1866 for (dom_list = data->domains; dom_list;
1867 dom_list = dom_list->next) {
1868 dom = dom_list->data;
1870 if (g_str_equal(dom, domain)) {
1876 if (dom_found == FALSE) {
1878 g_list_append(data->domains, g_strdup(domain));
1883 int __connman_dnsproxy_append(const char *interface, const char *domain,
1886 struct server_data *data;
1888 DBG("interface %s server %s", interface, server);
1890 if (server == NULL && domain == NULL)
1893 if (server == NULL) {
1894 append_domain(interface, domain);
1899 if (g_str_equal(server, "127.0.0.1") == TRUE)
1902 data = find_server(interface, server, IPPROTO_UDP);
1904 append_domain(interface, domain);
1908 data = create_server(interface, domain, server, IPPROTO_UDP);
1915 static void remove_server(const char *interface, const char *domain,
1916 const char *server, int protocol)
1918 struct server_data *data;
1920 data = find_server(interface, server, protocol);
1924 destroy_server(data);
1927 int __connman_dnsproxy_remove(const char *interface, const char *domain,
1930 DBG("interface %s server %s", interface, server);
1935 if (g_str_equal(server, "127.0.0.1") == TRUE)
1938 remove_server(interface, domain, server, IPPROTO_UDP);
1939 remove_server(interface, domain, server, IPPROTO_TCP);
1944 void __connman_dnsproxy_flush(void)
1948 list = request_pending_list;
1950 struct request_data *req = list->data;
1954 request_pending_list =
1955 g_slist_remove(request_pending_list, req);
1956 resolv(req, req->request, req->name);
1957 g_free(req->request);
1962 static void dnsproxy_offline_mode(connman_bool_t enabled)
1966 DBG("enabled %d", enabled);
1968 for (list = server_list; list; list = list->next) {
1969 struct server_data *data = list->data;
1971 if (enabled == FALSE) {
1972 connman_info("Enabling DNS server %s", data->server);
1973 data->enabled = TRUE;
1975 connman_info("Disabling DNS server %s", data->server);
1976 data->enabled = FALSE;
1981 static void dnsproxy_default_changed(struct connman_service *service)
1986 DBG("service %p", service);
1988 if (service == NULL) {
1989 /* When no services are active, then disable DNS proxying */
1990 dnsproxy_offline_mode(TRUE);
1994 interface = connman_service_get_interface(service);
1995 if (interface == NULL)
1998 for (list = server_list; list; list = list->next) {
1999 struct server_data *data = list->data;
2001 if (g_strcmp0(data->interface, interface) == 0) {
2002 connman_info("Enabling DNS server %s", data->server);
2003 data->enabled = TRUE;
2005 connman_info("Disabling DNS server %s", data->server);
2006 data->enabled = FALSE;
2013 static struct connman_notifier dnsproxy_notifier = {
2015 .default_changed = dnsproxy_default_changed,
2016 .offline_mode = dnsproxy_offline_mode,
2019 static unsigned char opt_edns0_type[2] = { 0x00, 0x29 };
2021 static int parse_request(unsigned char *buf, int len,
2022 char *name, unsigned int size)
2024 struct domain_hdr *hdr = (void *) buf;
2025 uint16_t qdcount = ntohs(hdr->qdcount);
2026 uint16_t arcount = ntohs(hdr->arcount);
2028 char *last_label = NULL;
2029 unsigned int remain, used = 0;
2034 DBG("id 0x%04x qr %d opcode %d qdcount %d arcount %d",
2035 hdr->id, hdr->qr, hdr->opcode,
2038 if (hdr->qr != 0 || qdcount != 1)
2041 memset(name, 0, size);
2043 ptr = buf + sizeof(struct domain_hdr);
2044 remain = len - sizeof(struct domain_hdr);
2046 while (remain > 0) {
2050 last_label = (char *) (ptr + 1);
2054 if (used + len + 1 > size)
2057 strncat(name, (char *) (ptr + 1), len);
2066 if (last_label && arcount && remain >= 9 && last_label[4] == 0 &&
2067 !memcmp(last_label + 5, opt_edns0_type, 2)) {
2068 uint16_t edns0_bufsize;
2070 edns0_bufsize = last_label[7] << 8 | last_label[8];
2072 DBG("EDNS0 buffer size %u", edns0_bufsize);
2074 /* This is an evil hack until full TCP support has been
2077 * Somtimes the EDNS0 request gets send with a too-small
2078 * buffer size. Since glibc doesn't seem to crash when it
2079 * gets a response biffer then it requested, just bump
2080 * the buffer size up to 4KiB.
2082 if (edns0_bufsize < 0x1000) {
2083 last_label[7] = 0x10;
2084 last_label[8] = 0x00;
2088 DBG("query %s", name);
2093 static gboolean tcp_listener_event(GIOChannel *channel, GIOCondition condition,
2096 unsigned char buf[768];
2098 struct request_data *req;
2099 struct server_data *server;
2100 int sk, client_sk, len, err;
2101 struct sockaddr_in6 client_addr;
2102 socklen_t client_addr_len = sizeof(client_addr);
2104 struct listener_data *ifdata = user_data;
2106 DBG("condition 0x%x", condition);
2108 if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
2109 if (ifdata->tcp_listener_watch > 0)
2110 g_source_remove(ifdata->tcp_listener_watch);
2111 ifdata->tcp_listener_watch = 0;
2113 connman_error("Error with TCP listener channel");
2118 sk = g_io_channel_unix_get_fd(channel);
2120 client_sk = accept(sk, (void *)&client_addr, &client_addr_len);
2121 if (client_sk < 0) {
2122 connman_error("Accept failure on TCP listener");
2123 ifdata->tcp_listener_watch = 0;
2127 len = recv(client_sk, buf, sizeof(buf), 0);
2131 DBG("Received %d bytes (id 0x%04x)", len, buf[2] | buf[3] << 8);
2133 err = parse_request(buf + 2, len - 2, query, sizeof(query));
2134 if (err < 0 || (g_slist_length(server_list) == 0)) {
2135 send_response(client_sk, buf, len, NULL, 0, IPPROTO_TCP);
2139 req = g_try_new0(struct request_data, 1);
2143 memcpy(&req->sa, &client_addr, client_addr_len);
2144 req->sa_len = client_addr_len;
2145 req->client_sk = client_sk;
2146 req->protocol = IPPROTO_TCP;
2149 if (request_id == 0x0000 || request_id == 0xffff)
2152 req->srcid = buf[2] | (buf[3] << 8);
2153 req->dstid = request_id;
2154 req->altid = request_id + 1;
2155 req->request_len = len;
2157 buf[2] = req->dstid & 0xff;
2158 buf[3] = req->dstid >> 8;
2161 req->ifdata = (struct listener_data *) ifdata;
2162 req->append_domain = FALSE;
2163 request_list = g_slist_append(request_list, req);
2165 for (list = server_list; list; list = list->next) {
2166 struct server_data *data = list->data;
2169 if (data->protocol != IPPROTO_UDP || data->enabled == FALSE)
2172 server = create_server(data->interface, NULL,
2173 data->server, IPPROTO_TCP);
2176 * If server is NULL, we're not connected yet.
2177 * Copy the relevant buffers and continue with
2178 * the next nameserver.
2179 * The request will actually be sent once we're
2180 * properly connected over TCP to this nameserver.
2182 if (server == NULL) {
2183 req->request = g_try_malloc0(req->request_len);
2184 if (req->request == NULL)
2187 memcpy(req->request, buf, req->request_len);
2189 req->name = g_try_malloc0(sizeof(query));
2190 if (req->name == NULL) {
2191 g_free(req->request);
2194 memcpy(req->name, query, sizeof(query));
2199 if (req->timeout > 0)
2200 g_source_remove(req->timeout);
2202 for (domains = data->domains; domains;
2203 domains = domains->next) {
2204 char *dom = domains->data;
2206 DBG("Adding domain %s to %s", dom, server->server);
2208 server->domains = g_list_append(server->domains,
2212 req->timeout = g_timeout_add_seconds(30, request_timeout, req);
2213 if (ns_resolv(server, req, buf, query) > 0) {
2214 if (req->timeout > 0) {
2215 g_source_remove(req->timeout);
2224 static gboolean udp_listener_event(GIOChannel *channel, GIOCondition condition,
2227 unsigned char buf[768];
2229 struct request_data *req;
2230 struct sockaddr_in6 client_addr;
2231 socklen_t client_addr_len = sizeof(client_addr);
2233 struct listener_data *ifdata = user_data;
2235 if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
2236 connman_error("Error with UDP listener channel");
2237 ifdata->udp_listener_watch = 0;
2241 sk = g_io_channel_unix_get_fd(channel);
2243 memset(&client_addr, 0, client_addr_len);
2244 len = recvfrom(sk, buf, sizeof(buf), 0, (void *)&client_addr,
2249 DBG("Received %d bytes (id 0x%04x)", len, buf[0] | buf[1] << 8);
2251 err = parse_request(buf, len, query, sizeof(query));
2252 if (err < 0 || (g_slist_length(server_list) == 0)) {
2253 send_response(sk, buf, len, (void *)&client_addr,
2254 client_addr_len, IPPROTO_UDP);
2258 req = g_try_new0(struct request_data, 1);
2262 memcpy(&req->sa, &client_addr, client_addr_len);
2263 req->sa_len = client_addr_len;
2265 req->protocol = IPPROTO_UDP;
2268 if (request_id == 0x0000 || request_id == 0xffff)
2271 req->srcid = buf[0] | (buf[1] << 8);
2272 req->dstid = request_id;
2273 req->altid = request_id + 1;
2274 req->request_len = len;
2276 buf[0] = req->dstid & 0xff;
2277 buf[1] = req->dstid >> 8;
2280 req->ifdata = (struct listener_data *) ifdata;
2281 req->timeout = g_timeout_add_seconds(5, request_timeout, req);
2282 req->append_domain = FALSE;
2283 request_list = g_slist_append(request_list, req);
2285 return resolv(req, buf, query);
2288 static int create_dns_listener(int protocol, struct listener_data *ifdata)
2290 GIOChannel *channel;
2294 struct sockaddr_in6 sin6;
2295 struct sockaddr_in sin;
2298 int sk, type, v6only = 0;
2299 int family = AF_INET6;
2302 DBG("interface %s", ifdata->ifname);
2307 type = SOCK_DGRAM | SOCK_CLOEXEC;
2312 type = SOCK_STREAM | SOCK_CLOEXEC;
2319 sk = socket(family, type, protocol);
2320 if (sk < 0 && family == AF_INET6 && errno == EAFNOSUPPORT) {
2321 connman_error("No IPv6 support; DNS proxy listening only on Legacy IP");
2323 sk = socket(family, type, protocol);
2326 connman_error("Failed to create %s listener socket", proto);
2330 if (setsockopt(sk, SOL_SOCKET, SO_BINDTODEVICE,
2332 strlen(ifdata->ifname) + 1) < 0) {
2333 connman_error("Failed to bind %s listener interface", proto);
2337 /* Ensure it accepts Legacy IP connections too */
2338 if (family == AF_INET6 &&
2339 setsockopt(sk, SOL_IPV6, IPV6_V6ONLY,
2340 &v6only, sizeof(v6only)) < 0) {
2341 connman_error("Failed to clear V6ONLY on %s listener socket",
2347 if (family == AF_INET) {
2348 memset(&s.sin, 0, sizeof(s.sin));
2349 s.sin.sin_family = AF_INET;
2350 s.sin.sin_port = htons(53);
2351 s.sin.sin_addr.s_addr = htonl(INADDR_ANY);
2352 slen = sizeof(s.sin);
2354 memset(&s.sin6, 0, sizeof(s.sin6));
2355 s.sin6.sin6_family = AF_INET6;
2356 s.sin6.sin6_port = htons(53);
2357 s.sin6.sin6_addr = in6addr_any;
2358 slen = sizeof(s.sin6);
2361 if (bind(sk, &s.sa, slen) < 0) {
2362 connman_error("Failed to bind %s listener socket", proto);
2367 if (protocol == IPPROTO_TCP && listen(sk, 10) < 0) {
2368 connman_error("Failed to listen on TCP socket");
2373 channel = g_io_channel_unix_new(sk);
2374 if (channel == NULL) {
2375 connman_error("Failed to create %s listener channel", proto);
2380 g_io_channel_set_close_on_unref(channel, TRUE);
2382 if (protocol == IPPROTO_TCP) {
2383 ifdata->tcp_listener_channel = channel;
2384 ifdata->tcp_listener_watch = g_io_add_watch(channel,
2385 G_IO_IN, tcp_listener_event, (gpointer) ifdata);
2387 ifdata->udp_listener_channel = channel;
2388 ifdata->udp_listener_watch = g_io_add_watch(channel,
2389 G_IO_IN, udp_listener_event, (gpointer) ifdata);
2395 static void destroy_udp_listener(struct listener_data *ifdata)
2397 DBG("interface %s", ifdata->ifname);
2399 if (ifdata->udp_listener_watch > 0)
2400 g_source_remove(ifdata->udp_listener_watch);
2402 g_io_channel_unref(ifdata->udp_listener_channel);
2405 static void destroy_tcp_listener(struct listener_data *ifdata)
2407 DBG("interface %s", ifdata->ifname);
2409 if (ifdata->tcp_listener_watch > 0)
2410 g_source_remove(ifdata->tcp_listener_watch);
2412 g_io_channel_unref(ifdata->tcp_listener_channel);
2415 static int create_listener(struct listener_data *ifdata)
2419 err = create_dns_listener(IPPROTO_UDP, ifdata);
2423 err = create_dns_listener(IPPROTO_TCP, ifdata);
2425 destroy_udp_listener(ifdata);
2429 if (g_strcmp0(ifdata->ifname, "lo") == 0)
2430 __connman_resolvfile_append("lo", NULL, "127.0.0.1");
2435 static void destroy_listener(struct listener_data *ifdata)
2439 if (g_strcmp0(ifdata->ifname, "lo") == 0)
2440 __connman_resolvfile_remove("lo", NULL, "127.0.0.1");
2442 for (list = request_pending_list; list; list = list->next) {
2443 struct request_data *req = list->data;
2445 DBG("Dropping pending request (id 0x%04x -> 0x%04x)",
2446 req->srcid, req->dstid);
2449 g_free(req->request);
2455 g_slist_free(request_pending_list);
2456 request_pending_list = NULL;
2458 for (list = request_list; list; list = list->next) {
2459 struct request_data *req = list->data;
2461 DBG("Dropping request (id 0x%04x -> 0x%04x)",
2462 req->srcid, req->dstid);
2465 g_free(req->request);
2471 g_slist_free(request_list);
2472 request_list = NULL;
2474 destroy_tcp_listener(ifdata);
2475 destroy_udp_listener(ifdata);
2478 int __connman_dnsproxy_add_listener(const char *interface)
2480 struct listener_data *ifdata;
2483 DBG("interface %s", interface);
2485 if (g_hash_table_lookup(listener_table, interface) != NULL)
2488 ifdata = g_try_new0(struct listener_data, 1);
2492 ifdata->ifname = g_strdup(interface);
2493 ifdata->udp_listener_channel = NULL;
2494 ifdata->udp_listener_watch = 0;
2495 ifdata->tcp_listener_channel = NULL;
2496 ifdata->tcp_listener_watch = 0;
2498 err = create_listener(ifdata);
2500 connman_error("Couldn't create listener for %s err %d",
2502 g_free(ifdata->ifname);
2506 g_hash_table_insert(listener_table, ifdata->ifname, ifdata);
2510 void __connman_dnsproxy_remove_listener(const char *interface)
2512 struct listener_data *ifdata;
2514 DBG("interface %s", interface);
2516 ifdata = g_hash_table_lookup(listener_table, interface);
2520 destroy_listener(ifdata);
2522 g_hash_table_remove(listener_table, interface);
2525 static void remove_listener(gpointer key, gpointer value, gpointer user_data)
2527 __connman_dnsproxy_remove_listener(key);
2530 int __connman_dnsproxy_init(void)
2536 listener_table = g_hash_table_new_full(g_str_hash, g_str_equal,
2538 err = __connman_dnsproxy_add_listener("lo");
2542 err = connman_notifier_register(&dnsproxy_notifier);
2549 __connman_dnsproxy_remove_listener("lo");
2550 g_hash_table_destroy(listener_table);
2555 void __connman_dnsproxy_cleanup(void)
2559 connman_notifier_unregister(&dnsproxy_notifier);
2561 g_hash_table_foreach(listener_table, remove_listener, NULL);
2563 g_hash_table_destroy(listener_table);