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>
45 #include <sys/smack.h>
46 #include <systemd/sd-daemon.h>
49 #define debug(fmt...) do { } while (0)
51 #if __BYTE_ORDER == __LITTLE_ENDIAN
66 } __attribute__ ((packed));
67 #elif __BYTE_ORDER == __BIG_ENDIAN
82 } __attribute__ ((packed));
84 #error "Unknown byte order"
90 } __attribute__ ((packed));
92 struct partial_reply {
102 struct sockaddr *server_addr;
103 socklen_t server_addr_len;
110 struct partial_reply *incoming_reply;
113 struct request_data {
115 struct sockaddr_in6 __sin6; /* Only for the length */
134 struct listener_data *ifdata;
138 struct listener_data {
141 GIOChannel *udp4_listener_channel;
142 GIOChannel *tcp4_listener_channel;
143 guint udp4_listener_watch;
144 guint tcp4_listener_watch;
146 GIOChannel *udp6_listener_channel;
147 GIOChannel *tcp6_listener_channel;
148 guint udp6_listener_watch;
149 guint tcp6_listener_watch;
153 * The TCP client requires some extra handling as we need to
154 * be prepared to receive also partial DNS requests.
156 struct tcp_partial_client_data {
158 struct listener_data *ifdata;
162 unsigned int buf_end;
173 unsigned int data_len;
174 unsigned char *data; /* contains DNS header + body */
181 struct cache_data *ipv4;
182 struct cache_data *ipv6;
185 struct domain_question {
188 } __attribute__ ((packed));
195 } __attribute__ ((packed));
198 * Max length of the DNS TCP packet.
200 #define TCP_MAX_BUF_LEN 4096
203 * We limit how long the cached DNS entry stays in the cache.
204 * By default the TTL (time-to-live) of the DNS response is used
205 * when setting the cache entry life time. The value is in seconds.
207 #if defined TIZEN_EXT
208 #define MAX_CACHE_TTL (60 * 60)
210 #define MAX_CACHE_TTL (60 * 30)
213 * Also limit the other end, cache at least for 30 seconds.
215 #define MIN_CACHE_TTL (30)
218 * We limit the cache size to some sane value so that cached data does
219 * not occupy too much memory. Each cached entry occupies on average
220 * about 100 bytes memory (depending on DNS name length).
221 * Example: caching www.connman.net uses 97 bytes memory.
222 * The value is the max amount of cached DNS responses (count).
224 #define MAX_CACHE_SIZE 256
226 static int cache_size;
227 static GHashTable *cache;
228 static int cache_refcount;
229 static GSList *server_list = NULL;
230 #if defined TIZEN_EXT
231 static GSList *server_list_sec = NULL;
233 static GSList *request_list = NULL;
234 static GHashTable *listener_table = NULL;
235 static time_t next_refresh;
236 static GHashTable *partial_tcp_req_table;
237 static guint cache_timer = 0;
239 #if defined TIZEN_EXT
240 static void destroy_server_sec(struct server_data *server);
241 static struct server_data *create_server_sec(int index,
242 const char *domain, const char *server,
246 static guint16 get_id(void)
250 __connman_util_get_random(&rand);
255 static int protocol_offset(int protocol)
271 * There is a power and efficiency benefit to have entries
272 * in our cache expire at the same time. To this extend,
273 * we round down the cache valid time to common boundaries.
275 static time_t round_down_ttl(time_t end_time, int ttl)
280 /* Less than 5 minutes, round to 10 second boundary */
282 end_time = end_time / 10;
283 end_time = end_time * 10;
284 } else { /* 5 or more minutes, round to 30 seconds */
285 end_time = end_time / 30;
286 end_time = end_time * 30;
291 static struct request_data *find_request(guint16 id)
295 for (list = request_list; list; list = list->next) {
296 struct request_data *req = list->data;
298 if (req->dstid == id || req->altid == id)
305 static struct server_data *find_server(int index,
311 debug("index %d server %s proto %d", index, server, protocol);
313 for (list = server_list; list; list = list->next) {
314 struct server_data *data = list->data;
316 if (index < 0 && data->index < 0 &&
317 g_str_equal(data->server, server) &&
318 data->protocol == protocol)
322 data->index < 0 || !data->server)
325 if (data->index == index &&
326 g_str_equal(data->server, server) &&
327 data->protocol == protocol)
334 /* we can keep using the same resolve's */
335 static GResolv *ipv4_resolve;
336 static GResolv *ipv6_resolve;
338 static void dummy_resolve_func(GResolvResultStatus status,
339 char **results, gpointer user_data)
344 * Refresh a DNS entry, but also age the hit count a bit */
345 static void refresh_dns_entry(struct cache_entry *entry, char *name)
350 ipv4_resolve = g_resolv_new(0);
351 g_resolv_set_address_family(ipv4_resolve, AF_INET);
352 g_resolv_add_nameserver(ipv4_resolve, "127.0.0.1", 53, 0);
356 ipv6_resolve = g_resolv_new(0);
357 g_resolv_set_address_family(ipv6_resolve, AF_INET6);
358 g_resolv_add_nameserver(ipv6_resolve, "::1", 53, 0);
362 debug("Refreshing A record for %s", name);
363 g_resolv_lookup_hostname(ipv4_resolve, name,
364 dummy_resolve_func, NULL);
369 debug("Refreshing AAAA record for %s", name);
370 g_resolv_lookup_hostname(ipv6_resolve, name,
371 dummy_resolve_func, NULL);
380 static int dns_name_length(unsigned char *buf)
382 if ((buf[0] & NS_CMPRSFLGS) == NS_CMPRSFLGS) /* compressed name */
384 return strlen((char *)buf) + 1;
387 static void update_cached_ttl(unsigned char *buf, int len, int new_ttl)
393 /* skip the header */
397 /* skip the query, which is a name and 2 16 bit words */
398 l = dns_name_length(c);
404 /* now we get the answer records */
408 l = dns_name_length(c);
413 /* then type + class, 2 bytes each */
419 /* now the 4 byte TTL field */
420 c[0] = new_ttl >> 24 & 0xff;
421 c[1] = new_ttl >> 16 & 0xff;
422 c[2] = new_ttl >> 8 & 0xff;
423 c[3] = new_ttl & 0xff;
429 /* now the 2 byte rdlen field */
430 w = c[0] << 8 | c[1];
436 static void send_cached_response(int sk, unsigned char *buf, int len,
437 const struct sockaddr *to, socklen_t tolen,
438 int protocol, int id, uint16_t answers, int ttl)
440 struct domain_hdr *hdr;
441 unsigned char *ptr = buf;
442 int err, offset, dns_len, adj_len = len - 2;
445 * The cached packet contains always the TCP offset (two bytes)
446 * so skip them for UDP.
457 dns_len = ptr[0] * 256 + ptr[1];
466 hdr = (void *) (ptr + offset);
470 hdr->rcode = ns_r_noerror;
471 hdr->ancount = htons(answers);
475 /* if this is a negative reply, we are authorative */
479 update_cached_ttl((unsigned char *)hdr, adj_len, ttl);
481 debug("sk %d id 0x%04x answers %d ptr %p length %d dns %d",
482 sk, hdr->id, answers, ptr, len, dns_len);
484 err = sendto(sk, ptr, len, MSG_NOSIGNAL, to, tolen);
486 connman_error("Cannot send cached DNS response: %s",
491 if (err != len || (dns_len != (len - 2) && protocol == IPPROTO_TCP) ||
492 (dns_len != len && protocol == IPPROTO_UDP))
493 debug("Packet length mismatch, sent %d wanted %d dns %d",
497 static void send_response(int sk, unsigned char *buf, size_t len,
498 const struct sockaddr *to, socklen_t tolen,
501 struct domain_hdr *hdr;
502 int err, offset = protocol_offset(protocol);
509 if (len < sizeof(*hdr) + offset)
512 hdr = (void *) (buf + offset);
515 buf[1] = sizeof(*hdr);
518 debug("id 0x%04x qr %d opcode %d", hdr->id, hdr->qr, hdr->opcode);
521 hdr->rcode = ns_r_servfail;
528 err = sendto(sk, buf, sizeof(*hdr) + offset, MSG_NOSIGNAL, to, tolen);
530 connman_error("Failed to send DNS response to %d: %s",
531 sk, strerror(errno));
536 static int get_req_udp_socket(struct request_data *req)
540 if (req->family == AF_INET)
541 channel = req->ifdata->udp4_listener_channel;
543 channel = req->ifdata->udp6_listener_channel;
548 return g_io_channel_unix_get_fd(channel);
551 static void destroy_request_data(struct request_data *req)
553 if (req->timeout > 0)
554 g_source_remove(req->timeout);
557 g_free(req->request);
562 static gboolean request_timeout(gpointer user_data)
564 struct request_data *req = user_data;
571 debug("id 0x%04x", req->srcid);
573 request_list = g_slist_remove(request_list, req);
575 if (req->protocol == IPPROTO_UDP) {
576 sk = get_req_udp_socket(req);
578 } else if (req->protocol == IPPROTO_TCP) {
584 if (req->resplen > 0 && req->resp) {
586 * Here we have received at least one reply (probably telling
587 * "not found" result), so send that back to client instead
588 * of more fatal server failed error.
591 sendto(sk, req->resp, req->resplen, MSG_NOSIGNAL,
594 } else if (req->request) {
596 * There was not reply from server at all.
598 struct domain_hdr *hdr;
600 hdr = (void *)(req->request + protocol_offset(req->protocol));
601 hdr->id = req->srcid;
604 send_response(sk, req->request, req->request_len,
605 sa, req->sa_len, req->protocol);
609 * We cannot leave TCP client hanging so just kick it out
610 * if we get a request timeout from server.
612 if (req->protocol == IPPROTO_TCP) {
613 debug("client %d removed", req->client_sk);
614 g_hash_table_remove(partial_tcp_req_table,
615 GINT_TO_POINTER(req->client_sk));
620 destroy_request_data(req);
625 static int append_query(unsigned char *buf, unsigned int size,
626 const char *query, const char *domain)
628 unsigned char *ptr = buf;
631 debug("query %s domain %s", query, domain);
636 tmp = strchr(query, '.');
642 memcpy(ptr + 1, query, len);
648 memcpy(ptr + 1, query, tmp - query);
649 ptr += tmp - query + 1;
657 tmp = strchr(domain, '.');
659 len = strlen(domain);
663 memcpy(ptr + 1, domain, len);
669 memcpy(ptr + 1, domain, tmp - domain);
670 ptr += tmp - domain + 1;
680 static bool cache_check_is_valid(struct cache_data *data,
686 if (data->cache_until < current_time)
693 * remove stale cached entries so that they can be refreshed
695 static void cache_enforce_validity(struct cache_entry *entry)
697 time_t current_time = time(NULL);
699 if (!cache_check_is_valid(entry->ipv4, current_time)
701 debug("cache timeout \"%s\" type A", entry->key);
702 g_free(entry->ipv4->data);
708 if (!cache_check_is_valid(entry->ipv6, current_time)
710 debug("cache timeout \"%s\" type AAAA", entry->key);
711 g_free(entry->ipv6->data);
717 static uint16_t cache_check_validity(char *question, uint16_t type,
718 struct cache_entry *entry)
720 time_t current_time = time(NULL);
721 bool want_refresh = false;
724 * if we have a popular entry, we want a refresh instead of
725 * total destruction of the entry.
730 cache_enforce_validity(entry);
734 if (!cache_check_is_valid(entry->ipv4, current_time)) {
735 debug("cache %s \"%s\" type A", entry->ipv4 ?
736 "timeout" : "entry missing", question);
739 entry->want_refresh = true;
742 * We do not remove cache entry if there is still
743 * valid IPv6 entry found in the cache.
745 if (!cache_check_is_valid(entry->ipv6, current_time) && !want_refresh) {
746 g_hash_table_remove(cache, question);
753 if (!cache_check_is_valid(entry->ipv6, current_time)) {
754 debug("cache %s \"%s\" type AAAA", entry->ipv6 ?
755 "timeout" : "entry missing", question);
758 entry->want_refresh = true;
760 if (!cache_check_is_valid(entry->ipv4, current_time) && !want_refresh) {
761 g_hash_table_remove(cache, question);
771 static void cache_element_destroy(gpointer value)
773 struct cache_entry *entry = value;
779 g_free(entry->ipv4->data);
784 g_free(entry->ipv6->data);
791 if (--cache_size < 0)
795 static gboolean try_remove_cache(gpointer user_data)
799 if (__sync_fetch_and_sub(&cache_refcount, 1) == 1) {
800 debug("No cache users, removing it.");
802 g_hash_table_destroy(cache);
809 static void create_cache(void)
811 if (__sync_fetch_and_add(&cache_refcount, 1) == 0)
812 cache = g_hash_table_new_full(g_str_hash,
815 cache_element_destroy);
818 static struct cache_entry *cache_check(gpointer request, int *qtype, int proto)
821 struct cache_entry *entry;
822 struct domain_question *q;
824 int offset, proto_offset;
829 proto_offset = protocol_offset(proto);
830 if (proto_offset < 0)
833 question = request + proto_offset + 12;
835 offset = strlen(question) + 1;
836 q = (void *) (question + offset);
837 type = ntohs(q->type);
839 /* We only cache either A (1) or AAAA (28) requests */
840 if (type != 1 && type != 28)
848 entry = g_hash_table_lookup(cache, question);
852 type = cache_check_validity(question, type, entry);
861 * Get a label/name from DNS resource record. The function decompresses the
862 * label if necessary. The function does not convert the name to presentation
863 * form. This means that the result string will contain label lengths instead
864 * of dots between labels. We intentionally do not want to convert to dotted
865 * format so that we can cache the wire format string directly.
867 static int get_name(int counter,
868 unsigned char *pkt, unsigned char *start, unsigned char *max,
869 unsigned char *output, int output_max, int *output_len,
870 unsigned char **end, char *name, size_t max_name, int *name_len)
874 /* Limit recursion to 10 (this means up to 10 labels in domain name) */
880 if ((*p & NS_CMPRSFLGS) == NS_CMPRSFLGS) {
881 uint16_t offset = (*p & 0x3F) * 256 + *(p + 1);
883 if (offset >= max - pkt)
889 return get_name(counter + 1, pkt, pkt + offset, max,
890 output, output_max, output_len, end,
891 name, max_name, name_len);
893 unsigned label_len = *p;
895 if (pkt + label_len > max)
898 if (*output_len > output_max)
901 if ((*name_len + 1 + label_len + 1) > max_name)
905 * We need the original name in order to check
906 * if this answer is the correct one.
908 name[(*name_len)++] = label_len;
909 memcpy(name + *name_len, p + 1, label_len + 1);
910 *name_len += label_len;
912 /* We compress the result */
913 output[0] = NS_CMPRSFLGS;
930 static int parse_rr(unsigned char *buf, unsigned char *start,
932 unsigned char *response, unsigned int *response_size,
933 uint16_t *type, uint16_t *class, int *ttl, int *rdlen,
935 char *name, size_t max_name)
937 struct domain_rr *rr;
939 int name_len = 0, output_len = 0, max_rsp = *response_size;
941 err = get_name(0, buf, start, max, response, max_rsp,
942 &output_len, end, name, max_name, &name_len);
948 if ((unsigned int) offset > *response_size)
951 rr = (void *) (*end);
956 *type = ntohs(rr->type);
957 *class = ntohs(rr->class);
958 *ttl = ntohl(rr->ttl);
959 *rdlen = ntohs(rr->rdlen);
964 memcpy(response + offset, *end, sizeof(struct domain_rr));
966 offset += sizeof(struct domain_rr);
967 *end += sizeof(struct domain_rr);
969 if ((unsigned int) (offset + *rdlen) > *response_size)
972 memcpy(response + offset, *end, *rdlen);
976 *response_size = offset + *rdlen;
981 static bool check_alias(GSList *aliases, char *name)
986 for (list = aliases; list; list = list->next) {
987 int len = strlen((char *)list->data);
988 if (strncmp((char *)list->data, name, len) == 0)
996 static int parse_response(unsigned char *buf, int buflen,
997 char *question, int qlen,
998 uint16_t *type, uint16_t *class, int *ttl,
999 unsigned char *response, unsigned int *response_len,
1002 struct domain_hdr *hdr = (void *) buf;
1003 struct domain_question *q;
1005 uint16_t qdcount = ntohs(hdr->qdcount);
1006 uint16_t ancount = ntohs(hdr->ancount);
1008 uint16_t qtype, qclass;
1009 unsigned char *next = NULL;
1010 unsigned int maxlen = *response_len;
1011 GSList *aliases = NULL, *list;
1012 char name[NS_MAXDNAME + 1];
1017 debug("qr %d qdcount %d", hdr->qr, qdcount);
1019 /* We currently only cache responses where question count is 1 */
1020 if (hdr->qr != 1 || qdcount != 1)
1023 ptr = buf + sizeof(struct domain_hdr);
1025 strncpy(question, (char *) ptr, qlen);
1026 qlen = strlen(question);
1027 ptr += qlen + 1; /* skip \0 */
1030 qtype = ntohs(q->type);
1032 /* We cache only A and AAAA records */
1033 if (qtype != 1 && qtype != 28)
1036 qclass = ntohs(q->class);
1038 ptr += 2 + 2; /* ptr points now to answers */
1044 memset(name, 0, sizeof(name));
1047 * We have a bunch of answers (like A, AAAA, CNAME etc) to
1048 * A or AAAA question. We traverse the answers and parse the
1049 * resource records. Only A and AAAA records are cached, all
1050 * the other records in answers are skipped.
1052 for (i = 0; i < ancount; i++) {
1054 * Get one address at a time to this buffer.
1055 * The max size of the answer is
1056 * 2 (pointer) + 2 (type) + 2 (class) +
1057 * 4 (ttl) + 2 (rdlen) + addr (16 or 4) = 28
1058 * for A or AAAA record.
1059 * For CNAME the size can be bigger.
1061 unsigned char rsp[NS_MAXCDNAME];
1062 unsigned int rsp_len = sizeof(rsp) - 1;
1065 memset(rsp, 0, sizeof(rsp));
1067 ret = parse_rr(buf, ptr, buf + buflen, rsp, &rsp_len,
1068 type, class, ttl, &rdlen, &next, name,
1076 * Now rsp contains compressed or uncompressed resource
1077 * record. Next we check if this record answers the question.
1078 * The name var contains the uncompressed label.
1079 * One tricky bit is the CNAME records as they alias
1080 * the name we might be interested in.
1084 * Go to next answer if the class is not the one we are
1087 if (*class != qclass) {
1094 * Try to resolve aliases also, type is CNAME(5).
1095 * This is important as otherwise the aliased names would not
1096 * be cached at all as the cache would not contain the aliased
1099 * If any CNAME is found in DNS packet, then we cache the alias
1100 * IP address instead of the question (as the server
1101 * said that question has only an alias).
1102 * This means in practice that if e.g., ipv6.google.com is
1103 * queried, DNS server returns CNAME of that name which is
1104 * ipv6.l.google.com. We then cache the address of the CNAME
1105 * but return the question name to client. So the alias
1106 * status of the name is not saved in cache and thus not
1107 * returned to the client. We do not return DNS packets from
1108 * cache to client saying that ipv6.google.com is an alias to
1109 * ipv6.l.google.com but we return instead a DNS packet that
1110 * says ipv6.google.com has address xxx which is in fact the
1111 * address of ipv6.l.google.com. For caching purposes this
1112 * should not cause any issues.
1114 if (*type == 5 && strncmp(question, name, qlen) == 0) {
1116 * So now the alias answered the question. This is
1117 * not very useful from caching point of view as
1118 * the following A or AAAA records will not match the
1119 * question. We need to find the real A/AAAA record
1120 * of the alias and cache that.
1122 unsigned char *end = NULL;
1123 int name_len = 0, output_len = 0;
1125 memset(rsp, 0, sizeof(rsp));
1126 rsp_len = sizeof(rsp) - 1;
1129 * Alias is in rdata part of the message,
1130 * and next-rdlen points to it. So we need to get
1131 * the real name of the alias.
1133 ret = get_name(0, buf, next - rdlen, buf + buflen,
1134 rsp, rsp_len, &output_len, &end,
1135 name, sizeof(name) - 1, &name_len);
1137 /* just ignore the error at this point */
1144 * We should now have the alias of the entry we might
1145 * want to cache. Just remember it for a while.
1146 * We check the alias list when we have parsed the
1149 aliases = g_slist_prepend(aliases, g_strdup(name));
1156 if (*type == qtype) {
1158 * We found correct type (A or AAAA)
1160 if (check_alias(aliases, name) ||
1161 (!aliases && strncmp(question, name,
1164 * We found an alias or the name of the rr
1165 * matches the question. If so, we append
1166 * the compressed label to the cache.
1167 * The end result is a response buffer that
1168 * will contain one or more cached and
1169 * compressed resource records.
1171 if (*response_len + rsp_len > maxlen) {
1175 memcpy(response + *response_len, rsp, rsp_len);
1176 *response_len += rsp_len;
1187 for (list = aliases; list; list = list->next)
1189 g_slist_free(aliases);
1194 struct cache_timeout {
1195 time_t current_time;
1200 static gboolean cache_check_entry(gpointer key, gpointer value,
1203 struct cache_timeout *data = user_data;
1204 struct cache_entry *entry = value;
1207 /* Scale the number of hits by half as part of cache aging */
1212 * If either IPv4 or IPv6 cached entry has expired, we
1213 * remove both from the cache.
1216 if (entry->ipv4 && entry->ipv4->timeout > 0) {
1217 max_timeout = entry->ipv4->cache_until;
1218 if (max_timeout > data->max_timeout)
1219 data->max_timeout = max_timeout;
1221 if (entry->ipv4->cache_until < data->current_time)
1225 if (entry->ipv6 && entry->ipv6->timeout > 0) {
1226 max_timeout = entry->ipv6->cache_until;
1227 if (max_timeout > data->max_timeout)
1228 data->max_timeout = max_timeout;
1230 if (entry->ipv6->cache_until < data->current_time)
1235 * if we're asked to try harder, also remove entries that have
1238 if (data->try_harder && entry->hits < 4)
1244 static void cache_cleanup(void)
1246 static int max_timeout;
1247 struct cache_timeout data;
1250 data.current_time = time(NULL);
1251 data.max_timeout = 0;
1252 data.try_harder = 0;
1255 * In the first pass, we only remove entries that have timed out.
1256 * We use a cache of the first time to expire to do this only
1257 * when it makes sense.
1259 if (max_timeout <= data.current_time) {
1260 count = g_hash_table_foreach_remove(cache, cache_check_entry,
1263 debug("removed %d in the first pass", count);
1266 * In the second pass, if the first pass turned up blank,
1267 * we also expire entries with a low hit count,
1268 * while aging the hit count at the same time.
1270 data.try_harder = 1;
1272 count = g_hash_table_foreach_remove(cache, cache_check_entry,
1277 * If we could not remove anything, then remember
1278 * what is the max timeout and do nothing if we
1279 * have not yet reached it. This will prevent
1280 * constant traversal of the cache if it is full.
1282 max_timeout = data.max_timeout;
1287 static gboolean cache_invalidate_entry(gpointer key, gpointer value,
1290 struct cache_entry *entry = value;
1292 /* first, delete any expired elements */
1293 cache_enforce_validity(entry);
1295 /* if anything is not expired, mark the entry for refresh */
1296 if (entry->hits > 0 && (entry->ipv4 || entry->ipv6))
1297 entry->want_refresh = true;
1299 /* delete the cached data */
1301 g_free(entry->ipv4->data);
1302 g_free(entry->ipv4);
1307 g_free(entry->ipv6->data);
1308 g_free(entry->ipv6);
1312 /* keep the entry if we want it refreshed, delete it otherwise */
1313 if (entry->want_refresh)
1320 * cache_invalidate is called from places where the DNS landscape
1321 * has changed, say because connections are added or we entered a VPN.
1322 * The logic is to wipe all cache data, but mark all non-expired
1323 * parts of the cache for refresh rather than deleting the whole cache.
1325 static void cache_invalidate(void)
1327 debug("Invalidating the DNS cache %p", cache);
1332 g_hash_table_foreach_remove(cache, cache_invalidate_entry, NULL);
1335 static void cache_refresh_entry(struct cache_entry *entry)
1338 cache_enforce_validity(entry);
1340 if (entry->hits > 2 && !entry->ipv4)
1341 entry->want_refresh = true;
1342 if (entry->hits > 2 && !entry->ipv6)
1343 entry->want_refresh = true;
1345 if (entry->want_refresh) {
1347 char dns_name[NS_MAXDNAME + 1];
1348 entry->want_refresh = false;
1350 /* turn a DNS name into a hostname with dots */
1351 strncpy(dns_name, entry->key, NS_MAXDNAME);
1359 debug("Refreshing %s\n", dns_name);
1360 /* then refresh the hostname */
1361 refresh_dns_entry(entry, &dns_name[1]);
1365 static void cache_refresh_iterator(gpointer key, gpointer value,
1368 struct cache_entry *entry = value;
1370 cache_refresh_entry(entry);
1373 static void cache_refresh(void)
1378 g_hash_table_foreach(cache, cache_refresh_iterator, NULL);
1381 static int reply_query_type(unsigned char *msg, int len)
1387 /* skip the header */
1388 c = msg + sizeof(struct domain_hdr);
1389 len -= sizeof(struct domain_hdr);
1394 /* now the query, which is a name and 2 16 bit words */
1395 l = dns_name_length(c);
1397 type = c[0] << 8 | c[1];
1402 static int cache_update(struct server_data *srv, unsigned char *msg,
1403 unsigned int msg_len)
1405 int offset = protocol_offset(srv->protocol);
1406 int err, qlen, ttl = 0;
1407 uint16_t answers = 0, type = 0, class = 0;
1408 struct domain_hdr *hdr = (void *)(msg + offset);
1409 struct domain_question *q;
1410 struct cache_entry *entry;
1411 struct cache_data *data;
1412 char question[NS_MAXDNAME + 1];
1413 unsigned char response[NS_MAXDNAME + 1];
1415 unsigned int rsplen;
1416 bool new_entry = true;
1417 time_t current_time;
1419 if (cache_size >= MAX_CACHE_SIZE) {
1421 if (cache_size >= MAX_CACHE_SIZE)
1425 current_time = time(NULL);
1427 /* don't do a cache refresh more than twice a minute */
1428 if (next_refresh < current_time) {
1430 next_refresh = current_time + 30;
1436 debug("offset %d hdr %p msg %p rcode %d", offset, hdr, msg, hdr->rcode);
1438 /* Continue only if response code is 0 (=ok) */
1439 if (hdr->rcode != ns_r_noerror)
1445 rsplen = sizeof(response) - 1;
1446 question[sizeof(question) - 1] = '\0';
1448 err = parse_response(msg + offset, msg_len - offset,
1449 question, sizeof(question) - 1,
1450 &type, &class, &ttl,
1451 response, &rsplen, &answers);
1454 * special case: if we do a ipv6 lookup and get no result
1455 * for a record that's already in our ipv4 cache.. we want
1456 * to cache the negative response.
1458 if ((err == -ENOMSG || err == -ENOBUFS) &&
1459 reply_query_type(msg + offset,
1460 msg_len - offset) == 28) {
1461 entry = g_hash_table_lookup(cache, question);
1462 if (entry && entry->ipv4 && !entry->ipv6) {
1463 int cache_offset = 0;
1465 data = g_try_new(struct cache_data, 1);
1468 data->inserted = entry->ipv4->inserted;
1470 data->answers = ntohs(hdr->ancount);
1471 data->timeout = entry->ipv4->timeout;
1472 if (srv->protocol == IPPROTO_UDP)
1474 data->data_len = msg_len + cache_offset;
1475 data->data = ptr = g_malloc(data->data_len);
1476 ptr[0] = (data->data_len - 2) / 256;
1477 ptr[1] = (data->data_len - 2) - ptr[0] * 256;
1478 if (srv->protocol == IPPROTO_UDP)
1480 data->valid_until = entry->ipv4->valid_until;
1481 data->cache_until = entry->ipv4->cache_until;
1482 memcpy(ptr, msg, msg_len);
1485 * we will get a "hit" when we serve the response
1489 if (entry->hits < 0)
1495 if (err < 0 || ttl == 0)
1498 qlen = strlen(question);
1501 * If the cache contains already data, check if the
1502 * type of the cached data is the same and do not add
1503 * to cache if data is already there.
1504 * This is needed so that we can cache both A and AAAA
1505 * records for the same name.
1507 entry = g_hash_table_lookup(cache, question);
1509 entry = g_try_new(struct cache_entry, 1);
1513 data = g_try_new(struct cache_data, 1);
1519 entry->key = g_strdup(question);
1520 entry->ipv4 = entry->ipv6 = NULL;
1521 entry->want_refresh = false;
1529 if (type == 1 && entry->ipv4)
1532 if (type == 28 && entry->ipv6)
1535 data = g_try_new(struct cache_data, 1);
1545 * compensate for the hit we'll get for serving
1546 * the response out of the cache
1549 if (entry->hits < 0)
1555 if (ttl < MIN_CACHE_TTL)
1556 ttl = MIN_CACHE_TTL;
1558 data->inserted = current_time;
1560 data->answers = answers;
1561 data->timeout = ttl;
1563 * The "2" in start of the length is the TCP offset. We allocate it
1564 * here even for UDP packet because it simplifies the sending
1567 data->data_len = 2 + 12 + qlen + 1 + 2 + 2 + rsplen;
1568 data->data = ptr = g_malloc(data->data_len);
1569 data->valid_until = current_time + ttl;
1572 * Restrict the cached DNS record TTL to some sane value
1573 * in order to prevent data staying in the cache too long.
1575 if (ttl > MAX_CACHE_TTL)
1576 ttl = MAX_CACHE_TTL;
1578 data->cache_until = round_down_ttl(current_time + ttl, ttl);
1588 * We cache the two extra bytes at the start of the message
1589 * in a TCP packet. When sending UDP packet, we skip the first
1590 * two bytes. This way we do not need to know the format
1591 * (UDP/TCP) of the cached message.
1593 if (srv->protocol == IPPROTO_UDP)
1594 memcpy(ptr + 2, msg, offset + 12);
1596 memcpy(ptr, msg, offset + 12);
1598 ptr[0] = (data->data_len - 2) / 256;
1599 ptr[1] = (data->data_len - 2) - ptr[0] * 256;
1600 if (srv->protocol == IPPROTO_UDP)
1603 memcpy(ptr + offset + 12, question, qlen + 1); /* copy also the \0 */
1605 q = (void *) (ptr + offset + 12 + qlen + 1);
1606 q->type = htons(type);
1607 q->class = htons(class);
1608 memcpy(ptr + offset + 12 + qlen + 1 + sizeof(struct domain_question),
1612 g_hash_table_replace(cache, entry->key, entry);
1616 debug("cache %d %squestion \"%s\" type %d ttl %d size %zd packet %u "
1618 cache_size, new_entry ? "new " : "old ",
1619 question, type, ttl,
1620 sizeof(*entry) + sizeof(*data) + data->data_len + qlen,
1622 srv->protocol == IPPROTO_TCP ?
1623 (unsigned int)(data->data[0] * 256 + data->data[1]) :
1629 static int ns_resolv(struct server_data *server, struct request_data *req,
1630 gpointer request, gpointer name)
1633 int sk, err, type = 0;
1634 char *dot, *lookup = (char *) name;
1635 struct cache_entry *entry;
1637 entry = cache_check(request, &type, req->protocol);
1640 struct cache_data *data;
1642 debug("cache hit %s type %s", lookup, type == 1 ? "A" : "AAAA");
1649 ttl_left = data->valid_until - time(NULL);
1653 if (data && req->protocol == IPPROTO_TCP) {
1654 send_cached_response(req->client_sk, data->data,
1655 data->data_len, NULL, 0, IPPROTO_TCP,
1656 req->srcid, data->answers, ttl_left);
1660 if (data && req->protocol == IPPROTO_UDP) {
1661 int udp_sk = get_req_udp_socket(req);
1666 send_cached_response(udp_sk, data->data,
1667 data->data_len, &req->sa, req->sa_len,
1668 IPPROTO_UDP, req->srcid, data->answers,
1674 #if defined TIZEN_EXT
1675 if (server->protocol == IPPROTO_UDP) {
1677 struct server_data *new_server = NULL;
1679 new_server = create_server_sec(server->index, NULL,
1680 server->server, IPPROTO_UDP);
1682 if (new_server != NULL) {
1683 for (domains = server->domains; domains;
1684 domains = domains->next) {
1685 char *dom = domains->data;
1687 DBG("Adding domain %s to %s",
1688 dom, new_server->server);
1690 new_server->domains = g_list_append(
1691 new_server->domains,
1695 server = new_server;
1699 sk = g_io_channel_unix_get_fd(server->channel);
1701 err = sendto(sk, request, req->request_len, MSG_NOSIGNAL,
1702 server->server_addr, server->server_addr_len);
1704 debug("Cannot send message to server %s sock %d "
1705 "protocol %d (%s/%d)",
1706 server->server, sk, server->protocol,
1707 strerror(errno), errno);
1713 /* If we have more than one dot, we don't add domains */
1714 dot = strchr(lookup, '.');
1715 if (dot && dot != lookup + strlen(lookup) - 1)
1718 if (server->domains && server->domains->data)
1719 req->append_domain = true;
1721 for (list = server->domains; list; list = list->next) {
1723 unsigned char alt[1024];
1724 struct domain_hdr *hdr = (void *) &alt;
1725 int altlen, domlen, offset;
1727 domain = list->data;
1732 offset = protocol_offset(server->protocol);
1736 domlen = strlen(domain) + 1;
1740 alt[offset] = req->altid & 0xff;
1741 alt[offset + 1] = req->altid >> 8;
1743 memcpy(alt + offset + 2, request + offset + 2, 10);
1744 hdr->qdcount = htons(1);
1746 altlen = append_query(alt + offset + 12, sizeof(alt) - 12,
1753 memcpy(alt + offset + altlen,
1754 request + offset + altlen - domlen,
1755 req->request_len - altlen - offset + domlen);
1757 if (server->protocol == IPPROTO_TCP) {
1758 int req_len = req->request_len + domlen - 2;
1760 alt[0] = (req_len >> 8) & 0xff;
1761 alt[1] = req_len & 0xff;
1764 debug("req %p dstid 0x%04x altid 0x%04x", req, req->dstid,
1767 err = send(sk, alt, req->request_len + domlen, MSG_NOSIGNAL);
1777 static char *convert_label(char *start, char *end, char *ptr, char *uptr,
1778 int remaining_len, int *used_comp, int *used_uncomp)
1781 char name[NS_MAXLABEL];
1783 pos = dn_expand((u_char *)start, (u_char *)end, (u_char *)ptr,
1786 debug("uncompress error [%d/%s]", errno, strerror(errno));
1791 * We need to compress back the name so that we get back to internal
1792 * label presentation.
1794 comp_pos = dn_comp(name, (u_char *)uptr, remaining_len, NULL, NULL);
1796 debug("compress error [%d/%s]", errno, strerror(errno));
1801 *used_uncomp = comp_pos;
1809 static char *uncompress(int16_t field_count, char *start, char *end,
1810 char *ptr, char *uncompressed, int uncomp_len,
1811 char **uncompressed_ptr)
1813 char *uptr = *uncompressed_ptr; /* position in result buffer */
1815 debug("count %d ptr %p end %p uptr %p", field_count, ptr, end, uptr);
1817 while (field_count-- > 0 && ptr < end) {
1818 int dlen; /* data field length */
1819 int ulen; /* uncompress length */
1820 int pos; /* position in compressed string */
1821 char name[NS_MAXLABEL]; /* tmp label */
1822 uint16_t dns_type, dns_class;
1825 if (!convert_label(start, end, ptr, name, NS_MAXLABEL,
1830 * Copy the uncompressed resource record, type, class and \0 to
1834 ulen = strlen(name);
1835 strncpy(uptr, name, uncomp_len - (uptr - uncompressed));
1837 debug("pos %d ulen %d left %d name %s", pos, ulen,
1838 (int)(uncomp_len - (uptr - uncompressed)), uptr);
1846 * We copy also the fixed portion of the result (type, class,
1847 * ttl, address length and the address)
1849 memcpy(uptr, ptr, NS_RRFIXEDSZ);
1851 dns_type = uptr[0] << 8 | uptr[1];
1852 dns_class = uptr[2] << 8 | uptr[3];
1854 if (dns_class != ns_c_in)
1857 ptr += NS_RRFIXEDSZ;
1858 uptr += NS_RRFIXEDSZ;
1861 * Then the variable portion of the result (data length).
1862 * Typically this portion is also compressed
1863 * so we need to uncompress it also when necessary.
1865 if (dns_type == ns_t_cname) {
1866 if (!convert_label(start, end, ptr, uptr,
1867 uncomp_len - (uptr - uncompressed),
1871 uptr[-2] = comp_pos << 8;
1872 uptr[-1] = comp_pos & 0xff;
1877 } else if (dns_type == ns_t_a || dns_type == ns_t_aaaa) {
1878 dlen = uptr[-2] << 8 | uptr[-1];
1880 if (ptr + dlen > end) {
1881 debug("data len %d too long", dlen);
1885 memcpy(uptr, ptr, dlen);
1889 } else if (dns_type == ns_t_soa) {
1893 /* Primary name server expansion */
1894 if (!convert_label(start, end, ptr, uptr,
1895 uncomp_len - (uptr - uncompressed),
1899 total_len += comp_pos;
1900 len_ptr = &uptr[-2];
1904 /* Responsible authority's mailbox */
1905 if (!convert_label(start, end, ptr, uptr,
1906 uncomp_len - (uptr - uncompressed),
1910 total_len += comp_pos;
1915 * Copy rest of the soa fields (serial number,
1916 * refresh interval, retry interval, expiration
1917 * limit and minimum ttl). They are 20 bytes long.
1919 memcpy(uptr, ptr, 20);
1925 * Finally fix the length of the data part
1927 len_ptr[0] = total_len << 8;
1928 len_ptr[1] = total_len & 0xff;
1931 *uncompressed_ptr = uptr;
1940 static int strip_domains(char *name, char *answers, int maxlen)
1943 int name_len = strlen(name);
1944 char *ptr, *start = answers, *end = answers + maxlen;
1946 while (maxlen > 0) {
1947 ptr = strstr(answers, name);
1949 char *domain = ptr + name_len;
1952 int domain_len = strlen(domain);
1954 memmove(answers + name_len,
1955 domain + domain_len,
1956 end - (domain + domain_len));
1959 maxlen -= domain_len;
1963 answers += strlen(answers) + 1;
1964 answers += 2 + 2 + 4; /* skip type, class and ttl fields */
1966 data_len = answers[0] << 8 | answers[1];
1967 answers += 2; /* skip the length field */
1969 if (answers + data_len > end)
1972 answers += data_len;
1973 maxlen -= answers - ptr;
1979 static int forward_dns_reply(unsigned char *reply, int reply_len, int protocol,
1980 struct server_data *data)
1982 struct domain_hdr *hdr;
1983 struct request_data *req;
1984 int dns_id, sk, err, offset = protocol_offset(protocol);
1989 hdr = (void *)(reply + offset);
1990 dns_id = reply[offset] | reply[offset + 1] << 8;
1992 debug("Received %d bytes (id 0x%04x)", reply_len, dns_id);
1994 req = find_request(dns_id);
1998 debug("req %p dstid 0x%04x altid 0x%04x rcode %d",
1999 req, req->dstid, req->altid, hdr->rcode);
2001 reply[offset] = req->srcid & 0xff;
2002 reply[offset + 1] = req->srcid >> 8;
2006 if (hdr->rcode == ns_r_noerror || !req->resp) {
2007 unsigned char *new_reply = NULL;
2010 * If the domain name was append
2011 * remove it before forwarding the reply.
2012 * If there were more than one question, then this
2013 * domain name ripping can be hairy so avoid that
2014 * and bail out in that that case.
2016 * The reason we are doing this magic is that if the
2017 * user's DNS client tries to resolv hostname without
2018 * domain part, it also expects to get the result without
2019 * a domain name part.
2021 if (req->append_domain && ntohs(hdr->qdcount) == 1) {
2022 uint16_t domain_len = 0;
2023 uint16_t header_len;
2024 uint16_t dns_type, dns_class;
2025 uint8_t host_len, dns_type_pos;
2026 char uncompressed[NS_MAXDNAME], *uptr;
2027 char *ptr, *eom = (char *)reply + reply_len;
2030 * ptr points to the first char of the hostname.
2031 * ->hostname.domain.net
2033 header_len = offset + sizeof(struct domain_hdr);
2034 ptr = (char *)reply + header_len;
2038 domain_len = strnlen(ptr + 1 + host_len,
2039 reply_len - header_len);
2042 * If the query type is anything other than A or AAAA,
2043 * then bail out and pass the message as is.
2044 * We only want to deal with IPv4 or IPv6 addresses.
2046 dns_type_pos = host_len + 1 + domain_len + 1;
2048 dns_type = ptr[dns_type_pos] << 8 |
2049 ptr[dns_type_pos + 1];
2050 dns_class = ptr[dns_type_pos + 2] << 8 |
2051 ptr[dns_type_pos + 3];
2052 if (dns_type != ns_t_a && dns_type != ns_t_aaaa &&
2053 dns_class != ns_c_in) {
2054 debug("Pass msg dns type %d class %d",
2055 dns_type, dns_class);
2060 * Remove the domain name and replace it by the end
2061 * of reply. Check if the domain is really there
2062 * before trying to copy the data. We also need to
2063 * uncompress the answers if necessary.
2064 * The domain_len can be 0 because if the original
2065 * query did not contain a domain name, then we are
2066 * sending two packets, first without the domain name
2067 * and the second packet with domain name.
2068 * The append_domain is set to true even if we sent
2069 * the first packet without domain name. In this
2070 * case we end up in this branch.
2072 if (domain_len > 0) {
2073 int len = host_len + 1;
2074 int new_len, fixed_len;
2078 * First copy host (without domain name) into
2081 uptr = &uncompressed[0];
2082 memcpy(uptr, ptr, len);
2084 uptr[len] = '\0'; /* host termination */
2088 * Copy type and class fields of the question.
2090 ptr += len + domain_len + 1;
2091 memcpy(uptr, ptr, NS_QFIXEDSZ);
2094 * ptr points to answers after this
2097 uptr += NS_QFIXEDSZ;
2099 fixed_len = answers - uncompressed;
2102 * We then uncompress the result to buffer
2103 * so that we can rip off the domain name
2104 * part from the question. First answers,
2105 * then name server (authority) information,
2106 * and finally additional record info.
2109 ptr = uncompress(ntohs(hdr->ancount),
2110 (char *)reply + offset, eom,
2111 ptr, uncompressed, NS_MAXDNAME,
2116 ptr = uncompress(ntohs(hdr->nscount),
2117 (char *)reply + offset, eom,
2118 ptr, uncompressed, NS_MAXDNAME,
2123 ptr = uncompress(ntohs(hdr->arcount),
2124 (char *)reply + offset, eom,
2125 ptr, uncompressed, NS_MAXDNAME,
2131 * The uncompressed buffer now contains almost
2132 * valid response. Final step is to get rid of
2133 * the domain name because at least glibc
2134 * gethostbyname() implementation does extra
2135 * checks and expects to find an answer without
2136 * domain name if we asked a query without
2137 * domain part. Note that glibc getaddrinfo()
2138 * works differently and accepts FQDN in answer
2140 new_len = strip_domains(uncompressed, answers,
2143 debug("Corrupted packet");
2148 * Because we have now uncompressed the answers
2149 * we might have to create a bigger buffer to
2150 * hold all that data.
2153 reply_len = header_len + new_len + fixed_len;
2155 new_reply = g_try_malloc(reply_len);
2159 memcpy(new_reply, reply, header_len);
2160 memcpy(new_reply + header_len, uncompressed,
2161 new_len + fixed_len);
2171 req->resp = g_try_malloc(reply_len);
2175 memcpy(req->resp, reply, reply_len);
2176 req->resplen = reply_len;
2178 cache_update(data, reply, reply_len);
2184 if (req->numresp < req->numserv) {
2185 if (hdr->rcode > ns_r_noerror) {
2187 } else if (hdr->ancount == 0 && req->append_domain) {
2192 request_list = g_slist_remove(request_list, req);
2194 if (protocol == IPPROTO_UDP) {
2195 sk = get_req_udp_socket(req);
2200 err = sendto(sk, req->resp, req->resplen, 0,
2201 &req->sa, req->sa_len);
2203 sk = req->client_sk;
2204 err = send(sk, req->resp, req->resplen, MSG_NOSIGNAL);
2208 debug("Cannot send msg, sk %d proto %d errno %d/%s", sk,
2209 protocol, errno, strerror(errno));
2211 debug("proto %d sent %d bytes to %d", protocol, err, sk);
2213 destroy_request_data(req);
2218 static void server_destroy_socket(struct server_data *data)
2220 debug("index %d server %s proto %d", data->index,
2221 data->server, data->protocol);
2223 if (data->watch > 0) {
2224 g_source_remove(data->watch);
2228 if (data->timeout > 0) {
2229 g_source_remove(data->timeout);
2233 if (data->channel) {
2234 g_io_channel_shutdown(data->channel, TRUE, NULL);
2235 g_io_channel_unref(data->channel);
2236 data->channel = NULL;
2239 g_free(data->incoming_reply);
2240 data->incoming_reply = NULL;
2243 static void destroy_server(struct server_data *server)
2245 debug("index %d server %s sock %d", server->index, server->server,
2247 g_io_channel_unix_get_fd(server->channel): -1);
2249 server_list = g_slist_remove(server_list, server);
2250 server_destroy_socket(server);
2252 if (server->protocol == IPPROTO_UDP && server->enabled)
2253 debug("Removing DNS server %s", server->server);
2255 g_free(server->server);
2256 g_list_free_full(server->domains, g_free);
2257 g_free(server->server_addr);
2260 * We do not remove cache right away but delay it few seconds.
2261 * The idea is that when IPv6 DNS server is added via RDNSS, it has a
2262 * lifetime. When the lifetime expires we decrease the refcount so it
2263 * is possible that the cache is then removed. Because a new DNS server
2264 * is usually created almost immediately we would then loose the cache
2265 * without any good reason. The small delay allows the new RDNSS to
2266 * create a new DNS server instance and the refcount does not go to 0.
2268 if (cache && !cache_timer)
2269 cache_timer = g_timeout_add_seconds(3, try_remove_cache, NULL);
2274 static gboolean udp_server_event(GIOChannel *channel, GIOCondition condition,
2277 unsigned char buf[4096];
2279 struct server_data *data = user_data;
2281 if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
2282 connman_error("Error with UDP server %s", data->server);
2283 server_destroy_socket(data);
2287 sk = g_io_channel_unix_get_fd(channel);
2289 len = recv(sk, buf, sizeof(buf), 0);
2292 forward_dns_reply(buf, len, IPPROTO_UDP, data);
2294 #if defined TIZEN_EXT
2297 for (list = server_list_sec; list; list = list->next) {
2298 struct server_data *new_data = list->data;
2300 if (new_data == data) {
2301 destroy_server_sec(data);
2310 static gboolean tcp_server_event(GIOChannel *channel, GIOCondition condition,
2314 struct server_data *server = user_data;
2316 sk = g_io_channel_unix_get_fd(channel);
2320 if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
2323 debug("TCP server channel closed, sk %d", sk);
2326 * Discard any partial response which is buffered; better
2327 * to get a proper response from a working server.
2329 g_free(server->incoming_reply);
2330 server->incoming_reply = NULL;
2332 list = request_list;
2334 struct request_data *req = list->data;
2335 struct domain_hdr *hdr;
2338 if (req->protocol == IPPROTO_UDP)
2345 * If we're not waiting for any further response
2346 * from another name server, then we send an error
2347 * response to the client.
2349 if (req->numserv && --(req->numserv))
2352 hdr = (void *) (req->request + 2);
2353 hdr->id = req->srcid;
2354 send_response(req->client_sk, req->request,
2355 req->request_len, NULL, 0, IPPROTO_TCP);
2357 request_list = g_slist_remove(request_list, req);
2360 destroy_server(server);
2365 if ((condition & G_IO_OUT) && !server->connected) {
2368 bool no_request_sent = true;
2369 struct server_data *udp_server;
2371 udp_server = find_server(server->index, server->server,
2374 for (domains = udp_server->domains; domains;
2375 domains = domains->next) {
2376 char *dom = domains->data;
2378 debug("Adding domain %s to %s",
2379 dom, server->server);
2381 server->domains = g_list_append(server->domains,
2386 server->connected = true;
2387 server_list = g_slist_append(server_list, server);
2389 if (server->timeout > 0) {
2390 g_source_remove(server->timeout);
2391 server->timeout = 0;
2394 for (list = request_list; list; ) {
2395 struct request_data *req = list->data;
2398 if (req->protocol == IPPROTO_UDP) {
2403 debug("Sending req %s over TCP", (char *)req->name);
2405 status = ns_resolv(server, req,
2406 req->request, req->name);
2409 * A cached result was sent,
2410 * so the request can be released
2413 request_list = g_slist_remove(request_list, req);
2414 destroy_request_data(req);
2423 no_request_sent = false;
2425 if (req->timeout > 0)
2426 g_source_remove(req->timeout);
2428 req->timeout = g_timeout_add_seconds(30,
2429 request_timeout, req);
2433 if (no_request_sent) {
2434 destroy_server(server);
2438 } else if (condition & G_IO_IN) {
2439 struct partial_reply *reply = server->incoming_reply;
2443 unsigned char reply_len_buf[2];
2446 bytes_recv = recv(sk, reply_len_buf, 2, MSG_PEEK);
2449 } else if (bytes_recv < 0) {
2450 if (errno == EAGAIN || errno == EWOULDBLOCK)
2453 connman_error("DNS proxy error %s",
2456 } else if (bytes_recv < 2)
2459 reply_len = reply_len_buf[1] | reply_len_buf[0] << 8;
2462 debug("TCP reply %d bytes from %d", reply_len, sk);
2464 reply = g_try_malloc(sizeof(*reply) + reply_len + 2);
2468 reply->len = reply_len;
2469 reply->received = 0;
2471 server->incoming_reply = reply;
2474 while (reply->received < reply->len) {
2475 bytes_recv = recv(sk, reply->buf + reply->received,
2476 reply->len - reply->received, 0);
2478 connman_error("DNS proxy TCP disconnect");
2480 } else if (bytes_recv < 0) {
2481 if (errno == EAGAIN || errno == EWOULDBLOCK)
2484 connman_error("DNS proxy error %s",
2488 reply->received += bytes_recv;
2491 forward_dns_reply(reply->buf, reply->received, IPPROTO_TCP,
2495 server->incoming_reply = NULL;
2497 destroy_server(server);
2505 static gboolean tcp_idle_timeout(gpointer user_data)
2507 struct server_data *server = user_data;
2514 destroy_server(server);
2519 static int server_create_socket(struct server_data *data)
2524 debug("index %d server %s proto %d", data->index,
2525 data->server, data->protocol);
2527 sk = socket(data->server_addr->sa_family,
2528 data->protocol == IPPROTO_TCP ? SOCK_STREAM : SOCK_DGRAM,
2532 connman_error("Failed to create server %s socket",
2534 server_destroy_socket(data);
2540 interface = connman_inet_ifname(data->index);
2542 if (setsockopt(sk, SOL_SOCKET, SO_BINDTODEVICE,
2544 strlen(interface) + 1) < 0) {
2546 connman_error("Failed to bind server %s "
2548 data->server, interface);
2550 server_destroy_socket(data);
2557 data->channel = g_io_channel_unix_new(sk);
2558 if (!data->channel) {
2559 connman_error("Failed to create server %s channel",
2562 server_destroy_socket(data);
2566 g_io_channel_set_close_on_unref(data->channel, TRUE);
2568 if (data->protocol == IPPROTO_TCP) {
2569 g_io_channel_set_flags(data->channel, G_IO_FLAG_NONBLOCK, NULL);
2570 data->watch = g_io_add_watch(data->channel,
2571 G_IO_OUT | G_IO_IN | G_IO_HUP | G_IO_NVAL | G_IO_ERR,
2572 tcp_server_event, data);
2573 data->timeout = g_timeout_add_seconds(30, tcp_idle_timeout,
2576 data->watch = g_io_add_watch(data->channel,
2577 G_IO_IN | G_IO_NVAL | G_IO_ERR | G_IO_HUP,
2578 udp_server_event, data);
2580 if (connect(sk, data->server_addr, data->server_addr_len) < 0) {
2583 if ((data->protocol == IPPROTO_TCP && errno != EINPROGRESS) ||
2584 data->protocol == IPPROTO_UDP) {
2586 connman_error("Failed to connect to server %s",
2588 server_destroy_socket(data);
2598 static void enable_fallback(bool enable)
2602 for (list = server_list; list; list = list->next) {
2603 struct server_data *data = list->data;
2605 if (data->index != -1)
2609 DBG("Enabling fallback DNS server %s", data->server);
2611 DBG("Disabling fallback DNS server %s", data->server);
2613 data->enabled = enable;
2617 #if defined TIZEN_EXT
2619 static void destroy_server_sec(struct server_data *server)
2624 if (server->channel)
2625 fd = g_io_channel_unix_get_fd(server->channel);
2629 DBG("index %d server %s sock %d", server->index, server->server, fd);
2631 server_list_sec = g_slist_remove(server_list_sec, server);
2636 server_destroy_socket(server);
2638 if (server->protocol == IPPROTO_UDP && server->enabled)
2639 DBG("Removing DNS server %s", server->server);
2641 g_free(server->server);
2642 for (list = server->domains; list; list = list->next) {
2643 char *domain = list->data;
2645 server->domains = g_list_remove(server->domains, domain);
2648 g_free(server->server_addr);
2651 * We do not remove cache right away but delay it few seconds.
2652 * The idea is that when IPv6 DNS server is added via RDNSS, it has a
2653 * lifetime. When the lifetime expires we decrease the refcount so it
2654 * is possible that the cache is then removed. Because a new DNS server
2655 * is usually created almost immediately we would then loose the cache
2656 * without any good reason. The small delay allows the new RDNSS to
2657 * create a new DNS server instance and the refcount does not go to 0.
2659 /* TODO: Need to check this */
2660 /* g_timeout_add_seconds(3, try_remove_cache, NULL); */
2665 static void destroy_all_server_sec()
2669 DBG("remove all dns server");
2671 for (list = server_list_sec; list; list = list->next) {
2672 struct server_data *server = list->data;
2673 destroy_server_sec(server);
2675 server_list_sec = NULL;
2678 static gboolean sec_udp_idle_timeout(gpointer user_data)
2680 struct server_data *server = user_data;
2687 destroy_server_sec(server);
2692 static struct server_data *create_server_sec(int index,
2693 const char *domain, const char *server,
2696 struct server_data *data;
2697 struct addrinfo hints, *rp;
2700 DBG("index %d server %s", index, server);
2702 data = g_try_new0(struct server_data, 1);
2704 connman_error("Failed to allocate server %s data", server);
2708 data->index = index;
2710 data->domains = g_list_append(data->domains, g_strdup(domain));
2711 data->server = g_strdup(server);
2712 data->protocol = protocol;
2714 memset(&hints, 0, sizeof(hints));
2718 hints.ai_socktype = SOCK_DGRAM;
2722 hints.ai_socktype = SOCK_STREAM;
2726 destroy_server_sec(data);
2729 hints.ai_family = AF_UNSPEC;
2730 hints.ai_flags = AI_NUMERICSERV | AI_NUMERICHOST;
2732 ret = getaddrinfo(data->server, "53", &hints, &rp);
2734 connman_error("Failed to parse server %s address: %s\n",
2735 data->server, gai_strerror(ret));
2737 destroy_server_sec(data);
2741 /* Do not blindly copy this code elsewhere; it doesn't loop over the
2742 results using ->ai_next as it should. That's OK in *this* case
2743 because it was a numeric lookup; we *know* there's only one. */
2745 data->server_addr_len = rp->ai_addrlen;
2747 switch (rp->ai_family) {
2749 data->server_addr = (struct sockaddr *)
2750 g_try_new0(struct sockaddr_in, 1);
2753 data->server_addr = (struct sockaddr *)
2754 g_try_new0(struct sockaddr_in6, 1);
2757 connman_error("Wrong address family %d", rp->ai_family);
2760 if (data->server_addr == NULL) {
2762 destroy_server_sec(data);
2765 memcpy(data->server_addr, rp->ai_addr, rp->ai_addrlen);
2768 if (server_create_socket(data) != 0) {
2769 destroy_server_sec(data);
2773 if (protocol == IPPROTO_UDP) {
2774 /* Enable new servers by default */
2775 data->enabled = TRUE;
2776 DBG("Adding DNS server %s", data->server);
2778 data->timeout = g_timeout_add_seconds(30, sec_udp_idle_timeout,
2781 server_list_sec = g_slist_append(server_list_sec, data);
2788 static struct server_data *create_server(int index,
2789 const char *domain, const char *server,
2792 struct server_data *data;
2793 struct addrinfo hints, *rp;
2796 DBG("index %d server %s", index, server);
2798 data = g_try_new0(struct server_data, 1);
2800 connman_error("Failed to allocate server %s data", server);
2804 data->index = index;
2806 data->domains = g_list_append(data->domains, g_strdup(domain));
2807 data->server = g_strdup(server);
2808 data->protocol = protocol;
2810 memset(&hints, 0, sizeof(hints));
2814 hints.ai_socktype = SOCK_DGRAM;
2818 hints.ai_socktype = SOCK_STREAM;
2822 destroy_server(data);
2825 hints.ai_family = AF_UNSPEC;
2826 hints.ai_flags = AI_NUMERICSERV | AI_NUMERICHOST;
2828 ret = getaddrinfo(data->server, "53", &hints, &rp);
2830 connman_error("Failed to parse server %s address: %s\n",
2831 data->server, gai_strerror(ret));
2832 destroy_server(data);
2836 /* Do not blindly copy this code elsewhere; it doesn't loop over the
2837 results using ->ai_next as it should. That's OK in *this* case
2838 because it was a numeric lookup; we *know* there's only one. */
2840 data->server_addr_len = rp->ai_addrlen;
2842 switch (rp->ai_family) {
2844 data->server_addr = (struct sockaddr *)
2845 g_try_new0(struct sockaddr_in, 1);
2848 data->server_addr = (struct sockaddr *)
2849 g_try_new0(struct sockaddr_in6, 1);
2852 connman_error("Wrong address family %d", rp->ai_family);
2855 if (!data->server_addr) {
2857 destroy_server(data);
2860 memcpy(data->server_addr, rp->ai_addr, rp->ai_addrlen);
2863 if (server_create_socket(data) != 0) {
2864 destroy_server(data);
2868 if (protocol == IPPROTO_UDP) {
2869 if (__connman_service_index_is_default(data->index) ||
2870 __connman_service_index_is_split_routing(
2872 data->enabled = true;
2873 DBG("Adding DNS server %s", data->server);
2875 enable_fallback(false);
2878 server_list = g_slist_append(server_list, data);
2884 static bool resolv(struct request_data *req,
2885 gpointer request, gpointer name)
2889 for (list = server_list; list; list = list->next) {
2890 struct server_data *data = list->data;
2892 if (data->protocol == IPPROTO_TCP) {
2893 DBG("server %s ignored proto TCP", data->server);
2897 debug("server %s enabled %d", data->server, data->enabled);
2902 if (!data->channel && data->protocol == IPPROTO_UDP) {
2903 if (server_create_socket(data) < 0) {
2904 DBG("socket creation failed while resolving");
2909 if (ns_resolv(data, req, request, name) > 0)
2916 static void update_domain(int index, const char *domain, bool append)
2920 DBG("index %d domain %s", index, domain);
2925 for (list = server_list; list; list = list->next) {
2926 struct server_data *data = list->data;
2929 bool dom_found = false;
2931 if (data->index < 0)
2934 if (data->index != index)
2937 for (dom_list = data->domains; dom_list;
2938 dom_list = dom_list->next) {
2939 dom = dom_list->data;
2941 if (g_str_equal(dom, domain)) {
2947 if (!dom_found && append) {
2949 g_list_append(data->domains, g_strdup(domain));
2950 } else if (dom_found && !append) {
2952 g_list_remove(data->domains, dom);
2958 static void append_domain(int index, const char *domain)
2960 update_domain(index, domain, true);
2963 static void remove_domain(int index, const char *domain)
2965 update_domain(index, domain, false);
2968 static void flush_requests(struct server_data *server)
2972 list = request_list;
2974 struct request_data *req = list->data;
2978 if (ns_resolv(server, req, req->request, req->name)) {
2980 * A cached result was sent,
2981 * so the request can be released
2984 g_slist_remove(request_list, req);
2985 destroy_request_data(req);
2989 if (req->timeout > 0)
2990 g_source_remove(req->timeout);
2992 req->timeout = g_timeout_add_seconds(5, request_timeout, req);
2996 int __connman_dnsproxy_append(int index, const char *domain,
2999 struct server_data *data;
3001 DBG("index %d server %s", index, server);
3003 if (!server && !domain)
3007 append_domain(index, domain);
3012 if (g_str_equal(server, "127.0.0.1"))
3015 if (g_str_equal(server, "::1"))
3018 data = find_server(index, server, IPPROTO_UDP);
3020 append_domain(index, domain);
3024 data = create_server(index, domain, server, IPPROTO_UDP);
3028 flush_requests(data);
3033 static void remove_server(int index, const char *domain,
3034 const char *server, int protocol)
3036 struct server_data *data;
3039 data = find_server(index, server, protocol);
3043 destroy_server(data);
3045 for (list = server_list; list; list = list->next) {
3046 struct server_data *data = list->data;
3048 if (data->index != -1 && data->enabled == true)
3052 enable_fallback(true);
3055 int __connman_dnsproxy_remove(int index, const char *domain,
3058 DBG("index %d server %s", index, server);
3060 if (!server && !domain)
3064 remove_domain(index, domain);
3069 if (g_str_equal(server, "127.0.0.1"))
3072 if (g_str_equal(server, "::1"))
3075 remove_server(index, domain, server, IPPROTO_UDP);
3076 remove_server(index, domain, server, IPPROTO_TCP);
3078 #if defined TIZEN_EXT
3079 destroy_all_server_sec();
3085 static void dnsproxy_offline_mode(bool enabled)
3089 DBG("enabled %d", enabled);
3091 for (list = server_list; list; list = list->next) {
3092 struct server_data *data = list->data;
3095 DBG("Enabling DNS server %s", data->server);
3096 data->enabled = true;
3100 DBG("Disabling DNS server %s", data->server);
3101 data->enabled = false;
3107 static void dnsproxy_default_changed(struct connman_service *service)
3109 bool server_enabled = false;
3113 DBG("service %p", service);
3115 /* DNS has changed, invalidate the cache */
3119 /* When no services are active, then disable DNS proxying */
3120 dnsproxy_offline_mode(true);
3124 index = __connman_service_get_index(service);
3128 for (list = server_list; list; list = list->next) {
3129 struct server_data *data = list->data;
3131 if (data->index == index) {
3132 DBG("Enabling DNS server %s", data->server);
3133 data->enabled = true;
3134 server_enabled = true;
3136 DBG("Disabling DNS server %s", data->server);
3137 data->enabled = false;
3141 if (!server_enabled)
3142 enable_fallback(true);
3147 static const struct connman_notifier dnsproxy_notifier = {
3149 .default_changed = dnsproxy_default_changed,
3150 .offline_mode = dnsproxy_offline_mode,
3153 static const unsigned char opt_edns0_type[2] = { 0x00, 0x29 };
3155 static int parse_request(unsigned char *buf, size_t len,
3156 char *name, unsigned int size)
3158 struct domain_hdr *hdr = (void *) buf;
3159 uint16_t qdcount = ntohs(hdr->qdcount);
3160 uint16_t ancount = ntohs(hdr->ancount);
3161 uint16_t nscount = ntohs(hdr->nscount);
3162 uint16_t arcount = ntohs(hdr->arcount);
3164 unsigned int remain, used = 0;
3166 if (len < sizeof(*hdr) + sizeof(struct qtype_qclass) ||
3167 hdr->qr || qdcount != 1 || ancount || nscount) {
3168 DBG("Dropped DNS request qr %d with len %zd qdcount %d "
3169 "ancount %d nscount %d", hdr->qr, len, qdcount, ancount,
3178 debug("id 0x%04x qr %d opcode %d qdcount %d arcount %d",
3179 hdr->id, hdr->qr, hdr->opcode,
3184 ptr = buf + sizeof(struct domain_hdr);
3185 remain = len - sizeof(struct domain_hdr);
3187 while (remain > 0) {
3188 uint8_t label_len = *ptr;
3190 if (label_len == 0x00) {
3192 struct qtype_qclass *q =
3193 (struct qtype_qclass *)(ptr + 1);
3195 if (remain < sizeof(*q)) {
3196 DBG("Dropped malformed DNS query");
3200 class = ntohs(q->qclass);
3201 if (class != 1 && class != 255) {
3202 DBG("Dropped non-IN DNS class %d", class);
3206 ptr += sizeof(*q) + 1;
3207 remain -= (sizeof(*q) + 1);
3211 if (used + label_len + 1 > size)
3214 strncat(name, (char *) (ptr + 1), label_len);
3217 used += label_len + 1;
3219 ptr += label_len + 1;
3220 remain -= label_len + 1;
3223 if (arcount && remain >= sizeof(struct domain_rr) + 1 && !ptr[0] &&
3224 ptr[1] == opt_edns0_type[0] && ptr[2] == opt_edns0_type[1]) {
3225 struct domain_rr *edns0 = (struct domain_rr *)(ptr + 1);
3227 DBG("EDNS0 buffer size %u", ntohs(edns0->class));
3228 } else if (!arcount && remain) {
3229 DBG("DNS request with %d garbage bytes", remain);
3232 debug("query %s", name);
3237 static void client_reset(struct tcp_partial_client_data *client)
3242 if (client->channel) {
3243 debug("client %d closing",
3244 g_io_channel_unix_get_fd(client->channel));
3246 g_io_channel_unref(client->channel);
3247 client->channel = NULL;
3250 if (client->watch > 0) {
3251 g_source_remove(client->watch);
3255 if (client->timeout > 0) {
3256 g_source_remove(client->timeout);
3257 client->timeout = 0;
3260 g_free(client->buf);
3263 client->buf_end = 0;
3266 static unsigned int get_msg_len(unsigned char *buf)
3268 return buf[0]<<8 | buf[1];
3271 static bool read_tcp_data(struct tcp_partial_client_data *client,
3272 void *client_addr, socklen_t client_addr_len,
3275 char query[TCP_MAX_BUF_LEN];
3276 struct request_data *req;
3278 unsigned int msg_len;
3280 bool waiting_for_connect = false;
3282 struct cache_entry *entry;
3284 client_sk = g_io_channel_unix_get_fd(client->channel);
3286 if (read_len == 0) {
3287 debug("client %d closed, pending %d bytes",
3288 client_sk, client->buf_end);
3289 g_hash_table_remove(partial_tcp_req_table,
3290 GINT_TO_POINTER(client_sk));
3294 debug("client %d received %d bytes", client_sk, read_len);
3296 client->buf_end += read_len;
3298 if (client->buf_end < 2)
3301 msg_len = get_msg_len(client->buf);
3302 if (msg_len > TCP_MAX_BUF_LEN) {
3303 debug("client %d sent too much data %d", client_sk, msg_len);
3304 g_hash_table_remove(partial_tcp_req_table,
3305 GINT_TO_POINTER(client_sk));
3310 debug("client %d msg len %d end %d past end %d", client_sk, msg_len,
3311 client->buf_end, client->buf_end - (msg_len + 2));
3313 if (client->buf_end < (msg_len + 2)) {
3314 debug("client %d still missing %d bytes",
3316 msg_len + 2 - client->buf_end);
3320 debug("client %d all data %d received", client_sk, msg_len);
3322 err = parse_request(client->buf + 2, msg_len,
3323 query, sizeof(query));
3324 if (err < 0 || (g_slist_length(server_list) == 0)) {
3325 send_response(client_sk, client->buf, msg_len + 2,
3326 NULL, 0, IPPROTO_TCP);
3330 req = g_try_new0(struct request_data, 1);
3334 memcpy(&req->sa, client_addr, client_addr_len);
3335 req->sa_len = client_addr_len;
3336 req->client_sk = client_sk;
3337 req->protocol = IPPROTO_TCP;
3338 req->family = client->family;
3340 req->srcid = client->buf[2] | (client->buf[3] << 8);
3341 req->dstid = get_id();
3342 req->altid = get_id();
3343 req->request_len = msg_len + 2;
3345 client->buf[2] = req->dstid & 0xff;
3346 client->buf[3] = req->dstid >> 8;
3349 req->ifdata = client->ifdata;
3350 req->append_domain = false;
3353 * Check if the answer is found in the cache before
3354 * creating sockets to the server.
3356 entry = cache_check(client->buf, &qtype, IPPROTO_TCP);
3359 struct cache_data *data;
3361 debug("cache hit %s type %s", query, qtype == 1 ? "A" : "AAAA");
3368 ttl_left = data->valid_until - time(NULL);
3371 send_cached_response(client_sk, data->data,
3372 data->data_len, NULL, 0, IPPROTO_TCP,
3373 req->srcid, data->answers, ttl_left);
3378 debug("data missing, ignoring cache for this query");
3381 for (list = server_list; list; list = list->next) {
3382 struct server_data *data = list->data;
3384 if (data->protocol != IPPROTO_UDP || !data->enabled)
3387 if (!create_server(data->index, NULL, data->server,
3391 waiting_for_connect = true;
3394 if (!waiting_for_connect) {
3395 /* No server is waiting for connect */
3396 send_response(client_sk, client->buf,
3397 req->request_len, NULL, 0, IPPROTO_TCP);
3403 * The server is not connected yet.
3404 * Copy the relevant buffers.
3405 * The request will actually be sent once we're
3406 * properly connected over TCP to the nameserver.
3408 req->request = g_try_malloc0(req->request_len);
3409 if (!req->request) {
3410 send_response(client_sk, client->buf,
3411 req->request_len, NULL, 0, IPPROTO_TCP);
3415 memcpy(req->request, client->buf, req->request_len);
3417 req->name = g_try_malloc0(sizeof(query));
3419 send_response(client_sk, client->buf,
3420 req->request_len, NULL, 0, IPPROTO_TCP);
3421 g_free(req->request);
3425 memcpy(req->name, query, sizeof(query));
3427 req->timeout = g_timeout_add_seconds(30, request_timeout, req);
3429 request_list = g_slist_append(request_list, req);
3432 if (client->buf_end > (msg_len + 2)) {
3433 debug("client %d buf %p -> %p end %d len %d new %d",
3435 client->buf + msg_len + 2,
3436 client->buf, client->buf_end,
3437 TCP_MAX_BUF_LEN - client->buf_end,
3438 client->buf_end - (msg_len + 2));
3439 memmove(client->buf, client->buf + msg_len + 2,
3440 TCP_MAX_BUF_LEN - client->buf_end);
3441 client->buf_end = client->buf_end - (msg_len + 2);
3444 * If we have a full message waiting, just read it
3447 msg_len = get_msg_len(client->buf);
3448 if ((msg_len + 2) == client->buf_end) {
3449 debug("client %d reading another %d bytes", client_sk,
3454 debug("client %d clearing reading buffer", client_sk);
3456 client->buf_end = 0;
3457 memset(client->buf, 0, TCP_MAX_BUF_LEN);
3460 * We received all the packets from client so we must also
3461 * remove the timeout handler here otherwise we might get
3462 * timeout while waiting the results from server.
3464 g_source_remove(client->timeout);
3465 client->timeout = 0;
3471 static gboolean tcp_client_event(GIOChannel *channel, GIOCondition condition,
3474 struct tcp_partial_client_data *client = user_data;
3475 struct sockaddr_in6 client_addr6;
3476 socklen_t client_addr6_len = sizeof(client_addr6);
3477 struct sockaddr_in client_addr4;
3478 socklen_t client_addr4_len = sizeof(client_addr4);
3480 socklen_t *client_addr_len;
3483 client_sk = g_io_channel_unix_get_fd(channel);
3485 if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
3486 g_hash_table_remove(partial_tcp_req_table,
3487 GINT_TO_POINTER(client_sk));
3489 connman_error("Error with TCP client %d channel", client_sk);
3493 switch (client->family) {
3495 client_addr = &client_addr4;
3496 client_addr_len = &client_addr4_len;
3499 client_addr = &client_addr6;
3500 client_addr_len = &client_addr6_len;
3503 g_hash_table_remove(partial_tcp_req_table,
3504 GINT_TO_POINTER(client_sk));
3505 connman_error("client %p corrupted", client);
3509 len = recvfrom(client_sk, client->buf + client->buf_end,
3510 TCP_MAX_BUF_LEN - client->buf_end, 0,
3511 client_addr, client_addr_len);
3513 if (errno == EAGAIN || errno == EWOULDBLOCK)
3516 debug("client %d cannot read errno %d/%s", client_sk, -errno,
3518 g_hash_table_remove(partial_tcp_req_table,
3519 GINT_TO_POINTER(client_sk));
3523 return read_tcp_data(client, client_addr, *client_addr_len, len);
3526 static gboolean client_timeout(gpointer user_data)
3528 struct tcp_partial_client_data *client = user_data;
3531 sock = g_io_channel_unix_get_fd(client->channel);
3533 debug("client %d timeout pending %d bytes", sock, client->buf_end);
3535 g_hash_table_remove(partial_tcp_req_table, GINT_TO_POINTER(sock));
3540 #if defined TIZEN_EXT
3541 static void recover_listener(GIOChannel *channel, struct listener_data *ifdata)
3545 index = ifdata->index;
3547 sk = g_io_channel_unix_get_fd(channel);
3550 __connman_dnsproxy_remove_listener(index);
3552 if (__connman_dnsproxy_add_listener(index) == 0)
3553 DBG("listener %d successfully recovered", index);
3557 static bool tcp_listener_event(GIOChannel *channel, GIOCondition condition,
3558 struct listener_data *ifdata, int family,
3559 guint *listener_watch)
3561 int sk, client_sk, len;
3562 unsigned int msg_len;
3563 struct tcp_partial_client_data *client;
3564 struct sockaddr_in6 client_addr6;
3565 socklen_t client_addr6_len = sizeof(client_addr6);
3566 struct sockaddr_in client_addr4;
3567 socklen_t client_addr4_len = sizeof(client_addr4);
3569 socklen_t *client_addr_len;
3573 debug("condition 0x%02x channel %p ifdata %p family %d",
3574 condition, channel, ifdata, family);
3576 if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
3577 #if defined TIZEN_EXT
3578 connman_error("Error %d with TCP listener channel", condition);
3580 recover_listener(channel, ifdata);
3582 if (*listener_watch > 0)
3583 g_source_remove(*listener_watch);
3584 *listener_watch = 0;
3586 connman_error("Error with TCP listener channel");
3592 sk = g_io_channel_unix_get_fd(channel);
3594 if (family == AF_INET) {
3595 client_addr = &client_addr4;
3596 client_addr_len = &client_addr4_len;
3598 client_addr = &client_addr6;
3599 client_addr_len = &client_addr6_len;
3602 tv.tv_sec = tv.tv_usec = 0;
3604 FD_SET(sk, &readfds);
3606 select(sk + 1, &readfds, NULL, NULL, &tv);
3607 if (FD_ISSET(sk, &readfds)) {
3608 client_sk = accept(sk, client_addr, client_addr_len);
3609 debug("client %d accepted", client_sk);
3611 debug("No data to read from master %d, waiting.", sk);
3615 if (client_sk < 0) {
3616 connman_error("Accept failure on TCP listener");
3617 *listener_watch = 0;
3621 fcntl(client_sk, F_SETFL, O_NONBLOCK);
3623 client = g_hash_table_lookup(partial_tcp_req_table,
3624 GINT_TO_POINTER(client_sk));
3626 client = g_try_new0(struct tcp_partial_client_data, 1);
3632 g_hash_table_insert(partial_tcp_req_table,
3633 GINT_TO_POINTER(client_sk),
3636 client->channel = g_io_channel_unix_new(client_sk);
3637 g_io_channel_set_close_on_unref(client->channel, TRUE);
3639 client->watch = g_io_add_watch(client->channel,
3640 G_IO_IN, tcp_client_event,
3643 client->ifdata = ifdata;
3645 debug("client %d created %p", client_sk, client);
3647 debug("client %d already exists %p", client_sk, client);
3651 client->buf = g_try_malloc(TCP_MAX_BUF_LEN);
3655 memset(client->buf, 0, TCP_MAX_BUF_LEN);
3656 client->buf_end = 0;
3657 client->family = family;
3659 if (client->timeout == 0)
3660 client->timeout = g_timeout_add_seconds(2, client_timeout,
3664 * Check how much data there is. If all is there, then we can
3665 * proceed normally, otherwise read the bits until everything
3666 * is received or timeout occurs.
3668 len = recv(client_sk, client->buf, TCP_MAX_BUF_LEN, 0);
3670 if (errno == EAGAIN || errno == EWOULDBLOCK) {
3671 debug("client %d no data to read, waiting", client_sk);
3675 debug("client %d cannot read errno %d/%s", client_sk, -errno,
3677 g_hash_table_remove(partial_tcp_req_table,
3678 GINT_TO_POINTER(client_sk));
3683 debug("client %d not enough data to read, waiting", client_sk);
3684 client->buf_end += len;
3688 msg_len = get_msg_len(client->buf);
3689 if (msg_len > TCP_MAX_BUF_LEN) {
3690 debug("client %d invalid message length %u ignoring packet",
3691 client_sk, msg_len);
3692 g_hash_table_remove(partial_tcp_req_table,
3693 GINT_TO_POINTER(client_sk));
3698 * The packet length bytes do not contain the total message length,
3699 * that is the reason to -2 below.
3701 #if defined TIZEN_EXT
3702 if (msg_len > (unsigned int)(len - 2)) {
3704 if (msg_len != (unsigned int)(len - 2)) {
3706 debug("client %d sent %d bytes but expecting %u pending %d",
3707 client_sk, len, msg_len + 2, msg_len + 2 - len);
3709 client->buf_end += len;
3713 return read_tcp_data(client, client_addr, *client_addr_len, len);
3716 static gboolean tcp4_listener_event(GIOChannel *channel, GIOCondition condition,
3719 struct listener_data *ifdata = user_data;
3721 return tcp_listener_event(channel, condition, ifdata, AF_INET,
3722 &ifdata->tcp4_listener_watch);
3725 static gboolean tcp6_listener_event(GIOChannel *channel, GIOCondition condition,
3728 struct listener_data *ifdata = user_data;
3730 return tcp_listener_event(channel, condition, user_data, AF_INET6,
3731 &ifdata->tcp6_listener_watch);
3734 static bool udp_listener_event(GIOChannel *channel, GIOCondition condition,
3735 struct listener_data *ifdata, int family,
3736 guint *listener_watch)
3738 unsigned char buf[768];
3740 struct request_data *req;
3741 struct sockaddr_in6 client_addr6;
3742 socklen_t client_addr6_len = sizeof(client_addr6);
3743 struct sockaddr_in client_addr4;
3744 socklen_t client_addr4_len = sizeof(client_addr4);
3746 socklen_t *client_addr_len;
3749 if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
3750 #if defined TIZEN_EXT
3751 connman_error("Error %d with UDP listener channel", condition);
3753 recover_listener(channel, ifdata);
3755 connman_error("Error with UDP listener channel");
3756 *listener_watch = 0;
3761 sk = g_io_channel_unix_get_fd(channel);
3763 if (family == AF_INET) {
3764 client_addr = &client_addr4;
3765 client_addr_len = &client_addr4_len;
3767 client_addr = &client_addr6;
3768 client_addr_len = &client_addr6_len;
3771 memset(client_addr, 0, *client_addr_len);
3772 len = recvfrom(sk, buf, sizeof(buf), 0, client_addr, client_addr_len);
3776 debug("Received %d bytes (id 0x%04x)", len, buf[0] | buf[1] << 8);
3778 err = parse_request(buf, len, query, sizeof(query));
3779 if (err < 0 || (g_slist_length(server_list) == 0)) {
3780 send_response(sk, buf, len, client_addr,
3781 *client_addr_len, IPPROTO_UDP);
3785 req = g_try_new0(struct request_data, 1);
3789 memcpy(&req->sa, client_addr, *client_addr_len);
3790 req->sa_len = *client_addr_len;
3792 req->protocol = IPPROTO_UDP;
3793 req->family = family;
3795 req->srcid = buf[0] | (buf[1] << 8);
3796 req->dstid = get_id();
3797 req->altid = get_id();
3798 req->request_len = len;
3800 buf[0] = req->dstid & 0xff;
3801 buf[1] = req->dstid >> 8;
3804 req->ifdata = ifdata;
3805 req->append_domain = false;
3807 if (resolv(req, buf, query)) {
3808 /* a cached result was sent, so the request can be released */
3813 req->name = g_strdup(query);
3814 req->request = g_malloc(len);
3815 memcpy(req->request, buf, len);
3816 #if defined TIZEN_EXT
3817 DBG("req %p dstid 0x%04x altid 0x%04x", req, req->dstid, req->altid);
3818 req->timeout = g_timeout_add_seconds(30, request_timeout, req);
3820 req->timeout = g_timeout_add_seconds(5, request_timeout, req);
3822 request_list = g_slist_append(request_list, req);
3827 static gboolean udp4_listener_event(GIOChannel *channel, GIOCondition condition,
3830 struct listener_data *ifdata = user_data;
3832 return udp_listener_event(channel, condition, ifdata, AF_INET,
3833 &ifdata->udp4_listener_watch);
3836 static gboolean udp6_listener_event(GIOChannel *channel, GIOCondition condition,
3839 struct listener_data *ifdata = user_data;
3841 return udp_listener_event(channel, condition, user_data, AF_INET6,
3842 &ifdata->udp6_listener_watch);
3845 static GIOChannel *get_listener(int family, int protocol, int index)
3847 GIOChannel *channel;
3849 #if !defined TIZEN_EXT
3852 struct sockaddr_in6 sin6;
3853 struct sockaddr_in sin;
3858 #if !defined TIZEN_EXT
3861 #if defined TIZEN_EXT
3865 int is_socket_inet = 0;
3868 debug("family %d protocol %d index %d", family, protocol, index);
3873 type = SOCK_DGRAM | SOCK_CLOEXEC;
3878 type = SOCK_STREAM | SOCK_CLOEXEC;
3884 #if defined TIZEN_EXT
3885 sd_num = sd_listen_fds(0);
3886 DBG("socket type(%s) systemd number of fds(%d)", proto, sd_num);
3888 DBG("fail to get the fd from systemd");
3892 if(protocol == IPPROTO_TCP)
3897 for(sk = SD_LISTEN_FDS_START; sk < SD_LISTEN_FDS_START+sd_num; ++sk){
3898 rv = sd_is_socket_inet(sk, family, type, -1, 53);
3900 DBG("socket fd (%d) is passed by systemd", sk);
3906 if (!is_socket_inet) {
3907 DBG("socket fd is not matched what connman requests");
3911 sk = socket(family, type, protocol);
3912 if (sk < 0 && family == AF_INET6 && errno == EAFNOSUPPORT) {
3913 connman_error("No IPv6 support");
3918 connman_error("Failed to create %s listener socket", proto);
3922 interface = connman_inet_ifname(index);
3923 if (!interface || setsockopt(sk, SOL_SOCKET, SO_BINDTODEVICE,
3925 strlen(interface) + 1) < 0) {
3926 connman_error("Failed to bind %s listener interface "
3928 proto, family == AF_INET ? "IPv4" : "IPv6",
3929 -errno, strerror(errno));
3936 if (family == AF_INET6) {
3937 memset(&s.sin6, 0, sizeof(s.sin6));
3938 s.sin6.sin6_family = AF_INET6;
3939 s.sin6.sin6_port = htons(53);
3940 slen = sizeof(s.sin6);
3942 if (__connman_inet_get_interface_address(index,
3944 &s.sin6.sin6_addr) < 0) {
3945 /* So we could not find suitable IPv6 address for
3946 * the interface. This could happen if we have
3947 * disabled IPv6 for the interface.
3953 } else if (family == AF_INET) {
3954 memset(&s.sin, 0, sizeof(s.sin));
3955 s.sin.sin_family = AF_INET;
3956 s.sin.sin_port = htons(53);
3957 slen = sizeof(s.sin);
3959 if (__connman_inet_get_interface_address(index,
3961 &s.sin.sin_addr) < 0) {
3971 #if defined TIZEN_EXT
3972 /* When ConnMan crashed,
3973 * probably DNS listener cannot bind existing address */
3975 if (setsockopt(sk, SOL_SOCKET, SO_REUSEADDR, &option, sizeof(option)) < 0) {
3976 connman_error("Failed to set socket option SO_REUSEADDR");
3981 #if !defined TIZEN_EXT
3982 if (bind(sk, &s.sa, slen) < 0) {
3983 connman_error("Failed to bind %s listener socket", proto);
3989 if (protocol == IPPROTO_TCP) {
3991 #if !defined TIZEN_EXT
3992 if (listen(sk, 10) < 0) {
3993 connman_error("Failed to listen on TCP socket %d/%s",
3994 -errno, strerror(errno));
4000 fcntl(sk, F_SETFL, O_NONBLOCK);
4003 channel = g_io_channel_unix_new(sk);
4005 connman_error("Failed to create %s listener channel", proto);
4010 g_io_channel_set_close_on_unref(channel, TRUE);
4015 #define UDP_IPv4_FAILED 0x01
4016 #define TCP_IPv4_FAILED 0x02
4017 #define UDP_IPv6_FAILED 0x04
4018 #define TCP_IPv6_FAILED 0x08
4019 #define UDP_FAILED (UDP_IPv4_FAILED | UDP_IPv6_FAILED)
4020 #define TCP_FAILED (TCP_IPv4_FAILED | TCP_IPv6_FAILED)
4021 #define IPv6_FAILED (UDP_IPv6_FAILED | TCP_IPv6_FAILED)
4022 #define IPv4_FAILED (UDP_IPv4_FAILED | TCP_IPv4_FAILED)
4024 static int create_dns_listener(int protocol, struct listener_data *ifdata)
4028 if (protocol == IPPROTO_TCP) {
4029 ifdata->tcp4_listener_channel = get_listener(AF_INET, protocol,
4031 if (ifdata->tcp4_listener_channel)
4032 #if defined TIZEN_EXT
4033 ifdata->tcp4_listener_watch =
4034 g_io_add_watch(ifdata->tcp4_listener_channel,
4035 G_IO_IN | G_IO_ERR | G_IO_HUP | G_IO_NVAL,
4036 tcp4_listener_event, (gpointer)ifdata);
4038 ifdata->tcp4_listener_watch =
4039 g_io_add_watch(ifdata->tcp4_listener_channel,
4040 G_IO_IN, tcp4_listener_event,
4044 ret |= TCP_IPv4_FAILED;
4046 ifdata->tcp6_listener_channel = get_listener(AF_INET6, protocol,
4048 if (ifdata->tcp6_listener_channel)
4049 #if defined TIZEN_EXT
4050 ifdata->tcp6_listener_watch =
4051 g_io_add_watch(ifdata->tcp6_listener_channel,
4052 G_IO_IN | G_IO_ERR | G_IO_HUP | G_IO_NVAL,
4053 tcp6_listener_event, (gpointer)ifdata);
4055 ifdata->tcp6_listener_watch =
4056 g_io_add_watch(ifdata->tcp6_listener_channel,
4057 G_IO_IN, tcp6_listener_event,
4061 ret |= TCP_IPv6_FAILED;
4063 ifdata->udp4_listener_channel = get_listener(AF_INET, protocol,
4065 if (ifdata->udp4_listener_channel)
4066 #if defined TIZEN_EXT
4067 ifdata->udp4_listener_watch =
4068 g_io_add_watch(ifdata->udp4_listener_channel,
4069 G_IO_IN | G_IO_ERR | G_IO_HUP | G_IO_NVAL,
4070 udp4_listener_event, (gpointer)ifdata);
4072 ifdata->udp4_listener_watch =
4073 g_io_add_watch(ifdata->udp4_listener_channel,
4074 G_IO_IN, udp4_listener_event,
4078 ret |= UDP_IPv4_FAILED;
4080 ifdata->udp6_listener_channel = get_listener(AF_INET6, protocol,
4082 if (ifdata->udp6_listener_channel)
4083 #if defined TIZEN_EXT
4084 ifdata->udp6_listener_watch =
4085 g_io_add_watch(ifdata->udp6_listener_channel,
4086 G_IO_IN | G_IO_ERR | G_IO_HUP | G_IO_NVAL,
4087 udp6_listener_event, (gpointer)ifdata);
4089 ifdata->udp6_listener_watch =
4090 g_io_add_watch(ifdata->udp6_listener_channel,
4091 G_IO_IN, udp6_listener_event,
4095 ret |= UDP_IPv6_FAILED;
4101 static void destroy_udp_listener(struct listener_data *ifdata)
4103 DBG("index %d", ifdata->index);
4105 if (ifdata->udp4_listener_watch > 0)
4106 g_source_remove(ifdata->udp4_listener_watch);
4108 if (ifdata->udp6_listener_watch > 0)
4109 g_source_remove(ifdata->udp6_listener_watch);
4111 if (ifdata->udp4_listener_channel)
4112 g_io_channel_unref(ifdata->udp4_listener_channel);
4113 if (ifdata->udp6_listener_channel)
4114 g_io_channel_unref(ifdata->udp6_listener_channel);
4117 static void destroy_tcp_listener(struct listener_data *ifdata)
4119 DBG("index %d", ifdata->index);
4121 if (ifdata->tcp4_listener_watch > 0)
4122 g_source_remove(ifdata->tcp4_listener_watch);
4123 if (ifdata->tcp6_listener_watch > 0)
4124 g_source_remove(ifdata->tcp6_listener_watch);
4126 if (ifdata->tcp4_listener_channel)
4127 g_io_channel_unref(ifdata->tcp4_listener_channel);
4128 if (ifdata->tcp6_listener_channel)
4129 g_io_channel_unref(ifdata->tcp6_listener_channel);
4132 static int create_listener(struct listener_data *ifdata)
4136 err = create_dns_listener(IPPROTO_UDP, ifdata);
4137 if ((err & UDP_FAILED) == UDP_FAILED)
4140 err |= create_dns_listener(IPPROTO_TCP, ifdata);
4141 if ((err & TCP_FAILED) == TCP_FAILED) {
4142 destroy_udp_listener(ifdata);
4146 index = connman_inet_ifindex("lo");
4147 if (ifdata->index == index) {
4148 if ((err & IPv6_FAILED) != IPv6_FAILED)
4149 __connman_resolvfile_append(index, NULL, "::1");
4151 if ((err & IPv4_FAILED) != IPv4_FAILED)
4152 __connman_resolvfile_append(index, NULL, "127.0.0.1");
4158 static void destroy_listener(struct listener_data *ifdata)
4163 index = connman_inet_ifindex("lo");
4164 if (ifdata->index == index) {
4165 __connman_resolvfile_remove(index, NULL, "127.0.0.1");
4166 __connman_resolvfile_remove(index, NULL, "::1");
4169 for (list = request_list; list; list = list->next) {
4170 struct request_data *req = list->data;
4172 debug("Dropping request (id 0x%04x -> 0x%04x)",
4173 req->srcid, req->dstid);
4174 destroy_request_data(req);
4178 g_slist_free(request_list);
4179 request_list = NULL;
4181 destroy_tcp_listener(ifdata);
4182 destroy_udp_listener(ifdata);
4185 int __connman_dnsproxy_add_listener(int index)
4187 struct listener_data *ifdata;
4190 DBG("index %d", index);
4195 if (!listener_table)
4198 if (g_hash_table_lookup(listener_table, GINT_TO_POINTER(index)))
4201 ifdata = g_try_new0(struct listener_data, 1);
4205 ifdata->index = index;
4206 ifdata->udp4_listener_channel = NULL;
4207 ifdata->udp4_listener_watch = 0;
4208 ifdata->tcp4_listener_channel = NULL;
4209 ifdata->tcp4_listener_watch = 0;
4210 ifdata->udp6_listener_channel = NULL;
4211 ifdata->udp6_listener_watch = 0;
4212 ifdata->tcp6_listener_channel = NULL;
4213 ifdata->tcp6_listener_watch = 0;
4215 err = create_listener(ifdata);
4217 connman_error("Couldn't create listener for index %d err %d",
4222 g_hash_table_insert(listener_table, GINT_TO_POINTER(ifdata->index),
4227 void __connman_dnsproxy_remove_listener(int index)
4229 struct listener_data *ifdata;
4231 DBG("index %d", index);
4233 if (!listener_table)
4236 ifdata = g_hash_table_lookup(listener_table, GINT_TO_POINTER(index));
4240 destroy_listener(ifdata);
4242 g_hash_table_remove(listener_table, GINT_TO_POINTER(index));
4245 static void remove_listener(gpointer key, gpointer value, gpointer user_data)
4247 int index = GPOINTER_TO_INT(key);
4248 struct listener_data *ifdata = value;
4250 DBG("index %d", index);
4252 destroy_listener(ifdata);
4255 static void free_partial_reqs(gpointer value)
4257 struct tcp_partial_client_data *data = value;
4263 int __connman_dnsproxy_init(void)
4269 listener_table = g_hash_table_new_full(g_direct_hash, g_direct_equal,
4272 partial_tcp_req_table = g_hash_table_new_full(g_direct_hash,
4277 index = connman_inet_ifindex("lo");
4278 err = __connman_dnsproxy_add_listener(index);
4282 err = connman_notifier_register(&dnsproxy_notifier);
4289 __connman_dnsproxy_remove_listener(index);
4290 g_hash_table_destroy(listener_table);
4291 g_hash_table_destroy(partial_tcp_req_table);
4296 int __connman_dnsproxy_set_mdns(int index, bool enabled)
4301 void __connman_dnsproxy_cleanup(void)
4306 g_source_remove(cache_timer);
4311 g_hash_table_destroy(cache);
4315 connman_notifier_unregister(&dnsproxy_notifier);
4317 g_hash_table_foreach(listener_table, remove_listener, NULL);
4319 g_hash_table_destroy(listener_table);
4321 g_hash_table_destroy(partial_tcp_req_table);
4324 g_resolv_unref(ipv4_resolve);
4326 g_resolv_unref(ipv6_resolve);