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 #define debug(fmt...) do { } while (0)
46 #if __BYTE_ORDER == __LITTLE_ENDIAN
61 } __attribute__ ((packed));
62 #elif __BYTE_ORDER == __BIG_ENDIAN
77 } __attribute__ ((packed));
79 #error "Unknown byte order"
85 } __attribute__ ((packed));
87 struct partial_reply {
97 struct sockaddr *server_addr;
98 socklen_t server_addr_len;
105 struct partial_reply *incoming_reply;
108 struct request_data {
110 struct sockaddr_in6 __sin6; /* Only for the length */
129 struct listener_data *ifdata;
133 struct listener_data {
136 GIOChannel *udp4_listener_channel;
137 GIOChannel *tcp4_listener_channel;
138 guint udp4_listener_watch;
139 guint tcp4_listener_watch;
141 GIOChannel *udp6_listener_channel;
142 GIOChannel *tcp6_listener_channel;
143 guint udp6_listener_watch;
144 guint tcp6_listener_watch;
148 * The TCP client requires some extra handling as we need to
149 * be prepared to receive also partial DNS requests.
151 struct tcp_partial_client_data {
153 struct listener_data *ifdata;
157 unsigned int buf_end;
168 unsigned int data_len;
169 unsigned char *data; /* contains DNS header + body */
176 struct cache_data *ipv4;
177 struct cache_data *ipv6;
180 struct domain_question {
183 } __attribute__ ((packed));
190 } __attribute__ ((packed));
193 * Max length of the DNS TCP packet.
195 #define TCP_MAX_BUF_LEN 4096
198 * We limit how long the cached DNS entry stays in the cache.
199 * By default the TTL (time-to-live) of the DNS response is used
200 * when setting the cache entry life time. The value is in seconds.
202 #define MAX_CACHE_TTL (60 * 30)
204 * Also limit the other end, cache at least for 30 seconds.
206 #define MIN_CACHE_TTL (30)
209 * We limit the cache size to some sane value so that cached data does
210 * not occupy too much memory. Each cached entry occupies on average
211 * about 100 bytes memory (depending on DNS name length).
212 * Example: caching www.connman.net uses 97 bytes memory.
213 * The value is the max amount of cached DNS responses (count).
215 #define MAX_CACHE_SIZE 256
217 static int cache_size;
218 static GHashTable *cache;
219 static int cache_refcount;
220 static GSList *server_list = NULL;
221 static GSList *request_list = NULL;
222 static GHashTable *listener_table = NULL;
223 static time_t next_refresh;
224 static GHashTable *partial_tcp_req_table;
225 static guint cache_timer = 0;
227 static guint16 get_id(void)
231 __connman_util_get_random(&rand);
236 static int protocol_offset(int protocol)
252 * There is a power and efficiency benefit to have entries
253 * in our cache expire at the same time. To this extend,
254 * we round down the cache valid time to common boundaries.
256 static time_t round_down_ttl(time_t end_time, int ttl)
261 /* Less than 5 minutes, round to 10 second boundary */
263 end_time = end_time / 10;
264 end_time = end_time * 10;
265 } else { /* 5 or more minutes, round to 30 seconds */
266 end_time = end_time / 30;
267 end_time = end_time * 30;
272 static struct request_data *find_request(guint16 id)
276 for (list = request_list; list; list = list->next) {
277 struct request_data *req = list->data;
279 if (req->dstid == id || req->altid == id)
286 static struct server_data *find_server(int index,
292 debug("index %d server %s proto %d", index, server, protocol);
294 for (list = server_list; list; list = list->next) {
295 struct server_data *data = list->data;
297 if (index < 0 && data->index < 0 &&
298 g_str_equal(data->server, server) &&
299 data->protocol == protocol)
303 data->index < 0 || !data->server)
306 if (data->index == index &&
307 g_str_equal(data->server, server) &&
308 data->protocol == protocol)
315 /* we can keep using the same resolve's */
316 static GResolv *ipv4_resolve;
317 static GResolv *ipv6_resolve;
319 static void dummy_resolve_func(GResolvResultStatus status,
320 char **results, gpointer user_data)
325 * Refresh a DNS entry, but also age the hit count a bit */
326 static void refresh_dns_entry(struct cache_entry *entry, char *name)
331 ipv4_resolve = g_resolv_new(0);
332 g_resolv_set_address_family(ipv4_resolve, AF_INET);
333 g_resolv_add_nameserver(ipv4_resolve, "127.0.0.1", 53, 0);
337 ipv6_resolve = g_resolv_new(0);
338 g_resolv_set_address_family(ipv6_resolve, AF_INET6);
339 g_resolv_add_nameserver(ipv6_resolve, "::1", 53, 0);
343 debug("Refreshing A record for %s", name);
344 g_resolv_lookup_hostname(ipv4_resolve, name,
345 dummy_resolve_func, NULL);
350 debug("Refreshing AAAA record for %s", name);
351 g_resolv_lookup_hostname(ipv6_resolve, name,
352 dummy_resolve_func, NULL);
361 static int dns_name_length(unsigned char *buf)
363 if ((buf[0] & NS_CMPRSFLGS) == NS_CMPRSFLGS) /* compressed name */
365 return strlen((char *)buf) + 1;
368 static void update_cached_ttl(unsigned char *buf, int len, int new_ttl)
374 /* skip the header */
378 /* skip the query, which is a name and 2 16 bit words */
379 l = dns_name_length(c);
385 /* now we get the answer records */
389 l = dns_name_length(c);
394 /* then type + class, 2 bytes each */
400 /* now the 4 byte TTL field */
401 c[0] = new_ttl >> 24 & 0xff;
402 c[1] = new_ttl >> 16 & 0xff;
403 c[2] = new_ttl >> 8 & 0xff;
404 c[3] = new_ttl & 0xff;
410 /* now the 2 byte rdlen field */
411 w = c[0] << 8 | c[1];
417 static void send_cached_response(int sk, unsigned char *buf, int len,
418 const struct sockaddr *to, socklen_t tolen,
419 int protocol, int id, uint16_t answers, int ttl)
421 struct domain_hdr *hdr;
422 unsigned char *ptr = buf;
423 int err, offset, dns_len, adj_len = len - 2;
426 * The cached packet contains always the TCP offset (two bytes)
427 * so skip them for UDP.
438 dns_len = ptr[0] * 256 + ptr[1];
447 hdr = (void *) (ptr + offset);
451 hdr->rcode = ns_r_noerror;
452 hdr->ancount = htons(answers);
456 /* if this is a negative reply, we are authoritative */
460 update_cached_ttl((unsigned char *)hdr, adj_len, ttl);
462 debug("sk %d id 0x%04x answers %d ptr %p length %d dns %d",
463 sk, hdr->id, answers, ptr, len, dns_len);
465 err = sendto(sk, ptr, len, MSG_NOSIGNAL, to, tolen);
467 connman_error("Cannot send cached DNS response: %s",
472 if (err != len || (dns_len != (len - 2) && protocol == IPPROTO_TCP) ||
473 (dns_len != len && protocol == IPPROTO_UDP))
474 debug("Packet length mismatch, sent %d wanted %d dns %d",
478 static void send_response(int sk, unsigned char *buf, size_t len,
479 const struct sockaddr *to, socklen_t tolen,
482 struct domain_hdr *hdr;
483 int err, offset = protocol_offset(protocol);
490 if (len < sizeof(*hdr) + offset)
493 hdr = (void *) (buf + offset);
496 buf[1] = sizeof(*hdr);
499 debug("id 0x%04x qr %d opcode %d", hdr->id, hdr->qr, hdr->opcode);
502 hdr->rcode = ns_r_servfail;
509 err = sendto(sk, buf, sizeof(*hdr) + offset, MSG_NOSIGNAL, to, tolen);
511 connman_error("Failed to send DNS response to %d: %s",
512 sk, strerror(errno));
517 static int get_req_udp_socket(struct request_data *req)
521 if (req->family == AF_INET)
522 channel = req->ifdata->udp4_listener_channel;
524 channel = req->ifdata->udp6_listener_channel;
529 return g_io_channel_unix_get_fd(channel);
532 static void destroy_request_data(struct request_data *req)
534 if (req->timeout > 0)
535 g_source_remove(req->timeout);
538 g_free(req->request);
543 static gboolean request_timeout(gpointer user_data)
545 struct request_data *req = user_data;
552 debug("id 0x%04x", req->srcid);
554 request_list = g_slist_remove(request_list, req);
556 if (req->protocol == IPPROTO_UDP) {
557 sk = get_req_udp_socket(req);
559 } else if (req->protocol == IPPROTO_TCP) {
565 if (req->resplen > 0 && req->resp) {
567 * Here we have received at least one reply (probably telling
568 * "not found" result), so send that back to client instead
569 * of more fatal server failed error.
572 sendto(sk, req->resp, req->resplen, MSG_NOSIGNAL,
575 } else if (req->request) {
577 * There was not reply from server at all.
579 struct domain_hdr *hdr;
581 hdr = (void *)(req->request + protocol_offset(req->protocol));
582 hdr->id = req->srcid;
585 send_response(sk, req->request, req->request_len,
586 sa, req->sa_len, req->protocol);
590 * We cannot leave TCP client hanging so just kick it out
591 * if we get a request timeout from server.
593 if (req->protocol == IPPROTO_TCP) {
594 debug("client %d removed", req->client_sk);
595 g_hash_table_remove(partial_tcp_req_table,
596 GINT_TO_POINTER(req->client_sk));
601 destroy_request_data(req);
606 static int append_query(unsigned char *buf, unsigned int size,
607 const char *query, const char *domain)
609 unsigned char *ptr = buf;
612 debug("query %s domain %s", query, domain);
617 tmp = strchr(query, '.');
623 memcpy(ptr + 1, query, len);
629 memcpy(ptr + 1, query, tmp - query);
630 ptr += tmp - query + 1;
638 tmp = strchr(domain, '.');
640 len = strlen(domain);
644 memcpy(ptr + 1, domain, len);
650 memcpy(ptr + 1, domain, tmp - domain);
651 ptr += tmp - domain + 1;
661 static bool cache_check_is_valid(struct cache_data *data,
667 if (data->cache_until < current_time)
674 * remove stale cached entries so that they can be refreshed
676 static void cache_enforce_validity(struct cache_entry *entry)
678 time_t current_time = time(NULL);
680 if (!cache_check_is_valid(entry->ipv4, current_time)
682 debug("cache timeout \"%s\" type A", entry->key);
683 g_free(entry->ipv4->data);
689 if (!cache_check_is_valid(entry->ipv6, current_time)
691 debug("cache timeout \"%s\" type AAAA", entry->key);
692 g_free(entry->ipv6->data);
698 static uint16_t cache_check_validity(char *question, uint16_t type,
699 struct cache_entry *entry)
701 time_t current_time = time(NULL);
702 bool want_refresh = false;
705 * if we have a popular entry, we want a refresh instead of
706 * total destruction of the entry.
711 cache_enforce_validity(entry);
715 if (!cache_check_is_valid(entry->ipv4, current_time)) {
716 debug("cache %s \"%s\" type A", entry->ipv4 ?
717 "timeout" : "entry missing", question);
720 entry->want_refresh = true;
723 * We do not remove cache entry if there is still
724 * valid IPv6 entry found in the cache.
726 if (!cache_check_is_valid(entry->ipv6, current_time) && !want_refresh) {
727 g_hash_table_remove(cache, question);
734 if (!cache_check_is_valid(entry->ipv6, current_time)) {
735 debug("cache %s \"%s\" type AAAA", entry->ipv6 ?
736 "timeout" : "entry missing", question);
739 entry->want_refresh = true;
741 if (!cache_check_is_valid(entry->ipv4, current_time) && !want_refresh) {
742 g_hash_table_remove(cache, question);
752 static void cache_element_destroy(gpointer value)
754 struct cache_entry *entry = value;
760 g_free(entry->ipv4->data);
765 g_free(entry->ipv6->data);
772 if (--cache_size < 0)
776 static gboolean try_remove_cache(gpointer user_data)
780 if (__sync_fetch_and_sub(&cache_refcount, 1) == 1) {
781 debug("No cache users, removing it.");
783 g_hash_table_destroy(cache);
790 static void create_cache(void)
792 if (__sync_fetch_and_add(&cache_refcount, 1) == 0)
793 cache = g_hash_table_new_full(g_str_hash,
796 cache_element_destroy);
799 static struct cache_entry *cache_check(gpointer request, int *qtype, int proto)
802 struct cache_entry *entry;
803 struct domain_question *q;
805 int offset, proto_offset;
810 proto_offset = protocol_offset(proto);
811 if (proto_offset < 0)
814 question = request + proto_offset + 12;
816 offset = strlen(question) + 1;
817 q = (void *) (question + offset);
818 type = ntohs(q->type);
820 /* We only cache either A (1) or AAAA (28) requests */
821 if (type != 1 && type != 28)
829 entry = g_hash_table_lookup(cache, question);
833 type = cache_check_validity(question, type, entry);
842 * Get a label/name from DNS resource record. The function decompresses the
843 * label if necessary. The function does not convert the name to presentation
844 * form. This means that the result string will contain label lengths instead
845 * of dots between labels. We intentionally do not want to convert to dotted
846 * format so that we can cache the wire format string directly.
848 static int get_name(int counter,
849 unsigned char *pkt, unsigned char *start, unsigned char *max,
850 unsigned char *output, int output_max, int *output_len,
851 unsigned char **end, char *name, size_t max_name, int *name_len)
855 /* Limit recursion to 10 (this means up to 10 labels in domain name) */
861 if ((*p & NS_CMPRSFLGS) == NS_CMPRSFLGS) {
862 uint16_t offset = (*p & 0x3F) * 256 + *(p + 1);
864 if (offset >= max - pkt)
870 return get_name(counter + 1, pkt, pkt + offset, max,
871 output, output_max, output_len, end,
872 name, max_name, name_len);
874 unsigned label_len = *p;
876 if (pkt + label_len > max)
879 if (*output_len > output_max)
882 if ((*name_len + 1 + label_len + 1) > max_name)
886 * We need the original name in order to check
887 * if this answer is the correct one.
889 name[(*name_len)++] = label_len;
890 memcpy(name + *name_len, p + 1, label_len + 1);
891 *name_len += label_len;
893 /* We compress the result */
894 output[0] = NS_CMPRSFLGS;
911 static int parse_rr(unsigned char *buf, unsigned char *start,
913 unsigned char *response, unsigned int *response_size,
914 uint16_t *type, uint16_t *class, int *ttl, int *rdlen,
916 char *name, size_t max_name)
918 struct domain_rr *rr;
920 int name_len = 0, output_len = 0, max_rsp = *response_size;
922 err = get_name(0, buf, start, max, response, max_rsp,
923 &output_len, end, name, max_name, &name_len);
929 if ((unsigned int) offset > *response_size)
932 rr = (void *) (*end);
937 *type = ntohs(rr->type);
938 *class = ntohs(rr->class);
939 *ttl = ntohl(rr->ttl);
940 *rdlen = ntohs(rr->rdlen);
945 memcpy(response + offset, *end, sizeof(struct domain_rr));
947 offset += sizeof(struct domain_rr);
948 *end += sizeof(struct domain_rr);
950 if ((unsigned int) (offset + *rdlen) > *response_size)
953 memcpy(response + offset, *end, *rdlen);
957 *response_size = offset + *rdlen;
962 static bool check_alias(GSList *aliases, char *name)
967 for (list = aliases; list; list = list->next) {
968 int len = strlen((char *)list->data);
969 if (strncmp((char *)list->data, name, len) == 0)
977 static int parse_response(unsigned char *buf, int buflen,
978 char *question, int qlen,
979 uint16_t *type, uint16_t *class, int *ttl,
980 unsigned char *response, unsigned int *response_len,
983 struct domain_hdr *hdr = (void *) buf;
984 struct domain_question *q;
986 uint16_t qdcount = ntohs(hdr->qdcount);
987 uint16_t ancount = ntohs(hdr->ancount);
989 uint16_t qtype, qclass;
990 unsigned char *next = NULL;
991 unsigned int maxlen = *response_len;
992 GSList *aliases = NULL, *list;
993 char name[NS_MAXDNAME + 1];
998 debug("qr %d qdcount %d", hdr->qr, qdcount);
1000 /* We currently only cache responses where question count is 1 */
1001 if (hdr->qr != 1 || qdcount != 1)
1004 ptr = buf + sizeof(struct domain_hdr);
1006 strncpy(question, (char *) ptr, qlen);
1007 qlen = strlen(question);
1008 ptr += qlen + 1; /* skip \0 */
1011 qtype = ntohs(q->type);
1013 /* We cache only A and AAAA records */
1014 if (qtype != 1 && qtype != 28)
1017 qclass = ntohs(q->class);
1019 ptr += 2 + 2; /* ptr points now to answers */
1025 memset(name, 0, sizeof(name));
1028 * We have a bunch of answers (like A, AAAA, CNAME etc) to
1029 * A or AAAA question. We traverse the answers and parse the
1030 * resource records. Only A and AAAA records are cached, all
1031 * the other records in answers are skipped.
1033 for (i = 0; i < ancount; i++) {
1035 * Get one address at a time to this buffer.
1036 * The max size of the answer is
1037 * 2 (pointer) + 2 (type) + 2 (class) +
1038 * 4 (ttl) + 2 (rdlen) + addr (16 or 4) = 28
1039 * for A or AAAA record.
1040 * For CNAME the size can be bigger.
1042 unsigned char rsp[NS_MAXCDNAME];
1043 unsigned int rsp_len = sizeof(rsp) - 1;
1046 memset(rsp, 0, sizeof(rsp));
1048 ret = parse_rr(buf, ptr, buf + buflen, rsp, &rsp_len,
1049 type, class, ttl, &rdlen, &next, name,
1057 * Now rsp contains compressed or uncompressed resource
1058 * record. Next we check if this record answers the question.
1059 * The name var contains the uncompressed label.
1060 * One tricky bit is the CNAME records as they alias
1061 * the name we might be interested in.
1065 * Go to next answer if the class is not the one we are
1068 if (*class != qclass) {
1075 * Try to resolve aliases also, type is CNAME(5).
1076 * This is important as otherwise the aliased names would not
1077 * be cached at all as the cache would not contain the aliased
1080 * If any CNAME is found in DNS packet, then we cache the alias
1081 * IP address instead of the question (as the server
1082 * said that question has only an alias).
1083 * This means in practice that if e.g., ipv6.google.com is
1084 * queried, DNS server returns CNAME of that name which is
1085 * ipv6.l.google.com. We then cache the address of the CNAME
1086 * but return the question name to client. So the alias
1087 * status of the name is not saved in cache and thus not
1088 * returned to the client. We do not return DNS packets from
1089 * cache to client saying that ipv6.google.com is an alias to
1090 * ipv6.l.google.com but we return instead a DNS packet that
1091 * says ipv6.google.com has address xxx which is in fact the
1092 * address of ipv6.l.google.com. For caching purposes this
1093 * should not cause any issues.
1095 if (*type == 5 && strncmp(question, name, qlen) == 0) {
1097 * So now the alias answered the question. This is
1098 * not very useful from caching point of view as
1099 * the following A or AAAA records will not match the
1100 * question. We need to find the real A/AAAA record
1101 * of the alias and cache that.
1103 unsigned char *end = NULL;
1104 int name_len = 0, output_len = 0;
1106 memset(rsp, 0, sizeof(rsp));
1107 rsp_len = sizeof(rsp) - 1;
1110 * Alias is in rdata part of the message,
1111 * and next-rdlen points to it. So we need to get
1112 * the real name of the alias.
1114 ret = get_name(0, buf, next - rdlen, buf + buflen,
1115 rsp, rsp_len, &output_len, &end,
1116 name, sizeof(name) - 1, &name_len);
1118 /* just ignore the error at this point */
1125 * We should now have the alias of the entry we might
1126 * want to cache. Just remember it for a while.
1127 * We check the alias list when we have parsed the
1130 aliases = g_slist_prepend(aliases, g_strdup(name));
1137 if (*type == qtype) {
1139 * We found correct type (A or AAAA)
1141 if (check_alias(aliases, name) ||
1142 (!aliases && strncmp(question, name,
1145 * We found an alias or the name of the rr
1146 * matches the question. If so, we append
1147 * the compressed label to the cache.
1148 * The end result is a response buffer that
1149 * will contain one or more cached and
1150 * compressed resource records.
1152 if (*response_len + rsp_len > maxlen) {
1156 memcpy(response + *response_len, rsp, rsp_len);
1157 *response_len += rsp_len;
1168 for (list = aliases; list; list = list->next)
1170 g_slist_free(aliases);
1175 struct cache_timeout {
1176 time_t current_time;
1181 static gboolean cache_check_entry(gpointer key, gpointer value,
1184 struct cache_timeout *data = user_data;
1185 struct cache_entry *entry = value;
1188 /* Scale the number of hits by half as part of cache aging */
1193 * If either IPv4 or IPv6 cached entry has expired, we
1194 * remove both from the cache.
1197 if (entry->ipv4 && entry->ipv4->timeout > 0) {
1198 max_timeout = entry->ipv4->cache_until;
1199 if (max_timeout > data->max_timeout)
1200 data->max_timeout = max_timeout;
1202 if (entry->ipv4->cache_until < data->current_time)
1206 if (entry->ipv6 && entry->ipv6->timeout > 0) {
1207 max_timeout = entry->ipv6->cache_until;
1208 if (max_timeout > data->max_timeout)
1209 data->max_timeout = max_timeout;
1211 if (entry->ipv6->cache_until < data->current_time)
1216 * if we're asked to try harder, also remove entries that have
1219 if (data->try_harder && entry->hits < 4)
1225 static void cache_cleanup(void)
1227 static int max_timeout;
1228 struct cache_timeout data;
1231 data.current_time = time(NULL);
1232 data.max_timeout = 0;
1233 data.try_harder = 0;
1236 * In the first pass, we only remove entries that have timed out.
1237 * We use a cache of the first time to expire to do this only
1238 * when it makes sense.
1240 if (max_timeout <= data.current_time) {
1241 count = g_hash_table_foreach_remove(cache, cache_check_entry,
1244 debug("removed %d in the first pass", count);
1247 * In the second pass, if the first pass turned up blank,
1248 * we also expire entries with a low hit count,
1249 * while aging the hit count at the same time.
1251 data.try_harder = 1;
1253 count = g_hash_table_foreach_remove(cache, cache_check_entry,
1258 * If we could not remove anything, then remember
1259 * what is the max timeout and do nothing if we
1260 * have not yet reached it. This will prevent
1261 * constant traversal of the cache if it is full.
1263 max_timeout = data.max_timeout;
1268 static gboolean cache_invalidate_entry(gpointer key, gpointer value,
1271 struct cache_entry *entry = value;
1273 /* first, delete any expired elements */
1274 cache_enforce_validity(entry);
1276 /* if anything is not expired, mark the entry for refresh */
1277 if (entry->hits > 0 && (entry->ipv4 || entry->ipv6))
1278 entry->want_refresh = true;
1280 /* delete the cached data */
1282 g_free(entry->ipv4->data);
1283 g_free(entry->ipv4);
1288 g_free(entry->ipv6->data);
1289 g_free(entry->ipv6);
1293 /* keep the entry if we want it refreshed, delete it otherwise */
1294 if (entry->want_refresh)
1301 * cache_invalidate is called from places where the DNS landscape
1302 * has changed, say because connections are added or we entered a VPN.
1303 * The logic is to wipe all cache data, but mark all non-expired
1304 * parts of the cache for refresh rather than deleting the whole cache.
1306 static void cache_invalidate(void)
1308 debug("Invalidating the DNS cache %p", cache);
1313 g_hash_table_foreach_remove(cache, cache_invalidate_entry, NULL);
1316 static void cache_refresh_entry(struct cache_entry *entry)
1319 cache_enforce_validity(entry);
1321 if (entry->hits > 2 && !entry->ipv4)
1322 entry->want_refresh = true;
1323 if (entry->hits > 2 && !entry->ipv6)
1324 entry->want_refresh = true;
1326 if (entry->want_refresh) {
1328 char dns_name[NS_MAXDNAME + 1];
1329 entry->want_refresh = false;
1331 /* turn a DNS name into a hostname with dots */
1332 strncpy(dns_name, entry->key, NS_MAXDNAME);
1340 debug("Refreshing %s\n", dns_name);
1341 /* then refresh the hostname */
1342 refresh_dns_entry(entry, &dns_name[1]);
1346 static void cache_refresh_iterator(gpointer key, gpointer value,
1349 struct cache_entry *entry = value;
1351 cache_refresh_entry(entry);
1354 static void cache_refresh(void)
1359 g_hash_table_foreach(cache, cache_refresh_iterator, NULL);
1362 static int reply_query_type(unsigned char *msg, int len)
1368 /* skip the header */
1369 c = msg + sizeof(struct domain_hdr);
1370 len -= sizeof(struct domain_hdr);
1375 /* now the query, which is a name and 2 16 bit words */
1376 l = dns_name_length(c);
1378 type = c[0] << 8 | c[1];
1383 static int cache_update(struct server_data *srv, unsigned char *msg,
1384 unsigned int msg_len)
1386 int offset = protocol_offset(srv->protocol);
1387 int err, qlen, ttl = 0;
1388 uint16_t answers = 0, type = 0, class = 0;
1389 struct domain_hdr *hdr = (void *)(msg + offset);
1390 struct domain_question *q;
1391 struct cache_entry *entry;
1392 struct cache_data *data;
1393 char question[NS_MAXDNAME + 1];
1394 unsigned char response[NS_MAXDNAME + 1];
1396 unsigned int rsplen;
1397 bool new_entry = true;
1398 time_t current_time;
1400 if (cache_size >= MAX_CACHE_SIZE) {
1402 if (cache_size >= MAX_CACHE_SIZE)
1406 current_time = time(NULL);
1408 /* don't do a cache refresh more than twice a minute */
1409 if (next_refresh < current_time) {
1411 next_refresh = current_time + 30;
1417 debug("offset %d hdr %p msg %p rcode %d", offset, hdr, msg, hdr->rcode);
1419 /* Continue only if response code is 0 (=ok) */
1420 if (hdr->rcode != ns_r_noerror)
1426 rsplen = sizeof(response) - 1;
1427 question[sizeof(question) - 1] = '\0';
1429 err = parse_response(msg + offset, msg_len - offset,
1430 question, sizeof(question) - 1,
1431 &type, &class, &ttl,
1432 response, &rsplen, &answers);
1435 * special case: if we do a ipv6 lookup and get no result
1436 * for a record that's already in our ipv4 cache.. we want
1437 * to cache the negative response.
1439 if ((err == -ENOMSG || err == -ENOBUFS) &&
1440 reply_query_type(msg + offset,
1441 msg_len - offset) == 28) {
1442 entry = g_hash_table_lookup(cache, question);
1443 if (entry && entry->ipv4 && !entry->ipv6) {
1444 int cache_offset = 0;
1446 data = g_try_new(struct cache_data, 1);
1449 data->inserted = entry->ipv4->inserted;
1451 data->answers = ntohs(hdr->ancount);
1452 data->timeout = entry->ipv4->timeout;
1453 if (srv->protocol == IPPROTO_UDP)
1455 data->data_len = msg_len + cache_offset;
1456 data->data = ptr = g_malloc(data->data_len);
1457 ptr[0] = (data->data_len - 2) / 256;
1458 ptr[1] = (data->data_len - 2) - ptr[0] * 256;
1459 if (srv->protocol == IPPROTO_UDP)
1461 data->valid_until = entry->ipv4->valid_until;
1462 data->cache_until = entry->ipv4->cache_until;
1463 memcpy(ptr, msg, msg_len);
1466 * we will get a "hit" when we serve the response
1470 if (entry->hits < 0)
1476 if (err < 0 || ttl == 0)
1479 qlen = strlen(question);
1482 * If the cache contains already data, check if the
1483 * type of the cached data is the same and do not add
1484 * to cache if data is already there.
1485 * This is needed so that we can cache both A and AAAA
1486 * records for the same name.
1488 entry = g_hash_table_lookup(cache, question);
1490 entry = g_try_new(struct cache_entry, 1);
1494 data = g_try_new(struct cache_data, 1);
1500 entry->key = g_strdup(question);
1501 entry->ipv4 = entry->ipv6 = NULL;
1502 entry->want_refresh = false;
1510 if (type == 1 && entry->ipv4)
1513 if (type == 28 && entry->ipv6)
1516 data = g_try_new(struct cache_data, 1);
1526 * compensate for the hit we'll get for serving
1527 * the response out of the cache
1530 if (entry->hits < 0)
1536 if (ttl < MIN_CACHE_TTL)
1537 ttl = MIN_CACHE_TTL;
1539 data->inserted = current_time;
1541 data->answers = answers;
1542 data->timeout = ttl;
1544 * The "2" in start of the length is the TCP offset. We allocate it
1545 * here even for UDP packet because it simplifies the sending
1548 data->data_len = 2 + 12 + qlen + 1 + 2 + 2 + rsplen;
1549 data->data = ptr = g_malloc(data->data_len);
1550 data->valid_until = current_time + ttl;
1553 * Restrict the cached DNS record TTL to some sane value
1554 * in order to prevent data staying in the cache too long.
1556 if (ttl > MAX_CACHE_TTL)
1557 ttl = MAX_CACHE_TTL;
1559 data->cache_until = round_down_ttl(current_time + ttl, ttl);
1569 * We cache the two extra bytes at the start of the message
1570 * in a TCP packet. When sending UDP packet, we skip the first
1571 * two bytes. This way we do not need to know the format
1572 * (UDP/TCP) of the cached message.
1574 if (srv->protocol == IPPROTO_UDP)
1575 memcpy(ptr + 2, msg, offset + 12);
1577 memcpy(ptr, msg, offset + 12);
1579 ptr[0] = (data->data_len - 2) / 256;
1580 ptr[1] = (data->data_len - 2) - ptr[0] * 256;
1581 if (srv->protocol == IPPROTO_UDP)
1584 memcpy(ptr + offset + 12, question, qlen + 1); /* copy also the \0 */
1586 q = (void *) (ptr + offset + 12 + qlen + 1);
1587 q->type = htons(type);
1588 q->class = htons(class);
1589 memcpy(ptr + offset + 12 + qlen + 1 + sizeof(struct domain_question),
1593 g_hash_table_replace(cache, entry->key, entry);
1597 debug("cache %d %squestion \"%s\" type %d ttl %d size %zd packet %u "
1599 cache_size, new_entry ? "new " : "old ",
1600 question, type, ttl,
1601 sizeof(*entry) + sizeof(*data) + data->data_len + qlen,
1603 srv->protocol == IPPROTO_TCP ?
1604 (unsigned int)(data->data[0] * 256 + data->data[1]) :
1610 static int ns_resolv(struct server_data *server, struct request_data *req,
1611 gpointer request, gpointer name)
1614 int sk, err, type = 0;
1615 char *dot, *lookup = (char *) name;
1616 struct cache_entry *entry;
1618 entry = cache_check(request, &type, req->protocol);
1621 struct cache_data *data;
1623 debug("cache hit %s type %s", lookup, type == 1 ? "A" : "AAAA");
1630 ttl_left = data->valid_until - time(NULL);
1634 if (data && req->protocol == IPPROTO_TCP) {
1635 send_cached_response(req->client_sk, data->data,
1636 data->data_len, NULL, 0, IPPROTO_TCP,
1637 req->srcid, data->answers, ttl_left);
1641 if (data && req->protocol == IPPROTO_UDP) {
1642 int udp_sk = get_req_udp_socket(req);
1647 send_cached_response(udp_sk, data->data,
1648 data->data_len, &req->sa, req->sa_len,
1649 IPPROTO_UDP, req->srcid, data->answers,
1655 sk = g_io_channel_unix_get_fd(server->channel);
1657 err = sendto(sk, request, req->request_len, MSG_NOSIGNAL,
1658 server->server_addr, server->server_addr_len);
1660 debug("Cannot send message to server %s sock %d "
1661 "protocol %d (%s/%d)",
1662 server->server, sk, server->protocol,
1663 strerror(errno), errno);
1669 /* If we have more than one dot, we don't add domains */
1670 dot = strchr(lookup, '.');
1671 if (dot && dot != lookup + strlen(lookup) - 1)
1674 if (server->domains && server->domains->data)
1675 req->append_domain = true;
1677 for (list = server->domains; list; list = list->next) {
1679 unsigned char alt[1024];
1680 struct domain_hdr *hdr = (void *) &alt;
1681 int altlen, domlen, offset;
1683 domain = list->data;
1688 offset = protocol_offset(server->protocol);
1692 domlen = strlen(domain) + 1;
1696 alt[offset] = req->altid & 0xff;
1697 alt[offset + 1] = req->altid >> 8;
1699 memcpy(alt + offset + 2, request + offset + 2, 10);
1700 hdr->qdcount = htons(1);
1702 altlen = append_query(alt + offset + 12, sizeof(alt) - 12,
1709 memcpy(alt + offset + altlen,
1710 request + offset + altlen - domlen,
1711 req->request_len - altlen - offset + domlen);
1713 if (server->protocol == IPPROTO_TCP) {
1714 int req_len = req->request_len + domlen - 2;
1716 alt[0] = (req_len >> 8) & 0xff;
1717 alt[1] = req_len & 0xff;
1720 debug("req %p dstid 0x%04x altid 0x%04x", req, req->dstid,
1723 err = send(sk, alt, req->request_len + domlen, MSG_NOSIGNAL);
1733 static char *convert_label(char *start, char *end, char *ptr, char *uptr,
1734 int remaining_len, int *used_comp, int *used_uncomp)
1737 char name[NS_MAXLABEL];
1739 pos = dn_expand((u_char *)start, (u_char *)end, (u_char *)ptr,
1742 debug("uncompress error [%d/%s]", errno, strerror(errno));
1747 * We need to compress back the name so that we get back to internal
1748 * label presentation.
1750 comp_pos = dn_comp(name, (u_char *)uptr, remaining_len, NULL, NULL);
1752 debug("compress error [%d/%s]", errno, strerror(errno));
1757 *used_uncomp = comp_pos;
1765 static char *uncompress(int16_t field_count, char *start, char *end,
1766 char *ptr, char *uncompressed, int uncomp_len,
1767 char **uncompressed_ptr)
1769 char *uptr = *uncompressed_ptr; /* position in result buffer */
1770 char * const uncomp_end = uncompressed + uncomp_len - 1;
1772 debug("count %d ptr %p end %p uptr %p", field_count, ptr, end, uptr);
1774 while (field_count-- > 0 && ptr < end) {
1775 int dlen; /* data field length */
1776 int ulen; /* uncompress length */
1777 int pos; /* position in compressed string */
1778 char name[NS_MAXLABEL]; /* tmp label */
1779 uint16_t dns_type, dns_class;
1782 if (!convert_label(start, end, ptr, name, NS_MAXLABEL,
1787 * Copy the uncompressed resource record, type, class and \0 to
1791 ulen = strlen(name) + 1;
1792 if ((uptr + ulen) > uncomp_end)
1794 strncpy(uptr, name, ulen);
1796 debug("pos %d ulen %d left %d name %s", pos, ulen,
1797 (int)(uncomp_end - (uptr + ulen)), uptr);
1804 * We copy also the fixed portion of the result (type, class,
1805 * ttl, address length and the address)
1807 if ((uptr + NS_RRFIXEDSZ) > uncomp_end) {
1808 debug("uncompressed data too large for buffer");
1811 memcpy(uptr, ptr, NS_RRFIXEDSZ);
1813 dns_type = uptr[0] << 8 | uptr[1];
1814 dns_class = uptr[2] << 8 | uptr[3];
1816 if (dns_class != ns_c_in)
1819 ptr += NS_RRFIXEDSZ;
1820 uptr += NS_RRFIXEDSZ;
1823 * Then the variable portion of the result (data length).
1824 * Typically this portion is also compressed
1825 * so we need to uncompress it also when necessary.
1827 if (dns_type == ns_t_cname) {
1828 if (!convert_label(start, end, ptr, uptr,
1829 uncomp_len - (uptr - uncompressed),
1833 uptr[-2] = comp_pos << 8;
1834 uptr[-1] = comp_pos & 0xff;
1839 } else if (dns_type == ns_t_a || dns_type == ns_t_aaaa) {
1840 dlen = uptr[-2] << 8 | uptr[-1];
1842 if ((ptr + dlen) > end || (uptr + dlen) > uncomp_end) {
1843 debug("data len %d too long", dlen);
1847 memcpy(uptr, ptr, dlen);
1851 } else if (dns_type == ns_t_soa) {
1855 /* Primary name server expansion */
1856 if (!convert_label(start, end, ptr, uptr,
1857 uncomp_len - (uptr - uncompressed),
1861 total_len += comp_pos;
1862 len_ptr = &uptr[-2];
1866 /* Responsible authority's mailbox */
1867 if (!convert_label(start, end, ptr, uptr,
1868 uncomp_len - (uptr - uncompressed),
1872 total_len += comp_pos;
1877 * Copy rest of the soa fields (serial number,
1878 * refresh interval, retry interval, expiration
1879 * limit and minimum ttl). They are 20 bytes long.
1881 if ((uptr + 20) > uncomp_end || (ptr + 20) > end) {
1882 debug("soa record too long");
1885 memcpy(uptr, ptr, 20);
1891 * Finally fix the length of the data part
1893 len_ptr[0] = total_len << 8;
1894 len_ptr[1] = total_len & 0xff;
1897 *uncompressed_ptr = uptr;
1906 static int strip_domains(char *name, char *answers, int maxlen)
1909 int name_len = strlen(name);
1910 char *ptr, *start = answers, *end = answers + maxlen;
1912 while (maxlen > 0) {
1913 ptr = strstr(answers, name);
1915 char *domain = ptr + name_len;
1918 int domain_len = strlen(domain);
1920 memmove(answers + name_len,
1921 domain + domain_len,
1922 end - (domain + domain_len));
1925 maxlen -= domain_len;
1929 answers += strlen(answers) + 1;
1930 answers += 2 + 2 + 4; /* skip type, class and ttl fields */
1932 data_len = answers[0] << 8 | answers[1];
1933 answers += 2; /* skip the length field */
1935 if (answers + data_len > end)
1938 answers += data_len;
1939 maxlen -= answers - ptr;
1945 static int forward_dns_reply(unsigned char *reply, int reply_len, int protocol,
1946 struct server_data *data)
1948 struct domain_hdr *hdr;
1949 struct request_data *req;
1950 int dns_id, sk, err, offset = protocol_offset(protocol);
1955 hdr = (void *)(reply + offset);
1956 dns_id = reply[offset] | reply[offset + 1] << 8;
1958 debug("Received %d bytes (id 0x%04x)", reply_len, dns_id);
1960 req = find_request(dns_id);
1964 debug("req %p dstid 0x%04x altid 0x%04x rcode %d",
1965 req, req->dstid, req->altid, hdr->rcode);
1967 reply[offset] = req->srcid & 0xff;
1968 reply[offset + 1] = req->srcid >> 8;
1972 if (hdr->rcode == ns_r_noerror || !req->resp) {
1973 unsigned char *new_reply = NULL;
1976 * If the domain name was append
1977 * remove it before forwarding the reply.
1978 * If there were more than one question, then this
1979 * domain name ripping can be hairy so avoid that
1980 * and bail out in that that case.
1982 * The reason we are doing this magic is that if the
1983 * user's DNS client tries to resolv hostname without
1984 * domain part, it also expects to get the result without
1985 * a domain name part.
1987 if (req->append_domain && ntohs(hdr->qdcount) == 1) {
1988 uint16_t domain_len = 0;
1989 uint16_t header_len;
1990 uint16_t dns_type, dns_class;
1991 uint8_t host_len, dns_type_pos;
1992 char uncompressed[NS_MAXDNAME], *uptr;
1993 char *ptr, *eom = (char *)reply + reply_len;
1996 * ptr points to the first char of the hostname.
1997 * ->hostname.domain.net
1999 header_len = offset + sizeof(struct domain_hdr);
2000 ptr = (char *)reply + header_len;
2004 domain_len = strnlen(ptr + 1 + host_len,
2005 reply_len - header_len);
2008 * If the query type is anything other than A or AAAA,
2009 * then bail out and pass the message as is.
2010 * We only want to deal with IPv4 or IPv6 addresses.
2012 dns_type_pos = host_len + 1 + domain_len + 1;
2014 dns_type = ptr[dns_type_pos] << 8 |
2015 ptr[dns_type_pos + 1];
2016 dns_class = ptr[dns_type_pos + 2] << 8 |
2017 ptr[dns_type_pos + 3];
2018 if (dns_type != ns_t_a && dns_type != ns_t_aaaa &&
2019 dns_class != ns_c_in) {
2020 debug("Pass msg dns type %d class %d",
2021 dns_type, dns_class);
2026 * Remove the domain name and replace it by the end
2027 * of reply. Check if the domain is really there
2028 * before trying to copy the data. We also need to
2029 * uncompress the answers if necessary.
2030 * The domain_len can be 0 because if the original
2031 * query did not contain a domain name, then we are
2032 * sending two packets, first without the domain name
2033 * and the second packet with domain name.
2034 * The append_domain is set to true even if we sent
2035 * the first packet without domain name. In this
2036 * case we end up in this branch.
2038 if (domain_len > 0) {
2039 int len = host_len + 1;
2040 int new_len, fixed_len;
2044 * First copy host (without domain name) into
2047 uptr = &uncompressed[0];
2048 memcpy(uptr, ptr, len);
2050 uptr[len] = '\0'; /* host termination */
2054 * Copy type and class fields of the question.
2056 ptr += len + domain_len + 1;
2057 memcpy(uptr, ptr, NS_QFIXEDSZ);
2060 * ptr points to answers after this
2063 uptr += NS_QFIXEDSZ;
2065 fixed_len = answers - uncompressed;
2068 * We then uncompress the result to buffer
2069 * so that we can rip off the domain name
2070 * part from the question. First answers,
2071 * then name server (authority) information,
2072 * and finally additional record info.
2075 ptr = uncompress(ntohs(hdr->ancount),
2076 (char *)reply + offset, eom,
2077 ptr, uncompressed, NS_MAXDNAME,
2082 ptr = uncompress(ntohs(hdr->nscount),
2083 (char *)reply + offset, eom,
2084 ptr, uncompressed, NS_MAXDNAME,
2089 ptr = uncompress(ntohs(hdr->arcount),
2090 (char *)reply + offset, eom,
2091 ptr, uncompressed, NS_MAXDNAME,
2097 * The uncompressed buffer now contains almost
2098 * valid response. Final step is to get rid of
2099 * the domain name because at least glibc
2100 * gethostbyname() implementation does extra
2101 * checks and expects to find an answer without
2102 * domain name if we asked a query without
2103 * domain part. Note that glibc getaddrinfo()
2104 * works differently and accepts FQDN in answer
2106 new_len = strip_domains(uncompressed, answers,
2109 debug("Corrupted packet");
2114 * Because we have now uncompressed the answers
2115 * we might have to create a bigger buffer to
2116 * hold all that data.
2119 reply_len = header_len + new_len + fixed_len;
2121 new_reply = g_try_malloc(reply_len);
2125 memcpy(new_reply, reply, header_len);
2126 memcpy(new_reply + header_len, uncompressed,
2127 new_len + fixed_len);
2137 req->resp = g_try_malloc(reply_len);
2141 memcpy(req->resp, reply, reply_len);
2142 req->resplen = reply_len;
2144 cache_update(data, reply, reply_len);
2150 if (req->numresp < req->numserv) {
2151 if (hdr->rcode > ns_r_noerror) {
2153 } else if (hdr->ancount == 0 && req->append_domain) {
2158 request_list = g_slist_remove(request_list, req);
2160 if (protocol == IPPROTO_UDP) {
2161 sk = get_req_udp_socket(req);
2166 err = sendto(sk, req->resp, req->resplen, 0,
2167 &req->sa, req->sa_len);
2169 sk = req->client_sk;
2170 err = send(sk, req->resp, req->resplen, MSG_NOSIGNAL);
2174 debug("Cannot send msg, sk %d proto %d errno %d/%s", sk,
2175 protocol, errno, strerror(errno));
2177 debug("proto %d sent %d bytes to %d", protocol, err, sk);
2179 destroy_request_data(req);
2184 static void server_destroy_socket(struct server_data *data)
2186 debug("index %d server %s proto %d", data->index,
2187 data->server, data->protocol);
2189 if (data->watch > 0) {
2190 g_source_remove(data->watch);
2194 if (data->timeout > 0) {
2195 g_source_remove(data->timeout);
2199 if (data->channel) {
2200 g_io_channel_shutdown(data->channel, TRUE, NULL);
2201 g_io_channel_unref(data->channel);
2202 data->channel = NULL;
2205 g_free(data->incoming_reply);
2206 data->incoming_reply = NULL;
2209 static void destroy_server(struct server_data *server)
2211 debug("index %d server %s sock %d", server->index, server->server,
2213 g_io_channel_unix_get_fd(server->channel): -1);
2215 server_list = g_slist_remove(server_list, server);
2216 server_destroy_socket(server);
2218 if (server->protocol == IPPROTO_UDP && server->enabled)
2219 debug("Removing DNS server %s", server->server);
2221 g_free(server->server);
2222 g_list_free_full(server->domains, g_free);
2223 g_free(server->server_addr);
2226 * We do not remove cache right away but delay it few seconds.
2227 * The idea is that when IPv6 DNS server is added via RDNSS, it has a
2228 * lifetime. When the lifetime expires we decrease the refcount so it
2229 * is possible that the cache is then removed. Because a new DNS server
2230 * is usually created almost immediately we would then loose the cache
2231 * without any good reason. The small delay allows the new RDNSS to
2232 * create a new DNS server instance and the refcount does not go to 0.
2234 if (cache && !cache_timer)
2235 cache_timer = g_timeout_add_seconds(3, try_remove_cache, NULL);
2240 static gboolean udp_server_event(GIOChannel *channel, GIOCondition condition,
2243 unsigned char buf[4096];
2245 struct server_data *data = user_data;
2247 if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
2248 connman_error("Error with UDP server %s", data->server);
2249 server_destroy_socket(data);
2253 sk = g_io_channel_unix_get_fd(channel);
2255 len = recv(sk, buf, sizeof(buf), 0);
2258 forward_dns_reply(buf, len, IPPROTO_UDP, data);
2263 static gboolean tcp_server_event(GIOChannel *channel, GIOCondition condition,
2267 struct server_data *server = user_data;
2269 sk = g_io_channel_unix_get_fd(channel);
2273 if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
2276 debug("TCP server channel closed, sk %d", sk);
2279 * Discard any partial response which is buffered; better
2280 * to get a proper response from a working server.
2282 g_free(server->incoming_reply);
2283 server->incoming_reply = NULL;
2285 list = request_list;
2287 struct request_data *req = list->data;
2288 struct domain_hdr *hdr;
2291 if (req->protocol == IPPROTO_UDP)
2298 * If we're not waiting for any further response
2299 * from another name server, then we send an error
2300 * response to the client.
2302 if (req->numserv && --(req->numserv))
2305 hdr = (void *) (req->request + 2);
2306 hdr->id = req->srcid;
2307 send_response(req->client_sk, req->request,
2308 req->request_len, NULL, 0, IPPROTO_TCP);
2310 request_list = g_slist_remove(request_list, req);
2313 destroy_server(server);
2318 if ((condition & G_IO_OUT) && !server->connected) {
2321 bool no_request_sent = true;
2322 struct server_data *udp_server;
2324 udp_server = find_server(server->index, server->server,
2327 for (domains = udp_server->domains; domains;
2328 domains = domains->next) {
2329 char *dom = domains->data;
2331 debug("Adding domain %s to %s",
2332 dom, server->server);
2334 server->domains = g_list_append(server->domains,
2339 server->connected = true;
2340 server_list = g_slist_append(server_list, server);
2342 if (server->timeout > 0) {
2343 g_source_remove(server->timeout);
2344 server->timeout = 0;
2347 for (list = request_list; list; ) {
2348 struct request_data *req = list->data;
2351 if (req->protocol == IPPROTO_UDP) {
2356 debug("Sending req %s over TCP", (char *)req->name);
2358 status = ns_resolv(server, req,
2359 req->request, req->name);
2362 * A cached result was sent,
2363 * so the request can be released
2366 request_list = g_slist_remove(request_list, req);
2367 destroy_request_data(req);
2376 no_request_sent = false;
2378 if (req->timeout > 0)
2379 g_source_remove(req->timeout);
2381 req->timeout = g_timeout_add_seconds(30,
2382 request_timeout, req);
2386 if (no_request_sent) {
2387 destroy_server(server);
2391 } else if (condition & G_IO_IN) {
2392 struct partial_reply *reply = server->incoming_reply;
2396 unsigned char reply_len_buf[2];
2399 bytes_recv = recv(sk, reply_len_buf, 2, MSG_PEEK);
2402 } else if (bytes_recv < 0) {
2403 if (errno == EAGAIN || errno == EWOULDBLOCK)
2406 connman_error("DNS proxy error %s",
2409 } else if (bytes_recv < 2)
2412 reply_len = reply_len_buf[1] | reply_len_buf[0] << 8;
2415 debug("TCP reply %d bytes from %d", reply_len, sk);
2417 reply = g_try_malloc(sizeof(*reply) + reply_len + 2);
2421 reply->len = reply_len;
2422 reply->received = 0;
2424 server->incoming_reply = reply;
2427 while (reply->received < reply->len) {
2428 bytes_recv = recv(sk, reply->buf + reply->received,
2429 reply->len - reply->received, 0);
2431 connman_error("DNS proxy TCP disconnect");
2433 } else if (bytes_recv < 0) {
2434 if (errno == EAGAIN || errno == EWOULDBLOCK)
2437 connman_error("DNS proxy error %s",
2441 reply->received += bytes_recv;
2444 forward_dns_reply(reply->buf, reply->received, IPPROTO_TCP,
2448 server->incoming_reply = NULL;
2450 destroy_server(server);
2458 static gboolean tcp_idle_timeout(gpointer user_data)
2460 struct server_data *server = user_data;
2467 destroy_server(server);
2472 static int server_create_socket(struct server_data *data)
2477 debug("index %d server %s proto %d", data->index,
2478 data->server, data->protocol);
2480 sk = socket(data->server_addr->sa_family,
2481 data->protocol == IPPROTO_TCP ? SOCK_STREAM : SOCK_DGRAM,
2485 connman_error("Failed to create server %s socket",
2487 server_destroy_socket(data);
2493 interface = connman_inet_ifname(data->index);
2495 if (setsockopt(sk, SOL_SOCKET, SO_BINDTODEVICE,
2497 strlen(interface) + 1) < 0) {
2499 connman_error("Failed to bind server %s "
2501 data->server, interface);
2503 server_destroy_socket(data);
2510 data->channel = g_io_channel_unix_new(sk);
2511 if (!data->channel) {
2512 connman_error("Failed to create server %s channel",
2515 server_destroy_socket(data);
2519 g_io_channel_set_close_on_unref(data->channel, TRUE);
2521 if (data->protocol == IPPROTO_TCP) {
2522 g_io_channel_set_flags(data->channel, G_IO_FLAG_NONBLOCK, NULL);
2523 data->watch = g_io_add_watch(data->channel,
2524 G_IO_OUT | G_IO_IN | G_IO_HUP | G_IO_NVAL | G_IO_ERR,
2525 tcp_server_event, data);
2526 data->timeout = g_timeout_add_seconds(30, tcp_idle_timeout,
2529 data->watch = g_io_add_watch(data->channel,
2530 G_IO_IN | G_IO_NVAL | G_IO_ERR | G_IO_HUP,
2531 udp_server_event, data);
2533 if (connect(sk, data->server_addr, data->server_addr_len) < 0) {
2536 if ((data->protocol == IPPROTO_TCP && errno != EINPROGRESS) ||
2537 data->protocol == IPPROTO_UDP) {
2539 connman_error("Failed to connect to server %s",
2541 server_destroy_socket(data);
2551 static void enable_fallback(bool enable)
2555 for (list = server_list; list; list = list->next) {
2556 struct server_data *data = list->data;
2558 if (data->index != -1)
2562 DBG("Enabling fallback DNS server %s", data->server);
2564 DBG("Disabling fallback DNS server %s", data->server);
2566 data->enabled = enable;
2570 static struct server_data *create_server(int index,
2571 const char *domain, const char *server,
2574 struct server_data *data;
2575 struct addrinfo hints, *rp;
2578 DBG("index %d server %s", index, server);
2580 data = g_try_new0(struct server_data, 1);
2582 connman_error("Failed to allocate server %s data", server);
2586 data->index = index;
2588 data->domains = g_list_append(data->domains, g_strdup(domain));
2589 data->server = g_strdup(server);
2590 data->protocol = protocol;
2592 memset(&hints, 0, sizeof(hints));
2596 hints.ai_socktype = SOCK_DGRAM;
2600 hints.ai_socktype = SOCK_STREAM;
2604 destroy_server(data);
2607 hints.ai_family = AF_UNSPEC;
2608 hints.ai_flags = AI_NUMERICSERV | AI_NUMERICHOST;
2610 ret = getaddrinfo(data->server, "53", &hints, &rp);
2612 connman_error("Failed to parse server %s address: %s\n",
2613 data->server, gai_strerror(ret));
2614 destroy_server(data);
2618 /* Do not blindly copy this code elsewhere; it doesn't loop over the
2619 results using ->ai_next as it should. That's OK in *this* case
2620 because it was a numeric lookup; we *know* there's only one. */
2622 data->server_addr_len = rp->ai_addrlen;
2624 switch (rp->ai_family) {
2626 data->server_addr = (struct sockaddr *)
2627 g_try_new0(struct sockaddr_in, 1);
2630 data->server_addr = (struct sockaddr *)
2631 g_try_new0(struct sockaddr_in6, 1);
2634 connman_error("Wrong address family %d", rp->ai_family);
2637 if (!data->server_addr) {
2639 destroy_server(data);
2642 memcpy(data->server_addr, rp->ai_addr, rp->ai_addrlen);
2645 if (server_create_socket(data) != 0) {
2646 destroy_server(data);
2650 if (protocol == IPPROTO_UDP) {
2651 if (__connman_service_index_is_default(data->index) ||
2652 __connman_service_index_is_split_routing(
2654 data->enabled = true;
2655 DBG("Adding DNS server %s", data->server);
2657 enable_fallback(false);
2660 server_list = g_slist_append(server_list, data);
2666 static bool resolv(struct request_data *req,
2667 gpointer request, gpointer name)
2671 for (list = server_list; list; list = list->next) {
2672 struct server_data *data = list->data;
2674 if (data->protocol == IPPROTO_TCP) {
2675 DBG("server %s ignored proto TCP", data->server);
2679 debug("server %s enabled %d", data->server, data->enabled);
2684 if (!data->channel && data->protocol == IPPROTO_UDP) {
2685 if (server_create_socket(data) < 0) {
2686 DBG("socket creation failed while resolving");
2691 if (ns_resolv(data, req, request, name) > 0)
2698 static void update_domain(int index, const char *domain, bool append)
2702 DBG("index %d domain %s", index, domain);
2707 for (list = server_list; list; list = list->next) {
2708 struct server_data *data = list->data;
2711 bool dom_found = false;
2713 if (data->index < 0)
2716 if (data->index != index)
2719 for (dom_list = data->domains; dom_list;
2720 dom_list = dom_list->next) {
2721 dom = dom_list->data;
2723 if (g_str_equal(dom, domain)) {
2729 if (!dom_found && append) {
2731 g_list_append(data->domains, g_strdup(domain));
2732 } else if (dom_found && !append) {
2734 g_list_remove(data->domains, dom);
2740 static void append_domain(int index, const char *domain)
2742 update_domain(index, domain, true);
2745 static void remove_domain(int index, const char *domain)
2747 update_domain(index, domain, false);
2750 static void flush_requests(struct server_data *server)
2754 list = request_list;
2756 struct request_data *req = list->data;
2760 if (ns_resolv(server, req, req->request, req->name)) {
2762 * A cached result was sent,
2763 * so the request can be released
2766 g_slist_remove(request_list, req);
2767 destroy_request_data(req);
2771 if (req->timeout > 0)
2772 g_source_remove(req->timeout);
2774 req->timeout = g_timeout_add_seconds(5, request_timeout, req);
2778 int __connman_dnsproxy_append(int index, const char *domain,
2781 struct server_data *data;
2783 DBG("index %d server %s", index, server);
2785 if (!server && !domain)
2789 append_domain(index, domain);
2794 if (g_str_equal(server, "127.0.0.1"))
2797 if (g_str_equal(server, "::1"))
2800 data = find_server(index, server, IPPROTO_UDP);
2802 append_domain(index, domain);
2806 data = create_server(index, domain, server, IPPROTO_UDP);
2810 flush_requests(data);
2815 static void remove_server(int index, const char *domain,
2816 const char *server, int protocol)
2818 struct server_data *data;
2821 data = find_server(index, server, protocol);
2825 destroy_server(data);
2827 for (list = server_list; list; list = list->next) {
2828 struct server_data *data = list->data;
2830 if (data->index != -1 && data->enabled == true)
2834 enable_fallback(true);
2837 int __connman_dnsproxy_remove(int index, const char *domain,
2840 DBG("index %d server %s", index, server);
2842 if (!server && !domain)
2846 remove_domain(index, domain);
2851 if (g_str_equal(server, "127.0.0.1"))
2854 if (g_str_equal(server, "::1"))
2857 remove_server(index, domain, server, IPPROTO_UDP);
2858 remove_server(index, domain, server, IPPROTO_TCP);
2863 static void dnsproxy_offline_mode(bool enabled)
2867 DBG("enabled %d", enabled);
2869 for (list = server_list; list; list = list->next) {
2870 struct server_data *data = list->data;
2873 DBG("Enabling DNS server %s", data->server);
2874 data->enabled = true;
2878 DBG("Disabling DNS server %s", data->server);
2879 data->enabled = false;
2885 static void dnsproxy_default_changed(struct connman_service *service)
2887 bool server_enabled = false;
2892 DBG("service %p", service);
2894 /* DNS has changed, invalidate the cache */
2898 /* When no services are active, then disable DNS proxying */
2899 dnsproxy_offline_mode(true);
2903 index = __connman_service_get_index(service);
2908 * In case non-split-routed VPN is set as split routed the DNS servers
2909 * the VPN must be enabled as well, when the transport becomes the
2912 vpn_index = __connman_connection_get_vpn_index(index);
2914 for (list = server_list; list; list = list->next) {
2915 struct server_data *data = list->data;
2917 if (data->index == index) {
2918 DBG("Enabling DNS server %s", data->server);
2919 data->enabled = true;
2920 server_enabled = true;
2921 } else if (data->index == vpn_index) {
2922 DBG("Enabling DNS server of VPN %s", data->server);
2923 data->enabled = true;
2925 DBG("Disabling DNS server %s", data->server);
2926 data->enabled = false;
2930 if (!server_enabled)
2931 enable_fallback(true);
2936 static void dnsproxy_service_state_changed(struct connman_service *service,
2937 enum connman_service_state state)
2943 case CONNMAN_SERVICE_STATE_DISCONNECT:
2944 case CONNMAN_SERVICE_STATE_IDLE:
2946 case CONNMAN_SERVICE_STATE_ASSOCIATION:
2947 case CONNMAN_SERVICE_STATE_CONFIGURATION:
2948 case CONNMAN_SERVICE_STATE_FAILURE:
2949 case CONNMAN_SERVICE_STATE_ONLINE:
2950 case CONNMAN_SERVICE_STATE_READY:
2951 case CONNMAN_SERVICE_STATE_UNKNOWN:
2955 index = __connman_service_get_index(service);
2959 struct server_data *data = list->data;
2961 /* Get next before the list is changed by destroy_server() */
2964 if (data->index == index) {
2965 DBG("removing server data of index %d", index);
2966 destroy_server(data);
2971 static const struct connman_notifier dnsproxy_notifier = {
2973 .default_changed = dnsproxy_default_changed,
2974 .offline_mode = dnsproxy_offline_mode,
2975 .service_state_changed = dnsproxy_service_state_changed,
2978 static const unsigned char opt_edns0_type[2] = { 0x00, 0x29 };
2980 static int parse_request(unsigned char *buf, size_t len,
2981 char *name, unsigned int size)
2983 struct domain_hdr *hdr = (void *) buf;
2984 uint16_t qdcount = ntohs(hdr->qdcount);
2985 uint16_t ancount = ntohs(hdr->ancount);
2986 uint16_t nscount = ntohs(hdr->nscount);
2987 uint16_t arcount = ntohs(hdr->arcount);
2989 unsigned int remain, used = 0;
2991 if (len < sizeof(*hdr) + sizeof(struct qtype_qclass) ||
2992 hdr->qr || qdcount != 1 || ancount || nscount) {
2993 DBG("Dropped DNS request qr %d with len %zd qdcount %d "
2994 "ancount %d nscount %d", hdr->qr, len, qdcount, ancount,
3003 debug("id 0x%04x qr %d opcode %d qdcount %d arcount %d",
3004 hdr->id, hdr->qr, hdr->opcode,
3009 ptr = buf + sizeof(struct domain_hdr);
3010 remain = len - sizeof(struct domain_hdr);
3012 while (remain > 0) {
3013 uint8_t label_len = *ptr;
3015 if (label_len == 0x00) {
3017 struct qtype_qclass *q =
3018 (struct qtype_qclass *)(ptr + 1);
3020 if (remain < sizeof(*q)) {
3021 DBG("Dropped malformed DNS query");
3025 class = ntohs(q->qclass);
3026 if (class != 1 && class != 255) {
3027 DBG("Dropped non-IN DNS class %d", class);
3031 ptr += sizeof(*q) + 1;
3032 remain -= (sizeof(*q) + 1);
3036 if (used + label_len + 1 > size)
3039 strncat(name, (char *) (ptr + 1), label_len);
3042 used += label_len + 1;
3044 ptr += label_len + 1;
3045 remain -= label_len + 1;
3048 if (arcount && remain >= sizeof(struct domain_rr) + 1 && !ptr[0] &&
3049 ptr[1] == opt_edns0_type[0] && ptr[2] == opt_edns0_type[1]) {
3050 struct domain_rr *edns0 = (struct domain_rr *)(ptr + 1);
3052 DBG("EDNS0 buffer size %u", ntohs(edns0->class));
3053 } else if (!arcount && remain) {
3054 DBG("DNS request with %d garbage bytes", remain);
3057 debug("query %s", name);
3062 static void client_reset(struct tcp_partial_client_data *client)
3067 if (client->channel) {
3068 debug("client %d closing",
3069 g_io_channel_unix_get_fd(client->channel));
3071 g_io_channel_unref(client->channel);
3072 client->channel = NULL;
3075 if (client->watch > 0) {
3076 g_source_remove(client->watch);
3080 if (client->timeout > 0) {
3081 g_source_remove(client->timeout);
3082 client->timeout = 0;
3085 g_free(client->buf);
3088 client->buf_end = 0;
3091 static unsigned int get_msg_len(unsigned char *buf)
3093 return buf[0]<<8 | buf[1];
3096 static bool read_tcp_data(struct tcp_partial_client_data *client,
3097 void *client_addr, socklen_t client_addr_len,
3100 char query[TCP_MAX_BUF_LEN];
3101 struct request_data *req;
3103 unsigned int msg_len;
3105 bool waiting_for_connect = false;
3107 struct cache_entry *entry;
3109 client_sk = g_io_channel_unix_get_fd(client->channel);
3111 if (read_len == 0) {
3112 debug("client %d closed, pending %d bytes",
3113 client_sk, client->buf_end);
3114 g_hash_table_remove(partial_tcp_req_table,
3115 GINT_TO_POINTER(client_sk));
3119 debug("client %d received %d bytes", client_sk, read_len);
3121 client->buf_end += read_len;
3123 if (client->buf_end < 2)
3126 msg_len = get_msg_len(client->buf);
3127 if (msg_len > TCP_MAX_BUF_LEN) {
3128 debug("client %d sent too much data %d", client_sk, msg_len);
3129 g_hash_table_remove(partial_tcp_req_table,
3130 GINT_TO_POINTER(client_sk));
3135 debug("client %d msg len %d end %d past end %d", client_sk, msg_len,
3136 client->buf_end, client->buf_end - (msg_len + 2));
3138 if (client->buf_end < (msg_len + 2)) {
3139 debug("client %d still missing %d bytes",
3141 msg_len + 2 - client->buf_end);
3145 debug("client %d all data %d received", client_sk, msg_len);
3147 err = parse_request(client->buf + 2, msg_len,
3148 query, sizeof(query));
3149 if (err < 0 || (g_slist_length(server_list) == 0)) {
3150 send_response(client_sk, client->buf, msg_len + 2,
3151 NULL, 0, IPPROTO_TCP);
3155 req = g_try_new0(struct request_data, 1);
3159 memcpy(&req->sa, client_addr, client_addr_len);
3160 req->sa_len = client_addr_len;
3161 req->client_sk = client_sk;
3162 req->protocol = IPPROTO_TCP;
3163 req->family = client->family;
3165 req->srcid = client->buf[2] | (client->buf[3] << 8);
3166 req->dstid = get_id();
3167 req->altid = get_id();
3168 req->request_len = msg_len + 2;
3170 client->buf[2] = req->dstid & 0xff;
3171 client->buf[3] = req->dstid >> 8;
3174 req->ifdata = client->ifdata;
3175 req->append_domain = false;
3178 * Check if the answer is found in the cache before
3179 * creating sockets to the server.
3181 entry = cache_check(client->buf, &qtype, IPPROTO_TCP);
3184 struct cache_data *data;
3186 debug("cache hit %s type %s", query, qtype == 1 ? "A" : "AAAA");
3193 ttl_left = data->valid_until - time(NULL);
3196 send_cached_response(client_sk, data->data,
3197 data->data_len, NULL, 0, IPPROTO_TCP,
3198 req->srcid, data->answers, ttl_left);
3203 debug("data missing, ignoring cache for this query");
3206 for (list = server_list; list; list = list->next) {
3207 struct server_data *data = list->data;
3209 if (data->protocol != IPPROTO_UDP || !data->enabled)
3212 if (!create_server(data->index, NULL, data->server,
3216 waiting_for_connect = true;
3219 if (!waiting_for_connect) {
3220 /* No server is waiting for connect */
3221 send_response(client_sk, client->buf,
3222 req->request_len, NULL, 0, IPPROTO_TCP);
3228 * The server is not connected yet.
3229 * Copy the relevant buffers.
3230 * The request will actually be sent once we're
3231 * properly connected over TCP to the nameserver.
3233 req->request = g_try_malloc0(req->request_len);
3234 if (!req->request) {
3235 send_response(client_sk, client->buf,
3236 req->request_len, NULL, 0, IPPROTO_TCP);
3240 memcpy(req->request, client->buf, req->request_len);
3242 req->name = g_try_malloc0(sizeof(query));
3244 send_response(client_sk, client->buf,
3245 req->request_len, NULL, 0, IPPROTO_TCP);
3246 g_free(req->request);
3250 memcpy(req->name, query, sizeof(query));
3252 req->timeout = g_timeout_add_seconds(30, request_timeout, req);
3254 request_list = g_slist_append(request_list, req);
3257 if (client->buf_end > (msg_len + 2)) {
3258 debug("client %d buf %p -> %p end %d len %d new %d",
3260 client->buf + msg_len + 2,
3261 client->buf, client->buf_end,
3262 TCP_MAX_BUF_LEN - client->buf_end,
3263 client->buf_end - (msg_len + 2));
3264 memmove(client->buf, client->buf + msg_len + 2,
3265 TCP_MAX_BUF_LEN - client->buf_end);
3266 client->buf_end = client->buf_end - (msg_len + 2);
3269 * If we have a full message waiting, just read it
3272 msg_len = get_msg_len(client->buf);
3273 if ((msg_len + 2) == client->buf_end) {
3274 debug("client %d reading another %d bytes", client_sk,
3279 debug("client %d clearing reading buffer", client_sk);
3281 client->buf_end = 0;
3282 memset(client->buf, 0, TCP_MAX_BUF_LEN);
3285 * We received all the packets from client so we must also
3286 * remove the timeout handler here otherwise we might get
3287 * timeout while waiting the results from server.
3289 g_source_remove(client->timeout);
3290 client->timeout = 0;
3296 static gboolean tcp_client_event(GIOChannel *channel, GIOCondition condition,
3299 struct tcp_partial_client_data *client = user_data;
3300 struct sockaddr_in6 client_addr6;
3301 socklen_t client_addr6_len = sizeof(client_addr6);
3302 struct sockaddr_in client_addr4;
3303 socklen_t client_addr4_len = sizeof(client_addr4);
3305 socklen_t *client_addr_len;
3308 client_sk = g_io_channel_unix_get_fd(channel);
3310 if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
3311 g_hash_table_remove(partial_tcp_req_table,
3312 GINT_TO_POINTER(client_sk));
3314 connman_error("Error with TCP client %d channel", client_sk);
3318 switch (client->family) {
3320 client_addr = &client_addr4;
3321 client_addr_len = &client_addr4_len;
3324 client_addr = &client_addr6;
3325 client_addr_len = &client_addr6_len;
3328 g_hash_table_remove(partial_tcp_req_table,
3329 GINT_TO_POINTER(client_sk));
3330 connman_error("client %p corrupted", client);
3334 len = recvfrom(client_sk, client->buf + client->buf_end,
3335 TCP_MAX_BUF_LEN - client->buf_end, 0,
3336 client_addr, client_addr_len);
3338 if (errno == EAGAIN || errno == EWOULDBLOCK)
3341 debug("client %d cannot read errno %d/%s", client_sk, -errno,
3343 g_hash_table_remove(partial_tcp_req_table,
3344 GINT_TO_POINTER(client_sk));
3348 return read_tcp_data(client, client_addr, *client_addr_len, len);
3351 static gboolean client_timeout(gpointer user_data)
3353 struct tcp_partial_client_data *client = user_data;
3356 sock = g_io_channel_unix_get_fd(client->channel);
3358 debug("client %d timeout pending %d bytes", sock, client->buf_end);
3360 g_hash_table_remove(partial_tcp_req_table, GINT_TO_POINTER(sock));
3365 static bool tcp_listener_event(GIOChannel *channel, GIOCondition condition,
3366 struct listener_data *ifdata, int family,
3367 guint *listener_watch)
3369 int sk, client_sk, len;
3370 unsigned int msg_len;
3371 struct tcp_partial_client_data *client;
3372 struct sockaddr_in6 client_addr6;
3373 socklen_t client_addr6_len = sizeof(client_addr6);
3374 struct sockaddr_in client_addr4;
3375 socklen_t client_addr4_len = sizeof(client_addr4);
3377 socklen_t *client_addr_len;
3381 debug("condition 0x%02x channel %p ifdata %p family %d",
3382 condition, channel, ifdata, family);
3384 if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
3385 if (*listener_watch > 0)
3386 g_source_remove(*listener_watch);
3387 *listener_watch = 0;
3389 connman_error("Error with TCP listener channel");
3394 sk = g_io_channel_unix_get_fd(channel);
3396 if (family == AF_INET) {
3397 client_addr = &client_addr4;
3398 client_addr_len = &client_addr4_len;
3400 client_addr = &client_addr6;
3401 client_addr_len = &client_addr6_len;
3404 tv.tv_sec = tv.tv_usec = 0;
3406 FD_SET(sk, &readfds);
3408 select(sk + 1, &readfds, NULL, NULL, &tv);
3409 if (FD_ISSET(sk, &readfds)) {
3410 client_sk = accept(sk, client_addr, client_addr_len);
3411 debug("client %d accepted", client_sk);
3413 debug("No data to read from master %d, waiting.", sk);
3417 if (client_sk < 0) {
3418 connman_error("Accept failure on TCP listener");
3419 *listener_watch = 0;
3423 fcntl(client_sk, F_SETFL, O_NONBLOCK);
3425 client = g_hash_table_lookup(partial_tcp_req_table,
3426 GINT_TO_POINTER(client_sk));
3428 client = g_try_new0(struct tcp_partial_client_data, 1);
3434 g_hash_table_insert(partial_tcp_req_table,
3435 GINT_TO_POINTER(client_sk),
3438 client->channel = g_io_channel_unix_new(client_sk);
3439 g_io_channel_set_close_on_unref(client->channel, TRUE);
3441 client->watch = g_io_add_watch(client->channel,
3442 G_IO_IN, tcp_client_event,
3445 client->ifdata = ifdata;
3447 debug("client %d created %p", client_sk, client);
3449 debug("client %d already exists %p", client_sk, client);
3453 client->buf = g_try_malloc(TCP_MAX_BUF_LEN);
3457 memset(client->buf, 0, TCP_MAX_BUF_LEN);
3458 client->buf_end = 0;
3459 client->family = family;
3461 if (client->timeout == 0)
3462 client->timeout = g_timeout_add_seconds(2, client_timeout,
3466 * Check how much data there is. If all is there, then we can
3467 * proceed normally, otherwise read the bits until everything
3468 * is received or timeout occurs.
3470 len = recv(client_sk, client->buf, TCP_MAX_BUF_LEN, 0);
3472 if (errno == EAGAIN || errno == EWOULDBLOCK) {
3473 debug("client %d no data to read, waiting", client_sk);
3477 debug("client %d cannot read errno %d/%s", client_sk, -errno,
3479 g_hash_table_remove(partial_tcp_req_table,
3480 GINT_TO_POINTER(client_sk));
3485 debug("client %d not enough data to read, waiting", client_sk);
3486 client->buf_end += len;
3490 msg_len = get_msg_len(client->buf);
3491 if (msg_len > TCP_MAX_BUF_LEN) {
3492 debug("client %d invalid message length %u ignoring packet",
3493 client_sk, msg_len);
3494 g_hash_table_remove(partial_tcp_req_table,
3495 GINT_TO_POINTER(client_sk));
3500 * The packet length bytes do not contain the total message length,
3501 * that is the reason to -2 below.
3503 if (msg_len != (unsigned int)(len - 2)) {
3504 debug("client %d sent %d bytes but expecting %u pending %d",
3505 client_sk, len, msg_len + 2, msg_len + 2 - len);
3507 client->buf_end += len;
3511 return read_tcp_data(client, client_addr, *client_addr_len, len);
3514 static gboolean tcp4_listener_event(GIOChannel *channel, GIOCondition condition,
3517 struct listener_data *ifdata = user_data;
3519 return tcp_listener_event(channel, condition, ifdata, AF_INET,
3520 &ifdata->tcp4_listener_watch);
3523 static gboolean tcp6_listener_event(GIOChannel *channel, GIOCondition condition,
3526 struct listener_data *ifdata = user_data;
3528 return tcp_listener_event(channel, condition, user_data, AF_INET6,
3529 &ifdata->tcp6_listener_watch);
3532 static bool udp_listener_event(GIOChannel *channel, GIOCondition condition,
3533 struct listener_data *ifdata, int family,
3534 guint *listener_watch)
3536 unsigned char buf[768];
3538 struct request_data *req;
3539 struct sockaddr_in6 client_addr6;
3540 socklen_t client_addr6_len = sizeof(client_addr6);
3541 struct sockaddr_in client_addr4;
3542 socklen_t client_addr4_len = sizeof(client_addr4);
3544 socklen_t *client_addr_len;
3547 if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
3548 connman_error("Error with UDP listener channel");
3549 *listener_watch = 0;
3553 sk = g_io_channel_unix_get_fd(channel);
3555 if (family == AF_INET) {
3556 client_addr = &client_addr4;
3557 client_addr_len = &client_addr4_len;
3559 client_addr = &client_addr6;
3560 client_addr_len = &client_addr6_len;
3563 memset(client_addr, 0, *client_addr_len);
3564 len = recvfrom(sk, buf, sizeof(buf), 0, client_addr, client_addr_len);
3568 debug("Received %d bytes (id 0x%04x)", len, buf[0] | buf[1] << 8);
3570 err = parse_request(buf, len, query, sizeof(query));
3571 if (err < 0 || (g_slist_length(server_list) == 0)) {
3572 send_response(sk, buf, len, client_addr,
3573 *client_addr_len, IPPROTO_UDP);
3577 req = g_try_new0(struct request_data, 1);
3581 memcpy(&req->sa, client_addr, *client_addr_len);
3582 req->sa_len = *client_addr_len;
3584 req->protocol = IPPROTO_UDP;
3585 req->family = family;
3587 req->srcid = buf[0] | (buf[1] << 8);
3588 req->dstid = get_id();
3589 req->altid = get_id();
3590 req->request_len = len;
3592 buf[0] = req->dstid & 0xff;
3593 buf[1] = req->dstid >> 8;
3596 req->ifdata = ifdata;
3597 req->append_domain = false;
3599 if (resolv(req, buf, query)) {
3600 /* a cached result was sent, so the request can be released */
3605 req->name = g_strdup(query);
3606 req->request = g_malloc(len);
3607 memcpy(req->request, buf, len);
3608 req->timeout = g_timeout_add_seconds(5, request_timeout, req);
3609 request_list = g_slist_append(request_list, req);
3614 static gboolean udp4_listener_event(GIOChannel *channel, GIOCondition condition,
3617 struct listener_data *ifdata = user_data;
3619 return udp_listener_event(channel, condition, ifdata, AF_INET,
3620 &ifdata->udp4_listener_watch);
3623 static gboolean udp6_listener_event(GIOChannel *channel, GIOCondition condition,
3626 struct listener_data *ifdata = user_data;
3628 return udp_listener_event(channel, condition, user_data, AF_INET6,
3629 &ifdata->udp6_listener_watch);
3632 static GIOChannel *get_listener(int family, int protocol, int index)
3634 GIOChannel *channel;
3638 struct sockaddr_in6 sin6;
3639 struct sockaddr_in sin;
3645 debug("family %d protocol %d index %d", family, protocol, index);
3650 type = SOCK_DGRAM | SOCK_CLOEXEC;
3655 type = SOCK_STREAM | SOCK_CLOEXEC;
3662 sk = socket(family, type, protocol);
3663 if (sk < 0 && family == AF_INET6 && errno == EAFNOSUPPORT) {
3664 connman_error("No IPv6 support");
3669 connman_error("Failed to create %s listener socket", proto);
3673 interface = connman_inet_ifname(index);
3674 if (!interface || setsockopt(sk, SOL_SOCKET, SO_BINDTODEVICE,
3676 strlen(interface) + 1) < 0) {
3677 connman_error("Failed to bind %s listener interface "
3679 proto, family == AF_INET ? "IPv4" : "IPv6",
3680 -errno, strerror(errno));
3687 if (family == AF_INET6) {
3688 memset(&s.sin6, 0, sizeof(s.sin6));
3689 s.sin6.sin6_family = AF_INET6;
3690 s.sin6.sin6_port = htons(53);
3691 slen = sizeof(s.sin6);
3693 if (__connman_inet_get_interface_address(index,
3695 &s.sin6.sin6_addr) < 0) {
3696 /* So we could not find suitable IPv6 address for
3697 * the interface. This could happen if we have
3698 * disabled IPv6 for the interface.
3704 } else if (family == AF_INET) {
3705 memset(&s.sin, 0, sizeof(s.sin));
3706 s.sin.sin_family = AF_INET;
3707 s.sin.sin_port = htons(53);
3708 slen = sizeof(s.sin);
3710 if (__connman_inet_get_interface_address(index,
3712 &s.sin.sin_addr) < 0) {
3721 if (bind(sk, &s.sa, slen) < 0) {
3722 connman_error("Failed to bind %s listener socket", proto);
3727 if (protocol == IPPROTO_TCP) {
3729 if (listen(sk, 10) < 0) {
3730 connman_error("Failed to listen on TCP socket %d/%s",
3731 -errno, strerror(errno));
3736 fcntl(sk, F_SETFL, O_NONBLOCK);
3739 channel = g_io_channel_unix_new(sk);
3741 connman_error("Failed to create %s listener channel", proto);
3746 g_io_channel_set_close_on_unref(channel, TRUE);
3751 #define UDP_IPv4_FAILED 0x01
3752 #define TCP_IPv4_FAILED 0x02
3753 #define UDP_IPv6_FAILED 0x04
3754 #define TCP_IPv6_FAILED 0x08
3755 #define UDP_FAILED (UDP_IPv4_FAILED | UDP_IPv6_FAILED)
3756 #define TCP_FAILED (TCP_IPv4_FAILED | TCP_IPv6_FAILED)
3757 #define IPv6_FAILED (UDP_IPv6_FAILED | TCP_IPv6_FAILED)
3758 #define IPv4_FAILED (UDP_IPv4_FAILED | TCP_IPv4_FAILED)
3760 static int create_dns_listener(int protocol, struct listener_data *ifdata)
3764 if (protocol == IPPROTO_TCP) {
3765 ifdata->tcp4_listener_channel = get_listener(AF_INET, protocol,
3767 if (ifdata->tcp4_listener_channel)
3768 ifdata->tcp4_listener_watch =
3769 g_io_add_watch(ifdata->tcp4_listener_channel,
3770 G_IO_IN, tcp4_listener_event,
3773 ret |= TCP_IPv4_FAILED;
3775 ifdata->tcp6_listener_channel = get_listener(AF_INET6, protocol,
3777 if (ifdata->tcp6_listener_channel)
3778 ifdata->tcp6_listener_watch =
3779 g_io_add_watch(ifdata->tcp6_listener_channel,
3780 G_IO_IN, tcp6_listener_event,
3783 ret |= TCP_IPv6_FAILED;
3785 ifdata->udp4_listener_channel = get_listener(AF_INET, protocol,
3787 if (ifdata->udp4_listener_channel)
3788 ifdata->udp4_listener_watch =
3789 g_io_add_watch(ifdata->udp4_listener_channel,
3790 G_IO_IN, udp4_listener_event,
3793 ret |= UDP_IPv4_FAILED;
3795 ifdata->udp6_listener_channel = get_listener(AF_INET6, protocol,
3797 if (ifdata->udp6_listener_channel)
3798 ifdata->udp6_listener_watch =
3799 g_io_add_watch(ifdata->udp6_listener_channel,
3800 G_IO_IN, udp6_listener_event,
3803 ret |= UDP_IPv6_FAILED;
3809 static void destroy_udp_listener(struct listener_data *ifdata)
3811 DBG("index %d", ifdata->index);
3813 if (ifdata->udp4_listener_watch > 0)
3814 g_source_remove(ifdata->udp4_listener_watch);
3816 if (ifdata->udp6_listener_watch > 0)
3817 g_source_remove(ifdata->udp6_listener_watch);
3819 if (ifdata->udp4_listener_channel)
3820 g_io_channel_unref(ifdata->udp4_listener_channel);
3821 if (ifdata->udp6_listener_channel)
3822 g_io_channel_unref(ifdata->udp6_listener_channel);
3825 static void destroy_tcp_listener(struct listener_data *ifdata)
3827 DBG("index %d", ifdata->index);
3829 if (ifdata->tcp4_listener_watch > 0)
3830 g_source_remove(ifdata->tcp4_listener_watch);
3831 if (ifdata->tcp6_listener_watch > 0)
3832 g_source_remove(ifdata->tcp6_listener_watch);
3834 if (ifdata->tcp4_listener_channel)
3835 g_io_channel_unref(ifdata->tcp4_listener_channel);
3836 if (ifdata->tcp6_listener_channel)
3837 g_io_channel_unref(ifdata->tcp6_listener_channel);
3840 static int create_listener(struct listener_data *ifdata)
3844 err = create_dns_listener(IPPROTO_UDP, ifdata);
3845 if ((err & UDP_FAILED) == UDP_FAILED)
3848 err |= create_dns_listener(IPPROTO_TCP, ifdata);
3849 if ((err & TCP_FAILED) == TCP_FAILED) {
3850 destroy_udp_listener(ifdata);
3854 index = connman_inet_ifindex("lo");
3855 if (ifdata->index == index) {
3856 if ((err & IPv6_FAILED) != IPv6_FAILED)
3857 __connman_resolvfile_append(index, NULL, "::1");
3859 if ((err & IPv4_FAILED) != IPv4_FAILED)
3860 __connman_resolvfile_append(index, NULL, "127.0.0.1");
3866 static void destroy_listener(struct listener_data *ifdata)
3871 index = connman_inet_ifindex("lo");
3872 if (ifdata->index == index) {
3873 __connman_resolvfile_remove(index, NULL, "127.0.0.1");
3874 __connman_resolvfile_remove(index, NULL, "::1");
3877 for (list = request_list; list; list = list->next) {
3878 struct request_data *req = list->data;
3880 debug("Dropping request (id 0x%04x -> 0x%04x)",
3881 req->srcid, req->dstid);
3882 destroy_request_data(req);
3886 g_slist_free(request_list);
3887 request_list = NULL;
3889 destroy_tcp_listener(ifdata);
3890 destroy_udp_listener(ifdata);
3893 int __connman_dnsproxy_add_listener(int index)
3895 struct listener_data *ifdata;
3898 DBG("index %d", index);
3903 if (!listener_table)
3906 if (g_hash_table_lookup(listener_table, GINT_TO_POINTER(index)))
3909 ifdata = g_try_new0(struct listener_data, 1);
3913 ifdata->index = index;
3914 ifdata->udp4_listener_channel = NULL;
3915 ifdata->udp4_listener_watch = 0;
3916 ifdata->tcp4_listener_channel = NULL;
3917 ifdata->tcp4_listener_watch = 0;
3918 ifdata->udp6_listener_channel = NULL;
3919 ifdata->udp6_listener_watch = 0;
3920 ifdata->tcp6_listener_channel = NULL;
3921 ifdata->tcp6_listener_watch = 0;
3923 err = create_listener(ifdata);
3925 connman_error("Couldn't create listener for index %d err %d",
3930 g_hash_table_insert(listener_table, GINT_TO_POINTER(ifdata->index),
3935 void __connman_dnsproxy_remove_listener(int index)
3937 struct listener_data *ifdata;
3939 DBG("index %d", index);
3941 if (!listener_table)
3944 ifdata = g_hash_table_lookup(listener_table, GINT_TO_POINTER(index));
3948 destroy_listener(ifdata);
3950 g_hash_table_remove(listener_table, GINT_TO_POINTER(index));
3953 static void remove_listener(gpointer key, gpointer value, gpointer user_data)
3955 int index = GPOINTER_TO_INT(key);
3956 struct listener_data *ifdata = value;
3958 DBG("index %d", index);
3960 destroy_listener(ifdata);
3963 static void free_partial_reqs(gpointer value)
3965 struct tcp_partial_client_data *data = value;
3971 int __connman_dnsproxy_init(void)
3977 listener_table = g_hash_table_new_full(g_direct_hash, g_direct_equal,
3980 partial_tcp_req_table = g_hash_table_new_full(g_direct_hash,
3985 index = connman_inet_ifindex("lo");
3986 err = __connman_dnsproxy_add_listener(index);
3990 err = connman_notifier_register(&dnsproxy_notifier);
3997 __connman_dnsproxy_remove_listener(index);
3998 g_hash_table_destroy(listener_table);
3999 g_hash_table_destroy(partial_tcp_req_table);
4004 int __connman_dnsproxy_set_mdns(int index, bool enabled)
4009 void __connman_dnsproxy_cleanup(void)
4014 g_source_remove(cache_timer);
4019 g_hash_table_destroy(cache);
4023 connman_notifier_unregister(&dnsproxy_notifier);
4025 g_hash_table_foreach(listener_table, remove_listener, NULL);
4027 g_hash_table_destroy(listener_table);
4029 g_hash_table_destroy(partial_tcp_req_table);
4032 g_resolv_unref(ipv4_resolve);
4034 g_resolv_unref(ipv6_resolve);