5 * Copyright (C) 2007-2012 Intel Corporation. All rights reserved.
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License version 2 as
9 * published by the Free Software Foundation.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
31 #include <arpa/inet.h>
32 #include <netinet/in.h>
33 #include <sys/types.h>
34 #include <sys/socket.h>
38 #include <gweb/gresolv.h>
44 #if __BYTE_ORDER == __LITTLE_ENDIAN
59 } __attribute__ ((packed));
60 #elif __BYTE_ORDER == __BIG_ENDIAN
75 } __attribute__ ((packed));
77 #error "Unknown byte order"
80 struct partial_reply {
90 struct sockaddr *server_addr;
91 socklen_t server_addr_len;
98 struct partial_reply *incoming_reply;
101 struct request_data {
103 struct sockaddr_in6 __sin6; /* Only for the length */
122 struct listener_data *ifdata;
123 gboolean append_domain;
126 struct listener_data {
129 GIOChannel *udp4_listener_channel;
130 GIOChannel *tcp4_listener_channel;
131 guint udp4_listener_watch;
132 guint tcp4_listener_watch;
134 GIOChannel *udp6_listener_channel;
135 GIOChannel *tcp6_listener_channel;
136 guint udp6_listener_watch;
137 guint tcp6_listener_watch;
141 * The TCP client requires some extra handling as we need to
142 * be prepared to receive also partial DNS requests.
144 struct tcp_partial_client_data {
146 struct listener_data *ifdata;
150 unsigned int buf_end;
161 unsigned int data_len;
162 unsigned char *data; /* contains DNS header + body */
169 struct cache_data *ipv4;
170 struct cache_data *ipv6;
173 struct domain_question {
176 } __attribute__ ((packed));
183 } __attribute__ ((packed));
186 * Max length of the DNS TCP packet.
188 #define TCP_MAX_BUF_LEN 4096
191 * We limit how long the cached DNS entry stays in the cache.
192 * By default the TTL (time-to-live) of the DNS response is used
193 * when setting the cache entry life time. The value is in seconds.
195 #define MAX_CACHE_TTL (60 * 30)
197 * Also limit the other end, cache at least for 30 seconds.
199 #define MIN_CACHE_TTL (30)
202 * We limit the cache size to some sane value so that cached data does
203 * not occupy too much memory. Each cached entry occupies on average
204 * about 100 bytes memory (depending on DNS name length).
205 * Example: caching www.connman.net uses 97 bytes memory.
206 * The value is the max amount of cached DNS responses (count).
208 #define MAX_CACHE_SIZE 256
210 static int cache_size;
211 static GHashTable *cache;
212 static int cache_refcount;
213 static GSList *server_list = NULL;
214 static GSList *request_list = NULL;
215 static GHashTable *listener_table = NULL;
216 static time_t next_refresh;
217 static GHashTable *partial_tcp_req_table;
219 static guint16 get_id()
224 static int protocol_offset(int protocol)
240 * There is a power and efficiency benefit to have entries
241 * in our cache expire at the same time. To this extend,
242 * we round down the cache valid time to common boundaries.
244 static time_t round_down_ttl(time_t end_time, int ttl)
249 /* Less than 5 minutes, round to 10 second boundary */
251 end_time = end_time / 10;
252 end_time = end_time * 10;
253 } else { /* 5 or more minutes, round to 30 seconds */
254 end_time = end_time / 30;
255 end_time = end_time * 30;
260 static struct request_data *find_request(guint16 id)
264 for (list = request_list; list; list = list->next) {
265 struct request_data *req = list->data;
267 if (req->dstid == id || req->altid == id)
274 static struct server_data *find_server(int index,
280 DBG("index %d server %s proto %d", index, server, protocol);
282 for (list = server_list; list; list = list->next) {
283 struct server_data *data = list->data;
285 if (index < 0 && data->index < 0 &&
286 g_str_equal(data->server, server) == TRUE &&
287 data->protocol == protocol)
291 data->index < 0 || data->server == NULL)
294 if (data->index == index &&
295 g_str_equal(data->server, server) == TRUE &&
296 data->protocol == protocol)
303 /* we can keep using the same resolve's */
304 static GResolv *ipv4_resolve;
305 static GResolv *ipv6_resolve;
307 static void dummy_resolve_func(GResolvResultStatus status,
308 char **results, gpointer user_data)
313 * Refresh a DNS entry, but also age the hit count a bit */
314 static void refresh_dns_entry(struct cache_entry *entry, char *name)
318 if (ipv4_resolve == NULL) {
319 ipv4_resolve = g_resolv_new(0);
320 g_resolv_set_address_family(ipv4_resolve, AF_INET);
321 g_resolv_add_nameserver(ipv4_resolve, "127.0.0.1", 53, 0);
324 if (ipv6_resolve == NULL) {
325 ipv6_resolve = g_resolv_new(0);
326 g_resolv_set_address_family(ipv6_resolve, AF_INET6);
327 g_resolv_add_nameserver(ipv6_resolve, "::1", 53, 0);
330 if (entry->ipv4 == NULL) {
331 DBG("Refresing A record for %s", name);
332 g_resolv_lookup_hostname(ipv4_resolve, name,
333 dummy_resolve_func, NULL);
337 if (entry->ipv6 == NULL) {
338 DBG("Refresing AAAA record for %s", name);
339 g_resolv_lookup_hostname(ipv6_resolve, name,
340 dummy_resolve_func, NULL);
349 static int dns_name_length(unsigned char *buf)
351 if ((buf[0] & NS_CMPRSFLGS) == NS_CMPRSFLGS) /* compressed name */
353 return strlen((char *)buf);
356 static void update_cached_ttl(unsigned char *buf, int len, int new_ttl)
363 /* skip the header */
367 /* skip the query, which is a name and 2 16 bit words */
368 l = dns_name_length(c);
374 /* now we get the answer records */
378 l = dns_name_length(c);
383 /* then type + class, 2 bytes each */
389 /* now the 4 byte TTL field */
397 /* now the 2 byte rdlen field */
400 len -= ntohs(*w) + 2;
404 static void send_cached_response(int sk, unsigned char *buf, int len,
405 const struct sockaddr *to, socklen_t tolen,
406 int protocol, int id, uint16_t answers, int ttl)
408 struct domain_hdr *hdr;
409 unsigned char *ptr = buf;
410 int err, offset, dns_len, adj_len = len - 2;
413 * The cached packet contains always the TCP offset (two bytes)
414 * so skip them for UDP.
425 dns_len = ptr[0] * 256 + ptr[1];
434 hdr = (void *) (ptr + offset);
439 hdr->ancount = htons(answers);
443 /* if this is a negative reply, we are authorative */
447 update_cached_ttl((unsigned char *)hdr, adj_len, ttl);
449 DBG("sk %d id 0x%04x answers %d ptr %p length %d dns %d",
450 sk, hdr->id, answers, ptr, len, dns_len);
452 err = sendto(sk, ptr, len, MSG_NOSIGNAL, to, tolen);
454 connman_error("Cannot send cached DNS response: %s",
459 if (err != len || (dns_len != (len - 2) && protocol == IPPROTO_TCP) ||
460 (dns_len != len && protocol == IPPROTO_UDP))
461 DBG("Packet length mismatch, sent %d wanted %d dns %d",
465 static void send_response(int sk, unsigned char *buf, int len,
466 const struct sockaddr *to, socklen_t tolen,
469 struct domain_hdr *hdr;
470 int err, offset = protocol_offset(protocol);
480 hdr = (void *) (buf + offset);
482 DBG("id 0x%04x qr %d opcode %d", hdr->id, hdr->qr, hdr->opcode);
491 err = sendto(sk, buf, len, MSG_NOSIGNAL, to, tolen);
493 connman_error("Failed to send DNS response to %d: %s",
494 sk, strerror(errno));
499 static int get_req_udp_socket(struct request_data *req)
503 if (req->family == AF_INET)
504 channel = req->ifdata->udp4_listener_channel;
506 channel = req->ifdata->udp6_listener_channel;
511 return g_io_channel_unix_get_fd(channel);
514 static void destroy_request_data(struct request_data *req)
516 if (req->timeout > 0)
517 g_source_remove(req->timeout);
520 g_free(req->request);
525 static gboolean request_timeout(gpointer user_data)
527 struct request_data *req = user_data;
532 DBG("id 0x%04x", req->srcid);
534 request_list = g_slist_remove(request_list, req);
537 if (req->resplen > 0 && req->resp != NULL) {
540 if (req->protocol == IPPROTO_UDP) {
541 sk = get_req_udp_socket(req);
545 err = sendto(sk, req->resp, req->resplen, MSG_NOSIGNAL,
546 &req->sa, req->sa_len);
549 err = send(sk, req->resp, req->resplen, MSG_NOSIGNAL);
555 } else if (req->request && req->numserv == 0) {
556 struct domain_hdr *hdr;
558 if (req->protocol == IPPROTO_TCP) {
559 hdr = (void *) (req->request + 2);
560 hdr->id = req->srcid;
561 send_response(req->client_sk, req->request,
562 req->request_len, NULL, 0, IPPROTO_TCP);
564 } else if (req->protocol == IPPROTO_UDP) {
567 hdr = (void *) (req->request);
568 hdr->id = req->srcid;
570 sk = get_req_udp_socket(req);
572 send_response(sk, req->request,
573 req->request_len, &req->sa,
574 req->sa_len, IPPROTO_UDP);
579 * We cannot leave TCP client hanging so just kick it out
580 * if we get a request timeout from server.
582 if (req->protocol == IPPROTO_TCP) {
583 DBG("client %d removed", req->client_sk);
584 g_hash_table_remove(partial_tcp_req_table,
585 GINT_TO_POINTER(req->client_sk));
589 destroy_request_data(req);
594 static int append_query(unsigned char *buf, unsigned int size,
595 const char *query, const char *domain)
597 unsigned char *ptr = buf;
600 DBG("query %s domain %s", query, domain);
602 while (query != NULL) {
605 tmp = strchr(query, '.');
611 memcpy(ptr + 1, query, len);
617 memcpy(ptr + 1, query, tmp - query);
618 ptr += tmp - query + 1;
623 while (domain != NULL) {
626 tmp = strchr(domain, '.');
628 len = strlen(domain);
632 memcpy(ptr + 1, domain, len);
638 memcpy(ptr + 1, domain, tmp - domain);
639 ptr += tmp - domain + 1;
649 static gboolean cache_check_is_valid(struct cache_data *data,
655 if (data->cache_until < current_time)
662 * remove stale cached entries so that they can be refreshed
664 static void cache_enforce_validity(struct cache_entry *entry)
666 time_t current_time = time(NULL);
668 if (cache_check_is_valid(entry->ipv4, current_time) == FALSE
670 DBG("cache timeout \"%s\" type A", entry->key);
671 g_free(entry->ipv4->data);
677 if (cache_check_is_valid(entry->ipv6, current_time) == FALSE
679 DBG("cache timeout \"%s\" type AAAA", entry->key);
680 g_free(entry->ipv6->data);
686 static uint16_t cache_check_validity(char *question, uint16_t type,
687 struct cache_entry *entry)
689 time_t current_time = time(NULL);
690 int want_refresh = 0;
693 * if we have a popular entry, we want a refresh instead of
694 * total destruction of the entry.
699 cache_enforce_validity(entry);
703 if (cache_check_is_valid(entry->ipv4, current_time) == FALSE) {
704 DBG("cache %s \"%s\" type A", entry->ipv4 ?
705 "timeout" : "entry missing", question);
708 entry->want_refresh = 1;
711 * We do not remove cache entry if there is still
712 * valid IPv6 entry found in the cache.
714 if (cache_check_is_valid(entry->ipv6, current_time)
715 == FALSE && want_refresh == FALSE) {
716 g_hash_table_remove(cache, question);
723 if (cache_check_is_valid(entry->ipv6, current_time) == FALSE) {
724 DBG("cache %s \"%s\" type AAAA", entry->ipv6 ?
725 "timeout" : "entry missing", question);
728 entry->want_refresh = 1;
730 if (cache_check_is_valid(entry->ipv4, current_time)
731 == FALSE && want_refresh == FALSE) {
732 g_hash_table_remove(cache, question);
742 static void cache_element_destroy(gpointer value)
744 struct cache_entry *entry = value;
749 if (entry->ipv4 != NULL) {
750 g_free(entry->ipv4->data);
754 if (entry->ipv6 != NULL) {
755 g_free(entry->ipv6->data);
762 if (--cache_size < 0)
766 static gboolean try_remove_cache(gpointer user_data)
768 if (__sync_fetch_and_sub(&cache_refcount, 1) == 1) {
769 DBG("No cache users, removing it.");
771 g_hash_table_destroy(cache);
778 static void create_cache()
780 if (__sync_fetch_and_add(&cache_refcount, 1) == 0)
781 cache = g_hash_table_new_full(g_str_hash,
784 cache_element_destroy);
787 static struct cache_entry *cache_check(gpointer request, int *qtype, int proto)
790 struct cache_entry *entry;
791 struct domain_question *q;
793 int offset, proto_offset;
798 proto_offset = protocol_offset(proto);
799 if (proto_offset < 0)
802 question = request + proto_offset + 12;
804 offset = strlen(question) + 1;
805 q = (void *) (question + offset);
806 type = ntohs(q->type);
808 /* We only cache either A (1) or AAAA (28) requests */
809 if (type != 1 && type != 28)
817 entry = g_hash_table_lookup(cache, question);
821 type = cache_check_validity(question, type, entry);
830 * Get a label/name from DNS resource record. The function decompresses the
831 * label if necessary. The function does not convert the name to presentation
832 * form. This means that the result string will contain label lengths instead
833 * of dots between labels. We intentionally do not want to convert to dotted
834 * format so that we can cache the wire format string directly.
836 static int get_name(int counter,
837 unsigned char *pkt, unsigned char *start, unsigned char *max,
838 unsigned char *output, int output_max, int *output_len,
839 unsigned char **end, char *name, int *name_len)
843 /* Limit recursion to 10 (this means up to 10 labels in domain name) */
849 if ((*p & NS_CMPRSFLGS) == NS_CMPRSFLGS) {
850 uint16_t offset = (*p & 0x3F) * 256 + *(p + 1);
852 if (offset >= max - pkt)
858 return get_name(counter + 1, pkt, pkt + offset, max,
859 output, output_max, output_len, end,
862 unsigned label_len = *p;
864 if (pkt + label_len > max)
867 if (*output_len > output_max)
871 * We need the original name in order to check
872 * if this answer is the correct one.
874 name[(*name_len)++] = label_len;
875 memcpy(name + *name_len, p + 1, label_len + 1);
876 *name_len += label_len;
878 /* We compress the result */
879 output[0] = NS_CMPRSFLGS;
896 static int parse_rr(unsigned char *buf, unsigned char *start,
898 unsigned char *response, unsigned int *response_size,
899 uint16_t *type, uint16_t *class, int *ttl, int *rdlen,
903 struct domain_rr *rr;
905 int name_len = 0, output_len = 0, max_rsp = *response_size;
907 err = get_name(0, buf, start, max, response, max_rsp,
908 &output_len, end, name, &name_len);
914 if ((unsigned int) offset > *response_size)
917 rr = (void *) (*end);
922 *type = ntohs(rr->type);
923 *class = ntohs(rr->class);
924 *ttl = ntohl(rr->ttl);
925 *rdlen = ntohs(rr->rdlen);
930 memcpy(response + offset, *end, sizeof(struct domain_rr));
932 offset += sizeof(struct domain_rr);
933 *end += sizeof(struct domain_rr);
935 if ((unsigned int) (offset + *rdlen) > *response_size)
938 memcpy(response + offset, *end, *rdlen);
942 *response_size = offset + *rdlen;
947 static gboolean check_alias(GSList *aliases, char *name)
951 if (aliases != NULL) {
952 for (list = aliases; list; list = list->next) {
953 int len = strlen((char *)list->data);
954 if (strncmp((char *)list->data, name, len) == 0)
962 static int parse_response(unsigned char *buf, int buflen,
963 char *question, int qlen,
964 uint16_t *type, uint16_t *class, int *ttl,
965 unsigned char *response, unsigned int *response_len,
968 struct domain_hdr *hdr = (void *) buf;
969 struct domain_question *q;
971 uint16_t qdcount = ntohs(hdr->qdcount);
972 uint16_t ancount = ntohs(hdr->ancount);
974 uint16_t qtype, qclass;
975 unsigned char *next = NULL;
976 unsigned int maxlen = *response_len;
977 GSList *aliases = NULL, *list;
978 char name[NS_MAXDNAME + 1];
983 DBG("qr %d qdcount %d", hdr->qr, qdcount);
985 /* We currently only cache responses where question count is 1 */
986 if (hdr->qr != 1 || qdcount != 1)
989 ptr = buf + sizeof(struct domain_hdr);
991 strncpy(question, (char *) ptr, qlen);
992 qlen = strlen(question);
993 ptr += qlen + 1; /* skip \0 */
996 qtype = ntohs(q->type);
998 /* We cache only A and AAAA records */
999 if (qtype != 1 && qtype != 28)
1002 qclass = ntohs(q->class);
1004 ptr += 2 + 2; /* ptr points now to answers */
1011 * We have a bunch of answers (like A, AAAA, CNAME etc) to
1012 * A or AAAA question. We traverse the answers and parse the
1013 * resource records. Only A and AAAA records are cached, all
1014 * the other records in answers are skipped.
1016 for (i = 0; i < ancount; i++) {
1018 * Get one address at a time to this buffer.
1019 * The max size of the answer is
1020 * 2 (pointer) + 2 (type) + 2 (class) +
1021 * 4 (ttl) + 2 (rdlen) + addr (16 or 4) = 28
1022 * for A or AAAA record.
1023 * For CNAME the size can be bigger.
1025 unsigned char rsp[NS_MAXCDNAME];
1026 unsigned int rsp_len = sizeof(rsp) - 1;
1029 memset(rsp, 0, sizeof(rsp));
1031 ret = parse_rr(buf, ptr, buf + buflen, rsp, &rsp_len,
1032 type, class, ttl, &rdlen, &next, name);
1039 * Now rsp contains compressed or uncompressed resource
1040 * record. Next we check if this record answers the question.
1041 * The name var contains the uncompressed label.
1042 * One tricky bit is the CNAME records as they alias
1043 * the name we might be interested in.
1047 * Go to next answer if the class is not the one we are
1050 if (*class != qclass) {
1057 * Try to resolve aliases also, type is CNAME(5).
1058 * This is important as otherwise the aliased names would not
1059 * be cached at all as the cache would not contain the aliased
1062 * If any CNAME is found in DNS packet, then we cache the alias
1063 * IP address instead of the question (as the server
1064 * said that question has only an alias).
1065 * This means in practice that if e.g., ipv6.google.com is
1066 * queried, DNS server returns CNAME of that name which is
1067 * ipv6.l.google.com. We then cache the address of the CNAME
1068 * but return the question name to client. So the alias
1069 * status of the name is not saved in cache and thus not
1070 * returned to the client. We do not return DNS packets from
1071 * cache to client saying that ipv6.google.com is an alias to
1072 * ipv6.l.google.com but we return instead a DNS packet that
1073 * says ipv6.google.com has address xxx which is in fact the
1074 * address of ipv6.l.google.com. For caching purposes this
1075 * should not cause any issues.
1077 if (*type == 5 && strncmp(question, name, qlen) == 0) {
1079 * So now the alias answered the question. This is
1080 * not very useful from caching point of view as
1081 * the following A or AAAA records will not match the
1082 * question. We need to find the real A/AAAA record
1083 * of the alias and cache that.
1085 unsigned char *end = NULL;
1086 int name_len = 0, output_len;
1088 memset(rsp, 0, sizeof(rsp));
1089 rsp_len = sizeof(rsp) - 1;
1092 * Alias is in rdata part of the message,
1093 * and next-rdlen points to it. So we need to get
1094 * the real name of the alias.
1096 ret = get_name(0, buf, next - rdlen, buf + buflen,
1097 rsp, rsp_len, &output_len, &end,
1100 /* just ignore the error at this point */
1107 * We should now have the alias of the entry we might
1108 * want to cache. Just remember it for a while.
1109 * We check the alias list when we have parsed the
1112 aliases = g_slist_prepend(aliases, g_strdup(name));
1119 if (*type == qtype) {
1121 * We found correct type (A or AAAA)
1123 if (check_alias(aliases, name) == TRUE ||
1124 (aliases == NULL && strncmp(question, name,
1127 * We found an alias or the name of the rr
1128 * matches the question. If so, we append
1129 * the compressed label to the cache.
1130 * The end result is a response buffer that
1131 * will contain one or more cached and
1132 * compressed resource records.
1134 if (*response_len + rsp_len > maxlen) {
1138 memcpy(response + *response_len, rsp, rsp_len);
1139 *response_len += rsp_len;
1150 for (list = aliases; list; list = list->next)
1152 g_slist_free(aliases);
1157 struct cache_timeout {
1158 time_t current_time;
1163 static gboolean cache_check_entry(gpointer key, gpointer value,
1166 struct cache_timeout *data = user_data;
1167 struct cache_entry *entry = value;
1170 /* Scale the number of hits by half as part of cache aging */
1175 * If either IPv4 or IPv6 cached entry has expired, we
1176 * remove both from the cache.
1179 if (entry->ipv4 != NULL && entry->ipv4->timeout > 0) {
1180 max_timeout = entry->ipv4->cache_until;
1181 if (max_timeout > data->max_timeout)
1182 data->max_timeout = max_timeout;
1184 if (entry->ipv4->cache_until < data->current_time)
1188 if (entry->ipv6 != NULL && entry->ipv6->timeout > 0) {
1189 max_timeout = entry->ipv6->cache_until;
1190 if (max_timeout > data->max_timeout)
1191 data->max_timeout = max_timeout;
1193 if (entry->ipv6->cache_until < data->current_time)
1198 * if we're asked to try harder, also remove entries that have
1201 if (data->try_harder && entry->hits < 4)
1207 static void cache_cleanup(void)
1209 static int max_timeout;
1210 struct cache_timeout data;
1213 data.current_time = time(NULL);
1214 data.max_timeout = 0;
1215 data.try_harder = 0;
1218 * In the first pass, we only remove entries that have timed out.
1219 * We use a cache of the first time to expire to do this only
1220 * when it makes sense.
1222 if (max_timeout <= data.current_time) {
1223 count = g_hash_table_foreach_remove(cache, cache_check_entry,
1226 DBG("removed %d in the first pass", count);
1229 * In the second pass, if the first pass turned up blank,
1230 * we also expire entries with a low hit count,
1231 * while aging the hit count at the same time.
1233 data.try_harder = 1;
1235 count = g_hash_table_foreach_remove(cache, cache_check_entry,
1240 * If we could not remove anything, then remember
1241 * what is the max timeout and do nothing if we
1242 * have not yet reached it. This will prevent
1243 * constant traversal of the cache if it is full.
1245 max_timeout = data.max_timeout;
1250 static gboolean cache_invalidate_entry(gpointer key, gpointer value,
1253 struct cache_entry *entry = value;
1255 /* first, delete any expired elements */
1256 cache_enforce_validity(entry);
1258 /* if anything is not expired, mark the entry for refresh */
1259 if (entry->hits > 0 && (entry->ipv4 || entry->ipv6))
1260 entry->want_refresh = 1;
1262 /* delete the cached data */
1264 g_free(entry->ipv4->data);
1265 g_free(entry->ipv4);
1270 g_free(entry->ipv6->data);
1271 g_free(entry->ipv6);
1275 /* keep the entry if we want it refreshed, delete it otherwise */
1276 if (entry->want_refresh)
1283 * cache_invalidate is called from places where the DNS landscape
1284 * has changed, say because connections are added or we entered a VPN.
1285 * The logic is to wipe all cache data, but mark all non-expired
1286 * parts of the cache for refresh rather than deleting the whole cache.
1288 static void cache_invalidate(void)
1290 DBG("Invalidating the DNS cache %p", cache);
1295 g_hash_table_foreach_remove(cache, cache_invalidate_entry, NULL);
1298 static void cache_refresh_entry(struct cache_entry *entry)
1301 cache_enforce_validity(entry);
1303 if (entry->hits > 2 && entry->ipv4 == NULL)
1304 entry->want_refresh = 1;
1305 if (entry->hits > 2 && entry->ipv6 == NULL)
1306 entry->want_refresh = 1;
1308 if (entry->want_refresh) {
1310 char dns_name[NS_MAXDNAME + 1];
1311 entry->want_refresh = 0;
1313 /* turn a DNS name into a hostname with dots */
1314 strncpy(dns_name, entry->key, NS_MAXDNAME);
1322 DBG("Refreshing %s\n", dns_name);
1323 /* then refresh the hostname */
1324 refresh_dns_entry(entry, &dns_name[1]);
1328 static void cache_refresh_iterator(gpointer key, gpointer value,
1331 struct cache_entry *entry = value;
1333 cache_refresh_entry(entry);
1336 static void cache_refresh(void)
1341 g_hash_table_foreach(cache, cache_refresh_iterator, NULL);
1344 static int reply_query_type(unsigned char *msg, int len)
1351 /* skip the header */
1352 c = msg + sizeof(struct domain_hdr);
1353 len -= sizeof(struct domain_hdr);
1358 /* now the query, which is a name and 2 16 bit words */
1359 l = dns_name_length(c) + 1;
1367 static int cache_update(struct server_data *srv, unsigned char *msg,
1368 unsigned int msg_len)
1370 int offset = protocol_offset(srv->protocol);
1371 int err, qlen, ttl = 0;
1372 uint16_t answers = 0, type = 0, class = 0;
1373 struct domain_hdr *hdr = (void *)(msg + offset);
1374 struct domain_question *q;
1375 struct cache_entry *entry;
1376 struct cache_data *data;
1377 char question[NS_MAXDNAME + 1];
1378 unsigned char response[NS_MAXDNAME + 1];
1380 unsigned int rsplen;
1381 gboolean new_entry = TRUE;
1382 time_t current_time;
1384 if (cache_size >= MAX_CACHE_SIZE) {
1386 if (cache_size >= MAX_CACHE_SIZE)
1390 current_time = time(NULL);
1392 /* don't do a cache refresh more than twice a minute */
1393 if (next_refresh < current_time) {
1395 next_refresh = current_time + 30;
1401 DBG("offset %d hdr %p msg %p rcode %d", offset, hdr, msg, hdr->rcode);
1403 /* Continue only if response code is 0 (=ok) */
1404 if (hdr->rcode != 0)
1407 rsplen = sizeof(response) - 1;
1408 question[sizeof(question) - 1] = '\0';
1410 err = parse_response(msg + offset, msg_len - offset,
1411 question, sizeof(question) - 1,
1412 &type, &class, &ttl,
1413 response, &rsplen, &answers);
1416 * special case: if we do a ipv6 lookup and get no result
1417 * for a record that's already in our ipv4 cache.. we want
1418 * to cache the negative response.
1420 if ((err == -ENOMSG || err == -ENOBUFS) &&
1421 reply_query_type(msg + offset,
1422 msg_len - offset) == 28) {
1423 if (cache == NULL) {
1427 entry = g_hash_table_lookup(cache, question);
1428 if (entry && entry->ipv4 && entry->ipv6 == NULL) {
1429 int cache_offset = 0;
1431 data = g_try_new(struct cache_data, 1);
1434 data->inserted = entry->ipv4->inserted;
1436 data->answers = ntohs(hdr->ancount);
1437 data->timeout = entry->ipv4->timeout;
1438 if (srv->protocol == IPPROTO_UDP)
1440 data->data_len = msg_len + cache_offset;
1441 data->data = ptr = g_malloc(data->data_len);
1442 ptr[0] = (data->data_len - 2) / 256;
1443 ptr[1] = (data->data_len - 2) - ptr[0] * 256;
1444 if (srv->protocol == IPPROTO_UDP)
1446 data->valid_until = entry->ipv4->valid_until;
1447 data->cache_until = entry->ipv4->cache_until;
1448 memcpy(ptr, msg, msg_len);
1451 * we will get a "hit" when we serve the response
1455 if (entry->hits < 0)
1461 if (err < 0 || ttl == 0)
1464 qlen = strlen(question);
1467 * If the cache contains already data, check if the
1468 * type of the cached data is the same and do not add
1469 * to cache if data is already there.
1470 * This is needed so that we can cache both A and AAAA
1471 * records for the same name.
1473 entry = g_hash_table_lookup(cache, question);
1474 if (entry == NULL) {
1475 entry = g_try_new(struct cache_entry, 1);
1479 data = g_try_new(struct cache_data, 1);
1485 entry->key = g_strdup(question);
1486 entry->ipv4 = entry->ipv6 = NULL;
1487 entry->want_refresh = 0;
1495 if (type == 1 && entry->ipv4 != NULL)
1498 if (type == 28 && entry->ipv6 != NULL)
1501 data = g_try_new(struct cache_data, 1);
1511 * compensate for the hit we'll get for serving
1512 * the response out of the cache
1515 if (entry->hits < 0)
1521 if (ttl < MIN_CACHE_TTL)
1522 ttl = MIN_CACHE_TTL;
1524 data->inserted = current_time;
1526 data->answers = answers;
1527 data->timeout = ttl;
1529 * The "2" in start of the length is the TCP offset. We allocate it
1530 * here even for UDP packet because it simplifies the sending
1533 data->data_len = 2 + 12 + qlen + 1 + 2 + 2 + rsplen;
1534 data->data = ptr = g_malloc(data->data_len);
1535 data->valid_until = current_time + ttl;
1538 * Restrict the cached DNS record TTL to some sane value
1539 * in order to prevent data staying in the cache too long.
1541 if (ttl > MAX_CACHE_TTL)
1542 ttl = MAX_CACHE_TTL;
1544 data->cache_until = round_down_ttl(current_time + ttl, ttl);
1546 if (data->data == NULL) {
1554 * We cache the two extra bytes at the start of the message
1555 * in a TCP packet. When sending UDP packet, we skip the first
1556 * two bytes. This way we do not need to know the format
1557 * (UDP/TCP) of the cached message.
1559 ptr[0] = (data->data_len - 2) / 256;
1560 ptr[1] = (data->data_len - 2) - ptr[0] * 256;
1561 if (srv->protocol == IPPROTO_UDP)
1564 memcpy(ptr, msg, offset + 12);
1565 memcpy(ptr + offset + 12, question, qlen + 1); /* copy also the \0 */
1567 q = (void *) (ptr + offset + 12 + qlen + 1);
1568 q->type = htons(type);
1569 q->class = htons(class);
1570 memcpy(ptr + offset + 12 + qlen + 1 + sizeof(struct domain_question),
1573 if (new_entry == TRUE) {
1574 g_hash_table_replace(cache, entry->key, entry);
1578 DBG("cache %d %squestion \"%s\" type %d ttl %d size %zd packet %u "
1580 cache_size, new_entry ? "new " : "old ",
1581 question, type, ttl,
1582 sizeof(*entry) + sizeof(*data) + data->data_len + qlen,
1584 srv->protocol == IPPROTO_TCP ?
1585 (unsigned int)(data->data[0] * 256 + data->data[1]) :
1591 static int ns_resolv(struct server_data *server, struct request_data *req,
1592 gpointer request, gpointer name)
1595 int sk, err, type = 0;
1596 char *dot, *lookup = (char *) name;
1597 struct cache_entry *entry;
1599 entry = cache_check(request, &type, req->protocol);
1600 if (entry != NULL) {
1602 struct cache_data *data;
1604 DBG("cache hit %s type %s", lookup, type == 1 ? "A" : "AAAA");
1611 ttl_left = data->valid_until - time(NULL);
1615 if (data != NULL && req->protocol == IPPROTO_TCP) {
1616 send_cached_response(req->client_sk, data->data,
1617 data->data_len, NULL, 0, IPPROTO_TCP,
1618 req->srcid, data->answers, ttl_left);
1622 if (data != NULL && req->protocol == IPPROTO_UDP) {
1623 int udp_sk = get_req_udp_socket(req);
1625 send_cached_response(udp_sk, data->data,
1626 data->data_len, &req->sa, req->sa_len,
1627 IPPROTO_UDP, req->srcid, data->answers,
1633 sk = g_io_channel_unix_get_fd(server->channel);
1635 err = sendto(sk, request, req->request_len, MSG_NOSIGNAL,
1636 server->server_addr, server->server_addr_len);
1638 DBG("Cannot send message to server %s sock %d "
1639 "protocol %d (%s/%d)",
1640 server->server, sk, server->protocol,
1641 strerror(errno), errno);
1647 /* If we have more than one dot, we don't add domains */
1648 dot = strchr(lookup, '.');
1649 if (dot != NULL && dot != lookup + strlen(lookup) - 1)
1652 if (server->domains != NULL && server->domains->data != NULL)
1653 req->append_domain = TRUE;
1655 for (list = server->domains; list; list = list->next) {
1657 unsigned char alt[1024];
1658 struct domain_hdr *hdr = (void *) &alt;
1659 int altlen, domlen, offset;
1661 domain = list->data;
1666 offset = protocol_offset(server->protocol);
1670 domlen = strlen(domain) + 1;
1674 alt[offset] = req->altid & 0xff;
1675 alt[offset + 1] = req->altid >> 8;
1677 memcpy(alt + offset + 2, request + offset + 2, 10);
1678 hdr->qdcount = htons(1);
1680 altlen = append_query(alt + offset + 12, sizeof(alt) - 12,
1687 memcpy(alt + offset + altlen,
1688 request + offset + altlen - domlen,
1689 req->request_len - altlen - offset + domlen);
1691 if (server->protocol == IPPROTO_TCP) {
1692 int req_len = req->request_len + domlen - 2;
1694 alt[0] = (req_len >> 8) & 0xff;
1695 alt[1] = req_len & 0xff;
1698 DBG("req %p dstid 0x%04x altid 0x%04x", req, req->dstid,
1701 err = send(sk, alt, req->request_len + domlen, MSG_NOSIGNAL);
1711 static int forward_dns_reply(unsigned char *reply, int reply_len, int protocol,
1712 struct server_data *data)
1714 struct domain_hdr *hdr;
1715 struct request_data *req;
1716 int dns_id, sk, err, offset = protocol_offset(protocol);
1721 hdr = (void *)(reply + offset);
1722 dns_id = reply[offset] | reply[offset + 1] << 8;
1724 DBG("Received %d bytes (id 0x%04x)", reply_len, dns_id);
1726 req = find_request(dns_id);
1730 DBG("req %p dstid 0x%04x altid 0x%04x rcode %d",
1731 req, req->dstid, req->altid, hdr->rcode);
1733 reply[offset] = req->srcid & 0xff;
1734 reply[offset + 1] = req->srcid >> 8;
1738 if (hdr->rcode == 0 || req->resp == NULL) {
1741 * If the domain name was append
1742 * remove it before forwarding the reply.
1744 if (req->append_domain == TRUE) {
1745 unsigned int domain_len = 0;
1748 unsigned int header_len;
1751 * ptr points to the first char of the hostname.
1752 * ->hostname.domain.net
1754 header_len = offset + sizeof(struct domain_hdr);
1755 ptr = reply + header_len;
1758 domain_len = strnlen((const char *)ptr + 1 +
1760 reply_len - header_len);
1763 DBG("host len %d domain len %d", host_len, domain_len);
1766 * Remove the domain name and replace it by the end
1767 * of reply. Check if the domain is really there
1768 * before trying to copy the data. The domain_len can
1769 * be 0 because if the original query did not contain
1770 * a domain name, then we are sending two packets,
1771 * first without the domain name and the second packet
1772 * with domain name. The append_domain is set to true
1773 * even if we sent the first packet without domain
1774 * name. In this case we end up in this branch.
1776 if (domain_len > 0) {
1778 * Note that we must use memmove() here,
1779 * because the memory areas can overlap.
1781 memmove(ptr + host_len + 1,
1782 ptr + host_len + domain_len + 1,
1783 reply_len - header_len - domain_len);
1785 reply_len = reply_len - domain_len;
1792 req->resp = g_try_malloc(reply_len);
1793 if (req->resp == NULL)
1796 memcpy(req->resp, reply, reply_len);
1797 req->resplen = reply_len;
1799 cache_update(data, reply, reply_len);
1802 if (hdr->rcode > 0 && req->numresp < req->numserv)
1805 request_list = g_slist_remove(request_list, req);
1807 if (protocol == IPPROTO_UDP) {
1808 sk = get_req_udp_socket(req);
1809 err = sendto(sk, req->resp, req->resplen, 0,
1810 &req->sa, req->sa_len);
1812 sk = req->client_sk;
1813 err = send(sk, req->resp, req->resplen, MSG_NOSIGNAL);
1817 DBG("Cannot send msg, sk %d proto %d errno %d/%s", sk,
1818 protocol, errno, strerror(errno));
1820 DBG("proto %d sent %d bytes to %d", protocol, err, sk);
1822 destroy_request_data(req);
1827 static void server_destroy_socket(struct server_data *data)
1829 DBG("index %d server %s proto %d", data->index,
1830 data->server, data->protocol);
1832 if (data->watch > 0) {
1833 g_source_remove(data->watch);
1837 if (data->timeout > 0) {
1838 g_source_remove(data->timeout);
1842 if (data->channel != NULL) {
1843 g_io_channel_shutdown(data->channel, TRUE, NULL);
1844 g_io_channel_unref(data->channel);
1845 data->channel = NULL;
1848 g_free(data->incoming_reply);
1849 data->incoming_reply = NULL;
1852 static void destroy_server(struct server_data *server)
1856 DBG("index %d server %s sock %d", server->index, server->server,
1857 server->channel != NULL ?
1858 g_io_channel_unix_get_fd(server->channel): -1);
1860 server_list = g_slist_remove(server_list, server);
1861 server_destroy_socket(server);
1863 if (server->protocol == IPPROTO_UDP && server->enabled)
1864 DBG("Removing DNS server %s", server->server);
1866 g_free(server->server);
1867 for (list = server->domains; list; list = list->next) {
1868 char *domain = list->data;
1870 server->domains = g_list_remove(server->domains, domain);
1873 g_free(server->server_addr);
1876 * We do not remove cache right away but delay it few seconds.
1877 * The idea is that when IPv6 DNS server is added via RDNSS, it has a
1878 * lifetime. When the lifetime expires we decrease the refcount so it
1879 * is possible that the cache is then removed. Because a new DNS server
1880 * is usually created almost immediately we would then loose the cache
1881 * without any good reason. The small delay allows the new RDNSS to
1882 * create a new DNS server instance and the refcount does not go to 0.
1884 g_timeout_add_seconds(3, try_remove_cache, NULL);
1889 static gboolean udp_server_event(GIOChannel *channel, GIOCondition condition,
1892 unsigned char buf[4096];
1894 struct server_data *data = user_data;
1896 if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
1897 connman_error("Error with UDP server %s", data->server);
1898 server_destroy_socket(data);
1902 sk = g_io_channel_unix_get_fd(channel);
1904 len = recv(sk, buf, sizeof(buf), 0);
1908 err = forward_dns_reply(buf, len, IPPROTO_UDP, data);
1915 static gboolean tcp_server_event(GIOChannel *channel, GIOCondition condition,
1919 struct server_data *server = user_data;
1921 sk = g_io_channel_unix_get_fd(channel);
1925 if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
1928 DBG("TCP server channel closed, sk %d", sk);
1931 * Discard any partial response which is buffered; better
1932 * to get a proper response from a working server.
1934 g_free(server->incoming_reply);
1935 server->incoming_reply = NULL;
1937 for (list = request_list; list; list = list->next) {
1938 struct request_data *req = list->data;
1939 struct domain_hdr *hdr;
1941 if (req->protocol == IPPROTO_UDP)
1944 if (req->request == NULL)
1948 * If we're not waiting for any further response
1949 * from another name server, then we send an error
1950 * response to the client.
1952 if (req->numserv && --(req->numserv))
1955 hdr = (void *) (req->request + 2);
1956 hdr->id = req->srcid;
1957 send_response(req->client_sk, req->request,
1958 req->request_len, NULL, 0, IPPROTO_TCP);
1960 request_list = g_slist_remove(request_list, req);
1963 destroy_server(server);
1968 if ((condition & G_IO_OUT) && !server->connected) {
1971 int no_request_sent = TRUE;
1972 struct server_data *udp_server;
1974 udp_server = find_server(server->index, server->server,
1976 if (udp_server != NULL) {
1977 for (domains = udp_server->domains; domains;
1978 domains = domains->next) {
1979 char *dom = domains->data;
1981 DBG("Adding domain %s to %s",
1982 dom, server->server);
1984 server->domains = g_list_append(server->domains,
1989 server->connected = TRUE;
1990 server_list = g_slist_append(server_list, server);
1992 if (server->timeout > 0) {
1993 g_source_remove(server->timeout);
1994 server->timeout = 0;
1997 for (list = request_list; list; ) {
1998 struct request_data *req = list->data;
2001 if (req->protocol == IPPROTO_UDP) {
2006 DBG("Sending req %s over TCP", (char *)req->name);
2008 status = ns_resolv(server, req,
2009 req->request, req->name);
2012 * A cached result was sent,
2013 * so the request can be released
2016 request_list = g_slist_remove(request_list, req);
2017 destroy_request_data(req);
2026 no_request_sent = FALSE;
2028 if (req->timeout > 0)
2029 g_source_remove(req->timeout);
2031 req->timeout = g_timeout_add_seconds(30,
2032 request_timeout, req);
2036 if (no_request_sent == TRUE) {
2037 destroy_server(server);
2041 } else if (condition & G_IO_IN) {
2042 struct partial_reply *reply = server->incoming_reply;
2046 unsigned char reply_len_buf[2];
2049 bytes_recv = recv(sk, reply_len_buf, 2, MSG_PEEK);
2052 } else if (bytes_recv < 0) {
2053 if (errno == EAGAIN || errno == EWOULDBLOCK)
2056 connman_error("DNS proxy error %s",
2059 } else if (bytes_recv < 2)
2062 reply_len = reply_len_buf[1] | reply_len_buf[0] << 8;
2065 DBG("TCP reply %d bytes from %d", reply_len, sk);
2067 reply = g_try_malloc(sizeof(*reply) + reply_len + 2);
2071 reply->len = reply_len;
2072 reply->received = 0;
2074 server->incoming_reply = reply;
2077 while (reply->received < reply->len) {
2078 bytes_recv = recv(sk, reply->buf + reply->received,
2079 reply->len - reply->received, 0);
2081 connman_error("DNS proxy TCP disconnect");
2083 } else if (bytes_recv < 0) {
2084 if (errno == EAGAIN || errno == EWOULDBLOCK)
2087 connman_error("DNS proxy error %s",
2091 reply->received += bytes_recv;
2094 forward_dns_reply(reply->buf, reply->received, IPPROTO_TCP,
2098 server->incoming_reply = NULL;
2100 destroy_server(server);
2108 static gboolean tcp_idle_timeout(gpointer user_data)
2110 struct server_data *server = user_data;
2117 destroy_server(server);
2122 static int server_create_socket(struct server_data *data)
2127 DBG("index %d server %s proto %d", data->index,
2128 data->server, data->protocol);
2130 sk = socket(data->server_addr->sa_family,
2131 data->protocol == IPPROTO_TCP ? SOCK_STREAM : SOCK_DGRAM,
2135 connman_error("Failed to create server %s socket",
2137 server_destroy_socket(data);
2143 interface = connman_inet_ifname(data->index);
2144 if (interface != NULL) {
2145 if (setsockopt(sk, SOL_SOCKET, SO_BINDTODEVICE,
2147 strlen(interface) + 1) < 0) {
2149 connman_error("Failed to bind server %s "
2151 data->server, interface);
2153 server_destroy_socket(data);
2160 data->channel = g_io_channel_unix_new(sk);
2161 if (data->channel == NULL) {
2162 connman_error("Failed to create server %s channel",
2165 server_destroy_socket(data);
2169 g_io_channel_set_close_on_unref(data->channel, TRUE);
2171 if (data->protocol == IPPROTO_TCP) {
2172 g_io_channel_set_flags(data->channel, G_IO_FLAG_NONBLOCK, NULL);
2173 data->watch = g_io_add_watch(data->channel,
2174 G_IO_OUT | G_IO_IN | G_IO_HUP | G_IO_NVAL | G_IO_ERR,
2175 tcp_server_event, data);
2176 data->timeout = g_timeout_add_seconds(30, tcp_idle_timeout,
2179 data->watch = g_io_add_watch(data->channel,
2180 G_IO_IN | G_IO_NVAL | G_IO_ERR | G_IO_HUP,
2181 udp_server_event, data);
2183 if (connect(sk, data->server_addr, data->server_addr_len) < 0) {
2186 if ((data->protocol == IPPROTO_TCP && errno != EINPROGRESS) ||
2187 data->protocol == IPPROTO_UDP) {
2189 connman_error("Failed to connect to server %s",
2191 server_destroy_socket(data);
2201 static struct server_data *create_server(int index,
2202 const char *domain, const char *server,
2205 struct server_data *data;
2206 struct addrinfo hints, *rp;
2209 DBG("index %d server %s", index, server);
2211 data = g_try_new0(struct server_data, 1);
2213 connman_error("Failed to allocate server %s data", server);
2217 data->index = index;
2219 data->domains = g_list_append(data->domains, g_strdup(domain));
2220 data->server = g_strdup(server);
2221 data->protocol = protocol;
2223 memset(&hints, 0, sizeof(hints));
2227 hints.ai_socktype = SOCK_DGRAM;
2231 hints.ai_socktype = SOCK_STREAM;
2235 destroy_server(data);
2238 hints.ai_family = AF_UNSPEC;
2239 hints.ai_flags = AI_NUMERICSERV | AI_NUMERICHOST;
2241 ret = getaddrinfo(data->server, "53", &hints, &rp);
2243 connman_error("Failed to parse server %s address: %s\n",
2244 data->server, gai_strerror(ret));
2245 destroy_server(data);
2249 /* Do not blindly copy this code elsewhere; it doesn't loop over the
2250 results using ->ai_next as it should. That's OK in *this* case
2251 because it was a numeric lookup; we *know* there's only one. */
2253 data->server_addr_len = rp->ai_addrlen;
2255 switch (rp->ai_family) {
2257 data->server_addr = (struct sockaddr *)
2258 g_try_new0(struct sockaddr_in, 1);
2261 data->server_addr = (struct sockaddr *)
2262 g_try_new0(struct sockaddr_in6, 1);
2265 connman_error("Wrong address family %d", rp->ai_family);
2268 if (data->server_addr == NULL) {
2270 destroy_server(data);
2273 memcpy(data->server_addr, rp->ai_addr, rp->ai_addrlen);
2276 if (server_create_socket(data) != 0) {
2277 destroy_server(data);
2281 if (protocol == IPPROTO_UDP) {
2282 /* Enable new servers by default */
2283 data->enabled = TRUE;
2284 DBG("Adding DNS server %s", data->server);
2286 server_list = g_slist_append(server_list, data);
2292 static gboolean resolv(struct request_data *req,
2293 gpointer request, gpointer name)
2297 for (list = server_list; list; list = list->next) {
2298 struct server_data *data = list->data;
2300 if (data->protocol == IPPROTO_TCP) {
2301 DBG("server %s ignored proto TCP", data->server);
2305 DBG("server %s enabled %d", data->server, data->enabled);
2307 if (data->enabled == FALSE)
2310 if (data->channel == NULL && data->protocol == IPPROTO_UDP) {
2311 if (server_create_socket(data) < 0) {
2312 DBG("socket creation failed while resolving");
2317 if (ns_resolv(data, req, request, name) > 0)
2324 static void append_domain(int index, const char *domain)
2328 DBG("index %d domain %s", index, domain);
2333 for (list = server_list; list; list = list->next) {
2334 struct server_data *data = list->data;
2337 gboolean dom_found = FALSE;
2339 if (data->index < 0)
2342 if (data->index != index)
2345 for (dom_list = data->domains; dom_list;
2346 dom_list = dom_list->next) {
2347 dom = dom_list->data;
2349 if (g_str_equal(dom, domain)) {
2355 if (dom_found == FALSE) {
2357 g_list_append(data->domains, g_strdup(domain));
2362 int __connman_dnsproxy_append(int index, const char *domain,
2365 struct server_data *data;
2367 DBG("index %d server %s", index, server);
2369 if (server == NULL && domain == NULL)
2372 if (server == NULL) {
2373 append_domain(index, domain);
2378 if (g_str_equal(server, "127.0.0.1") == TRUE)
2381 if (g_str_equal(server, "::1") == TRUE)
2384 data = find_server(index, server, IPPROTO_UDP);
2386 append_domain(index, domain);
2390 data = create_server(index, domain, server, IPPROTO_UDP);
2397 static void remove_server(int index, const char *domain,
2398 const char *server, int protocol)
2400 struct server_data *data;
2402 data = find_server(index, server, protocol);
2406 destroy_server(data);
2409 int __connman_dnsproxy_remove(int index, const char *domain,
2412 DBG("index %d server %s", index, server);
2417 if (g_str_equal(server, "127.0.0.1") == TRUE)
2420 if (g_str_equal(server, "::1") == TRUE)
2423 remove_server(index, domain, server, IPPROTO_UDP);
2424 remove_server(index, domain, server, IPPROTO_TCP);
2429 void __connman_dnsproxy_flush(void)
2433 list = request_list;
2435 struct request_data *req = list->data;
2439 if (resolv(req, req->request, req->name) == TRUE) {
2441 * A cached result was sent,
2442 * so the request can be released
2445 g_slist_remove(request_list, req);
2446 destroy_request_data(req);
2450 if (req->timeout > 0)
2451 g_source_remove(req->timeout);
2452 req->timeout = g_timeout_add_seconds(5, request_timeout, req);
2456 static void dnsproxy_offline_mode(connman_bool_t enabled)
2460 DBG("enabled %d", enabled);
2462 for (list = server_list; list; list = list->next) {
2463 struct server_data *data = list->data;
2465 if (enabled == FALSE) {
2466 DBG("Enabling DNS server %s", data->server);
2467 data->enabled = TRUE;
2471 DBG("Disabling DNS server %s", data->server);
2472 data->enabled = FALSE;
2478 static void dnsproxy_default_changed(struct connman_service *service)
2483 DBG("service %p", service);
2485 /* DNS has changed, invalidate the cache */
2488 if (service == NULL) {
2489 /* When no services are active, then disable DNS proxying */
2490 dnsproxy_offline_mode(TRUE);
2494 index = __connman_service_get_index(service);
2498 for (list = server_list; list; list = list->next) {
2499 struct server_data *data = list->data;
2501 if (data->index == index) {
2502 DBG("Enabling DNS server %s", data->server);
2503 data->enabled = TRUE;
2505 DBG("Disabling DNS server %s", data->server);
2506 data->enabled = FALSE;
2513 static struct connman_notifier dnsproxy_notifier = {
2515 .default_changed = dnsproxy_default_changed,
2516 .offline_mode = dnsproxy_offline_mode,
2519 static unsigned char opt_edns0_type[2] = { 0x00, 0x29 };
2521 static int parse_request(unsigned char *buf, int len,
2522 char *name, unsigned int size)
2524 struct domain_hdr *hdr = (void *) buf;
2525 uint16_t qdcount = ntohs(hdr->qdcount);
2526 uint16_t arcount = ntohs(hdr->arcount);
2528 char *last_label = NULL;
2529 unsigned int remain, used = 0;
2534 DBG("id 0x%04x qr %d opcode %d qdcount %d arcount %d",
2535 hdr->id, hdr->qr, hdr->opcode,
2538 if (hdr->qr != 0 || qdcount != 1)
2543 ptr = buf + sizeof(struct domain_hdr);
2544 remain = len - sizeof(struct domain_hdr);
2546 while (remain > 0) {
2547 uint8_t label_len = *ptr;
2549 if (label_len == 0x00) {
2550 last_label = (char *) (ptr + 1);
2554 if (used + label_len + 1 > size)
2557 strncat(name, (char *) (ptr + 1), label_len);
2560 used += label_len + 1;
2562 ptr += label_len + 1;
2563 remain -= label_len + 1;
2566 if (last_label && arcount && remain >= 9 && last_label[4] == 0 &&
2567 !memcmp(last_label + 5, opt_edns0_type, 2)) {
2568 uint16_t edns0_bufsize;
2570 edns0_bufsize = last_label[7] << 8 | last_label[8];
2572 DBG("EDNS0 buffer size %u", edns0_bufsize);
2574 /* This is an evil hack until full TCP support has been
2577 * Somtimes the EDNS0 request gets send with a too-small
2578 * buffer size. Since glibc doesn't seem to crash when it
2579 * gets a response biffer then it requested, just bump
2580 * the buffer size up to 4KiB.
2582 if (edns0_bufsize < 0x1000) {
2583 last_label[7] = 0x10;
2584 last_label[8] = 0x00;
2588 DBG("query %s", name);
2593 static void client_reset(struct tcp_partial_client_data *client)
2598 if (client->channel != NULL) {
2599 DBG("client %d closing",
2600 g_io_channel_unix_get_fd(client->channel));
2602 g_io_channel_unref(client->channel);
2603 client->channel = NULL;
2606 if (client->watch > 0) {
2607 g_source_remove(client->watch);
2611 if (client->timeout > 0) {
2612 g_source_remove(client->timeout);
2613 client->timeout = 0;
2616 g_free(client->buf);
2619 client->buf_end = 0;
2622 static unsigned int get_msg_len(unsigned char *buf)
2624 return buf[0]<<8 | buf[1];
2627 static gboolean read_tcp_data(struct tcp_partial_client_data *client,
2628 void *client_addr, socklen_t client_addr_len,
2631 char query[TCP_MAX_BUF_LEN];
2632 struct request_data *req;
2634 unsigned int msg_len;
2636 int waiting_for_connect = FALSE, qtype = 0;
2637 struct cache_entry *entry;
2639 client_sk = g_io_channel_unix_get_fd(client->channel);
2641 if (read_len == 0) {
2642 DBG("client %d closed, pending %d bytes",
2643 client_sk, client->buf_end);
2644 g_hash_table_remove(partial_tcp_req_table,
2645 GINT_TO_POINTER(client_sk));
2649 DBG("client %d received %d bytes", client_sk, read_len);
2651 client->buf_end += read_len;
2653 if (client->buf_end < 2)
2656 msg_len = get_msg_len(client->buf);
2657 if (msg_len > TCP_MAX_BUF_LEN) {
2658 DBG("client %d sent too much data %d", client_sk, msg_len);
2659 g_hash_table_remove(partial_tcp_req_table,
2660 GINT_TO_POINTER(client_sk));
2665 DBG("client %d msg len %d end %d past end %d", client_sk, msg_len,
2666 client->buf_end, client->buf_end - (msg_len + 2));
2668 if (client->buf_end < (msg_len + 2)) {
2669 DBG("client %d still missing %d bytes",
2671 msg_len + 2 - client->buf_end);
2675 DBG("client %d all data %d received", client_sk, msg_len);
2677 err = parse_request(client->buf + 2, msg_len,
2678 query, sizeof(query));
2679 if (err < 0 || (g_slist_length(server_list) == 0)) {
2680 send_response(client_sk, client->buf, msg_len + 2,
2681 NULL, 0, IPPROTO_TCP);
2685 req = g_try_new0(struct request_data, 1);
2689 memcpy(&req->sa, client_addr, client_addr_len);
2690 req->sa_len = client_addr_len;
2691 req->client_sk = client_sk;
2692 req->protocol = IPPROTO_TCP;
2693 req->family = client->family;
2695 req->srcid = client->buf[2] | (client->buf[3] << 8);
2696 req->dstid = get_id();
2697 req->altid = get_id();
2698 req->request_len = msg_len + 2;
2700 client->buf[2] = req->dstid & 0xff;
2701 client->buf[3] = req->dstid >> 8;
2704 req->ifdata = client->ifdata;
2705 req->append_domain = FALSE;
2708 * Check if the answer is found in the cache before
2709 * creating sockets to the server.
2711 entry = cache_check(client->buf, &qtype, IPPROTO_TCP);
2712 if (entry != NULL) {
2714 struct cache_data *data;
2716 DBG("cache hit %s type %s", query, qtype == 1 ? "A" : "AAAA");
2723 ttl_left = data->valid_until - time(NULL);
2726 send_cached_response(client_sk, data->data,
2727 data->data_len, NULL, 0, IPPROTO_TCP,
2728 req->srcid, data->answers, ttl_left);
2733 DBG("data missing, ignoring cache for this query");
2736 for (list = server_list; list; list = list->next) {
2737 struct server_data *data = list->data;
2739 if (data->protocol != IPPROTO_UDP || data->enabled == FALSE)
2742 if(create_server(data->index, NULL,
2743 data->server, IPPROTO_TCP) == NULL)
2746 waiting_for_connect = TRUE;
2749 if (waiting_for_connect == FALSE) {
2750 /* No server is waiting for connect */
2751 send_response(client_sk, client->buf,
2752 req->request_len, NULL, 0, IPPROTO_TCP);
2758 * The server is not connected yet.
2759 * Copy the relevant buffers.
2760 * The request will actually be sent once we're
2761 * properly connected over TCP to the nameserver.
2763 req->request = g_try_malloc0(req->request_len);
2764 if (req->request == NULL) {
2765 send_response(client_sk, client->buf,
2766 req->request_len, NULL, 0, IPPROTO_TCP);
2770 memcpy(req->request, client->buf, req->request_len);
2772 req->name = g_try_malloc0(sizeof(query));
2773 if (req->name == NULL) {
2774 send_response(client_sk, client->buf,
2775 req->request_len, NULL, 0, IPPROTO_TCP);
2776 g_free(req->request);
2780 memcpy(req->name, query, sizeof(query));
2782 req->timeout = g_timeout_add_seconds(30, request_timeout, req);
2784 request_list = g_slist_append(request_list, req);
2787 if (client->buf_end > (msg_len + 2)) {
2788 DBG("client %d buf %p -> %p end %d len %d new %d",
2790 client->buf + msg_len + 2,
2791 client->buf, client->buf_end,
2792 TCP_MAX_BUF_LEN - client->buf_end,
2793 client->buf_end - (msg_len + 2));
2794 memmove(client->buf, client->buf + msg_len + 2,
2795 TCP_MAX_BUF_LEN - client->buf_end);
2796 client->buf_end = client->buf_end - (msg_len + 2);
2799 * If we have a full message waiting, just read it
2802 msg_len = get_msg_len(client->buf);
2803 if ((msg_len + 2) == client->buf_end) {
2804 DBG("client %d reading another %d bytes", client_sk,
2809 DBG("client %d clearing reading buffer", client_sk);
2811 client->buf_end = 0;
2812 memset(client->buf, 0, TCP_MAX_BUF_LEN);
2815 * We received all the packets from client so we must also
2816 * remove the timeout handler here otherwise we might get
2817 * timeout while waiting the results from server.
2819 g_source_remove(client->timeout);
2820 client->timeout = 0;
2826 static gboolean tcp_client_event(GIOChannel *channel, GIOCondition condition,
2829 struct tcp_partial_client_data *client = user_data;
2830 struct sockaddr_in6 client_addr6;
2831 socklen_t client_addr6_len = sizeof(client_addr6);
2832 struct sockaddr_in client_addr4;
2833 socklen_t client_addr4_len = sizeof(client_addr4);
2835 socklen_t *client_addr_len;
2838 client_sk = g_io_channel_unix_get_fd(channel);
2840 if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
2841 g_hash_table_remove(partial_tcp_req_table,
2842 GINT_TO_POINTER(client_sk));
2844 connman_error("Error with TCP client %d channel", client_sk);
2848 switch (client->family) {
2850 client_addr = &client_addr4;
2851 client_addr_len = &client_addr4_len;
2854 client_addr = &client_addr6;
2855 client_addr_len = &client_addr6_len;
2858 g_hash_table_remove(partial_tcp_req_table,
2859 GINT_TO_POINTER(client_sk));
2860 connman_error("client %p corrupted", client);
2864 len = recvfrom(client_sk, client->buf + client->buf_end,
2865 TCP_MAX_BUF_LEN - client->buf_end, 0,
2866 client_addr, client_addr_len);
2868 if (errno == EAGAIN || errno == EWOULDBLOCK)
2871 DBG("client %d cannot read errno %d/%s", client_sk, -errno,
2873 g_hash_table_remove(partial_tcp_req_table,
2874 GINT_TO_POINTER(client_sk));
2878 return read_tcp_data(client, client_addr, *client_addr_len, len);
2881 static gboolean client_timeout(gpointer user_data)
2883 struct tcp_partial_client_data *client = user_data;
2886 sock = g_io_channel_unix_get_fd(client->channel);
2888 DBG("client %d timeout pending %d bytes", sock, client->buf_end);
2890 g_hash_table_remove(partial_tcp_req_table, GINT_TO_POINTER(sock));
2895 static gboolean tcp_listener_event(GIOChannel *channel, GIOCondition condition,
2896 struct listener_data *ifdata, int family,
2897 guint *listener_watch)
2899 int sk, client_sk, len;
2900 unsigned int msg_len;
2901 struct tcp_partial_client_data *client;
2902 struct sockaddr_in6 client_addr6;
2903 socklen_t client_addr6_len = sizeof(client_addr6);
2904 struct sockaddr_in client_addr4;
2905 socklen_t client_addr4_len = sizeof(client_addr4);
2907 socklen_t *client_addr_len;
2911 DBG("condition 0x%02x channel %p ifdata %p family %d",
2912 condition, channel, ifdata, family);
2914 if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
2915 if (*listener_watch > 0)
2916 g_source_remove(*listener_watch);
2917 *listener_watch = 0;
2919 connman_error("Error with TCP listener channel");
2924 sk = g_io_channel_unix_get_fd(channel);
2926 if (family == AF_INET) {
2927 client_addr = &client_addr4;
2928 client_addr_len = &client_addr4_len;
2930 client_addr = &client_addr6;
2931 client_addr_len = &client_addr6_len;
2934 tv.tv_sec = tv.tv_usec = 0;
2936 FD_SET(sk, &readfds);
2938 select(sk + 1, &readfds, NULL, NULL, &tv);
2939 if (FD_ISSET(sk, &readfds)) {
2940 client_sk = accept(sk, client_addr, client_addr_len);
2941 DBG("client %d accepted", client_sk);
2943 DBG("No data to read from master %d, waiting.", sk);
2947 if (client_sk < 0) {
2948 connman_error("Accept failure on TCP listener");
2949 *listener_watch = 0;
2953 fcntl(client_sk, F_SETFL, O_NONBLOCK);
2955 client = g_hash_table_lookup(partial_tcp_req_table,
2956 GINT_TO_POINTER(client_sk));
2957 if (client == NULL) {
2958 client = g_try_new0(struct tcp_partial_client_data, 1);
2962 g_hash_table_insert(partial_tcp_req_table,
2963 GINT_TO_POINTER(client_sk),
2966 client->channel = g_io_channel_unix_new(client_sk);
2967 g_io_channel_set_close_on_unref(client->channel, TRUE);
2969 client->watch = g_io_add_watch(client->channel,
2970 G_IO_IN, tcp_client_event,
2973 client->ifdata = ifdata;
2975 DBG("client %d created %p", client_sk, client);
2977 DBG("client %d already exists %p", client_sk, client);
2980 if (client->buf == NULL) {
2981 client->buf = g_try_malloc(TCP_MAX_BUF_LEN);
2982 if (client->buf == NULL)
2985 memset(client->buf, 0, TCP_MAX_BUF_LEN);
2986 client->buf_end = 0;
2987 client->family = family;
2989 if (client->timeout == 0)
2990 client->timeout = g_timeout_add_seconds(2, client_timeout,
2994 * Check how much data there is. If all is there, then we can
2995 * proceed normally, otherwise read the bits until everything
2996 * is received or timeout occurs.
2998 len = recv(client_sk, client->buf, TCP_MAX_BUF_LEN, 0);
3000 if (errno == EAGAIN || errno == EWOULDBLOCK) {
3001 DBG("client %d no data to read, waiting", client_sk);
3005 DBG("client %d cannot read errno %d/%s", client_sk, -errno,
3007 g_hash_table_remove(partial_tcp_req_table,
3008 GINT_TO_POINTER(client_sk));
3013 DBG("client %d not enough data to read, waiting", client_sk);
3014 client->buf_end += len;
3018 msg_len = get_msg_len(client->buf);
3019 if (msg_len > TCP_MAX_BUF_LEN) {
3020 DBG("client %d invalid message length %u ignoring packet",
3021 client_sk, msg_len);
3022 g_hash_table_remove(partial_tcp_req_table,
3023 GINT_TO_POINTER(client_sk));
3028 * The packet length bytes do not contain the total message length,
3029 * that is the reason to -2 below.
3031 if (msg_len != (unsigned int)(len - 2)) {
3032 DBG("client %d sent %d bytes but expecting %u pending %d",
3033 client_sk, len, msg_len + 2, msg_len + 2 - len);
3035 client->buf_end += len;
3039 return read_tcp_data(client, client_addr, *client_addr_len, len);
3042 static gboolean tcp4_listener_event(GIOChannel *channel, GIOCondition condition,
3045 struct listener_data *ifdata = user_data;
3047 return tcp_listener_event(channel, condition, ifdata, AF_INET,
3048 &ifdata->tcp4_listener_watch);
3051 static gboolean tcp6_listener_event(GIOChannel *channel, GIOCondition condition,
3054 struct listener_data *ifdata = user_data;
3056 return tcp_listener_event(channel, condition, user_data, AF_INET6,
3057 &ifdata->tcp6_listener_watch);
3060 static gboolean udp_listener_event(GIOChannel *channel, GIOCondition condition,
3061 struct listener_data *ifdata, int family,
3062 guint *listener_watch)
3064 unsigned char buf[768];
3066 struct request_data *req;
3067 struct sockaddr_in6 client_addr6;
3068 socklen_t client_addr6_len = sizeof(client_addr6);
3069 struct sockaddr_in client_addr4;
3070 socklen_t client_addr4_len = sizeof(client_addr4);
3072 socklen_t *client_addr_len;
3075 if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
3076 connman_error("Error with UDP listener channel");
3077 *listener_watch = 0;
3081 sk = g_io_channel_unix_get_fd(channel);
3083 if (family == AF_INET) {
3084 client_addr = &client_addr4;
3085 client_addr_len = &client_addr4_len;
3087 client_addr = &client_addr6;
3088 client_addr_len = &client_addr6_len;
3091 memset(client_addr, 0, *client_addr_len);
3092 len = recvfrom(sk, buf, sizeof(buf), 0, client_addr, client_addr_len);
3096 DBG("Received %d bytes (id 0x%04x)", len, buf[0] | buf[1] << 8);
3098 err = parse_request(buf, len, query, sizeof(query));
3099 if (err < 0 || (g_slist_length(server_list) == 0)) {
3100 send_response(sk, buf, len, client_addr,
3101 *client_addr_len, IPPROTO_UDP);
3105 req = g_try_new0(struct request_data, 1);
3109 memcpy(&req->sa, client_addr, *client_addr_len);
3110 req->sa_len = *client_addr_len;
3112 req->protocol = IPPROTO_UDP;
3113 req->family = family;
3115 req->srcid = buf[0] | (buf[1] << 8);
3116 req->dstid = get_id();
3117 req->altid = get_id();
3118 req->request_len = len;
3120 buf[0] = req->dstid & 0xff;
3121 buf[1] = req->dstid >> 8;
3124 req->ifdata = ifdata;
3125 req->append_domain = FALSE;
3127 if (resolv(req, buf, query) == TRUE) {
3128 /* a cached result was sent, so the request can be released */
3133 req->timeout = g_timeout_add_seconds(5, request_timeout, req);
3134 request_list = g_slist_append(request_list, req);
3139 static gboolean udp4_listener_event(GIOChannel *channel, GIOCondition condition,
3142 struct listener_data *ifdata = user_data;
3144 return udp_listener_event(channel, condition, ifdata, AF_INET,
3145 &ifdata->udp4_listener_watch);
3148 static gboolean udp6_listener_event(GIOChannel *channel, GIOCondition condition,
3151 struct listener_data *ifdata = user_data;
3153 return udp_listener_event(channel, condition, user_data, AF_INET6,
3154 &ifdata->udp6_listener_watch);
3157 static GIOChannel *get_listener(int family, int protocol, int index)
3159 GIOChannel *channel;
3163 struct sockaddr_in6 sin6;
3164 struct sockaddr_in sin;
3170 DBG("family %d protocol %d index %d", family, protocol, index);
3175 type = SOCK_DGRAM | SOCK_CLOEXEC;
3180 type = SOCK_STREAM | SOCK_CLOEXEC;
3187 sk = socket(family, type, protocol);
3188 if (sk < 0 && family == AF_INET6 && errno == EAFNOSUPPORT) {
3189 connman_error("No IPv6 support");
3194 connman_error("Failed to create %s listener socket", proto);
3198 interface = connman_inet_ifname(index);
3199 if (interface == NULL || setsockopt(sk, SOL_SOCKET, SO_BINDTODEVICE,
3201 strlen(interface) + 1) < 0) {
3202 connman_error("Failed to bind %s listener interface "
3204 proto, family == AF_INET ? "IPv4" : "IPv6",
3205 -errno, strerror(errno));
3212 if (family == AF_INET6) {
3213 memset(&s.sin6, 0, sizeof(s.sin6));
3214 s.sin6.sin6_family = AF_INET6;
3215 s.sin6.sin6_port = htons(53);
3216 slen = sizeof(s.sin6);
3218 if (__connman_inet_get_interface_address(index,
3220 &s.sin6.sin6_addr) < 0) {
3221 /* So we could not find suitable IPv6 address for
3222 * the interface. This could happen if we have
3223 * disabled IPv6 for the interface.
3229 } else if (family == AF_INET) {
3230 memset(&s.sin, 0, sizeof(s.sin));
3231 s.sin.sin_family = AF_INET;
3232 s.sin.sin_port = htons(53);
3233 slen = sizeof(s.sin);
3235 if (__connman_inet_get_interface_address(index,
3237 &s.sin.sin_addr) < 0) {
3246 if (bind(sk, &s.sa, slen) < 0) {
3247 connman_error("Failed to bind %s listener socket", proto);
3252 if (protocol == IPPROTO_TCP) {
3254 if (listen(sk, 10) < 0) {
3255 connman_error("Failed to listen on TCP socket %d/%s",
3256 -errno, strerror(errno));
3261 fcntl(sk, F_SETFL, O_NONBLOCK);
3264 channel = g_io_channel_unix_new(sk);
3265 if (channel == NULL) {
3266 connman_error("Failed to create %s listener channel", proto);
3271 g_io_channel_set_close_on_unref(channel, TRUE);
3276 #define UDP_IPv4_FAILED 0x01
3277 #define TCP_IPv4_FAILED 0x02
3278 #define UDP_IPv6_FAILED 0x04
3279 #define TCP_IPv6_FAILED 0x08
3280 #define UDP_FAILED (UDP_IPv4_FAILED | UDP_IPv6_FAILED)
3281 #define TCP_FAILED (TCP_IPv4_FAILED | TCP_IPv6_FAILED)
3282 #define IPv6_FAILED (UDP_IPv6_FAILED | TCP_IPv6_FAILED)
3283 #define IPv4_FAILED (UDP_IPv4_FAILED | TCP_IPv4_FAILED)
3285 static int create_dns_listener(int protocol, struct listener_data *ifdata)
3289 if (protocol == IPPROTO_TCP) {
3290 ifdata->tcp4_listener_channel = get_listener(AF_INET, protocol,
3292 if (ifdata->tcp4_listener_channel != NULL)
3293 ifdata->tcp4_listener_watch =
3294 g_io_add_watch(ifdata->tcp4_listener_channel,
3295 G_IO_IN, tcp4_listener_event,
3298 ret |= TCP_IPv4_FAILED;
3300 ifdata->tcp6_listener_channel = get_listener(AF_INET6, protocol,
3302 if (ifdata->tcp6_listener_channel != NULL)
3303 ifdata->tcp6_listener_watch =
3304 g_io_add_watch(ifdata->tcp6_listener_channel,
3305 G_IO_IN, tcp6_listener_event,
3308 ret |= TCP_IPv6_FAILED;
3310 ifdata->udp4_listener_channel = get_listener(AF_INET, protocol,
3312 if (ifdata->udp4_listener_channel != NULL)
3313 ifdata->udp4_listener_watch =
3314 g_io_add_watch(ifdata->udp4_listener_channel,
3315 G_IO_IN, udp4_listener_event,
3318 ret |= UDP_IPv4_FAILED;
3320 ifdata->udp6_listener_channel = get_listener(AF_INET6, protocol,
3322 if (ifdata->udp6_listener_channel != NULL)
3323 ifdata->udp6_listener_watch =
3324 g_io_add_watch(ifdata->udp6_listener_channel,
3325 G_IO_IN, udp6_listener_event,
3328 ret |= UDP_IPv6_FAILED;
3334 static void destroy_udp_listener(struct listener_data *ifdata)
3336 DBG("index %d", ifdata->index);
3338 if (ifdata->udp4_listener_watch > 0)
3339 g_source_remove(ifdata->udp4_listener_watch);
3341 if (ifdata->udp6_listener_watch > 0)
3342 g_source_remove(ifdata->udp6_listener_watch);
3344 g_io_channel_unref(ifdata->udp4_listener_channel);
3345 g_io_channel_unref(ifdata->udp6_listener_channel);
3348 static void destroy_tcp_listener(struct listener_data *ifdata)
3350 DBG("index %d", ifdata->index);
3352 if (ifdata->tcp4_listener_watch > 0)
3353 g_source_remove(ifdata->tcp4_listener_watch);
3354 if (ifdata->tcp6_listener_watch > 0)
3355 g_source_remove(ifdata->tcp6_listener_watch);
3357 g_io_channel_unref(ifdata->tcp4_listener_channel);
3358 g_io_channel_unref(ifdata->tcp6_listener_channel);
3361 static int create_listener(struct listener_data *ifdata)
3365 err = create_dns_listener(IPPROTO_UDP, ifdata);
3366 if ((err & UDP_FAILED) == UDP_FAILED)
3369 err |= create_dns_listener(IPPROTO_TCP, ifdata);
3370 if ((err & TCP_FAILED) == TCP_FAILED) {
3371 destroy_udp_listener(ifdata);
3375 index = connman_inet_ifindex("lo");
3376 if (ifdata->index == index) {
3377 if ((err & IPv6_FAILED) != IPv6_FAILED)
3378 __connman_resolvfile_append(index, NULL, "::1");
3380 if ((err & IPv4_FAILED) != IPv4_FAILED)
3381 __connman_resolvfile_append(index, NULL, "127.0.0.1");
3387 static void destroy_listener(struct listener_data *ifdata)
3392 index = connman_inet_ifindex("lo");
3393 if (ifdata->index == index) {
3394 __connman_resolvfile_remove(index, NULL, "127.0.0.1");
3395 __connman_resolvfile_remove(index, NULL, "::1");
3398 for (list = request_list; list; list = list->next) {
3399 struct request_data *req = list->data;
3401 DBG("Dropping request (id 0x%04x -> 0x%04x)",
3402 req->srcid, req->dstid);
3403 destroy_request_data(req);
3407 g_slist_free(request_list);
3408 request_list = NULL;
3410 destroy_tcp_listener(ifdata);
3411 destroy_udp_listener(ifdata);
3414 int __connman_dnsproxy_add_listener(int index)
3416 struct listener_data *ifdata;
3419 DBG("index %d", index);
3424 if (listener_table == NULL)
3427 if (g_hash_table_lookup(listener_table, GINT_TO_POINTER(index)) != NULL)
3430 ifdata = g_try_new0(struct listener_data, 1);
3434 ifdata->index = index;
3435 ifdata->udp4_listener_channel = NULL;
3436 ifdata->udp4_listener_watch = 0;
3437 ifdata->tcp4_listener_channel = NULL;
3438 ifdata->tcp4_listener_watch = 0;
3439 ifdata->udp6_listener_channel = NULL;
3440 ifdata->udp6_listener_watch = 0;
3441 ifdata->tcp6_listener_channel = NULL;
3442 ifdata->tcp6_listener_watch = 0;
3444 err = create_listener(ifdata);
3446 connman_error("Couldn't create listener for index %d err %d",
3451 g_hash_table_insert(listener_table, GINT_TO_POINTER(ifdata->index),
3456 void __connman_dnsproxy_remove_listener(int index)
3458 struct listener_data *ifdata;
3460 DBG("index %d", index);
3462 if (listener_table == NULL)
3465 ifdata = g_hash_table_lookup(listener_table, GINT_TO_POINTER(index));
3469 destroy_listener(ifdata);
3471 g_hash_table_remove(listener_table, GINT_TO_POINTER(index));
3474 static void remove_listener(gpointer key, gpointer value, gpointer user_data)
3476 int index = GPOINTER_TO_INT(key);
3477 struct listener_data *ifdata = value;
3479 DBG("index %d", index);
3481 destroy_listener(ifdata);
3484 static void free_partial_reqs(gpointer value)
3486 struct tcp_partial_client_data *data = value;
3492 int __connman_dnsproxy_init(void)
3498 srandom(time(NULL));
3500 listener_table = g_hash_table_new_full(g_direct_hash, g_direct_equal,
3503 partial_tcp_req_table = g_hash_table_new_full(g_direct_hash,
3508 index = connman_inet_ifindex("lo");
3509 err = __connman_dnsproxy_add_listener(index);
3513 err = connman_notifier_register(&dnsproxy_notifier);
3520 __connman_dnsproxy_remove_listener(index);
3521 g_hash_table_destroy(listener_table);
3522 g_hash_table_destroy(partial_tcp_req_table);
3527 void __connman_dnsproxy_cleanup(void)
3531 connman_notifier_unregister(&dnsproxy_notifier);
3533 g_hash_table_foreach(listener_table, remove_listener, NULL);
3535 g_hash_table_destroy(listener_table);
3537 g_hash_table_destroy(partial_tcp_req_table);