5 * Copyright (C) 2007-2014 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;
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(void)
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) &&
287 data->protocol == protocol)
291 data->index < 0 || !data->server)
294 if (data->index == index &&
295 g_str_equal(data->server, server) &&
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)
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);
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);
331 DBG("Refresing A record for %s", name);
332 g_resolv_lookup_hostname(ipv4_resolve, name,
333 dummy_resolve_func, 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)
362 /* skip the header */
366 /* skip the query, which is a name and 2 16 bit words */
367 l = dns_name_length(c);
373 /* now we get the answer records */
377 l = dns_name_length(c);
382 /* then type + class, 2 bytes each */
388 /* now the 4 byte TTL field */
389 c[0] = new_ttl >> 24 & 0xff;
390 c[1] = new_ttl >> 16 & 0xff;
391 c[2] = new_ttl >> 8 & 0xff;
392 c[3] = new_ttl & 0xff;
398 /* now the 2 byte rdlen field */
399 w = c[0] << 8 | c[1];
405 static void send_cached_response(int sk, unsigned char *buf, int len,
406 const struct sockaddr *to, socklen_t tolen,
407 int protocol, int id, uint16_t answers, int ttl)
409 struct domain_hdr *hdr;
410 unsigned char *ptr = buf;
411 int err, offset, dns_len, adj_len = len - 2;
414 * The cached packet contains always the TCP offset (two bytes)
415 * so skip them for UDP.
426 dns_len = ptr[0] * 256 + ptr[1];
435 hdr = (void *) (ptr + offset);
439 hdr->rcode = ns_r_noerror;
440 hdr->ancount = htons(answers);
444 /* if this is a negative reply, we are authorative */
448 update_cached_ttl((unsigned char *)hdr, adj_len, ttl);
450 DBG("sk %d id 0x%04x answers %d ptr %p length %d dns %d",
451 sk, hdr->id, answers, ptr, len, dns_len);
453 err = sendto(sk, ptr, len, MSG_NOSIGNAL, to, tolen);
455 connman_error("Cannot send cached DNS response: %s",
460 if (err != len || (dns_len != (len - 2) && protocol == IPPROTO_TCP) ||
461 (dns_len != len && protocol == IPPROTO_UDP))
462 DBG("Packet length mismatch, sent %d wanted %d dns %d",
466 static void send_response(int sk, unsigned char *buf, int len,
467 const struct sockaddr *to, socklen_t tolen,
470 struct domain_hdr *hdr;
471 int err, offset = protocol_offset(protocol);
481 hdr = (void *) (buf + offset);
483 DBG("id 0x%04x qr %d opcode %d", hdr->id, hdr->qr, hdr->opcode);
486 hdr->rcode = ns_r_servfail;
492 err = sendto(sk, buf, len, MSG_NOSIGNAL, to, tolen);
494 connman_error("Failed to send DNS response to %d: %s",
495 sk, strerror(errno));
500 static int get_req_udp_socket(struct request_data *req)
504 if (req->family == AF_INET)
505 channel = req->ifdata->udp4_listener_channel;
507 channel = req->ifdata->udp6_listener_channel;
512 return g_io_channel_unix_get_fd(channel);
515 static void destroy_request_data(struct request_data *req)
517 if (req->timeout > 0)
518 g_source_remove(req->timeout);
521 g_free(req->request);
526 static gboolean request_timeout(gpointer user_data)
528 struct request_data *req = user_data;
533 DBG("id 0x%04x", req->srcid);
535 request_list = g_slist_remove(request_list, req);
538 if (req->resplen > 0 && req->resp) {
541 if (req->protocol == IPPROTO_UDP) {
542 sk = get_req_udp_socket(req);
546 err = sendto(sk, req->resp, req->resplen, MSG_NOSIGNAL,
547 &req->sa, req->sa_len);
550 err = send(sk, req->resp, req->resplen, MSG_NOSIGNAL);
556 } else if (req->request && req->numserv == 0) {
557 struct domain_hdr *hdr;
559 if (req->protocol == IPPROTO_TCP) {
560 hdr = (void *) (req->request + 2);
561 hdr->id = req->srcid;
562 send_response(req->client_sk, req->request,
563 req->request_len, NULL, 0, IPPROTO_TCP);
565 } else if (req->protocol == IPPROTO_UDP) {
568 hdr = (void *) (req->request);
569 hdr->id = req->srcid;
571 sk = get_req_udp_socket(req);
573 send_response(sk, req->request,
574 req->request_len, &req->sa,
575 req->sa_len, IPPROTO_UDP);
580 * We cannot leave TCP client hanging so just kick it out
581 * if we get a request timeout from server.
583 if (req->protocol == IPPROTO_TCP) {
584 DBG("client %d removed", req->client_sk);
585 g_hash_table_remove(partial_tcp_req_table,
586 GINT_TO_POINTER(req->client_sk));
590 destroy_request_data(req);
595 static int append_query(unsigned char *buf, unsigned int size,
596 const char *query, const char *domain)
598 unsigned char *ptr = buf;
601 DBG("query %s domain %s", query, domain);
606 tmp = strchr(query, '.');
612 memcpy(ptr + 1, query, len);
618 memcpy(ptr + 1, query, tmp - query);
619 ptr += tmp - query + 1;
627 tmp = strchr(domain, '.');
629 len = strlen(domain);
633 memcpy(ptr + 1, domain, len);
639 memcpy(ptr + 1, domain, tmp - domain);
640 ptr += tmp - domain + 1;
650 static bool cache_check_is_valid(struct cache_data *data,
656 if (data->cache_until < current_time)
663 * remove stale cached entries so that they can be refreshed
665 static void cache_enforce_validity(struct cache_entry *entry)
667 time_t current_time = time(NULL);
669 if (!cache_check_is_valid(entry->ipv4, current_time)
671 DBG("cache timeout \"%s\" type A", entry->key);
672 g_free(entry->ipv4->data);
678 if (!cache_check_is_valid(entry->ipv6, current_time)
680 DBG("cache timeout \"%s\" type AAAA", entry->key);
681 g_free(entry->ipv6->data);
687 static uint16_t cache_check_validity(char *question, uint16_t type,
688 struct cache_entry *entry)
690 time_t current_time = time(NULL);
691 bool want_refresh = false;
694 * if we have a popular entry, we want a refresh instead of
695 * total destruction of the entry.
700 cache_enforce_validity(entry);
704 if (!cache_check_is_valid(entry->ipv4, current_time)) {
705 DBG("cache %s \"%s\" type A", entry->ipv4 ?
706 "timeout" : "entry missing", question);
709 entry->want_refresh = true;
712 * We do not remove cache entry if there is still
713 * valid IPv6 entry found in the cache.
715 if (!cache_check_is_valid(entry->ipv6, current_time) && !want_refresh) {
716 g_hash_table_remove(cache, question);
723 if (!cache_check_is_valid(entry->ipv6, current_time)) {
724 DBG("cache %s \"%s\" type AAAA", entry->ipv6 ?
725 "timeout" : "entry missing", question);
728 entry->want_refresh = true;
730 if (!cache_check_is_valid(entry->ipv4, current_time) && !want_refresh) {
731 g_hash_table_remove(cache, question);
741 static void cache_element_destroy(gpointer value)
743 struct cache_entry *entry = value;
749 g_free(entry->ipv4->data);
754 g_free(entry->ipv6->data);
761 if (--cache_size < 0)
765 static gboolean try_remove_cache(gpointer user_data)
767 if (__sync_fetch_and_sub(&cache_refcount, 1) == 1) {
768 DBG("No cache users, removing it.");
770 g_hash_table_destroy(cache);
777 static void create_cache(void)
779 if (__sync_fetch_and_add(&cache_refcount, 1) == 0)
780 cache = g_hash_table_new_full(g_str_hash,
783 cache_element_destroy);
786 static struct cache_entry *cache_check(gpointer request, int *qtype, int proto)
789 struct cache_entry *entry;
790 struct domain_question *q;
792 int offset, proto_offset;
797 proto_offset = protocol_offset(proto);
798 if (proto_offset < 0)
801 question = request + proto_offset + 12;
803 offset = strlen(question) + 1;
804 q = (void *) (question + offset);
805 type = ntohs(q->type);
807 /* We only cache either A (1) or AAAA (28) requests */
808 if (type != 1 && type != 28)
816 entry = g_hash_table_lookup(cache, question);
820 type = cache_check_validity(question, type, entry);
829 * Get a label/name from DNS resource record. The function decompresses the
830 * label if necessary. The function does not convert the name to presentation
831 * form. This means that the result string will contain label lengths instead
832 * of dots between labels. We intentionally do not want to convert to dotted
833 * format so that we can cache the wire format string directly.
835 static int get_name(int counter,
836 unsigned char *pkt, unsigned char *start, unsigned char *max,
837 unsigned char *output, int output_max, int *output_len,
838 unsigned char **end, char *name, int *name_len)
842 /* Limit recursion to 10 (this means up to 10 labels in domain name) */
848 if ((*p & NS_CMPRSFLGS) == NS_CMPRSFLGS) {
849 uint16_t offset = (*p & 0x3F) * 256 + *(p + 1);
851 if (offset >= max - pkt)
857 return get_name(counter + 1, pkt, pkt + offset, max,
858 output, output_max, output_len, end,
861 unsigned label_len = *p;
863 if (pkt + label_len > max)
866 if (*output_len > output_max)
870 * We need the original name in order to check
871 * if this answer is the correct one.
873 name[(*name_len)++] = label_len;
874 memcpy(name + *name_len, p + 1, label_len + 1);
875 *name_len += label_len;
877 /* We compress the result */
878 output[0] = NS_CMPRSFLGS;
895 static int parse_rr(unsigned char *buf, unsigned char *start,
897 unsigned char *response, unsigned int *response_size,
898 uint16_t *type, uint16_t *class, int *ttl, int *rdlen,
902 struct domain_rr *rr;
904 int name_len = 0, output_len = 0, max_rsp = *response_size;
906 err = get_name(0, buf, start, max, response, max_rsp,
907 &output_len, end, name, &name_len);
913 if ((unsigned int) offset > *response_size)
916 rr = (void *) (*end);
921 *type = ntohs(rr->type);
922 *class = ntohs(rr->class);
923 *ttl = ntohl(rr->ttl);
924 *rdlen = ntohs(rr->rdlen);
929 memcpy(response + offset, *end, sizeof(struct domain_rr));
931 offset += sizeof(struct domain_rr);
932 *end += sizeof(struct domain_rr);
934 if ((unsigned int) (offset + *rdlen) > *response_size)
937 memcpy(response + offset, *end, *rdlen);
941 *response_size = offset + *rdlen;
946 static bool check_alias(GSList *aliases, char *name)
951 for (list = aliases; list; list = list->next) {
952 int len = strlen((char *)list->data);
953 if (strncmp((char *)list->data, name, len) == 0)
961 static int parse_response(unsigned char *buf, int buflen,
962 char *question, int qlen,
963 uint16_t *type, uint16_t *class, int *ttl,
964 unsigned char *response, unsigned int *response_len,
967 struct domain_hdr *hdr = (void *) buf;
968 struct domain_question *q;
970 uint16_t qdcount = ntohs(hdr->qdcount);
971 uint16_t ancount = ntohs(hdr->ancount);
973 uint16_t qtype, qclass;
974 unsigned char *next = NULL;
975 unsigned int maxlen = *response_len;
976 GSList *aliases = NULL, *list;
977 char name[NS_MAXDNAME + 1];
982 DBG("qr %d qdcount %d", hdr->qr, qdcount);
984 /* We currently only cache responses where question count is 1 */
985 if (hdr->qr != 1 || qdcount != 1)
988 ptr = buf + sizeof(struct domain_hdr);
990 strncpy(question, (char *) ptr, qlen);
991 qlen = strlen(question);
992 ptr += qlen + 1; /* skip \0 */
995 qtype = ntohs(q->type);
997 /* We cache only A and AAAA records */
998 if (qtype != 1 && qtype != 28)
1001 qclass = ntohs(q->class);
1003 ptr += 2 + 2; /* ptr points now to answers */
1009 memset(name, 0, sizeof(name));
1012 * We have a bunch of answers (like A, AAAA, CNAME etc) to
1013 * A or AAAA question. We traverse the answers and parse the
1014 * resource records. Only A and AAAA records are cached, all
1015 * the other records in answers are skipped.
1017 for (i = 0; i < ancount; i++) {
1019 * Get one address at a time to this buffer.
1020 * The max size of the answer is
1021 * 2 (pointer) + 2 (type) + 2 (class) +
1022 * 4 (ttl) + 2 (rdlen) + addr (16 or 4) = 28
1023 * for A or AAAA record.
1024 * For CNAME the size can be bigger.
1026 unsigned char rsp[NS_MAXCDNAME];
1027 unsigned int rsp_len = sizeof(rsp) - 1;
1030 memset(rsp, 0, sizeof(rsp));
1032 ret = parse_rr(buf, ptr, buf + buflen, rsp, &rsp_len,
1033 type, class, ttl, &rdlen, &next, name);
1040 * Now rsp contains compressed or uncompressed resource
1041 * record. Next we check if this record answers the question.
1042 * The name var contains the uncompressed label.
1043 * One tricky bit is the CNAME records as they alias
1044 * the name we might be interested in.
1048 * Go to next answer if the class is not the one we are
1051 if (*class != qclass) {
1058 * Try to resolve aliases also, type is CNAME(5).
1059 * This is important as otherwise the aliased names would not
1060 * be cached at all as the cache would not contain the aliased
1063 * If any CNAME is found in DNS packet, then we cache the alias
1064 * IP address instead of the question (as the server
1065 * said that question has only an alias).
1066 * This means in practice that if e.g., ipv6.google.com is
1067 * queried, DNS server returns CNAME of that name which is
1068 * ipv6.l.google.com. We then cache the address of the CNAME
1069 * but return the question name to client. So the alias
1070 * status of the name is not saved in cache and thus not
1071 * returned to the client. We do not return DNS packets from
1072 * cache to client saying that ipv6.google.com is an alias to
1073 * ipv6.l.google.com but we return instead a DNS packet that
1074 * says ipv6.google.com has address xxx which is in fact the
1075 * address of ipv6.l.google.com. For caching purposes this
1076 * should not cause any issues.
1078 if (*type == 5 && strncmp(question, name, qlen) == 0) {
1080 * So now the alias answered the question. This is
1081 * not very useful from caching point of view as
1082 * the following A or AAAA records will not match the
1083 * question. We need to find the real A/AAAA record
1084 * of the alias and cache that.
1086 unsigned char *end = NULL;
1087 int name_len = 0, output_len = 0;
1089 memset(rsp, 0, sizeof(rsp));
1090 rsp_len = sizeof(rsp) - 1;
1093 * Alias is in rdata part of the message,
1094 * and next-rdlen points to it. So we need to get
1095 * the real name of the alias.
1097 ret = get_name(0, buf, next - rdlen, buf + buflen,
1098 rsp, rsp_len, &output_len, &end,
1101 /* just ignore the error at this point */
1108 * We should now have the alias of the entry we might
1109 * want to cache. Just remember it for a while.
1110 * We check the alias list when we have parsed the
1113 aliases = g_slist_prepend(aliases, g_strdup(name));
1120 if (*type == qtype) {
1122 * We found correct type (A or AAAA)
1124 if (check_alias(aliases, name) ||
1125 (!aliases && strncmp(question, name,
1128 * We found an alias or the name of the rr
1129 * matches the question. If so, we append
1130 * the compressed label to the cache.
1131 * The end result is a response buffer that
1132 * will contain one or more cached and
1133 * compressed resource records.
1135 if (*response_len + rsp_len > maxlen) {
1139 memcpy(response + *response_len, rsp, rsp_len);
1140 *response_len += rsp_len;
1151 for (list = aliases; list; list = list->next)
1153 g_slist_free(aliases);
1158 struct cache_timeout {
1159 time_t current_time;
1164 static gboolean cache_check_entry(gpointer key, gpointer value,
1167 struct cache_timeout *data = user_data;
1168 struct cache_entry *entry = value;
1171 /* Scale the number of hits by half as part of cache aging */
1176 * If either IPv4 or IPv6 cached entry has expired, we
1177 * remove both from the cache.
1180 if (entry->ipv4 && entry->ipv4->timeout > 0) {
1181 max_timeout = entry->ipv4->cache_until;
1182 if (max_timeout > data->max_timeout)
1183 data->max_timeout = max_timeout;
1185 if (entry->ipv4->cache_until < data->current_time)
1189 if (entry->ipv6 && entry->ipv6->timeout > 0) {
1190 max_timeout = entry->ipv6->cache_until;
1191 if (max_timeout > data->max_timeout)
1192 data->max_timeout = max_timeout;
1194 if (entry->ipv6->cache_until < data->current_time)
1199 * if we're asked to try harder, also remove entries that have
1202 if (data->try_harder && entry->hits < 4)
1208 static void cache_cleanup(void)
1210 static int max_timeout;
1211 struct cache_timeout data;
1214 data.current_time = time(NULL);
1215 data.max_timeout = 0;
1216 data.try_harder = 0;
1219 * In the first pass, we only remove entries that have timed out.
1220 * We use a cache of the first time to expire to do this only
1221 * when it makes sense.
1223 if (max_timeout <= data.current_time) {
1224 count = g_hash_table_foreach_remove(cache, cache_check_entry,
1227 DBG("removed %d in the first pass", count);
1230 * In the second pass, if the first pass turned up blank,
1231 * we also expire entries with a low hit count,
1232 * while aging the hit count at the same time.
1234 data.try_harder = 1;
1236 count = g_hash_table_foreach_remove(cache, cache_check_entry,
1241 * If we could not remove anything, then remember
1242 * what is the max timeout and do nothing if we
1243 * have not yet reached it. This will prevent
1244 * constant traversal of the cache if it is full.
1246 max_timeout = data.max_timeout;
1251 static gboolean cache_invalidate_entry(gpointer key, gpointer value,
1254 struct cache_entry *entry = value;
1256 /* first, delete any expired elements */
1257 cache_enforce_validity(entry);
1259 /* if anything is not expired, mark the entry for refresh */
1260 if (entry->hits > 0 && (entry->ipv4 || entry->ipv6))
1261 entry->want_refresh = true;
1263 /* delete the cached data */
1265 g_free(entry->ipv4->data);
1266 g_free(entry->ipv4);
1271 g_free(entry->ipv6->data);
1272 g_free(entry->ipv6);
1276 /* keep the entry if we want it refreshed, delete it otherwise */
1277 if (entry->want_refresh)
1284 * cache_invalidate is called from places where the DNS landscape
1285 * has changed, say because connections are added or we entered a VPN.
1286 * The logic is to wipe all cache data, but mark all non-expired
1287 * parts of the cache for refresh rather than deleting the whole cache.
1289 static void cache_invalidate(void)
1291 DBG("Invalidating the DNS cache %p", cache);
1296 g_hash_table_foreach_remove(cache, cache_invalidate_entry, NULL);
1299 static void cache_refresh_entry(struct cache_entry *entry)
1302 cache_enforce_validity(entry);
1304 if (entry->hits > 2 && !entry->ipv4)
1305 entry->want_refresh = true;
1306 if (entry->hits > 2 && !entry->ipv6)
1307 entry->want_refresh = true;
1309 if (entry->want_refresh) {
1311 char dns_name[NS_MAXDNAME + 1];
1312 entry->want_refresh = false;
1314 /* turn a DNS name into a hostname with dots */
1315 strncpy(dns_name, entry->key, NS_MAXDNAME);
1323 DBG("Refreshing %s\n", dns_name);
1324 /* then refresh the hostname */
1325 refresh_dns_entry(entry, &dns_name[1]);
1329 static void cache_refresh_iterator(gpointer key, gpointer value,
1332 struct cache_entry *entry = value;
1334 cache_refresh_entry(entry);
1337 static void cache_refresh(void)
1342 g_hash_table_foreach(cache, cache_refresh_iterator, NULL);
1345 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;
1361 type = c[0] << 8 | c[1];
1366 static int cache_update(struct server_data *srv, unsigned char *msg,
1367 unsigned int msg_len)
1369 int offset = protocol_offset(srv->protocol);
1370 int err, qlen, ttl = 0;
1371 uint16_t answers = 0, type = 0, class = 0;
1372 struct domain_hdr *hdr = (void *)(msg + offset);
1373 struct domain_question *q;
1374 struct cache_entry *entry;
1375 struct cache_data *data;
1376 char question[NS_MAXDNAME + 1];
1377 unsigned char response[NS_MAXDNAME + 1];
1379 unsigned int rsplen;
1380 bool new_entry = true;
1381 time_t current_time;
1383 if (cache_size >= MAX_CACHE_SIZE) {
1385 if (cache_size >= MAX_CACHE_SIZE)
1389 current_time = time(NULL);
1391 /* don't do a cache refresh more than twice a minute */
1392 if (next_refresh < current_time) {
1394 next_refresh = current_time + 30;
1400 DBG("offset %d hdr %p msg %p rcode %d", offset, hdr, msg, hdr->rcode);
1402 /* Continue only if response code is 0 (=ok) */
1403 if (hdr->rcode != ns_r_noerror)
1409 rsplen = sizeof(response) - 1;
1410 question[sizeof(question) - 1] = '\0';
1412 err = parse_response(msg + offset, msg_len - offset,
1413 question, sizeof(question) - 1,
1414 &type, &class, &ttl,
1415 response, &rsplen, &answers);
1418 * special case: if we do a ipv6 lookup and get no result
1419 * for a record that's already in our ipv4 cache.. we want
1420 * to cache the negative response.
1422 if ((err == -ENOMSG || err == -ENOBUFS) &&
1423 reply_query_type(msg + offset,
1424 msg_len - offset) == 28) {
1425 entry = g_hash_table_lookup(cache, question);
1426 if (entry && entry->ipv4 && !entry->ipv6) {
1427 int cache_offset = 0;
1429 data = g_try_new(struct cache_data, 1);
1432 data->inserted = entry->ipv4->inserted;
1434 data->answers = ntohs(hdr->ancount);
1435 data->timeout = entry->ipv4->timeout;
1436 if (srv->protocol == IPPROTO_UDP)
1438 data->data_len = msg_len + cache_offset;
1439 data->data = ptr = g_malloc(data->data_len);
1440 ptr[0] = (data->data_len - 2) / 256;
1441 ptr[1] = (data->data_len - 2) - ptr[0] * 256;
1442 if (srv->protocol == IPPROTO_UDP)
1444 data->valid_until = entry->ipv4->valid_until;
1445 data->cache_until = entry->ipv4->cache_until;
1446 memcpy(ptr, msg, msg_len);
1449 * we will get a "hit" when we serve the response
1453 if (entry->hits < 0)
1459 if (err < 0 || ttl == 0)
1462 qlen = strlen(question);
1465 * If the cache contains already data, check if the
1466 * type of the cached data is the same and do not add
1467 * to cache if data is already there.
1468 * This is needed so that we can cache both A and AAAA
1469 * records for the same name.
1471 entry = g_hash_table_lookup(cache, question);
1473 entry = g_try_new(struct cache_entry, 1);
1477 data = g_try_new(struct cache_data, 1);
1483 entry->key = g_strdup(question);
1484 entry->ipv4 = entry->ipv6 = NULL;
1485 entry->want_refresh = false;
1493 if (type == 1 && entry->ipv4)
1496 if (type == 28 && entry->ipv6)
1499 data = g_try_new(struct cache_data, 1);
1509 * compensate for the hit we'll get for serving
1510 * the response out of the cache
1513 if (entry->hits < 0)
1519 if (ttl < MIN_CACHE_TTL)
1520 ttl = MIN_CACHE_TTL;
1522 data->inserted = current_time;
1524 data->answers = answers;
1525 data->timeout = ttl;
1527 * The "2" in start of the length is the TCP offset. We allocate it
1528 * here even for UDP packet because it simplifies the sending
1531 data->data_len = 2 + 12 + qlen + 1 + 2 + 2 + rsplen;
1532 data->data = ptr = g_malloc(data->data_len);
1533 data->valid_until = current_time + ttl;
1536 * Restrict the cached DNS record TTL to some sane value
1537 * in order to prevent data staying in the cache too long.
1539 if (ttl > MAX_CACHE_TTL)
1540 ttl = MAX_CACHE_TTL;
1542 data->cache_until = round_down_ttl(current_time + ttl, ttl);
1552 * We cache the two extra bytes at the start of the message
1553 * in a TCP packet. When sending UDP packet, we skip the first
1554 * two bytes. This way we do not need to know the format
1555 * (UDP/TCP) of the cached message.
1557 if (srv->protocol == IPPROTO_UDP)
1558 memcpy(ptr + 2, msg, offset + 12);
1560 memcpy(ptr, msg, offset + 12);
1562 ptr[0] = (data->data_len - 2) / 256;
1563 ptr[1] = (data->data_len - 2) - ptr[0] * 256;
1564 if (srv->protocol == IPPROTO_UDP)
1567 memcpy(ptr + offset + 12, question, qlen + 1); /* copy also the \0 */
1569 q = (void *) (ptr + offset + 12 + qlen + 1);
1570 q->type = htons(type);
1571 q->class = htons(class);
1572 memcpy(ptr + offset + 12 + qlen + 1 + sizeof(struct domain_question),
1576 g_hash_table_replace(cache, entry->key, entry);
1580 DBG("cache %d %squestion \"%s\" type %d ttl %d size %zd packet %u "
1582 cache_size, new_entry ? "new " : "old ",
1583 question, type, ttl,
1584 sizeof(*entry) + sizeof(*data) + data->data_len + qlen,
1586 srv->protocol == IPPROTO_TCP ?
1587 (unsigned int)(data->data[0] * 256 + data->data[1]) :
1593 static int ns_resolv(struct server_data *server, struct request_data *req,
1594 gpointer request, gpointer name)
1597 int sk, err, type = 0;
1598 char *dot, *lookup = (char *) name;
1599 struct cache_entry *entry;
1601 entry = cache_check(request, &type, req->protocol);
1604 struct cache_data *data;
1606 DBG("cache hit %s type %s", lookup, type == 1 ? "A" : "AAAA");
1613 ttl_left = data->valid_until - time(NULL);
1617 if (data && req->protocol == IPPROTO_TCP) {
1618 send_cached_response(req->client_sk, data->data,
1619 data->data_len, NULL, 0, IPPROTO_TCP,
1620 req->srcid, data->answers, ttl_left);
1624 if (data && req->protocol == IPPROTO_UDP) {
1625 int udp_sk = get_req_udp_socket(req);
1630 send_cached_response(udp_sk, data->data,
1631 data->data_len, &req->sa, req->sa_len,
1632 IPPROTO_UDP, req->srcid, data->answers,
1638 sk = g_io_channel_unix_get_fd(server->channel);
1640 err = sendto(sk, request, req->request_len, MSG_NOSIGNAL,
1641 server->server_addr, server->server_addr_len);
1643 DBG("Cannot send message to server %s sock %d "
1644 "protocol %d (%s/%d)",
1645 server->server, sk, server->protocol,
1646 strerror(errno), errno);
1652 /* If we have more than one dot, we don't add domains */
1653 dot = strchr(lookup, '.');
1654 if (dot && dot != lookup + strlen(lookup) - 1)
1657 if (server->domains && server->domains->data)
1658 req->append_domain = true;
1660 for (list = server->domains; list; list = list->next) {
1662 unsigned char alt[1024];
1663 struct domain_hdr *hdr = (void *) &alt;
1664 int altlen, domlen, offset;
1666 domain = list->data;
1671 offset = protocol_offset(server->protocol);
1675 domlen = strlen(domain) + 1;
1679 alt[offset] = req->altid & 0xff;
1680 alt[offset + 1] = req->altid >> 8;
1682 memcpy(alt + offset + 2, request + offset + 2, 10);
1683 hdr->qdcount = htons(1);
1685 altlen = append_query(alt + offset + 12, sizeof(alt) - 12,
1692 memcpy(alt + offset + altlen,
1693 request + offset + altlen - domlen,
1694 req->request_len - altlen - offset + domlen);
1696 if (server->protocol == IPPROTO_TCP) {
1697 int req_len = req->request_len + domlen - 2;
1699 alt[0] = (req_len >> 8) & 0xff;
1700 alt[1] = req_len & 0xff;
1703 DBG("req %p dstid 0x%04x altid 0x%04x", req, req->dstid,
1706 err = send(sk, alt, req->request_len + domlen, MSG_NOSIGNAL);
1716 static char *convert_label(char *start, char *end, char *ptr, char *uptr,
1717 int remaining_len, int *used_comp, int *used_uncomp)
1720 char name[NS_MAXLABEL];
1722 pos = dn_expand((u_char *)start, (u_char *)end, (u_char *)ptr,
1725 DBG("uncompress error [%d/%s]", errno, strerror(errno));
1730 * We need to compress back the name so that we get back to internal
1731 * label presentation.
1733 comp_pos = dn_comp(name, (u_char *)uptr, remaining_len, NULL, NULL);
1735 DBG("compress error [%d/%s]", errno, strerror(errno));
1740 *used_uncomp = comp_pos;
1748 static char *uncompress(int16_t field_count, char *start, char *end,
1749 char *ptr, char *uncompressed, int uncomp_len,
1750 char **uncompressed_ptr)
1752 char *uptr = *uncompressed_ptr; /* position in result buffer */
1754 DBG("count %d ptr %p end %p uptr %p", field_count, ptr, end, uptr);
1756 while (field_count-- > 0 && ptr < end) {
1757 int dlen; /* data field length */
1758 int ulen; /* uncompress length */
1759 int pos; /* position in compressed string */
1760 char name[NS_MAXLABEL]; /* tmp label */
1761 uint16_t dns_type, dns_class;
1764 if (!convert_label(start, end, ptr, name, NS_MAXLABEL,
1769 * Copy the uncompressed resource record, type, class and \0 to
1773 ulen = strlen(name);
1774 strncpy(uptr, name, uncomp_len - (uptr - uncompressed));
1776 DBG("pos %d ulen %d left %d name %s", pos, ulen,
1777 (int)(uncomp_len - (uptr - uncompressed)), uptr);
1785 * We copy also the fixed portion of the result (type, class,
1786 * ttl, address length and the address)
1788 memcpy(uptr, ptr, NS_RRFIXEDSZ);
1790 dns_type = uptr[0] << 8 | uptr[1];
1791 dns_class = uptr[2] << 8 | uptr[3];
1793 if (dns_class != ns_c_in)
1796 ptr += NS_RRFIXEDSZ;
1797 uptr += NS_RRFIXEDSZ;
1800 * Then the variable portion of the result (data length).
1801 * Typically this portion is also compressed
1802 * so we need to uncompress it also when necessary.
1804 if (dns_type == ns_t_cname) {
1805 if (!convert_label(start, end, ptr, uptr,
1806 uncomp_len - (uptr - uncompressed),
1810 uptr[-2] = comp_pos << 8;
1811 uptr[-1] = comp_pos & 0xff;
1816 } else if (dns_type == ns_t_a || dns_type == ns_t_aaaa) {
1817 dlen = uptr[-2] << 8 | uptr[-1];
1819 if (ptr + dlen > end) {
1820 DBG("data len %d too long", dlen);
1824 memcpy(uptr, ptr, dlen);
1828 } else if (dns_type == ns_t_soa) {
1832 /* Primary name server expansion */
1833 if (!convert_label(start, end, ptr, uptr,
1834 uncomp_len - (uptr - uncompressed),
1838 total_len += comp_pos;
1839 len_ptr = &uptr[-2];
1843 /* Responsible authority's mailbox */
1844 if (!convert_label(start, end, ptr, uptr,
1845 uncomp_len - (uptr - uncompressed),
1849 total_len += comp_pos;
1854 * Copy rest of the soa fields (serial number,
1855 * refresh interval, retry interval, expiration
1856 * limit and minimum ttl). They are 20 bytes long.
1858 memcpy(uptr, ptr, 20);
1864 * Finally fix the length of the data part
1866 len_ptr[0] = total_len << 8;
1867 len_ptr[1] = total_len & 0xff;
1870 *uncompressed_ptr = uptr;
1879 static int strip_domains(char *name, char *answers, int maxlen)
1882 int name_len = strlen(name);
1883 char *ptr, *start = answers, *end = answers + maxlen;
1885 while (maxlen > 0) {
1886 ptr = strstr(answers, name);
1888 char *domain = ptr + name_len;
1891 int domain_len = strlen(domain);
1893 memmove(answers + name_len,
1894 domain + domain_len,
1895 end - (domain + domain_len));
1898 maxlen -= domain_len;
1902 answers += strlen(answers) + 1;
1903 answers += 2 + 2 + 4; /* skip type, class and ttl fields */
1905 data_len = answers[0] << 8 | answers[1];
1906 answers += 2; /* skip the length field */
1908 if (answers + data_len > end)
1911 answers += data_len;
1912 maxlen -= answers - ptr;
1918 static int forward_dns_reply(unsigned char *reply, int reply_len, int protocol,
1919 struct server_data *data)
1921 struct domain_hdr *hdr;
1922 struct request_data *req;
1923 int dns_id, sk, err, offset = protocol_offset(protocol);
1928 hdr = (void *)(reply + offset);
1929 dns_id = reply[offset] | reply[offset + 1] << 8;
1931 DBG("Received %d bytes (id 0x%04x)", reply_len, dns_id);
1933 req = find_request(dns_id);
1937 DBG("req %p dstid 0x%04x altid 0x%04x rcode %d",
1938 req, req->dstid, req->altid, hdr->rcode);
1940 reply[offset] = req->srcid & 0xff;
1941 reply[offset + 1] = req->srcid >> 8;
1945 if (hdr->rcode == ns_r_noerror || !req->resp) {
1946 unsigned char *new_reply = NULL;
1949 * If the domain name was append
1950 * remove it before forwarding the reply.
1951 * If there were more than one question, then this
1952 * domain name ripping can be hairy so avoid that
1953 * and bail out in that that case.
1955 * The reason we are doing this magic is that if the
1956 * user's DNS client tries to resolv hostname without
1957 * domain part, it also expects to get the result without
1958 * a domain name part.
1960 if (req->append_domain && ntohs(hdr->qdcount) == 1) {
1961 uint16_t domain_len = 0;
1962 uint16_t header_len;
1963 uint16_t dns_type, dns_class;
1964 uint8_t host_len, dns_type_pos;
1965 char uncompressed[NS_MAXDNAME], *uptr;
1966 char *ptr, *eom = (char *)reply + reply_len;
1969 * ptr points to the first char of the hostname.
1970 * ->hostname.domain.net
1972 header_len = offset + sizeof(struct domain_hdr);
1973 ptr = (char *)reply + header_len;
1977 domain_len = strnlen(ptr + 1 + host_len,
1978 reply_len - header_len);
1981 * If the query type is anything other than A or AAAA,
1982 * then bail out and pass the message as is.
1983 * We only want to deal with IPv4 or IPv6 addresses.
1985 dns_type_pos = host_len + 1 + domain_len + 1;
1987 dns_type = ptr[dns_type_pos] << 8 |
1988 ptr[dns_type_pos + 1];
1989 dns_class = ptr[dns_type_pos + 2] << 8 |
1990 ptr[dns_type_pos + 3];
1991 if (dns_type != ns_t_a && dns_type != ns_t_aaaa &&
1992 dns_class != ns_c_in) {
1993 DBG("Pass msg dns type %d class %d",
1994 dns_type, dns_class);
1999 * Remove the domain name and replace it by the end
2000 * of reply. Check if the domain is really there
2001 * before trying to copy the data. We also need to
2002 * uncompress the answers if necessary.
2003 * The domain_len can be 0 because if the original
2004 * query did not contain a domain name, then we are
2005 * sending two packets, first without the domain name
2006 * and the second packet with domain name.
2007 * The append_domain is set to true even if we sent
2008 * the first packet without domain name. In this
2009 * case we end up in this branch.
2011 if (domain_len > 0) {
2012 int len = host_len + 1;
2013 int new_len, fixed_len;
2017 * First copy host (without domain name) into
2020 uptr = &uncompressed[0];
2021 memcpy(uptr, ptr, len);
2023 uptr[len] = '\0'; /* host termination */
2027 * Copy type and class fields of the question.
2029 ptr += len + domain_len + 1;
2030 memcpy(uptr, ptr, NS_QFIXEDSZ);
2033 * ptr points to answers after this
2036 uptr += NS_QFIXEDSZ;
2038 fixed_len = answers - uncompressed;
2041 * We then uncompress the result to buffer
2042 * so that we can rip off the domain name
2043 * part from the question. First answers,
2044 * then name server (authority) information,
2045 * and finally additional record info.
2048 ptr = uncompress(ntohs(hdr->ancount),
2049 (char *)reply + offset, eom,
2050 ptr, uncompressed, NS_MAXDNAME,
2055 ptr = uncompress(ntohs(hdr->nscount),
2056 (char *)reply + offset, eom,
2057 ptr, uncompressed, NS_MAXDNAME,
2062 ptr = uncompress(ntohs(hdr->arcount),
2063 (char *)reply + offset, eom,
2064 ptr, uncompressed, NS_MAXDNAME,
2070 * The uncompressed buffer now contains almost
2071 * valid response. Final step is to get rid of
2072 * the domain name because at least glibc
2073 * gethostbyname() implementation does extra
2074 * checks and expects to find an answer without
2075 * domain name if we asked a query without
2076 * domain part. Note that glibc getaddrinfo()
2077 * works differently and accepts FQDN in answer
2079 new_len = strip_domains(uncompressed, answers,
2082 DBG("Corrupted packet");
2087 * Because we have now uncompressed the answers
2088 * we might have to create a bigger buffer to
2089 * hold all that data.
2092 reply_len = header_len + new_len + fixed_len;
2094 new_reply = g_try_malloc(reply_len);
2098 memcpy(new_reply, reply, header_len);
2099 memcpy(new_reply + header_len, uncompressed,
2100 new_len + fixed_len);
2110 req->resp = g_try_malloc(reply_len);
2114 memcpy(req->resp, reply, reply_len);
2115 req->resplen = reply_len;
2117 cache_update(data, reply, reply_len);
2123 if (req->numresp < req->numserv) {
2124 if (hdr->rcode > ns_r_noerror) {
2126 } else if (hdr->ancount == 0 && req->append_domain) {
2131 request_list = g_slist_remove(request_list, req);
2133 if (protocol == IPPROTO_UDP) {
2134 sk = get_req_udp_socket(req);
2139 err = sendto(sk, req->resp, req->resplen, 0,
2140 &req->sa, req->sa_len);
2142 sk = req->client_sk;
2143 err = send(sk, req->resp, req->resplen, MSG_NOSIGNAL);
2147 DBG("Cannot send msg, sk %d proto %d errno %d/%s", sk,
2148 protocol, errno, strerror(errno));
2150 DBG("proto %d sent %d bytes to %d", protocol, err, sk);
2152 destroy_request_data(req);
2157 static void server_destroy_socket(struct server_data *data)
2159 DBG("index %d server %s proto %d", data->index,
2160 data->server, data->protocol);
2162 if (data->watch > 0) {
2163 g_source_remove(data->watch);
2167 if (data->timeout > 0) {
2168 g_source_remove(data->timeout);
2172 if (data->channel) {
2173 g_io_channel_shutdown(data->channel, TRUE, NULL);
2174 g_io_channel_unref(data->channel);
2175 data->channel = NULL;
2178 g_free(data->incoming_reply);
2179 data->incoming_reply = NULL;
2182 static void destroy_server(struct server_data *server)
2184 DBG("index %d server %s sock %d", server->index, server->server,
2186 g_io_channel_unix_get_fd(server->channel): -1);
2188 server_list = g_slist_remove(server_list, server);
2189 server_destroy_socket(server);
2191 if (server->protocol == IPPROTO_UDP && server->enabled)
2192 DBG("Removing DNS server %s", server->server);
2194 g_free(server->server);
2195 g_list_free_full(server->domains, g_free);
2196 g_free(server->server_addr);
2199 * We do not remove cache right away but delay it few seconds.
2200 * The idea is that when IPv6 DNS server is added via RDNSS, it has a
2201 * lifetime. When the lifetime expires we decrease the refcount so it
2202 * is possible that the cache is then removed. Because a new DNS server
2203 * is usually created almost immediately we would then loose the cache
2204 * without any good reason. The small delay allows the new RDNSS to
2205 * create a new DNS server instance and the refcount does not go to 0.
2208 g_timeout_add_seconds(3, try_remove_cache, NULL);
2213 static gboolean udp_server_event(GIOChannel *channel, GIOCondition condition,
2216 unsigned char buf[4096];
2218 struct server_data *data = user_data;
2220 if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
2221 connman_error("Error with UDP server %s", data->server);
2222 server_destroy_socket(data);
2226 sk = g_io_channel_unix_get_fd(channel);
2228 len = recv(sk, buf, sizeof(buf), 0);
2232 err = forward_dns_reply(buf, len, IPPROTO_UDP, data);
2239 static gboolean tcp_server_event(GIOChannel *channel, GIOCondition condition,
2243 struct server_data *server = user_data;
2245 sk = g_io_channel_unix_get_fd(channel);
2249 if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
2252 DBG("TCP server channel closed, sk %d", sk);
2255 * Discard any partial response which is buffered; better
2256 * to get a proper response from a working server.
2258 g_free(server->incoming_reply);
2259 server->incoming_reply = NULL;
2261 for (list = request_list; list; list = list->next) {
2262 struct request_data *req = list->data;
2263 struct domain_hdr *hdr;
2265 if (req->protocol == IPPROTO_UDP)
2272 * If we're not waiting for any further response
2273 * from another name server, then we send an error
2274 * response to the client.
2276 if (req->numserv && --(req->numserv))
2279 hdr = (void *) (req->request + 2);
2280 hdr->id = req->srcid;
2281 send_response(req->client_sk, req->request,
2282 req->request_len, NULL, 0, IPPROTO_TCP);
2284 request_list = g_slist_remove(request_list, req);
2287 destroy_server(server);
2292 if ((condition & G_IO_OUT) && !server->connected) {
2295 bool no_request_sent = true;
2296 struct server_data *udp_server;
2298 udp_server = find_server(server->index, server->server,
2301 for (domains = udp_server->domains; domains;
2302 domains = domains->next) {
2303 char *dom = domains->data;
2305 DBG("Adding domain %s to %s",
2306 dom, server->server);
2308 server->domains = g_list_append(server->domains,
2313 server->connected = true;
2314 server_list = g_slist_append(server_list, server);
2316 if (server->timeout > 0) {
2317 g_source_remove(server->timeout);
2318 server->timeout = 0;
2321 for (list = request_list; list; ) {
2322 struct request_data *req = list->data;
2325 if (req->protocol == IPPROTO_UDP) {
2330 DBG("Sending req %s over TCP", (char *)req->name);
2332 status = ns_resolv(server, req,
2333 req->request, req->name);
2336 * A cached result was sent,
2337 * so the request can be released
2340 request_list = g_slist_remove(request_list, req);
2341 destroy_request_data(req);
2350 no_request_sent = false;
2352 if (req->timeout > 0)
2353 g_source_remove(req->timeout);
2355 req->timeout = g_timeout_add_seconds(30,
2356 request_timeout, req);
2360 if (no_request_sent) {
2361 destroy_server(server);
2365 } else if (condition & G_IO_IN) {
2366 struct partial_reply *reply = server->incoming_reply;
2370 unsigned char reply_len_buf[2];
2373 bytes_recv = recv(sk, reply_len_buf, 2, MSG_PEEK);
2376 } else if (bytes_recv < 0) {
2377 if (errno == EAGAIN || errno == EWOULDBLOCK)
2380 connman_error("DNS proxy error %s",
2383 } else if (bytes_recv < 2)
2386 reply_len = reply_len_buf[1] | reply_len_buf[0] << 8;
2389 DBG("TCP reply %d bytes from %d", reply_len, sk);
2391 reply = g_try_malloc(sizeof(*reply) + reply_len + 2);
2395 reply->len = reply_len;
2396 reply->received = 0;
2398 server->incoming_reply = reply;
2401 while (reply->received < reply->len) {
2402 bytes_recv = recv(sk, reply->buf + reply->received,
2403 reply->len - reply->received, 0);
2405 connman_error("DNS proxy TCP disconnect");
2407 } else if (bytes_recv < 0) {
2408 if (errno == EAGAIN || errno == EWOULDBLOCK)
2411 connman_error("DNS proxy error %s",
2415 reply->received += bytes_recv;
2418 forward_dns_reply(reply->buf, reply->received, IPPROTO_TCP,
2422 server->incoming_reply = NULL;
2424 destroy_server(server);
2432 static gboolean tcp_idle_timeout(gpointer user_data)
2434 struct server_data *server = user_data;
2441 destroy_server(server);
2446 static int server_create_socket(struct server_data *data)
2451 DBG("index %d server %s proto %d", data->index,
2452 data->server, data->protocol);
2454 sk = socket(data->server_addr->sa_family,
2455 data->protocol == IPPROTO_TCP ? SOCK_STREAM : SOCK_DGRAM,
2459 connman_error("Failed to create server %s socket",
2461 server_destroy_socket(data);
2467 interface = connman_inet_ifname(data->index);
2469 if (setsockopt(sk, SOL_SOCKET, SO_BINDTODEVICE,
2471 strlen(interface) + 1) < 0) {
2473 connman_error("Failed to bind server %s "
2475 data->server, interface);
2477 server_destroy_socket(data);
2484 data->channel = g_io_channel_unix_new(sk);
2485 if (!data->channel) {
2486 connman_error("Failed to create server %s channel",
2489 server_destroy_socket(data);
2493 g_io_channel_set_close_on_unref(data->channel, TRUE);
2495 if (data->protocol == IPPROTO_TCP) {
2496 g_io_channel_set_flags(data->channel, G_IO_FLAG_NONBLOCK, NULL);
2497 data->watch = g_io_add_watch(data->channel,
2498 G_IO_OUT | G_IO_IN | G_IO_HUP | G_IO_NVAL | G_IO_ERR,
2499 tcp_server_event, data);
2500 data->timeout = g_timeout_add_seconds(30, tcp_idle_timeout,
2503 data->watch = g_io_add_watch(data->channel,
2504 G_IO_IN | G_IO_NVAL | G_IO_ERR | G_IO_HUP,
2505 udp_server_event, data);
2507 if (connect(sk, data->server_addr, data->server_addr_len) < 0) {
2510 if ((data->protocol == IPPROTO_TCP && errno != EINPROGRESS) ||
2511 data->protocol == IPPROTO_UDP) {
2513 connman_error("Failed to connect to server %s",
2515 server_destroy_socket(data);
2525 static struct server_data *create_server(int index,
2526 const char *domain, const char *server,
2529 struct server_data *data;
2530 struct addrinfo hints, *rp;
2533 DBG("index %d server %s", index, server);
2535 data = g_try_new0(struct server_data, 1);
2537 connman_error("Failed to allocate server %s data", server);
2541 data->index = index;
2543 data->domains = g_list_append(data->domains, g_strdup(domain));
2544 data->server = g_strdup(server);
2545 data->protocol = protocol;
2547 memset(&hints, 0, sizeof(hints));
2551 hints.ai_socktype = SOCK_DGRAM;
2555 hints.ai_socktype = SOCK_STREAM;
2559 destroy_server(data);
2562 hints.ai_family = AF_UNSPEC;
2563 hints.ai_flags = AI_NUMERICSERV | AI_NUMERICHOST;
2565 ret = getaddrinfo(data->server, "53", &hints, &rp);
2567 connman_error("Failed to parse server %s address: %s\n",
2568 data->server, gai_strerror(ret));
2569 destroy_server(data);
2573 /* Do not blindly copy this code elsewhere; it doesn't loop over the
2574 results using ->ai_next as it should. That's OK in *this* case
2575 because it was a numeric lookup; we *know* there's only one. */
2577 data->server_addr_len = rp->ai_addrlen;
2579 switch (rp->ai_family) {
2581 data->server_addr = (struct sockaddr *)
2582 g_try_new0(struct sockaddr_in, 1);
2585 data->server_addr = (struct sockaddr *)
2586 g_try_new0(struct sockaddr_in6, 1);
2589 connman_error("Wrong address family %d", rp->ai_family);
2592 if (!data->server_addr) {
2594 destroy_server(data);
2597 memcpy(data->server_addr, rp->ai_addr, rp->ai_addrlen);
2600 if (server_create_socket(data) != 0) {
2601 destroy_server(data);
2605 if (protocol == IPPROTO_UDP) {
2606 if (__connman_service_index_is_default(data->index) ||
2607 __connman_service_index_is_split_routing(
2609 data->enabled = true;
2610 DBG("Adding DNS server %s", data->server);
2613 server_list = g_slist_append(server_list, data);
2619 static bool resolv(struct request_data *req,
2620 gpointer request, gpointer name)
2624 for (list = server_list; list; list = list->next) {
2625 struct server_data *data = list->data;
2627 if (data->protocol == IPPROTO_TCP) {
2628 DBG("server %s ignored proto TCP", data->server);
2632 DBG("server %s enabled %d", data->server, data->enabled);
2637 if (!data->channel && data->protocol == IPPROTO_UDP) {
2638 if (server_create_socket(data) < 0) {
2639 DBG("socket creation failed while resolving");
2644 if (ns_resolv(data, req, request, name) > 0)
2651 static void append_domain(int index, const char *domain)
2655 DBG("index %d domain %s", index, domain);
2660 for (list = server_list; list; list = list->next) {
2661 struct server_data *data = list->data;
2664 bool dom_found = false;
2666 if (data->index < 0)
2669 if (data->index != index)
2672 for (dom_list = data->domains; dom_list;
2673 dom_list = dom_list->next) {
2674 dom = dom_list->data;
2676 if (g_str_equal(dom, domain)) {
2684 g_list_append(data->domains, g_strdup(domain));
2689 int __connman_dnsproxy_append(int index, const char *domain,
2692 struct server_data *data;
2694 DBG("index %d server %s", index, server);
2696 if (!server && !domain)
2700 append_domain(index, domain);
2705 if (g_str_equal(server, "127.0.0.1"))
2708 if (g_str_equal(server, "::1"))
2711 data = find_server(index, server, IPPROTO_UDP);
2713 append_domain(index, domain);
2717 data = create_server(index, domain, server, IPPROTO_UDP);
2724 static void remove_server(int index, const char *domain,
2725 const char *server, int protocol)
2727 struct server_data *data;
2729 data = find_server(index, server, protocol);
2733 destroy_server(data);
2736 int __connman_dnsproxy_remove(int index, const char *domain,
2739 DBG("index %d server %s", index, server);
2744 if (g_str_equal(server, "127.0.0.1"))
2747 if (g_str_equal(server, "::1"))
2750 remove_server(index, domain, server, IPPROTO_UDP);
2751 remove_server(index, domain, server, IPPROTO_TCP);
2756 void __connman_dnsproxy_flush(void)
2760 list = request_list;
2762 struct request_data *req = list->data;
2766 if (resolv(req, req->request, req->name)) {
2768 * A cached result was sent,
2769 * so the request can be released
2772 g_slist_remove(request_list, req);
2773 destroy_request_data(req);
2777 if (req->timeout > 0)
2778 g_source_remove(req->timeout);
2779 req->timeout = g_timeout_add_seconds(5, request_timeout, req);
2783 static void dnsproxy_offline_mode(bool enabled)
2787 DBG("enabled %d", enabled);
2789 for (list = server_list; list; list = list->next) {
2790 struct server_data *data = list->data;
2793 DBG("Enabling DNS server %s", data->server);
2794 data->enabled = true;
2798 DBG("Disabling DNS server %s", data->server);
2799 data->enabled = false;
2805 static void dnsproxy_default_changed(struct connman_service *service)
2810 DBG("service %p", service);
2812 /* DNS has changed, invalidate the cache */
2816 /* When no services are active, then disable DNS proxying */
2817 dnsproxy_offline_mode(true);
2821 index = __connman_service_get_index(service);
2825 for (list = server_list; list; list = list->next) {
2826 struct server_data *data = list->data;
2828 if (data->index == index) {
2829 DBG("Enabling DNS server %s", data->server);
2830 data->enabled = true;
2832 DBG("Disabling DNS server %s", data->server);
2833 data->enabled = false;
2840 static struct connman_notifier dnsproxy_notifier = {
2842 .default_changed = dnsproxy_default_changed,
2843 .offline_mode = dnsproxy_offline_mode,
2846 static unsigned char opt_edns0_type[2] = { 0x00, 0x29 };
2848 static int parse_request(unsigned char *buf, int len,
2849 char *name, unsigned int size)
2851 struct domain_hdr *hdr = (void *) buf;
2852 uint16_t qdcount = ntohs(hdr->qdcount);
2853 uint16_t arcount = ntohs(hdr->arcount);
2855 char *last_label = NULL;
2856 unsigned int remain, used = 0;
2861 DBG("id 0x%04x qr %d opcode %d qdcount %d arcount %d",
2862 hdr->id, hdr->qr, hdr->opcode,
2865 if (hdr->qr != 0 || qdcount != 1)
2870 ptr = buf + sizeof(struct domain_hdr);
2871 remain = len - sizeof(struct domain_hdr);
2873 while (remain > 0) {
2874 uint8_t label_len = *ptr;
2876 if (label_len == 0x00) {
2877 last_label = (char *) (ptr + 1);
2881 if (used + label_len + 1 > size)
2884 strncat(name, (char *) (ptr + 1), label_len);
2887 used += label_len + 1;
2889 ptr += label_len + 1;
2890 remain -= label_len + 1;
2893 if (last_label && arcount && remain >= 9 && last_label[4] == 0 &&
2894 !memcmp(last_label + 5, opt_edns0_type, 2)) {
2895 uint16_t edns0_bufsize;
2897 edns0_bufsize = last_label[7] << 8 | last_label[8];
2899 DBG("EDNS0 buffer size %u", edns0_bufsize);
2901 /* This is an evil hack until full TCP support has been
2904 * Somtimes the EDNS0 request gets send with a too-small
2905 * buffer size. Since glibc doesn't seem to crash when it
2906 * gets a response biffer then it requested, just bump
2907 * the buffer size up to 4KiB.
2909 if (edns0_bufsize < 0x1000) {
2910 last_label[7] = 0x10;
2911 last_label[8] = 0x00;
2915 DBG("query %s", name);
2920 static void client_reset(struct tcp_partial_client_data *client)
2925 if (client->channel) {
2926 DBG("client %d closing",
2927 g_io_channel_unix_get_fd(client->channel));
2929 g_io_channel_unref(client->channel);
2930 client->channel = NULL;
2933 if (client->watch > 0) {
2934 g_source_remove(client->watch);
2938 if (client->timeout > 0) {
2939 g_source_remove(client->timeout);
2940 client->timeout = 0;
2943 g_free(client->buf);
2946 client->buf_end = 0;
2949 static unsigned int get_msg_len(unsigned char *buf)
2951 return buf[0]<<8 | buf[1];
2954 static bool read_tcp_data(struct tcp_partial_client_data *client,
2955 void *client_addr, socklen_t client_addr_len,
2958 char query[TCP_MAX_BUF_LEN];
2959 struct request_data *req;
2961 unsigned int msg_len;
2963 bool waiting_for_connect = false;
2965 struct cache_entry *entry;
2967 client_sk = g_io_channel_unix_get_fd(client->channel);
2969 if (read_len == 0) {
2970 DBG("client %d closed, pending %d bytes",
2971 client_sk, client->buf_end);
2972 g_hash_table_remove(partial_tcp_req_table,
2973 GINT_TO_POINTER(client_sk));
2977 DBG("client %d received %d bytes", client_sk, read_len);
2979 client->buf_end += read_len;
2981 if (client->buf_end < 2)
2984 msg_len = get_msg_len(client->buf);
2985 if (msg_len > TCP_MAX_BUF_LEN) {
2986 DBG("client %d sent too much data %d", client_sk, msg_len);
2987 g_hash_table_remove(partial_tcp_req_table,
2988 GINT_TO_POINTER(client_sk));
2993 DBG("client %d msg len %d end %d past end %d", client_sk, msg_len,
2994 client->buf_end, client->buf_end - (msg_len + 2));
2996 if (client->buf_end < (msg_len + 2)) {
2997 DBG("client %d still missing %d bytes",
2999 msg_len + 2 - client->buf_end);
3003 DBG("client %d all data %d received", client_sk, msg_len);
3005 err = parse_request(client->buf + 2, msg_len,
3006 query, sizeof(query));
3007 if (err < 0 || (g_slist_length(server_list) == 0)) {
3008 send_response(client_sk, client->buf, msg_len + 2,
3009 NULL, 0, IPPROTO_TCP);
3013 req = g_try_new0(struct request_data, 1);
3017 memcpy(&req->sa, client_addr, client_addr_len);
3018 req->sa_len = client_addr_len;
3019 req->client_sk = client_sk;
3020 req->protocol = IPPROTO_TCP;
3021 req->family = client->family;
3023 req->srcid = client->buf[2] | (client->buf[3] << 8);
3024 req->dstid = get_id();
3025 req->altid = get_id();
3026 req->request_len = msg_len + 2;
3028 client->buf[2] = req->dstid & 0xff;
3029 client->buf[3] = req->dstid >> 8;
3032 req->ifdata = client->ifdata;
3033 req->append_domain = false;
3036 * Check if the answer is found in the cache before
3037 * creating sockets to the server.
3039 entry = cache_check(client->buf, &qtype, IPPROTO_TCP);
3042 struct cache_data *data;
3044 DBG("cache hit %s type %s", query, qtype == 1 ? "A" : "AAAA");
3051 ttl_left = data->valid_until - time(NULL);
3054 send_cached_response(client_sk, data->data,
3055 data->data_len, NULL, 0, IPPROTO_TCP,
3056 req->srcid, data->answers, ttl_left);
3061 DBG("data missing, ignoring cache for this query");
3064 for (list = server_list; list; list = list->next) {
3065 struct server_data *data = list->data;
3067 if (data->protocol != IPPROTO_UDP || !data->enabled)
3070 if (!create_server(data->index, NULL, data->server,
3074 waiting_for_connect = true;
3077 if (!waiting_for_connect) {
3078 /* No server is waiting for connect */
3079 send_response(client_sk, client->buf,
3080 req->request_len, NULL, 0, IPPROTO_TCP);
3086 * The server is not connected yet.
3087 * Copy the relevant buffers.
3088 * The request will actually be sent once we're
3089 * properly connected over TCP to the nameserver.
3091 req->request = g_try_malloc0(req->request_len);
3092 if (!req->request) {
3093 send_response(client_sk, client->buf,
3094 req->request_len, NULL, 0, IPPROTO_TCP);
3098 memcpy(req->request, client->buf, req->request_len);
3100 req->name = g_try_malloc0(sizeof(query));
3102 send_response(client_sk, client->buf,
3103 req->request_len, NULL, 0, IPPROTO_TCP);
3104 g_free(req->request);
3108 memcpy(req->name, query, sizeof(query));
3110 req->timeout = g_timeout_add_seconds(30, request_timeout, req);
3112 request_list = g_slist_append(request_list, req);
3115 if (client->buf_end > (msg_len + 2)) {
3116 DBG("client %d buf %p -> %p end %d len %d new %d",
3118 client->buf + msg_len + 2,
3119 client->buf, client->buf_end,
3120 TCP_MAX_BUF_LEN - client->buf_end,
3121 client->buf_end - (msg_len + 2));
3122 memmove(client->buf, client->buf + msg_len + 2,
3123 TCP_MAX_BUF_LEN - client->buf_end);
3124 client->buf_end = client->buf_end - (msg_len + 2);
3127 * If we have a full message waiting, just read it
3130 msg_len = get_msg_len(client->buf);
3131 if ((msg_len + 2) == client->buf_end) {
3132 DBG("client %d reading another %d bytes", client_sk,
3137 DBG("client %d clearing reading buffer", client_sk);
3139 client->buf_end = 0;
3140 memset(client->buf, 0, TCP_MAX_BUF_LEN);
3143 * We received all the packets from client so we must also
3144 * remove the timeout handler here otherwise we might get
3145 * timeout while waiting the results from server.
3147 g_source_remove(client->timeout);
3148 client->timeout = 0;
3154 static gboolean tcp_client_event(GIOChannel *channel, GIOCondition condition,
3157 struct tcp_partial_client_data *client = user_data;
3158 struct sockaddr_in6 client_addr6;
3159 socklen_t client_addr6_len = sizeof(client_addr6);
3160 struct sockaddr_in client_addr4;
3161 socklen_t client_addr4_len = sizeof(client_addr4);
3163 socklen_t *client_addr_len;
3166 client_sk = g_io_channel_unix_get_fd(channel);
3168 if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
3169 g_hash_table_remove(partial_tcp_req_table,
3170 GINT_TO_POINTER(client_sk));
3172 connman_error("Error with TCP client %d channel", client_sk);
3176 switch (client->family) {
3178 client_addr = &client_addr4;
3179 client_addr_len = &client_addr4_len;
3182 client_addr = &client_addr6;
3183 client_addr_len = &client_addr6_len;
3186 g_hash_table_remove(partial_tcp_req_table,
3187 GINT_TO_POINTER(client_sk));
3188 connman_error("client %p corrupted", client);
3192 len = recvfrom(client_sk, client->buf + client->buf_end,
3193 TCP_MAX_BUF_LEN - client->buf_end, 0,
3194 client_addr, client_addr_len);
3196 if (errno == EAGAIN || errno == EWOULDBLOCK)
3199 DBG("client %d cannot read errno %d/%s", client_sk, -errno,
3201 g_hash_table_remove(partial_tcp_req_table,
3202 GINT_TO_POINTER(client_sk));
3206 return read_tcp_data(client, client_addr, *client_addr_len, len);
3209 static gboolean client_timeout(gpointer user_data)
3211 struct tcp_partial_client_data *client = user_data;
3214 sock = g_io_channel_unix_get_fd(client->channel);
3216 DBG("client %d timeout pending %d bytes", sock, client->buf_end);
3218 g_hash_table_remove(partial_tcp_req_table, GINT_TO_POINTER(sock));
3223 static bool tcp_listener_event(GIOChannel *channel, GIOCondition condition,
3224 struct listener_data *ifdata, int family,
3225 guint *listener_watch)
3227 int sk, client_sk, len;
3228 unsigned int msg_len;
3229 struct tcp_partial_client_data *client;
3230 struct sockaddr_in6 client_addr6;
3231 socklen_t client_addr6_len = sizeof(client_addr6);
3232 struct sockaddr_in client_addr4;
3233 socklen_t client_addr4_len = sizeof(client_addr4);
3235 socklen_t *client_addr_len;
3239 DBG("condition 0x%02x channel %p ifdata %p family %d",
3240 condition, channel, ifdata, family);
3242 if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
3243 if (*listener_watch > 0)
3244 g_source_remove(*listener_watch);
3245 *listener_watch = 0;
3247 connman_error("Error with TCP listener channel");
3252 sk = g_io_channel_unix_get_fd(channel);
3254 if (family == AF_INET) {
3255 client_addr = &client_addr4;
3256 client_addr_len = &client_addr4_len;
3258 client_addr = &client_addr6;
3259 client_addr_len = &client_addr6_len;
3262 tv.tv_sec = tv.tv_usec = 0;
3264 FD_SET(sk, &readfds);
3266 select(sk + 1, &readfds, NULL, NULL, &tv);
3267 if (FD_ISSET(sk, &readfds)) {
3268 client_sk = accept(sk, client_addr, client_addr_len);
3269 DBG("client %d accepted", client_sk);
3271 DBG("No data to read from master %d, waiting.", sk);
3275 if (client_sk < 0) {
3276 connman_error("Accept failure on TCP listener");
3277 *listener_watch = 0;
3281 fcntl(client_sk, F_SETFL, O_NONBLOCK);
3283 client = g_hash_table_lookup(partial_tcp_req_table,
3284 GINT_TO_POINTER(client_sk));
3286 client = g_try_new0(struct tcp_partial_client_data, 1);
3292 g_hash_table_insert(partial_tcp_req_table,
3293 GINT_TO_POINTER(client_sk),
3296 client->channel = g_io_channel_unix_new(client_sk);
3297 g_io_channel_set_close_on_unref(client->channel, TRUE);
3299 client->watch = g_io_add_watch(client->channel,
3300 G_IO_IN, tcp_client_event,
3303 client->ifdata = ifdata;
3305 DBG("client %d created %p", client_sk, client);
3307 DBG("client %d already exists %p", client_sk, client);
3311 client->buf = g_try_malloc(TCP_MAX_BUF_LEN);
3315 memset(client->buf, 0, TCP_MAX_BUF_LEN);
3316 client->buf_end = 0;
3317 client->family = family;
3319 if (client->timeout == 0)
3320 client->timeout = g_timeout_add_seconds(2, client_timeout,
3324 * Check how much data there is. If all is there, then we can
3325 * proceed normally, otherwise read the bits until everything
3326 * is received or timeout occurs.
3328 len = recv(client_sk, client->buf, TCP_MAX_BUF_LEN, 0);
3330 if (errno == EAGAIN || errno == EWOULDBLOCK) {
3331 DBG("client %d no data to read, waiting", client_sk);
3335 DBG("client %d cannot read errno %d/%s", client_sk, -errno,
3337 g_hash_table_remove(partial_tcp_req_table,
3338 GINT_TO_POINTER(client_sk));
3343 DBG("client %d not enough data to read, waiting", client_sk);
3344 client->buf_end += len;
3348 msg_len = get_msg_len(client->buf);
3349 if (msg_len > TCP_MAX_BUF_LEN) {
3350 DBG("client %d invalid message length %u ignoring packet",
3351 client_sk, msg_len);
3352 g_hash_table_remove(partial_tcp_req_table,
3353 GINT_TO_POINTER(client_sk));
3358 * The packet length bytes do not contain the total message length,
3359 * that is the reason to -2 below.
3361 if (msg_len != (unsigned int)(len - 2)) {
3362 DBG("client %d sent %d bytes but expecting %u pending %d",
3363 client_sk, len, msg_len + 2, msg_len + 2 - len);
3365 client->buf_end += len;
3369 return read_tcp_data(client, client_addr, *client_addr_len, len);
3372 static gboolean tcp4_listener_event(GIOChannel *channel, GIOCondition condition,
3375 struct listener_data *ifdata = user_data;
3377 return tcp_listener_event(channel, condition, ifdata, AF_INET,
3378 &ifdata->tcp4_listener_watch);
3381 static gboolean tcp6_listener_event(GIOChannel *channel, GIOCondition condition,
3384 struct listener_data *ifdata = user_data;
3386 return tcp_listener_event(channel, condition, user_data, AF_INET6,
3387 &ifdata->tcp6_listener_watch);
3390 static bool udp_listener_event(GIOChannel *channel, GIOCondition condition,
3391 struct listener_data *ifdata, int family,
3392 guint *listener_watch)
3394 unsigned char buf[768];
3396 struct request_data *req;
3397 struct sockaddr_in6 client_addr6;
3398 socklen_t client_addr6_len = sizeof(client_addr6);
3399 struct sockaddr_in client_addr4;
3400 socklen_t client_addr4_len = sizeof(client_addr4);
3402 socklen_t *client_addr_len;
3405 if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
3406 connman_error("Error with UDP listener channel");
3407 *listener_watch = 0;
3411 sk = g_io_channel_unix_get_fd(channel);
3413 if (family == AF_INET) {
3414 client_addr = &client_addr4;
3415 client_addr_len = &client_addr4_len;
3417 client_addr = &client_addr6;
3418 client_addr_len = &client_addr6_len;
3421 memset(client_addr, 0, *client_addr_len);
3422 len = recvfrom(sk, buf, sizeof(buf), 0, client_addr, client_addr_len);
3426 DBG("Received %d bytes (id 0x%04x)", len, buf[0] | buf[1] << 8);
3428 err = parse_request(buf, len, query, sizeof(query));
3429 if (err < 0 || (g_slist_length(server_list) == 0)) {
3430 send_response(sk, buf, len, client_addr,
3431 *client_addr_len, IPPROTO_UDP);
3435 req = g_try_new0(struct request_data, 1);
3439 memcpy(&req->sa, client_addr, *client_addr_len);
3440 req->sa_len = *client_addr_len;
3442 req->protocol = IPPROTO_UDP;
3443 req->family = family;
3445 req->srcid = buf[0] | (buf[1] << 8);
3446 req->dstid = get_id();
3447 req->altid = get_id();
3448 req->request_len = len;
3450 buf[0] = req->dstid & 0xff;
3451 buf[1] = req->dstid >> 8;
3454 req->ifdata = ifdata;
3455 req->append_domain = false;
3457 if (resolv(req, buf, query)) {
3458 /* a cached result was sent, so the request can be released */
3463 req->timeout = g_timeout_add_seconds(5, request_timeout, req);
3464 request_list = g_slist_append(request_list, req);
3469 static gboolean udp4_listener_event(GIOChannel *channel, GIOCondition condition,
3472 struct listener_data *ifdata = user_data;
3474 return udp_listener_event(channel, condition, ifdata, AF_INET,
3475 &ifdata->udp4_listener_watch);
3478 static gboolean udp6_listener_event(GIOChannel *channel, GIOCondition condition,
3481 struct listener_data *ifdata = user_data;
3483 return udp_listener_event(channel, condition, user_data, AF_INET6,
3484 &ifdata->udp6_listener_watch);
3487 static GIOChannel *get_listener(int family, int protocol, int index)
3489 GIOChannel *channel;
3493 struct sockaddr_in6 sin6;
3494 struct sockaddr_in sin;
3500 DBG("family %d protocol %d index %d", family, protocol, index);
3505 type = SOCK_DGRAM | SOCK_CLOEXEC;
3510 type = SOCK_STREAM | SOCK_CLOEXEC;
3517 sk = socket(family, type, protocol);
3518 if (sk < 0 && family == AF_INET6 && errno == EAFNOSUPPORT) {
3519 connman_error("No IPv6 support");
3524 connman_error("Failed to create %s listener socket", proto);
3528 interface = connman_inet_ifname(index);
3529 if (!interface || setsockopt(sk, SOL_SOCKET, SO_BINDTODEVICE,
3531 strlen(interface) + 1) < 0) {
3532 connman_error("Failed to bind %s listener interface "
3534 proto, family == AF_INET ? "IPv4" : "IPv6",
3535 -errno, strerror(errno));
3542 if (family == AF_INET6) {
3543 memset(&s.sin6, 0, sizeof(s.sin6));
3544 s.sin6.sin6_family = AF_INET6;
3545 s.sin6.sin6_port = htons(53);
3546 slen = sizeof(s.sin6);
3548 if (__connman_inet_get_interface_address(index,
3550 &s.sin6.sin6_addr) < 0) {
3551 /* So we could not find suitable IPv6 address for
3552 * the interface. This could happen if we have
3553 * disabled IPv6 for the interface.
3559 } else if (family == AF_INET) {
3560 memset(&s.sin, 0, sizeof(s.sin));
3561 s.sin.sin_family = AF_INET;
3562 s.sin.sin_port = htons(53);
3563 slen = sizeof(s.sin);
3565 if (__connman_inet_get_interface_address(index,
3567 &s.sin.sin_addr) < 0) {
3576 if (bind(sk, &s.sa, slen) < 0) {
3577 connman_error("Failed to bind %s listener socket", proto);
3582 if (protocol == IPPROTO_TCP) {
3584 if (listen(sk, 10) < 0) {
3585 connman_error("Failed to listen on TCP socket %d/%s",
3586 -errno, strerror(errno));
3591 fcntl(sk, F_SETFL, O_NONBLOCK);
3594 channel = g_io_channel_unix_new(sk);
3596 connman_error("Failed to create %s listener channel", proto);
3601 g_io_channel_set_close_on_unref(channel, TRUE);
3606 #define UDP_IPv4_FAILED 0x01
3607 #define TCP_IPv4_FAILED 0x02
3608 #define UDP_IPv6_FAILED 0x04
3609 #define TCP_IPv6_FAILED 0x08
3610 #define UDP_FAILED (UDP_IPv4_FAILED | UDP_IPv6_FAILED)
3611 #define TCP_FAILED (TCP_IPv4_FAILED | TCP_IPv6_FAILED)
3612 #define IPv6_FAILED (UDP_IPv6_FAILED | TCP_IPv6_FAILED)
3613 #define IPv4_FAILED (UDP_IPv4_FAILED | TCP_IPv4_FAILED)
3615 static int create_dns_listener(int protocol, struct listener_data *ifdata)
3619 if (protocol == IPPROTO_TCP) {
3620 ifdata->tcp4_listener_channel = get_listener(AF_INET, protocol,
3622 if (ifdata->tcp4_listener_channel)
3623 ifdata->tcp4_listener_watch =
3624 g_io_add_watch(ifdata->tcp4_listener_channel,
3625 G_IO_IN, tcp4_listener_event,
3628 ret |= TCP_IPv4_FAILED;
3630 ifdata->tcp6_listener_channel = get_listener(AF_INET6, protocol,
3632 if (ifdata->tcp6_listener_channel)
3633 ifdata->tcp6_listener_watch =
3634 g_io_add_watch(ifdata->tcp6_listener_channel,
3635 G_IO_IN, tcp6_listener_event,
3638 ret |= TCP_IPv6_FAILED;
3640 ifdata->udp4_listener_channel = get_listener(AF_INET, protocol,
3642 if (ifdata->udp4_listener_channel)
3643 ifdata->udp4_listener_watch =
3644 g_io_add_watch(ifdata->udp4_listener_channel,
3645 G_IO_IN, udp4_listener_event,
3648 ret |= UDP_IPv4_FAILED;
3650 ifdata->udp6_listener_channel = get_listener(AF_INET6, protocol,
3652 if (ifdata->udp6_listener_channel)
3653 ifdata->udp6_listener_watch =
3654 g_io_add_watch(ifdata->udp6_listener_channel,
3655 G_IO_IN, udp6_listener_event,
3658 ret |= UDP_IPv6_FAILED;
3664 static void destroy_udp_listener(struct listener_data *ifdata)
3666 DBG("index %d", ifdata->index);
3668 if (ifdata->udp4_listener_watch > 0)
3669 g_source_remove(ifdata->udp4_listener_watch);
3671 if (ifdata->udp6_listener_watch > 0)
3672 g_source_remove(ifdata->udp6_listener_watch);
3674 if (ifdata->udp4_listener_channel)
3675 g_io_channel_unref(ifdata->udp4_listener_channel);
3676 if (ifdata->udp6_listener_channel)
3677 g_io_channel_unref(ifdata->udp6_listener_channel);
3680 static void destroy_tcp_listener(struct listener_data *ifdata)
3682 DBG("index %d", ifdata->index);
3684 if (ifdata->tcp4_listener_watch > 0)
3685 g_source_remove(ifdata->tcp4_listener_watch);
3686 if (ifdata->tcp6_listener_watch > 0)
3687 g_source_remove(ifdata->tcp6_listener_watch);
3689 if (ifdata->tcp4_listener_channel)
3690 g_io_channel_unref(ifdata->tcp4_listener_channel);
3691 if (ifdata->tcp6_listener_channel)
3692 g_io_channel_unref(ifdata->tcp6_listener_channel);
3695 static int create_listener(struct listener_data *ifdata)
3699 err = create_dns_listener(IPPROTO_UDP, ifdata);
3700 if ((err & UDP_FAILED) == UDP_FAILED)
3703 err |= create_dns_listener(IPPROTO_TCP, ifdata);
3704 if ((err & TCP_FAILED) == TCP_FAILED) {
3705 destroy_udp_listener(ifdata);
3709 index = connman_inet_ifindex("lo");
3710 if (ifdata->index == index) {
3711 if ((err & IPv6_FAILED) != IPv6_FAILED)
3712 __connman_resolvfile_append(index, NULL, "::1");
3714 if ((err & IPv4_FAILED) != IPv4_FAILED)
3715 __connman_resolvfile_append(index, NULL, "127.0.0.1");
3721 static void destroy_listener(struct listener_data *ifdata)
3726 index = connman_inet_ifindex("lo");
3727 if (ifdata->index == index) {
3728 __connman_resolvfile_remove(index, NULL, "127.0.0.1");
3729 __connman_resolvfile_remove(index, NULL, "::1");
3732 for (list = request_list; list; list = list->next) {
3733 struct request_data *req = list->data;
3735 DBG("Dropping request (id 0x%04x -> 0x%04x)",
3736 req->srcid, req->dstid);
3737 destroy_request_data(req);
3741 g_slist_free(request_list);
3742 request_list = NULL;
3744 destroy_tcp_listener(ifdata);
3745 destroy_udp_listener(ifdata);
3748 int __connman_dnsproxy_add_listener(int index)
3750 struct listener_data *ifdata;
3753 DBG("index %d", index);
3758 if (!listener_table)
3761 if (g_hash_table_lookup(listener_table, GINT_TO_POINTER(index)))
3764 ifdata = g_try_new0(struct listener_data, 1);
3768 ifdata->index = index;
3769 ifdata->udp4_listener_channel = NULL;
3770 ifdata->udp4_listener_watch = 0;
3771 ifdata->tcp4_listener_channel = NULL;
3772 ifdata->tcp4_listener_watch = 0;
3773 ifdata->udp6_listener_channel = NULL;
3774 ifdata->udp6_listener_watch = 0;
3775 ifdata->tcp6_listener_channel = NULL;
3776 ifdata->tcp6_listener_watch = 0;
3778 err = create_listener(ifdata);
3780 connman_error("Couldn't create listener for index %d err %d",
3785 g_hash_table_insert(listener_table, GINT_TO_POINTER(ifdata->index),
3790 void __connman_dnsproxy_remove_listener(int index)
3792 struct listener_data *ifdata;
3794 DBG("index %d", index);
3796 if (!listener_table)
3799 ifdata = g_hash_table_lookup(listener_table, GINT_TO_POINTER(index));
3803 destroy_listener(ifdata);
3805 g_hash_table_remove(listener_table, GINT_TO_POINTER(index));
3808 static void remove_listener(gpointer key, gpointer value, gpointer user_data)
3810 int index = GPOINTER_TO_INT(key);
3811 struct listener_data *ifdata = value;
3813 DBG("index %d", index);
3815 destroy_listener(ifdata);
3818 static void free_partial_reqs(gpointer value)
3820 struct tcp_partial_client_data *data = value;
3826 int __connman_dnsproxy_init(void)
3832 srandom(time(NULL));
3834 listener_table = g_hash_table_new_full(g_direct_hash, g_direct_equal,
3837 partial_tcp_req_table = g_hash_table_new_full(g_direct_hash,
3842 index = connman_inet_ifindex("lo");
3843 err = __connman_dnsproxy_add_listener(index);
3847 err = connman_notifier_register(&dnsproxy_notifier);
3854 __connman_dnsproxy_remove_listener(index);
3855 g_hash_table_destroy(listener_table);
3856 g_hash_table_destroy(partial_tcp_req_table);
3861 void __connman_dnsproxy_cleanup(void)
3865 connman_notifier_unregister(&dnsproxy_notifier);
3867 g_hash_table_foreach(listener_table, remove_listener, NULL);
3869 g_hash_table_destroy(listener_table);
3871 g_hash_table_destroy(partial_tcp_req_table);