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);
513 #if !defined TIZEN_EXT
516 buf[1] = sizeof(*hdr);
520 debug("id 0x%04x qr %d opcode %d", hdr->id, hdr->qr, hdr->opcode);
523 hdr->rcode = ns_r_servfail;
525 #if !defined TIZEN_EXT
532 #if defined TIZEN_EXT
533 err = sendto(sk, buf, len, MSG_NOSIGNAL, to, tolen);
535 err = sendto(sk, buf, sizeof(*hdr) + offset, MSG_NOSIGNAL, to, tolen);
538 connman_error("Failed to send DNS response to %d: %s",
539 sk, strerror(errno));
544 static int get_req_udp_socket(struct request_data *req)
548 if (req->family == AF_INET)
549 channel = req->ifdata->udp4_listener_channel;
551 channel = req->ifdata->udp6_listener_channel;
556 return g_io_channel_unix_get_fd(channel);
559 static void destroy_request_data(struct request_data *req)
561 if (req->timeout > 0)
562 g_source_remove(req->timeout);
565 g_free(req->request);
570 static gboolean request_timeout(gpointer user_data)
572 struct request_data *req = user_data;
579 debug("id 0x%04x", req->srcid);
581 request_list = g_slist_remove(request_list, req);
583 if (req->protocol == IPPROTO_UDP) {
584 sk = get_req_udp_socket(req);
586 } else if (req->protocol == IPPROTO_TCP) {
592 if (req->resplen > 0 && req->resp) {
594 * Here we have received at least one reply (probably telling
595 * "not found" result), so send that back to client instead
596 * of more fatal server failed error.
599 sendto(sk, req->resp, req->resplen, MSG_NOSIGNAL,
602 } else if (req->request) {
604 * There was not reply from server at all.
606 struct domain_hdr *hdr;
608 hdr = (void *)(req->request + protocol_offset(req->protocol));
609 hdr->id = req->srcid;
612 send_response(sk, req->request, req->request_len,
613 sa, req->sa_len, req->protocol);
617 * We cannot leave TCP client hanging so just kick it out
618 * if we get a request timeout from server.
620 if (req->protocol == IPPROTO_TCP) {
621 debug("client %d removed", req->client_sk);
622 g_hash_table_remove(partial_tcp_req_table,
623 GINT_TO_POINTER(req->client_sk));
628 destroy_request_data(req);
633 static int append_query(unsigned char *buf, unsigned int size,
634 const char *query, const char *domain)
636 unsigned char *ptr = buf;
639 debug("query %s domain %s", query, domain);
644 tmp = strchr(query, '.');
650 memcpy(ptr + 1, query, len);
656 memcpy(ptr + 1, query, tmp - query);
657 ptr += tmp - query + 1;
665 tmp = strchr(domain, '.');
667 len = strlen(domain);
671 memcpy(ptr + 1, domain, len);
677 memcpy(ptr + 1, domain, tmp - domain);
678 ptr += tmp - domain + 1;
688 static bool cache_check_is_valid(struct cache_data *data,
694 if (data->cache_until < current_time)
701 * remove stale cached entries so that they can be refreshed
703 static void cache_enforce_validity(struct cache_entry *entry)
705 time_t current_time = time(NULL);
707 if (!cache_check_is_valid(entry->ipv4, current_time)
709 debug("cache timeout \"%s\" type A", entry->key);
710 g_free(entry->ipv4->data);
716 if (!cache_check_is_valid(entry->ipv6, current_time)
718 debug("cache timeout \"%s\" type AAAA", entry->key);
719 g_free(entry->ipv6->data);
725 static uint16_t cache_check_validity(char *question, uint16_t type,
726 struct cache_entry *entry)
728 time_t current_time = time(NULL);
729 bool want_refresh = false;
732 * if we have a popular entry, we want a refresh instead of
733 * total destruction of the entry.
738 cache_enforce_validity(entry);
742 if (!cache_check_is_valid(entry->ipv4, current_time)) {
743 debug("cache %s \"%s\" type A", entry->ipv4 ?
744 "timeout" : "entry missing", question);
747 entry->want_refresh = true;
750 * We do not remove cache entry if there is still
751 * valid IPv6 entry found in the cache.
753 if (!cache_check_is_valid(entry->ipv6, current_time) && !want_refresh) {
754 g_hash_table_remove(cache, question);
761 if (!cache_check_is_valid(entry->ipv6, current_time)) {
762 debug("cache %s \"%s\" type AAAA", entry->ipv6 ?
763 "timeout" : "entry missing", question);
766 entry->want_refresh = true;
768 if (!cache_check_is_valid(entry->ipv4, current_time) && !want_refresh) {
769 g_hash_table_remove(cache, question);
779 static void cache_element_destroy(gpointer value)
781 struct cache_entry *entry = value;
787 g_free(entry->ipv4->data);
792 g_free(entry->ipv6->data);
799 if (--cache_size < 0)
803 static gboolean try_remove_cache(gpointer user_data)
807 if (__sync_fetch_and_sub(&cache_refcount, 1) == 1) {
808 debug("No cache users, removing it.");
810 g_hash_table_destroy(cache);
817 static void create_cache(void)
819 if (__sync_fetch_and_add(&cache_refcount, 1) == 0)
820 cache = g_hash_table_new_full(g_str_hash,
823 cache_element_destroy);
826 static struct cache_entry *cache_check(gpointer request, int *qtype, int proto)
829 struct cache_entry *entry;
830 struct domain_question *q;
832 int offset, proto_offset;
837 proto_offset = protocol_offset(proto);
838 if (proto_offset < 0)
841 question = request + proto_offset + 12;
843 offset = strlen(question) + 1;
844 q = (void *) (question + offset);
845 type = ntohs(q->type);
847 /* We only cache either A (1) or AAAA (28) requests */
848 if (type != 1 && type != 28)
856 entry = g_hash_table_lookup(cache, question);
860 type = cache_check_validity(question, type, entry);
869 * Get a label/name from DNS resource record. The function decompresses the
870 * label if necessary. The function does not convert the name to presentation
871 * form. This means that the result string will contain label lengths instead
872 * of dots between labels. We intentionally do not want to convert to dotted
873 * format so that we can cache the wire format string directly.
875 static int get_name(int counter,
876 unsigned char *pkt, unsigned char *start, unsigned char *max,
877 unsigned char *output, int output_max, int *output_len,
878 unsigned char **end, char *name, size_t max_name, int *name_len)
882 /* Limit recursion to 10 (this means up to 10 labels in domain name) */
888 if ((*p & NS_CMPRSFLGS) == NS_CMPRSFLGS) {
889 uint16_t offset = (*p & 0x3F) * 256 + *(p + 1);
891 if (offset >= max - pkt)
897 return get_name(counter + 1, pkt, pkt + offset, max,
898 output, output_max, output_len, end,
899 name, max_name, name_len);
901 unsigned label_len = *p;
903 if (pkt + label_len > max)
906 if (*output_len > output_max)
909 if ((*name_len + 1 + label_len + 1) > max_name)
913 * We need the original name in order to check
914 * if this answer is the correct one.
916 name[(*name_len)++] = label_len;
917 memcpy(name + *name_len, p + 1, label_len + 1);
918 *name_len += label_len;
920 /* We compress the result */
921 output[0] = NS_CMPRSFLGS;
938 static int parse_rr(unsigned char *buf, unsigned char *start,
940 unsigned char *response, unsigned int *response_size,
941 uint16_t *type, uint16_t *class, int *ttl, int *rdlen,
943 char *name, size_t max_name)
945 struct domain_rr *rr;
947 int name_len = 0, output_len = 0, max_rsp = *response_size;
949 err = get_name(0, buf, start, max, response, max_rsp,
950 &output_len, end, name, max_name, &name_len);
956 if ((unsigned int) offset > *response_size)
959 rr = (void *) (*end);
964 *type = ntohs(rr->type);
965 *class = ntohs(rr->class);
966 *ttl = ntohl(rr->ttl);
967 *rdlen = ntohs(rr->rdlen);
972 memcpy(response + offset, *end, sizeof(struct domain_rr));
974 offset += sizeof(struct domain_rr);
975 *end += sizeof(struct domain_rr);
977 if ((unsigned int) (offset + *rdlen) > *response_size)
980 memcpy(response + offset, *end, *rdlen);
984 *response_size = offset + *rdlen;
989 static bool check_alias(GSList *aliases, char *name)
994 for (list = aliases; list; list = list->next) {
995 int len = strlen((char *)list->data);
996 if (strncmp((char *)list->data, name, len) == 0)
1004 static int parse_response(unsigned char *buf, int buflen,
1005 char *question, int qlen,
1006 uint16_t *type, uint16_t *class, int *ttl,
1007 unsigned char *response, unsigned int *response_len,
1010 struct domain_hdr *hdr = (void *) buf;
1011 struct domain_question *q;
1013 uint16_t qdcount = ntohs(hdr->qdcount);
1014 uint16_t ancount = ntohs(hdr->ancount);
1016 uint16_t qtype, qclass;
1017 unsigned char *next = NULL;
1018 unsigned int maxlen = *response_len;
1019 GSList *aliases = NULL, *list;
1020 char name[NS_MAXDNAME + 1];
1025 debug("qr %d qdcount %d", hdr->qr, qdcount);
1027 /* We currently only cache responses where question count is 1 */
1028 if (hdr->qr != 1 || qdcount != 1)
1031 ptr = buf + sizeof(struct domain_hdr);
1033 strncpy(question, (char *) ptr, qlen);
1034 qlen = strlen(question);
1035 ptr += qlen + 1; /* skip \0 */
1038 qtype = ntohs(q->type);
1040 /* We cache only A and AAAA records */
1041 if (qtype != 1 && qtype != 28)
1044 qclass = ntohs(q->class);
1046 ptr += 2 + 2; /* ptr points now to answers */
1052 memset(name, 0, sizeof(name));
1055 * We have a bunch of answers (like A, AAAA, CNAME etc) to
1056 * A or AAAA question. We traverse the answers and parse the
1057 * resource records. Only A and AAAA records are cached, all
1058 * the other records in answers are skipped.
1060 for (i = 0; i < ancount; i++) {
1062 * Get one address at a time to this buffer.
1063 * The max size of the answer is
1064 * 2 (pointer) + 2 (type) + 2 (class) +
1065 * 4 (ttl) + 2 (rdlen) + addr (16 or 4) = 28
1066 * for A or AAAA record.
1067 * For CNAME the size can be bigger.
1069 unsigned char rsp[NS_MAXCDNAME];
1070 unsigned int rsp_len = sizeof(rsp) - 1;
1073 memset(rsp, 0, sizeof(rsp));
1075 ret = parse_rr(buf, ptr, buf + buflen, rsp, &rsp_len,
1076 type, class, ttl, &rdlen, &next, name,
1084 * Now rsp contains compressed or uncompressed resource
1085 * record. Next we check if this record answers the question.
1086 * The name var contains the uncompressed label.
1087 * One tricky bit is the CNAME records as they alias
1088 * the name we might be interested in.
1092 * Go to next answer if the class is not the one we are
1095 if (*class != qclass) {
1102 * Try to resolve aliases also, type is CNAME(5).
1103 * This is important as otherwise the aliased names would not
1104 * be cached at all as the cache would not contain the aliased
1107 * If any CNAME is found in DNS packet, then we cache the alias
1108 * IP address instead of the question (as the server
1109 * said that question has only an alias).
1110 * This means in practice that if e.g., ipv6.google.com is
1111 * queried, DNS server returns CNAME of that name which is
1112 * ipv6.l.google.com. We then cache the address of the CNAME
1113 * but return the question name to client. So the alias
1114 * status of the name is not saved in cache and thus not
1115 * returned to the client. We do not return DNS packets from
1116 * cache to client saying that ipv6.google.com is an alias to
1117 * ipv6.l.google.com but we return instead a DNS packet that
1118 * says ipv6.google.com has address xxx which is in fact the
1119 * address of ipv6.l.google.com. For caching purposes this
1120 * should not cause any issues.
1122 if (*type == 5 && strncmp(question, name, qlen) == 0) {
1124 * So now the alias answered the question. This is
1125 * not very useful from caching point of view as
1126 * the following A or AAAA records will not match the
1127 * question. We need to find the real A/AAAA record
1128 * of the alias and cache that.
1130 unsigned char *end = NULL;
1131 int name_len = 0, output_len = 0;
1133 memset(rsp, 0, sizeof(rsp));
1134 rsp_len = sizeof(rsp) - 1;
1137 * Alias is in rdata part of the message,
1138 * and next-rdlen points to it. So we need to get
1139 * the real name of the alias.
1141 ret = get_name(0, buf, next - rdlen, buf + buflen,
1142 rsp, rsp_len, &output_len, &end,
1143 name, sizeof(name) - 1, &name_len);
1145 /* just ignore the error at this point */
1152 * We should now have the alias of the entry we might
1153 * want to cache. Just remember it for a while.
1154 * We check the alias list when we have parsed the
1157 aliases = g_slist_prepend(aliases, g_strdup(name));
1164 if (*type == qtype) {
1166 * We found correct type (A or AAAA)
1168 if (check_alias(aliases, name) ||
1169 (!aliases && strncmp(question, name,
1172 * We found an alias or the name of the rr
1173 * matches the question. If so, we append
1174 * the compressed label to the cache.
1175 * The end result is a response buffer that
1176 * will contain one or more cached and
1177 * compressed resource records.
1179 if (*response_len + rsp_len > maxlen) {
1183 memcpy(response + *response_len, rsp, rsp_len);
1184 *response_len += rsp_len;
1195 for (list = aliases; list; list = list->next)
1197 g_slist_free(aliases);
1202 struct cache_timeout {
1203 time_t current_time;
1208 static gboolean cache_check_entry(gpointer key, gpointer value,
1211 struct cache_timeout *data = user_data;
1212 struct cache_entry *entry = value;
1215 /* Scale the number of hits by half as part of cache aging */
1220 * If either IPv4 or IPv6 cached entry has expired, we
1221 * remove both from the cache.
1224 if (entry->ipv4 && entry->ipv4->timeout > 0) {
1225 max_timeout = entry->ipv4->cache_until;
1226 if (max_timeout > data->max_timeout)
1227 data->max_timeout = max_timeout;
1229 if (entry->ipv4->cache_until < data->current_time)
1233 if (entry->ipv6 && entry->ipv6->timeout > 0) {
1234 max_timeout = entry->ipv6->cache_until;
1235 if (max_timeout > data->max_timeout)
1236 data->max_timeout = max_timeout;
1238 if (entry->ipv6->cache_until < data->current_time)
1243 * if we're asked to try harder, also remove entries that have
1246 if (data->try_harder && entry->hits < 4)
1252 static void cache_cleanup(void)
1254 static int max_timeout;
1255 struct cache_timeout data;
1258 data.current_time = time(NULL);
1259 data.max_timeout = 0;
1260 data.try_harder = 0;
1263 * In the first pass, we only remove entries that have timed out.
1264 * We use a cache of the first time to expire to do this only
1265 * when it makes sense.
1267 if (max_timeout <= data.current_time) {
1268 count = g_hash_table_foreach_remove(cache, cache_check_entry,
1271 debug("removed %d in the first pass", count);
1274 * In the second pass, if the first pass turned up blank,
1275 * we also expire entries with a low hit count,
1276 * while aging the hit count at the same time.
1278 data.try_harder = 1;
1280 count = g_hash_table_foreach_remove(cache, cache_check_entry,
1285 * If we could not remove anything, then remember
1286 * what is the max timeout and do nothing if we
1287 * have not yet reached it. This will prevent
1288 * constant traversal of the cache if it is full.
1290 max_timeout = data.max_timeout;
1295 static gboolean cache_invalidate_entry(gpointer key, gpointer value,
1298 struct cache_entry *entry = value;
1300 /* first, delete any expired elements */
1301 cache_enforce_validity(entry);
1303 /* if anything is not expired, mark the entry for refresh */
1304 if (entry->hits > 0 && (entry->ipv4 || entry->ipv6))
1305 entry->want_refresh = true;
1307 /* delete the cached data */
1309 g_free(entry->ipv4->data);
1310 g_free(entry->ipv4);
1315 g_free(entry->ipv6->data);
1316 g_free(entry->ipv6);
1320 /* keep the entry if we want it refreshed, delete it otherwise */
1321 if (entry->want_refresh)
1328 * cache_invalidate is called from places where the DNS landscape
1329 * has changed, say because connections are added or we entered a VPN.
1330 * The logic is to wipe all cache data, but mark all non-expired
1331 * parts of the cache for refresh rather than deleting the whole cache.
1333 static void cache_invalidate(void)
1335 debug("Invalidating the DNS cache %p", cache);
1340 g_hash_table_foreach_remove(cache, cache_invalidate_entry, NULL);
1343 static void cache_refresh_entry(struct cache_entry *entry)
1346 cache_enforce_validity(entry);
1348 if (entry->hits > 2 && !entry->ipv4)
1349 entry->want_refresh = true;
1350 if (entry->hits > 2 && !entry->ipv6)
1351 entry->want_refresh = true;
1353 if (entry->want_refresh) {
1355 char dns_name[NS_MAXDNAME + 1];
1356 entry->want_refresh = false;
1358 /* turn a DNS name into a hostname with dots */
1359 strncpy(dns_name, entry->key, NS_MAXDNAME);
1367 debug("Refreshing %s\n", dns_name);
1368 /* then refresh the hostname */
1369 refresh_dns_entry(entry, &dns_name[1]);
1373 static void cache_refresh_iterator(gpointer key, gpointer value,
1376 struct cache_entry *entry = value;
1378 cache_refresh_entry(entry);
1381 static void cache_refresh(void)
1386 g_hash_table_foreach(cache, cache_refresh_iterator, NULL);
1389 static int reply_query_type(unsigned char *msg, int len)
1395 /* skip the header */
1396 c = msg + sizeof(struct domain_hdr);
1397 len -= sizeof(struct domain_hdr);
1402 /* now the query, which is a name and 2 16 bit words */
1403 l = dns_name_length(c);
1405 type = c[0] << 8 | c[1];
1410 static int cache_update(struct server_data *srv, unsigned char *msg,
1411 unsigned int msg_len)
1413 int offset = protocol_offset(srv->protocol);
1414 int err, qlen, ttl = 0;
1415 uint16_t answers = 0, type = 0, class = 0;
1416 struct domain_hdr *hdr = (void *)(msg + offset);
1417 struct domain_question *q;
1418 struct cache_entry *entry;
1419 struct cache_data *data;
1420 char question[NS_MAXDNAME + 1];
1421 unsigned char response[NS_MAXDNAME + 1];
1423 unsigned int rsplen;
1424 bool new_entry = true;
1425 time_t current_time;
1427 if (cache_size >= MAX_CACHE_SIZE) {
1429 if (cache_size >= MAX_CACHE_SIZE)
1433 current_time = time(NULL);
1435 /* don't do a cache refresh more than twice a minute */
1436 if (next_refresh < current_time) {
1438 next_refresh = current_time + 30;
1444 debug("offset %d hdr %p msg %p rcode %d", offset, hdr, msg, hdr->rcode);
1446 /* Continue only if response code is 0 (=ok) */
1447 if (hdr->rcode != ns_r_noerror)
1453 rsplen = sizeof(response) - 1;
1454 question[sizeof(question) - 1] = '\0';
1456 err = parse_response(msg + offset, msg_len - offset,
1457 question, sizeof(question) - 1,
1458 &type, &class, &ttl,
1459 response, &rsplen, &answers);
1462 * special case: if we do a ipv6 lookup and get no result
1463 * for a record that's already in our ipv4 cache.. we want
1464 * to cache the negative response.
1466 if ((err == -ENOMSG || err == -ENOBUFS) &&
1467 reply_query_type(msg + offset,
1468 msg_len - offset) == 28) {
1469 entry = g_hash_table_lookup(cache, question);
1470 if (entry && entry->ipv4 && !entry->ipv6) {
1471 int cache_offset = 0;
1473 data = g_try_new(struct cache_data, 1);
1476 data->inserted = entry->ipv4->inserted;
1478 data->answers = ntohs(hdr->ancount);
1479 data->timeout = entry->ipv4->timeout;
1480 if (srv->protocol == IPPROTO_UDP)
1482 data->data_len = msg_len + cache_offset;
1483 data->data = ptr = g_malloc(data->data_len);
1484 ptr[0] = (data->data_len - 2) / 256;
1485 ptr[1] = (data->data_len - 2) - ptr[0] * 256;
1486 if (srv->protocol == IPPROTO_UDP)
1488 data->valid_until = entry->ipv4->valid_until;
1489 data->cache_until = entry->ipv4->cache_until;
1490 memcpy(ptr, msg, msg_len);
1493 * we will get a "hit" when we serve the response
1497 if (entry->hits < 0)
1503 if (err < 0 || ttl == 0)
1506 qlen = strlen(question);
1509 * If the cache contains already data, check if the
1510 * type of the cached data is the same and do not add
1511 * to cache if data is already there.
1512 * This is needed so that we can cache both A and AAAA
1513 * records for the same name.
1515 entry = g_hash_table_lookup(cache, question);
1517 entry = g_try_new(struct cache_entry, 1);
1521 data = g_try_new(struct cache_data, 1);
1527 entry->key = g_strdup(question);
1528 entry->ipv4 = entry->ipv6 = NULL;
1529 entry->want_refresh = false;
1537 if (type == 1 && entry->ipv4)
1540 if (type == 28 && entry->ipv6)
1543 data = g_try_new(struct cache_data, 1);
1553 * compensate for the hit we'll get for serving
1554 * the response out of the cache
1557 if (entry->hits < 0)
1563 if (ttl < MIN_CACHE_TTL)
1564 ttl = MIN_CACHE_TTL;
1566 data->inserted = current_time;
1568 data->answers = answers;
1569 data->timeout = ttl;
1571 * The "2" in start of the length is the TCP offset. We allocate it
1572 * here even for UDP packet because it simplifies the sending
1575 data->data_len = 2 + 12 + qlen + 1 + 2 + 2 + rsplen;
1576 data->data = ptr = g_malloc(data->data_len);
1577 data->valid_until = current_time + ttl;
1580 * Restrict the cached DNS record TTL to some sane value
1581 * in order to prevent data staying in the cache too long.
1583 if (ttl > MAX_CACHE_TTL)
1584 ttl = MAX_CACHE_TTL;
1586 data->cache_until = round_down_ttl(current_time + ttl, ttl);
1596 * We cache the two extra bytes at the start of the message
1597 * in a TCP packet. When sending UDP packet, we skip the first
1598 * two bytes. This way we do not need to know the format
1599 * (UDP/TCP) of the cached message.
1601 if (srv->protocol == IPPROTO_UDP)
1602 memcpy(ptr + 2, msg, offset + 12);
1604 memcpy(ptr, msg, offset + 12);
1606 ptr[0] = (data->data_len - 2) / 256;
1607 ptr[1] = (data->data_len - 2) - ptr[0] * 256;
1608 if (srv->protocol == IPPROTO_UDP)
1611 memcpy(ptr + offset + 12, question, qlen + 1); /* copy also the \0 */
1613 q = (void *) (ptr + offset + 12 + qlen + 1);
1614 q->type = htons(type);
1615 q->class = htons(class);
1616 memcpy(ptr + offset + 12 + qlen + 1 + sizeof(struct domain_question),
1620 g_hash_table_replace(cache, entry->key, entry);
1624 debug("cache %d %squestion \"%s\" type %d ttl %d size %zd packet %u "
1626 cache_size, new_entry ? "new " : "old ",
1627 question, type, ttl,
1628 sizeof(*entry) + sizeof(*data) + data->data_len + qlen,
1630 srv->protocol == IPPROTO_TCP ?
1631 (unsigned int)(data->data[0] * 256 + data->data[1]) :
1637 static int ns_resolv(struct server_data *server, struct request_data *req,
1638 gpointer request, gpointer name)
1641 int sk, err, type = 0;
1642 char *dot, *lookup = (char *) name;
1643 struct cache_entry *entry;
1645 entry = cache_check(request, &type, req->protocol);
1648 struct cache_data *data;
1650 debug("cache hit %s type %s", lookup, type == 1 ? "A" : "AAAA");
1657 ttl_left = data->valid_until - time(NULL);
1661 if (data && req->protocol == IPPROTO_TCP) {
1662 send_cached_response(req->client_sk, data->data,
1663 data->data_len, NULL, 0, IPPROTO_TCP,
1664 req->srcid, data->answers, ttl_left);
1668 if (data && req->protocol == IPPROTO_UDP) {
1669 int udp_sk = get_req_udp_socket(req);
1674 send_cached_response(udp_sk, data->data,
1675 data->data_len, &req->sa, req->sa_len,
1676 IPPROTO_UDP, req->srcid, data->answers,
1682 #if defined TIZEN_EXT
1683 if (server->protocol == IPPROTO_UDP) {
1685 struct server_data *new_server = NULL;
1687 new_server = create_server_sec(server->index, NULL,
1688 server->server, IPPROTO_UDP);
1690 if (new_server != NULL) {
1691 for (domains = server->domains; domains;
1692 domains = domains->next) {
1693 char *dom = domains->data;
1695 DBG("Adding domain %s to %s",
1696 dom, new_server->server);
1698 new_server->domains = g_list_append(
1699 new_server->domains,
1703 server = new_server;
1707 sk = g_io_channel_unix_get_fd(server->channel);
1709 err = sendto(sk, request, req->request_len, MSG_NOSIGNAL,
1710 server->server_addr, server->server_addr_len);
1712 debug("Cannot send message to server %s sock %d "
1713 "protocol %d (%s/%d)",
1714 server->server, sk, server->protocol,
1715 strerror(errno), errno);
1721 /* If we have more than one dot, we don't add domains */
1722 dot = strchr(lookup, '.');
1723 if (dot && dot != lookup + strlen(lookup) - 1)
1726 if (server->domains && server->domains->data)
1727 req->append_domain = true;
1729 for (list = server->domains; list; list = list->next) {
1731 unsigned char alt[1024];
1732 struct domain_hdr *hdr = (void *) &alt;
1733 int altlen, domlen, offset;
1735 domain = list->data;
1740 offset = protocol_offset(server->protocol);
1744 domlen = strlen(domain) + 1;
1748 alt[offset] = req->altid & 0xff;
1749 alt[offset + 1] = req->altid >> 8;
1751 memcpy(alt + offset + 2, request + offset + 2, 10);
1752 hdr->qdcount = htons(1);
1754 altlen = append_query(alt + offset + 12, sizeof(alt) - 12,
1761 memcpy(alt + offset + altlen,
1762 request + offset + altlen - domlen,
1763 req->request_len - altlen - offset + domlen);
1765 if (server->protocol == IPPROTO_TCP) {
1766 int req_len = req->request_len + domlen - 2;
1768 alt[0] = (req_len >> 8) & 0xff;
1769 alt[1] = req_len & 0xff;
1772 debug("req %p dstid 0x%04x altid 0x%04x", req, req->dstid,
1775 err = send(sk, alt, req->request_len + domlen, MSG_NOSIGNAL);
1785 static char *convert_label(char *start, char *end, char *ptr, char *uptr,
1786 int remaining_len, int *used_comp, int *used_uncomp)
1789 char name[NS_MAXLABEL];
1791 pos = dn_expand((u_char *)start, (u_char *)end, (u_char *)ptr,
1794 debug("uncompress error [%d/%s]", errno, strerror(errno));
1799 * We need to compress back the name so that we get back to internal
1800 * label presentation.
1802 comp_pos = dn_comp(name, (u_char *)uptr, remaining_len, NULL, NULL);
1804 debug("compress error [%d/%s]", errno, strerror(errno));
1809 *used_uncomp = comp_pos;
1817 static char *uncompress(int16_t field_count, char *start, char *end,
1818 char *ptr, char *uncompressed, int uncomp_len,
1819 char **uncompressed_ptr)
1821 char *uptr = *uncompressed_ptr; /* position in result buffer */
1823 debug("count %d ptr %p end %p uptr %p", field_count, ptr, end, uptr);
1825 while (field_count-- > 0 && ptr < end) {
1826 int dlen; /* data field length */
1827 int ulen; /* uncompress length */
1828 int pos; /* position in compressed string */
1829 char name[NS_MAXLABEL]; /* tmp label */
1830 uint16_t dns_type, dns_class;
1833 if (!convert_label(start, end, ptr, name, NS_MAXLABEL,
1838 * Copy the uncompressed resource record, type, class and \0 to
1842 ulen = strlen(name);
1843 strncpy(uptr, name, uncomp_len - (uptr - uncompressed));
1845 debug("pos %d ulen %d left %d name %s", pos, ulen,
1846 (int)(uncomp_len - (uptr - uncompressed)), uptr);
1854 * We copy also the fixed portion of the result (type, class,
1855 * ttl, address length and the address)
1857 memcpy(uptr, ptr, NS_RRFIXEDSZ);
1859 dns_type = uptr[0] << 8 | uptr[1];
1860 dns_class = uptr[2] << 8 | uptr[3];
1862 if (dns_class != ns_c_in)
1865 ptr += NS_RRFIXEDSZ;
1866 uptr += NS_RRFIXEDSZ;
1869 * Then the variable portion of the result (data length).
1870 * Typically this portion is also compressed
1871 * so we need to uncompress it also when necessary.
1873 if (dns_type == ns_t_cname) {
1874 if (!convert_label(start, end, ptr, uptr,
1875 uncomp_len - (uptr - uncompressed),
1879 uptr[-2] = comp_pos << 8;
1880 uptr[-1] = comp_pos & 0xff;
1885 } else if (dns_type == ns_t_a || dns_type == ns_t_aaaa) {
1886 dlen = uptr[-2] << 8 | uptr[-1];
1888 if (ptr + dlen > end) {
1889 debug("data len %d too long", dlen);
1893 memcpy(uptr, ptr, dlen);
1897 } else if (dns_type == ns_t_soa) {
1901 /* Primary name server expansion */
1902 if (!convert_label(start, end, ptr, uptr,
1903 uncomp_len - (uptr - uncompressed),
1907 total_len += comp_pos;
1908 len_ptr = &uptr[-2];
1912 /* Responsible authority's mailbox */
1913 if (!convert_label(start, end, ptr, uptr,
1914 uncomp_len - (uptr - uncompressed),
1918 total_len += comp_pos;
1923 * Copy rest of the soa fields (serial number,
1924 * refresh interval, retry interval, expiration
1925 * limit and minimum ttl). They are 20 bytes long.
1927 memcpy(uptr, ptr, 20);
1933 * Finally fix the length of the data part
1935 len_ptr[0] = total_len << 8;
1936 len_ptr[1] = total_len & 0xff;
1939 *uncompressed_ptr = uptr;
1948 static int strip_domains(char *name, char *answers, int maxlen)
1951 int name_len = strlen(name);
1952 char *ptr, *start = answers, *end = answers + maxlen;
1954 while (maxlen > 0) {
1955 ptr = strstr(answers, name);
1957 char *domain = ptr + name_len;
1960 int domain_len = strlen(domain);
1962 memmove(answers + name_len,
1963 domain + domain_len,
1964 end - (domain + domain_len));
1967 maxlen -= domain_len;
1971 answers += strlen(answers) + 1;
1972 answers += 2 + 2 + 4; /* skip type, class and ttl fields */
1974 data_len = answers[0] << 8 | answers[1];
1975 answers += 2; /* skip the length field */
1977 if (answers + data_len > end)
1980 answers += data_len;
1981 maxlen -= answers - ptr;
1987 static int forward_dns_reply(unsigned char *reply, int reply_len, int protocol,
1988 struct server_data *data)
1990 struct domain_hdr *hdr;
1991 struct request_data *req;
1992 int dns_id, sk, err, offset = protocol_offset(protocol);
1997 hdr = (void *)(reply + offset);
1998 dns_id = reply[offset] | reply[offset + 1] << 8;
2000 debug("Received %d bytes (id 0x%04x)", reply_len, dns_id);
2002 req = find_request(dns_id);
2006 debug("req %p dstid 0x%04x altid 0x%04x rcode %d",
2007 req, req->dstid, req->altid, hdr->rcode);
2009 reply[offset] = req->srcid & 0xff;
2010 reply[offset + 1] = req->srcid >> 8;
2014 if (hdr->rcode == ns_r_noerror || !req->resp) {
2015 unsigned char *new_reply = NULL;
2018 * If the domain name was append
2019 * remove it before forwarding the reply.
2020 * If there were more than one question, then this
2021 * domain name ripping can be hairy so avoid that
2022 * and bail out in that that case.
2024 * The reason we are doing this magic is that if the
2025 * user's DNS client tries to resolv hostname without
2026 * domain part, it also expects to get the result without
2027 * a domain name part.
2029 if (req->append_domain && ntohs(hdr->qdcount) == 1) {
2030 uint16_t domain_len = 0;
2031 uint16_t header_len;
2032 uint16_t dns_type, dns_class;
2033 uint8_t host_len, dns_type_pos;
2034 char uncompressed[NS_MAXDNAME], *uptr;
2035 char *ptr, *eom = (char *)reply + reply_len;
2038 * ptr points to the first char of the hostname.
2039 * ->hostname.domain.net
2041 header_len = offset + sizeof(struct domain_hdr);
2042 ptr = (char *)reply + header_len;
2046 domain_len = strnlen(ptr + 1 + host_len,
2047 reply_len - header_len);
2050 * If the query type is anything other than A or AAAA,
2051 * then bail out and pass the message as is.
2052 * We only want to deal with IPv4 or IPv6 addresses.
2054 dns_type_pos = host_len + 1 + domain_len + 1;
2056 dns_type = ptr[dns_type_pos] << 8 |
2057 ptr[dns_type_pos + 1];
2058 dns_class = ptr[dns_type_pos + 2] << 8 |
2059 ptr[dns_type_pos + 3];
2060 if (dns_type != ns_t_a && dns_type != ns_t_aaaa &&
2061 dns_class != ns_c_in) {
2062 debug("Pass msg dns type %d class %d",
2063 dns_type, dns_class);
2068 * Remove the domain name and replace it by the end
2069 * of reply. Check if the domain is really there
2070 * before trying to copy the data. We also need to
2071 * uncompress the answers if necessary.
2072 * The domain_len can be 0 because if the original
2073 * query did not contain a domain name, then we are
2074 * sending two packets, first without the domain name
2075 * and the second packet with domain name.
2076 * The append_domain is set to true even if we sent
2077 * the first packet without domain name. In this
2078 * case we end up in this branch.
2080 if (domain_len > 0) {
2081 int len = host_len + 1;
2082 int new_len, fixed_len;
2086 * First copy host (without domain name) into
2089 uptr = &uncompressed[0];
2090 memcpy(uptr, ptr, len);
2092 uptr[len] = '\0'; /* host termination */
2096 * Copy type and class fields of the question.
2098 ptr += len + domain_len + 1;
2099 memcpy(uptr, ptr, NS_QFIXEDSZ);
2102 * ptr points to answers after this
2105 uptr += NS_QFIXEDSZ;
2107 fixed_len = answers - uncompressed;
2110 * We then uncompress the result to buffer
2111 * so that we can rip off the domain name
2112 * part from the question. First answers,
2113 * then name server (authority) information,
2114 * and finally additional record info.
2117 ptr = uncompress(ntohs(hdr->ancount),
2118 (char *)reply + offset, eom,
2119 ptr, uncompressed, NS_MAXDNAME,
2124 ptr = uncompress(ntohs(hdr->nscount),
2125 (char *)reply + offset, eom,
2126 ptr, uncompressed, NS_MAXDNAME,
2131 ptr = uncompress(ntohs(hdr->arcount),
2132 (char *)reply + offset, eom,
2133 ptr, uncompressed, NS_MAXDNAME,
2139 * The uncompressed buffer now contains almost
2140 * valid response. Final step is to get rid of
2141 * the domain name because at least glibc
2142 * gethostbyname() implementation does extra
2143 * checks and expects to find an answer without
2144 * domain name if we asked a query without
2145 * domain part. Note that glibc getaddrinfo()
2146 * works differently and accepts FQDN in answer
2148 new_len = strip_domains(uncompressed, answers,
2151 debug("Corrupted packet");
2156 * Because we have now uncompressed the answers
2157 * we might have to create a bigger buffer to
2158 * hold all that data.
2161 reply_len = header_len + new_len + fixed_len;
2163 new_reply = g_try_malloc(reply_len);
2167 memcpy(new_reply, reply, header_len);
2168 memcpy(new_reply + header_len, uncompressed,
2169 new_len + fixed_len);
2179 req->resp = g_try_malloc(reply_len);
2180 #if defined TIZEN_EXT
2190 memcpy(req->resp, reply, reply_len);
2191 req->resplen = reply_len;
2193 cache_update(data, reply, reply_len);
2199 if (req->numresp < req->numserv) {
2200 if (hdr->rcode > ns_r_noerror) {
2202 } else if (hdr->ancount == 0 && req->append_domain) {
2207 request_list = g_slist_remove(request_list, req);
2209 if (protocol == IPPROTO_UDP) {
2210 sk = get_req_udp_socket(req);
2215 err = sendto(sk, req->resp, req->resplen, 0,
2216 &req->sa, req->sa_len);
2218 sk = req->client_sk;
2219 err = send(sk, req->resp, req->resplen, MSG_NOSIGNAL);
2223 debug("Cannot send msg, sk %d proto %d errno %d/%s", sk,
2224 protocol, errno, strerror(errno));
2226 debug("proto %d sent %d bytes to %d", protocol, err, sk);
2228 destroy_request_data(req);
2233 static void server_destroy_socket(struct server_data *data)
2235 debug("index %d server %s proto %d", data->index,
2236 data->server, data->protocol);
2238 if (data->watch > 0) {
2239 g_source_remove(data->watch);
2243 if (data->timeout > 0) {
2244 g_source_remove(data->timeout);
2248 if (data->channel) {
2249 g_io_channel_shutdown(data->channel, TRUE, NULL);
2250 g_io_channel_unref(data->channel);
2251 data->channel = NULL;
2254 g_free(data->incoming_reply);
2255 data->incoming_reply = NULL;
2258 static void destroy_server(struct server_data *server)
2260 debug("index %d server %s sock %d", server->index, server->server,
2262 g_io_channel_unix_get_fd(server->channel): -1);
2264 server_list = g_slist_remove(server_list, server);
2265 server_destroy_socket(server);
2267 if (server->protocol == IPPROTO_UDP && server->enabled)
2268 debug("Removing DNS server %s", server->server);
2270 g_free(server->server);
2271 g_list_free_full(server->domains, g_free);
2272 g_free(server->server_addr);
2275 * We do not remove cache right away but delay it few seconds.
2276 * The idea is that when IPv6 DNS server is added via RDNSS, it has a
2277 * lifetime. When the lifetime expires we decrease the refcount so it
2278 * is possible that the cache is then removed. Because a new DNS server
2279 * is usually created almost immediately we would then loose the cache
2280 * without any good reason. The small delay allows the new RDNSS to
2281 * create a new DNS server instance and the refcount does not go to 0.
2283 if (cache && !cache_timer)
2284 cache_timer = g_timeout_add_seconds(3, try_remove_cache, NULL);
2289 static gboolean udp_server_event(GIOChannel *channel, GIOCondition condition,
2292 unsigned char buf[4096];
2294 struct server_data *data = user_data;
2296 if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
2297 connman_error("Error with UDP server %s", data->server);
2298 server_destroy_socket(data);
2302 sk = g_io_channel_unix_get_fd(channel);
2304 len = recv(sk, buf, sizeof(buf), 0);
2307 forward_dns_reply(buf, len, IPPROTO_UDP, data);
2309 #if defined TIZEN_EXT
2312 for (list = server_list_sec; list; list = list->next) {
2313 struct server_data *new_data = list->data;
2315 if (new_data == data) {
2316 destroy_server_sec(data);
2325 static gboolean tcp_server_event(GIOChannel *channel, GIOCondition condition,
2329 struct server_data *server = user_data;
2331 sk = g_io_channel_unix_get_fd(channel);
2335 if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
2338 debug("TCP server channel closed, sk %d", sk);
2341 * Discard any partial response which is buffered; better
2342 * to get a proper response from a working server.
2344 g_free(server->incoming_reply);
2345 server->incoming_reply = NULL;
2347 list = request_list;
2349 struct request_data *req = list->data;
2350 struct domain_hdr *hdr;
2353 if (req->protocol == IPPROTO_UDP)
2360 * If we're not waiting for any further response
2361 * from another name server, then we send an error
2362 * response to the client.
2364 if (req->numserv && --(req->numserv))
2367 hdr = (void *) (req->request + 2);
2368 hdr->id = req->srcid;
2369 send_response(req->client_sk, req->request,
2370 req->request_len, NULL, 0, IPPROTO_TCP);
2372 request_list = g_slist_remove(request_list, req);
2375 destroy_server(server);
2380 if ((condition & G_IO_OUT) && !server->connected) {
2383 bool no_request_sent = true;
2384 struct server_data *udp_server;
2386 udp_server = find_server(server->index, server->server,
2389 for (domains = udp_server->domains; domains;
2390 domains = domains->next) {
2391 char *dom = domains->data;
2393 debug("Adding domain %s to %s",
2394 dom, server->server);
2396 server->domains = g_list_append(server->domains,
2401 server->connected = true;
2402 server_list = g_slist_append(server_list, server);
2404 if (server->timeout > 0) {
2405 g_source_remove(server->timeout);
2406 server->timeout = 0;
2409 for (list = request_list; list; ) {
2410 struct request_data *req = list->data;
2413 if (req->protocol == IPPROTO_UDP) {
2418 debug("Sending req %s over TCP", (char *)req->name);
2420 status = ns_resolv(server, req,
2421 req->request, req->name);
2424 * A cached result was sent,
2425 * so the request can be released
2428 request_list = g_slist_remove(request_list, req);
2429 destroy_request_data(req);
2438 no_request_sent = false;
2440 if (req->timeout > 0)
2441 g_source_remove(req->timeout);
2443 req->timeout = g_timeout_add_seconds(30,
2444 request_timeout, req);
2448 if (no_request_sent) {
2449 destroy_server(server);
2453 } else if (condition & G_IO_IN) {
2454 struct partial_reply *reply = server->incoming_reply;
2458 unsigned char reply_len_buf[2];
2461 bytes_recv = recv(sk, reply_len_buf, 2, MSG_PEEK);
2464 } else if (bytes_recv < 0) {
2465 if (errno == EAGAIN || errno == EWOULDBLOCK)
2468 connman_error("DNS proxy error %s",
2471 } else if (bytes_recv < 2)
2474 reply_len = reply_len_buf[1] | reply_len_buf[0] << 8;
2477 debug("TCP reply %d bytes from %d", reply_len, sk);
2479 reply = g_try_malloc(sizeof(*reply) + reply_len + 2);
2483 reply->len = reply_len;
2484 reply->received = 0;
2486 server->incoming_reply = reply;
2489 while (reply->received < reply->len) {
2490 bytes_recv = recv(sk, reply->buf + reply->received,
2491 reply->len - reply->received, 0);
2493 connman_error("DNS proxy TCP disconnect");
2495 } else if (bytes_recv < 0) {
2496 if (errno == EAGAIN || errno == EWOULDBLOCK)
2499 connman_error("DNS proxy error %s",
2503 reply->received += bytes_recv;
2506 forward_dns_reply(reply->buf, reply->received, IPPROTO_TCP,
2510 server->incoming_reply = NULL;
2512 destroy_server(server);
2520 static gboolean tcp_idle_timeout(gpointer user_data)
2522 struct server_data *server = user_data;
2529 destroy_server(server);
2534 static int server_create_socket(struct server_data *data)
2539 debug("index %d server %s proto %d", data->index,
2540 data->server, data->protocol);
2542 sk = socket(data->server_addr->sa_family,
2543 data->protocol == IPPROTO_TCP ? SOCK_STREAM : SOCK_DGRAM,
2547 connman_error("Failed to create server %s socket",
2549 server_destroy_socket(data);
2555 interface = connman_inet_ifname(data->index);
2557 if (setsockopt(sk, SOL_SOCKET, SO_BINDTODEVICE,
2559 strlen(interface) + 1) < 0) {
2561 connman_error("Failed to bind server %s "
2563 data->server, interface);
2565 server_destroy_socket(data);
2572 data->channel = g_io_channel_unix_new(sk);
2573 if (!data->channel) {
2574 connman_error("Failed to create server %s channel",
2577 server_destroy_socket(data);
2581 g_io_channel_set_close_on_unref(data->channel, TRUE);
2583 if (data->protocol == IPPROTO_TCP) {
2584 g_io_channel_set_flags(data->channel, G_IO_FLAG_NONBLOCK, NULL);
2585 data->watch = g_io_add_watch(data->channel,
2586 G_IO_OUT | G_IO_IN | G_IO_HUP | G_IO_NVAL | G_IO_ERR,
2587 tcp_server_event, data);
2588 data->timeout = g_timeout_add_seconds(30, tcp_idle_timeout,
2591 data->watch = g_io_add_watch(data->channel,
2592 G_IO_IN | G_IO_NVAL | G_IO_ERR | G_IO_HUP,
2593 udp_server_event, data);
2595 if (connect(sk, data->server_addr, data->server_addr_len) < 0) {
2598 if ((data->protocol == IPPROTO_TCP && errno != EINPROGRESS) ||
2599 data->protocol == IPPROTO_UDP) {
2601 connman_error("Failed to connect to server %s",
2603 server_destroy_socket(data);
2613 static void enable_fallback(bool enable)
2617 for (list = server_list; list; list = list->next) {
2618 struct server_data *data = list->data;
2620 if (data->index != -1)
2624 DBG("Enabling fallback DNS server %s", data->server);
2626 DBG("Disabling fallback DNS server %s", data->server);
2628 data->enabled = enable;
2632 #if defined TIZEN_EXT
2634 static void destroy_server_sec(struct server_data *server)
2639 if (server->channel)
2640 fd = g_io_channel_unix_get_fd(server->channel);
2644 DBG("index %d server %s sock %d", server->index, server->server, fd);
2646 server_list_sec = g_slist_remove(server_list_sec, server);
2651 server_destroy_socket(server);
2653 if (server->protocol == IPPROTO_UDP && server->enabled)
2654 DBG("Removing DNS server %s", server->server);
2656 g_free(server->server);
2657 for (list = server->domains; list; list = list->next) {
2658 char *domain = list->data;
2660 server->domains = g_list_remove(server->domains, domain);
2663 g_free(server->server_addr);
2666 * We do not remove cache right away but delay it few seconds.
2667 * The idea is that when IPv6 DNS server is added via RDNSS, it has a
2668 * lifetime. When the lifetime expires we decrease the refcount so it
2669 * is possible that the cache is then removed. Because a new DNS server
2670 * is usually created almost immediately we would then loose the cache
2671 * without any good reason. The small delay allows the new RDNSS to
2672 * create a new DNS server instance and the refcount does not go to 0.
2674 /* TODO: Need to check this */
2675 /* g_timeout_add_seconds(3, try_remove_cache, NULL); */
2680 static void destroy_all_server_sec()
2684 DBG("remove all dns server");
2686 for (list = server_list_sec; list; list = list->next) {
2687 struct server_data *server = list->data;
2688 destroy_server_sec(server);
2690 server_list_sec = NULL;
2693 static gboolean sec_udp_idle_timeout(gpointer user_data)
2695 struct server_data *server = user_data;
2702 destroy_server_sec(server);
2707 static struct server_data *create_server_sec(int index,
2708 const char *domain, const char *server,
2711 struct server_data *data;
2712 struct addrinfo hints, *rp;
2715 DBG("index %d server %s", index, server);
2717 data = g_try_new0(struct server_data, 1);
2719 connman_error("Failed to allocate server %s data", server);
2723 data->index = index;
2725 data->domains = g_list_append(data->domains, g_strdup(domain));
2726 data->server = g_strdup(server);
2727 data->protocol = protocol;
2729 memset(&hints, 0, sizeof(hints));
2733 hints.ai_socktype = SOCK_DGRAM;
2737 hints.ai_socktype = SOCK_STREAM;
2741 destroy_server_sec(data);
2744 hints.ai_family = AF_UNSPEC;
2745 hints.ai_flags = AI_NUMERICSERV | AI_NUMERICHOST;
2747 ret = getaddrinfo(data->server, "53", &hints, &rp);
2749 connman_error("Failed to parse server %s address: %s\n",
2750 data->server, gai_strerror(ret));
2752 destroy_server_sec(data);
2756 /* Do not blindly copy this code elsewhere; it doesn't loop over the
2757 results using ->ai_next as it should. That's OK in *this* case
2758 because it was a numeric lookup; we *know* there's only one. */
2760 data->server_addr_len = rp->ai_addrlen;
2762 switch (rp->ai_family) {
2764 data->server_addr = (struct sockaddr *)
2765 g_try_new0(struct sockaddr_in, 1);
2768 data->server_addr = (struct sockaddr *)
2769 g_try_new0(struct sockaddr_in6, 1);
2772 connman_error("Wrong address family %d", rp->ai_family);
2775 if (data->server_addr == NULL) {
2777 destroy_server_sec(data);
2780 memcpy(data->server_addr, rp->ai_addr, rp->ai_addrlen);
2783 if (server_create_socket(data) != 0) {
2784 destroy_server_sec(data);
2788 if (protocol == IPPROTO_UDP) {
2789 /* Enable new servers by default */
2790 data->enabled = TRUE;
2791 DBG("Adding DNS server %s", data->server);
2793 data->timeout = g_timeout_add_seconds(30, sec_udp_idle_timeout,
2796 server_list_sec = g_slist_append(server_list_sec, data);
2803 static struct server_data *create_server(int index,
2804 const char *domain, const char *server,
2807 struct server_data *data;
2808 struct addrinfo hints, *rp;
2811 DBG("index %d server %s", index, server);
2813 data = g_try_new0(struct server_data, 1);
2815 connman_error("Failed to allocate server %s data", server);
2819 data->index = index;
2821 data->domains = g_list_append(data->domains, g_strdup(domain));
2822 data->server = g_strdup(server);
2823 data->protocol = protocol;
2825 memset(&hints, 0, sizeof(hints));
2829 hints.ai_socktype = SOCK_DGRAM;
2833 hints.ai_socktype = SOCK_STREAM;
2837 destroy_server(data);
2840 hints.ai_family = AF_UNSPEC;
2841 hints.ai_flags = AI_NUMERICSERV | AI_NUMERICHOST;
2843 ret = getaddrinfo(data->server, "53", &hints, &rp);
2845 connman_error("Failed to parse server %s address: %s\n",
2846 data->server, gai_strerror(ret));
2847 destroy_server(data);
2851 /* Do not blindly copy this code elsewhere; it doesn't loop over the
2852 results using ->ai_next as it should. That's OK in *this* case
2853 because it was a numeric lookup; we *know* there's only one. */
2855 data->server_addr_len = rp->ai_addrlen;
2857 switch (rp->ai_family) {
2859 data->server_addr = (struct sockaddr *)
2860 g_try_new0(struct sockaddr_in, 1);
2863 data->server_addr = (struct sockaddr *)
2864 g_try_new0(struct sockaddr_in6, 1);
2867 connman_error("Wrong address family %d", rp->ai_family);
2870 if (!data->server_addr) {
2872 destroy_server(data);
2875 memcpy(data->server_addr, rp->ai_addr, rp->ai_addrlen);
2878 if (server_create_socket(data) != 0) {
2879 destroy_server(data);
2883 if (protocol == IPPROTO_UDP) {
2884 if (__connman_service_index_is_default(data->index) ||
2885 __connman_service_index_is_split_routing(
2887 data->enabled = true;
2888 DBG("Adding DNS server %s", data->server);
2890 enable_fallback(false);
2893 server_list = g_slist_append(server_list, data);
2899 static bool resolv(struct request_data *req,
2900 gpointer request, gpointer name)
2904 for (list = server_list; list; list = list->next) {
2905 struct server_data *data = list->data;
2907 if (data->protocol == IPPROTO_TCP) {
2908 DBG("server %s ignored proto TCP", data->server);
2912 debug("server %s enabled %d", data->server, data->enabled);
2917 if (!data->channel && data->protocol == IPPROTO_UDP) {
2918 if (server_create_socket(data) < 0) {
2919 DBG("socket creation failed while resolving");
2924 if (ns_resolv(data, req, request, name) > 0)
2931 static void update_domain(int index, const char *domain, bool append)
2935 DBG("index %d domain %s", index, domain);
2940 for (list = server_list; list; list = list->next) {
2941 struct server_data *data = list->data;
2944 bool dom_found = false;
2946 if (data->index < 0)
2949 if (data->index != index)
2952 for (dom_list = data->domains; dom_list;
2953 dom_list = dom_list->next) {
2954 dom = dom_list->data;
2956 if (g_str_equal(dom, domain)) {
2962 if (!dom_found && append) {
2964 g_list_append(data->domains, g_strdup(domain));
2965 } else if (dom_found && !append) {
2967 g_list_remove(data->domains, dom);
2973 static void append_domain(int index, const char *domain)
2975 update_domain(index, domain, true);
2978 static void remove_domain(int index, const char *domain)
2980 update_domain(index, domain, false);
2983 static void flush_requests(struct server_data *server)
2987 list = request_list;
2989 struct request_data *req = list->data;
2993 if (ns_resolv(server, req, req->request, req->name)) {
2995 * A cached result was sent,
2996 * so the request can be released
2999 g_slist_remove(request_list, req);
3000 destroy_request_data(req);
3004 if (req->timeout > 0)
3005 g_source_remove(req->timeout);
3007 req->timeout = g_timeout_add_seconds(5, request_timeout, req);
3011 int __connman_dnsproxy_append(int index, const char *domain,
3014 struct server_data *data;
3016 DBG("index %d server %s", index, server);
3018 if (!server && !domain)
3022 append_domain(index, domain);
3027 if (g_str_equal(server, "127.0.0.1"))
3030 if (g_str_equal(server, "::1"))
3033 data = find_server(index, server, IPPROTO_UDP);
3035 append_domain(index, domain);
3039 data = create_server(index, domain, server, IPPROTO_UDP);
3043 flush_requests(data);
3048 static void remove_server(int index, const char *domain,
3049 const char *server, int protocol)
3051 struct server_data *data;
3054 data = find_server(index, server, protocol);
3058 destroy_server(data);
3060 for (list = server_list; list; list = list->next) {
3061 struct server_data *data = list->data;
3063 if (data->index != -1 && data->enabled == true)
3067 enable_fallback(true);
3070 int __connman_dnsproxy_remove(int index, const char *domain,
3073 DBG("index %d server %s", index, server);
3075 if (!server && !domain)
3079 remove_domain(index, domain);
3084 if (g_str_equal(server, "127.0.0.1"))
3087 if (g_str_equal(server, "::1"))
3090 remove_server(index, domain, server, IPPROTO_UDP);
3091 remove_server(index, domain, server, IPPROTO_TCP);
3093 #if defined TIZEN_EXT
3094 destroy_all_server_sec();
3100 static void dnsproxy_offline_mode(bool enabled)
3104 DBG("enabled %d", enabled);
3106 for (list = server_list; list; list = list->next) {
3107 struct server_data *data = list->data;
3110 DBG("Enabling DNS server %s", data->server);
3111 data->enabled = true;
3115 DBG("Disabling DNS server %s", data->server);
3116 data->enabled = false;
3122 static void dnsproxy_default_changed(struct connman_service *service)
3124 bool server_enabled = false;
3128 DBG("service %p", service);
3130 /* DNS has changed, invalidate the cache */
3134 /* When no services are active, then disable DNS proxying */
3135 dnsproxy_offline_mode(true);
3139 index = __connman_service_get_index(service);
3143 for (list = server_list; list; list = list->next) {
3144 struct server_data *data = list->data;
3146 if (data->index == index) {
3147 DBG("Enabling DNS server %s", data->server);
3148 data->enabled = true;
3149 server_enabled = true;
3151 DBG("Disabling DNS server %s", data->server);
3152 data->enabled = false;
3156 if (!server_enabled)
3157 enable_fallback(true);
3162 static const struct connman_notifier dnsproxy_notifier = {
3164 .default_changed = dnsproxy_default_changed,
3165 .offline_mode = dnsproxy_offline_mode,
3168 static const unsigned char opt_edns0_type[2] = { 0x00, 0x29 };
3170 static int parse_request(unsigned char *buf, size_t len,
3171 char *name, unsigned int size)
3173 struct domain_hdr *hdr = (void *) buf;
3174 uint16_t qdcount = ntohs(hdr->qdcount);
3175 uint16_t ancount = ntohs(hdr->ancount);
3176 uint16_t nscount = ntohs(hdr->nscount);
3177 uint16_t arcount = ntohs(hdr->arcount);
3179 unsigned int remain, used = 0;
3181 if (len < sizeof(*hdr) + sizeof(struct qtype_qclass) ||
3182 hdr->qr || qdcount != 1 || ancount || nscount) {
3183 DBG("Dropped DNS request qr %d with len %zd qdcount %d "
3184 "ancount %d nscount %d", hdr->qr, len, qdcount, ancount,
3193 debug("id 0x%04x qr %d opcode %d qdcount %d arcount %d",
3194 hdr->id, hdr->qr, hdr->opcode,
3199 ptr = buf + sizeof(struct domain_hdr);
3200 remain = len - sizeof(struct domain_hdr);
3202 while (remain > 0) {
3203 uint8_t label_len = *ptr;
3205 if (label_len == 0x00) {
3207 struct qtype_qclass *q =
3208 (struct qtype_qclass *)(ptr + 1);
3210 if (remain < sizeof(*q)) {
3211 DBG("Dropped malformed DNS query");
3215 class = ntohs(q->qclass);
3216 if (class != 1 && class != 255) {
3217 DBG("Dropped non-IN DNS class %d", class);
3221 ptr += sizeof(*q) + 1;
3222 remain -= (sizeof(*q) + 1);
3226 if (used + label_len + 1 > size)
3229 strncat(name, (char *) (ptr + 1), label_len);
3232 used += label_len + 1;
3234 ptr += label_len + 1;
3235 remain -= label_len + 1;
3238 if (arcount && remain >= sizeof(struct domain_rr) + 1 && !ptr[0] &&
3239 ptr[1] == opt_edns0_type[0] && ptr[2] == opt_edns0_type[1]) {
3240 struct domain_rr *edns0 = (struct domain_rr *)(ptr + 1);
3242 DBG("EDNS0 buffer size %u", ntohs(edns0->class));
3243 } else if (!arcount && remain) {
3244 DBG("DNS request with %d garbage bytes", remain);
3247 debug("query %s", name);
3252 static void client_reset(struct tcp_partial_client_data *client)
3257 if (client->channel) {
3258 debug("client %d closing",
3259 g_io_channel_unix_get_fd(client->channel));
3261 g_io_channel_unref(client->channel);
3262 client->channel = NULL;
3265 if (client->watch > 0) {
3266 g_source_remove(client->watch);
3270 if (client->timeout > 0) {
3271 g_source_remove(client->timeout);
3272 client->timeout = 0;
3275 g_free(client->buf);
3278 client->buf_end = 0;
3281 static unsigned int get_msg_len(unsigned char *buf)
3283 return buf[0]<<8 | buf[1];
3286 static bool read_tcp_data(struct tcp_partial_client_data *client,
3287 void *client_addr, socklen_t client_addr_len,
3290 char query[TCP_MAX_BUF_LEN];
3291 struct request_data *req;
3293 unsigned int msg_len;
3295 bool waiting_for_connect = false;
3297 struct cache_entry *entry;
3299 client_sk = g_io_channel_unix_get_fd(client->channel);
3301 if (read_len == 0) {
3302 debug("client %d closed, pending %d bytes",
3303 client_sk, client->buf_end);
3304 g_hash_table_remove(partial_tcp_req_table,
3305 GINT_TO_POINTER(client_sk));
3309 debug("client %d received %d bytes", client_sk, read_len);
3311 client->buf_end += read_len;
3313 if (client->buf_end < 2)
3316 msg_len = get_msg_len(client->buf);
3317 if (msg_len > TCP_MAX_BUF_LEN) {
3318 debug("client %d sent too much data %d", client_sk, msg_len);
3319 g_hash_table_remove(partial_tcp_req_table,
3320 GINT_TO_POINTER(client_sk));
3325 debug("client %d msg len %d end %d past end %d", client_sk, msg_len,
3326 client->buf_end, client->buf_end - (msg_len + 2));
3328 if (client->buf_end < (msg_len + 2)) {
3329 debug("client %d still missing %d bytes",
3331 msg_len + 2 - client->buf_end);
3335 debug("client %d all data %d received", client_sk, msg_len);
3337 err = parse_request(client->buf + 2, msg_len,
3338 query, sizeof(query));
3339 if (err < 0 || (g_slist_length(server_list) == 0)) {
3340 send_response(client_sk, client->buf, msg_len + 2,
3341 NULL, 0, IPPROTO_TCP);
3345 req = g_try_new0(struct request_data, 1);
3349 memcpy(&req->sa, client_addr, client_addr_len);
3350 req->sa_len = client_addr_len;
3351 req->client_sk = client_sk;
3352 req->protocol = IPPROTO_TCP;
3353 req->family = client->family;
3355 req->srcid = client->buf[2] | (client->buf[3] << 8);
3356 req->dstid = get_id();
3357 req->altid = get_id();
3358 req->request_len = msg_len + 2;
3360 client->buf[2] = req->dstid & 0xff;
3361 client->buf[3] = req->dstid >> 8;
3364 req->ifdata = client->ifdata;
3365 req->append_domain = false;
3368 * Check if the answer is found in the cache before
3369 * creating sockets to the server.
3371 entry = cache_check(client->buf, &qtype, IPPROTO_TCP);
3374 struct cache_data *data;
3376 debug("cache hit %s type %s", query, qtype == 1 ? "A" : "AAAA");
3383 ttl_left = data->valid_until - time(NULL);
3386 send_cached_response(client_sk, data->data,
3387 data->data_len, NULL, 0, IPPROTO_TCP,
3388 req->srcid, data->answers, ttl_left);
3393 debug("data missing, ignoring cache for this query");
3396 for (list = server_list; list; list = list->next) {
3397 struct server_data *data = list->data;
3399 if (data->protocol != IPPROTO_UDP || !data->enabled)
3402 if (!create_server(data->index, NULL, data->server,
3406 waiting_for_connect = true;
3409 if (!waiting_for_connect) {
3410 /* No server is waiting for connect */
3411 send_response(client_sk, client->buf,
3412 req->request_len, NULL, 0, IPPROTO_TCP);
3418 * The server is not connected yet.
3419 * Copy the relevant buffers.
3420 * The request will actually be sent once we're
3421 * properly connected over TCP to the nameserver.
3423 req->request = g_try_malloc0(req->request_len);
3424 if (!req->request) {
3425 send_response(client_sk, client->buf,
3426 req->request_len, NULL, 0, IPPROTO_TCP);
3430 memcpy(req->request, client->buf, req->request_len);
3432 req->name = g_try_malloc0(sizeof(query));
3434 send_response(client_sk, client->buf,
3435 req->request_len, NULL, 0, IPPROTO_TCP);
3436 g_free(req->request);
3440 memcpy(req->name, query, sizeof(query));
3442 req->timeout = g_timeout_add_seconds(30, request_timeout, req);
3444 request_list = g_slist_append(request_list, req);
3447 if (client->buf_end > (msg_len + 2)) {
3448 debug("client %d buf %p -> %p end %d len %d new %d",
3450 client->buf + msg_len + 2,
3451 client->buf, client->buf_end,
3452 TCP_MAX_BUF_LEN - client->buf_end,
3453 client->buf_end - (msg_len + 2));
3454 memmove(client->buf, client->buf + msg_len + 2,
3455 TCP_MAX_BUF_LEN - client->buf_end);
3456 client->buf_end = client->buf_end - (msg_len + 2);
3459 * If we have a full message waiting, just read it
3462 msg_len = get_msg_len(client->buf);
3463 if ((msg_len + 2) == client->buf_end) {
3464 debug("client %d reading another %d bytes", client_sk,
3469 debug("client %d clearing reading buffer", client_sk);
3471 client->buf_end = 0;
3472 memset(client->buf, 0, TCP_MAX_BUF_LEN);
3475 * We received all the packets from client so we must also
3476 * remove the timeout handler here otherwise we might get
3477 * timeout while waiting the results from server.
3479 g_source_remove(client->timeout);
3480 client->timeout = 0;
3486 static gboolean tcp_client_event(GIOChannel *channel, GIOCondition condition,
3489 struct tcp_partial_client_data *client = user_data;
3490 struct sockaddr_in6 client_addr6;
3491 socklen_t client_addr6_len = sizeof(client_addr6);
3492 struct sockaddr_in client_addr4;
3493 socklen_t client_addr4_len = sizeof(client_addr4);
3495 socklen_t *client_addr_len;
3498 client_sk = g_io_channel_unix_get_fd(channel);
3500 if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
3501 g_hash_table_remove(partial_tcp_req_table,
3502 GINT_TO_POINTER(client_sk));
3504 connman_error("Error with TCP client %d channel", client_sk);
3508 switch (client->family) {
3510 client_addr = &client_addr4;
3511 client_addr_len = &client_addr4_len;
3514 client_addr = &client_addr6;
3515 client_addr_len = &client_addr6_len;
3518 g_hash_table_remove(partial_tcp_req_table,
3519 GINT_TO_POINTER(client_sk));
3520 connman_error("client %p corrupted", client);
3524 len = recvfrom(client_sk, client->buf + client->buf_end,
3525 TCP_MAX_BUF_LEN - client->buf_end, 0,
3526 client_addr, client_addr_len);
3528 if (errno == EAGAIN || errno == EWOULDBLOCK)
3531 debug("client %d cannot read errno %d/%s", client_sk, -errno,
3533 g_hash_table_remove(partial_tcp_req_table,
3534 GINT_TO_POINTER(client_sk));
3538 return read_tcp_data(client, client_addr, *client_addr_len, len);
3541 static gboolean client_timeout(gpointer user_data)
3543 struct tcp_partial_client_data *client = user_data;
3546 sock = g_io_channel_unix_get_fd(client->channel);
3548 debug("client %d timeout pending %d bytes", sock, client->buf_end);
3550 g_hash_table_remove(partial_tcp_req_table, GINT_TO_POINTER(sock));
3555 #if defined TIZEN_EXT
3556 static void recover_listener(GIOChannel *channel, struct listener_data *ifdata)
3560 index = ifdata->index;
3562 sk = g_io_channel_unix_get_fd(channel);
3565 __connman_dnsproxy_remove_listener(index);
3567 if (__connman_dnsproxy_add_listener(index) == 0)
3568 DBG("listener %d successfully recovered", index);
3572 static bool tcp_listener_event(GIOChannel *channel, GIOCondition condition,
3573 struct listener_data *ifdata, int family,
3574 guint *listener_watch)
3576 int sk, client_sk, len;
3577 unsigned int msg_len;
3578 struct tcp_partial_client_data *client;
3579 struct sockaddr_in6 client_addr6;
3580 socklen_t client_addr6_len = sizeof(client_addr6);
3581 struct sockaddr_in client_addr4;
3582 socklen_t client_addr4_len = sizeof(client_addr4);
3584 socklen_t *client_addr_len;
3588 debug("condition 0x%02x channel %p ifdata %p family %d",
3589 condition, channel, ifdata, family);
3591 if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
3592 #if defined TIZEN_EXT
3593 connman_error("Error %d with TCP listener channel", condition);
3595 recover_listener(channel, ifdata);
3597 if (*listener_watch > 0)
3598 g_source_remove(*listener_watch);
3599 *listener_watch = 0;
3601 connman_error("Error with TCP listener channel");
3607 sk = g_io_channel_unix_get_fd(channel);
3609 if (family == AF_INET) {
3610 client_addr = &client_addr4;
3611 client_addr_len = &client_addr4_len;
3613 client_addr = &client_addr6;
3614 client_addr_len = &client_addr6_len;
3617 tv.tv_sec = tv.tv_usec = 0;
3619 FD_SET(sk, &readfds);
3621 select(sk + 1, &readfds, NULL, NULL, &tv);
3622 if (FD_ISSET(sk, &readfds)) {
3623 client_sk = accept(sk, client_addr, client_addr_len);
3624 debug("client %d accepted", client_sk);
3626 debug("No data to read from master %d, waiting.", sk);
3630 if (client_sk < 0) {
3631 connman_error("Accept failure on TCP listener");
3632 *listener_watch = 0;
3636 fcntl(client_sk, F_SETFL, O_NONBLOCK);
3638 client = g_hash_table_lookup(partial_tcp_req_table,
3639 GINT_TO_POINTER(client_sk));
3641 client = g_try_new0(struct tcp_partial_client_data, 1);
3647 g_hash_table_insert(partial_tcp_req_table,
3648 GINT_TO_POINTER(client_sk),
3651 client->channel = g_io_channel_unix_new(client_sk);
3652 g_io_channel_set_close_on_unref(client->channel, TRUE);
3654 client->watch = g_io_add_watch(client->channel,
3655 G_IO_IN, tcp_client_event,
3658 client->ifdata = ifdata;
3660 debug("client %d created %p", client_sk, client);
3662 debug("client %d already exists %p", client_sk, client);
3666 client->buf = g_try_malloc(TCP_MAX_BUF_LEN);
3670 memset(client->buf, 0, TCP_MAX_BUF_LEN);
3671 client->buf_end = 0;
3672 client->family = family;
3674 if (client->timeout == 0)
3675 client->timeout = g_timeout_add_seconds(2, client_timeout,
3679 * Check how much data there is. If all is there, then we can
3680 * proceed normally, otherwise read the bits until everything
3681 * is received or timeout occurs.
3683 len = recv(client_sk, client->buf, TCP_MAX_BUF_LEN, 0);
3685 if (errno == EAGAIN || errno == EWOULDBLOCK) {
3686 debug("client %d no data to read, waiting", client_sk);
3690 debug("client %d cannot read errno %d/%s", client_sk, -errno,
3692 g_hash_table_remove(partial_tcp_req_table,
3693 GINT_TO_POINTER(client_sk));
3698 debug("client %d not enough data to read, waiting", client_sk);
3699 client->buf_end += len;
3703 msg_len = get_msg_len(client->buf);
3704 if (msg_len > TCP_MAX_BUF_LEN) {
3705 debug("client %d invalid message length %u ignoring packet",
3706 client_sk, msg_len);
3707 g_hash_table_remove(partial_tcp_req_table,
3708 GINT_TO_POINTER(client_sk));
3713 * The packet length bytes do not contain the total message length,
3714 * that is the reason to -2 below.
3716 #if defined TIZEN_EXT
3717 if (msg_len > (unsigned int)(len - 2)) {
3719 if (msg_len != (unsigned int)(len - 2)) {
3721 debug("client %d sent %d bytes but expecting %u pending %d",
3722 client_sk, len, msg_len + 2, msg_len + 2 - len);
3724 client->buf_end += len;
3728 return read_tcp_data(client, client_addr, *client_addr_len, len);
3731 static gboolean tcp4_listener_event(GIOChannel *channel, GIOCondition condition,
3734 struct listener_data *ifdata = user_data;
3736 return tcp_listener_event(channel, condition, ifdata, AF_INET,
3737 &ifdata->tcp4_listener_watch);
3740 static gboolean tcp6_listener_event(GIOChannel *channel, GIOCondition condition,
3743 struct listener_data *ifdata = user_data;
3745 return tcp_listener_event(channel, condition, user_data, AF_INET6,
3746 &ifdata->tcp6_listener_watch);
3749 static bool udp_listener_event(GIOChannel *channel, GIOCondition condition,
3750 struct listener_data *ifdata, int family,
3751 guint *listener_watch)
3753 unsigned char buf[768];
3755 struct request_data *req;
3756 struct sockaddr_in6 client_addr6;
3757 socklen_t client_addr6_len = sizeof(client_addr6);
3758 struct sockaddr_in client_addr4;
3759 socklen_t client_addr4_len = sizeof(client_addr4);
3761 socklen_t *client_addr_len;
3764 if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
3765 #if defined TIZEN_EXT
3766 connman_error("Error %d with UDP listener channel", condition);
3768 recover_listener(channel, ifdata);
3770 connman_error("Error with UDP listener channel");
3771 *listener_watch = 0;
3776 sk = g_io_channel_unix_get_fd(channel);
3778 if (family == AF_INET) {
3779 client_addr = &client_addr4;
3780 client_addr_len = &client_addr4_len;
3782 client_addr = &client_addr6;
3783 client_addr_len = &client_addr6_len;
3786 memset(client_addr, 0, *client_addr_len);
3787 len = recvfrom(sk, buf, sizeof(buf), 0, client_addr, client_addr_len);
3791 debug("Received %d bytes (id 0x%04x)", len, buf[0] | buf[1] << 8);
3793 err = parse_request(buf, len, query, sizeof(query));
3794 if (err < 0 || (g_slist_length(server_list) == 0)) {
3795 send_response(sk, buf, len, client_addr,
3796 *client_addr_len, IPPROTO_UDP);
3800 req = g_try_new0(struct request_data, 1);
3804 memcpy(&req->sa, client_addr, *client_addr_len);
3805 req->sa_len = *client_addr_len;
3807 req->protocol = IPPROTO_UDP;
3808 req->family = family;
3810 req->srcid = buf[0] | (buf[1] << 8);
3811 req->dstid = get_id();
3812 req->altid = get_id();
3813 req->request_len = len;
3815 buf[0] = req->dstid & 0xff;
3816 buf[1] = req->dstid >> 8;
3819 req->ifdata = ifdata;
3820 req->append_domain = false;
3822 if (resolv(req, buf, query)) {
3823 /* a cached result was sent, so the request can be released */
3828 req->name = g_strdup(query);
3829 req->request = g_malloc(len);
3830 memcpy(req->request, buf, len);
3831 #if defined TIZEN_EXT
3832 DBG("req %p dstid 0x%04x altid 0x%04x", req, req->dstid, req->altid);
3833 req->timeout = g_timeout_add_seconds(30, request_timeout, req);
3835 req->timeout = g_timeout_add_seconds(5, request_timeout, req);
3837 request_list = g_slist_append(request_list, req);
3842 static gboolean udp4_listener_event(GIOChannel *channel, GIOCondition condition,
3845 struct listener_data *ifdata = user_data;
3847 return udp_listener_event(channel, condition, ifdata, AF_INET,
3848 &ifdata->udp4_listener_watch);
3851 static gboolean udp6_listener_event(GIOChannel *channel, GIOCondition condition,
3854 struct listener_data *ifdata = user_data;
3856 return udp_listener_event(channel, condition, user_data, AF_INET6,
3857 &ifdata->udp6_listener_watch);
3860 static GIOChannel *get_listener(int family, int protocol, int index)
3862 GIOChannel *channel;
3864 #if !defined TIZEN_EXT
3867 struct sockaddr_in6 sin6;
3868 struct sockaddr_in sin;
3873 #if !defined TIZEN_EXT
3876 #if defined TIZEN_EXT
3880 int is_socket_inet = 0;
3883 debug("family %d protocol %d index %d", family, protocol, index);
3888 type = SOCK_DGRAM | SOCK_CLOEXEC;
3893 type = SOCK_STREAM | SOCK_CLOEXEC;
3899 #if defined TIZEN_EXT
3900 sd_num = sd_listen_fds(0);
3901 DBG("socket type(%s) systemd number of fds(%d)", proto, sd_num);
3903 DBG("fail to get the fd from systemd");
3907 if(protocol == IPPROTO_TCP)
3912 for(sk = SD_LISTEN_FDS_START; sk < SD_LISTEN_FDS_START+sd_num; ++sk){
3913 rv = sd_is_socket_inet(sk, family, type, -1, 53);
3915 DBG("socket fd (%d) is passed by systemd", sk);
3921 if (!is_socket_inet) {
3922 DBG("socket fd is not matched what connman requests");
3926 sk = socket(family, type, protocol);
3927 if (sk < 0 && family == AF_INET6 && errno == EAFNOSUPPORT) {
3928 connman_error("No IPv6 support");
3933 connman_error("Failed to create %s listener socket", proto);
3937 interface = connman_inet_ifname(index);
3938 if (!interface || setsockopt(sk, SOL_SOCKET, SO_BINDTODEVICE,
3940 strlen(interface) + 1) < 0) {
3941 connman_error("Failed to bind %s listener interface "
3943 proto, family == AF_INET ? "IPv4" : "IPv6",
3944 -errno, strerror(errno));
3951 if (family == AF_INET6) {
3952 memset(&s.sin6, 0, sizeof(s.sin6));
3953 s.sin6.sin6_family = AF_INET6;
3954 s.sin6.sin6_port = htons(53);
3955 slen = sizeof(s.sin6);
3957 if (__connman_inet_get_interface_address(index,
3959 &s.sin6.sin6_addr) < 0) {
3960 /* So we could not find suitable IPv6 address for
3961 * the interface. This could happen if we have
3962 * disabled IPv6 for the interface.
3968 } else if (family == AF_INET) {
3969 memset(&s.sin, 0, sizeof(s.sin));
3970 s.sin.sin_family = AF_INET;
3971 s.sin.sin_port = htons(53);
3972 slen = sizeof(s.sin);
3974 if (__connman_inet_get_interface_address(index,
3976 &s.sin.sin_addr) < 0) {
3986 #if defined TIZEN_EXT
3987 /* When ConnMan crashed,
3988 * probably DNS listener cannot bind existing address */
3990 if (setsockopt(sk, SOL_SOCKET, SO_REUSEADDR, &option, sizeof(option)) < 0) {
3991 connman_error("Failed to set socket option SO_REUSEADDR");
3996 #if !defined TIZEN_EXT
3997 if (bind(sk, &s.sa, slen) < 0) {
3998 connman_error("Failed to bind %s listener socket", proto);
4004 if (protocol == IPPROTO_TCP) {
4006 #if !defined TIZEN_EXT
4007 if (listen(sk, 10) < 0) {
4008 connman_error("Failed to listen on TCP socket %d/%s",
4009 -errno, strerror(errno));
4015 fcntl(sk, F_SETFL, O_NONBLOCK);
4018 channel = g_io_channel_unix_new(sk);
4020 connman_error("Failed to create %s listener channel", proto);
4025 g_io_channel_set_close_on_unref(channel, TRUE);
4030 #define UDP_IPv4_FAILED 0x01
4031 #define TCP_IPv4_FAILED 0x02
4032 #define UDP_IPv6_FAILED 0x04
4033 #define TCP_IPv6_FAILED 0x08
4034 #define UDP_FAILED (UDP_IPv4_FAILED | UDP_IPv6_FAILED)
4035 #define TCP_FAILED (TCP_IPv4_FAILED | TCP_IPv6_FAILED)
4036 #define IPv6_FAILED (UDP_IPv6_FAILED | TCP_IPv6_FAILED)
4037 #define IPv4_FAILED (UDP_IPv4_FAILED | TCP_IPv4_FAILED)
4039 static int create_dns_listener(int protocol, struct listener_data *ifdata)
4043 if (protocol == IPPROTO_TCP) {
4044 ifdata->tcp4_listener_channel = get_listener(AF_INET, protocol,
4046 if (ifdata->tcp4_listener_channel)
4047 #if defined TIZEN_EXT
4048 ifdata->tcp4_listener_watch =
4049 g_io_add_watch(ifdata->tcp4_listener_channel,
4050 G_IO_IN | G_IO_ERR | G_IO_HUP | G_IO_NVAL,
4051 tcp4_listener_event, (gpointer)ifdata);
4053 ifdata->tcp4_listener_watch =
4054 g_io_add_watch(ifdata->tcp4_listener_channel,
4055 G_IO_IN, tcp4_listener_event,
4059 ret |= TCP_IPv4_FAILED;
4061 ifdata->tcp6_listener_channel = get_listener(AF_INET6, protocol,
4063 if (ifdata->tcp6_listener_channel)
4064 #if defined TIZEN_EXT
4065 ifdata->tcp6_listener_watch =
4066 g_io_add_watch(ifdata->tcp6_listener_channel,
4067 G_IO_IN | G_IO_ERR | G_IO_HUP | G_IO_NVAL,
4068 tcp6_listener_event, (gpointer)ifdata);
4070 ifdata->tcp6_listener_watch =
4071 g_io_add_watch(ifdata->tcp6_listener_channel,
4072 G_IO_IN, tcp6_listener_event,
4076 ret |= TCP_IPv6_FAILED;
4078 ifdata->udp4_listener_channel = get_listener(AF_INET, protocol,
4080 if (ifdata->udp4_listener_channel)
4081 #if defined TIZEN_EXT
4082 ifdata->udp4_listener_watch =
4083 g_io_add_watch(ifdata->udp4_listener_channel,
4084 G_IO_IN | G_IO_ERR | G_IO_HUP | G_IO_NVAL,
4085 udp4_listener_event, (gpointer)ifdata);
4087 ifdata->udp4_listener_watch =
4088 g_io_add_watch(ifdata->udp4_listener_channel,
4089 G_IO_IN, udp4_listener_event,
4093 ret |= UDP_IPv4_FAILED;
4095 ifdata->udp6_listener_channel = get_listener(AF_INET6, protocol,
4097 if (ifdata->udp6_listener_channel)
4098 #if defined TIZEN_EXT
4099 ifdata->udp6_listener_watch =
4100 g_io_add_watch(ifdata->udp6_listener_channel,
4101 G_IO_IN | G_IO_ERR | G_IO_HUP | G_IO_NVAL,
4102 udp6_listener_event, (gpointer)ifdata);
4104 ifdata->udp6_listener_watch =
4105 g_io_add_watch(ifdata->udp6_listener_channel,
4106 G_IO_IN, udp6_listener_event,
4110 ret |= UDP_IPv6_FAILED;
4116 static void destroy_udp_listener(struct listener_data *ifdata)
4118 DBG("index %d", ifdata->index);
4120 if (ifdata->udp4_listener_watch > 0)
4121 g_source_remove(ifdata->udp4_listener_watch);
4123 if (ifdata->udp6_listener_watch > 0)
4124 g_source_remove(ifdata->udp6_listener_watch);
4126 if (ifdata->udp4_listener_channel)
4127 g_io_channel_unref(ifdata->udp4_listener_channel);
4128 if (ifdata->udp6_listener_channel)
4129 g_io_channel_unref(ifdata->udp6_listener_channel);
4132 static void destroy_tcp_listener(struct listener_data *ifdata)
4134 DBG("index %d", ifdata->index);
4136 if (ifdata->tcp4_listener_watch > 0)
4137 g_source_remove(ifdata->tcp4_listener_watch);
4138 if (ifdata->tcp6_listener_watch > 0)
4139 g_source_remove(ifdata->tcp6_listener_watch);
4141 if (ifdata->tcp4_listener_channel)
4142 g_io_channel_unref(ifdata->tcp4_listener_channel);
4143 if (ifdata->tcp6_listener_channel)
4144 g_io_channel_unref(ifdata->tcp6_listener_channel);
4147 static int create_listener(struct listener_data *ifdata)
4151 err = create_dns_listener(IPPROTO_UDP, ifdata);
4152 if ((err & UDP_FAILED) == UDP_FAILED)
4155 err |= create_dns_listener(IPPROTO_TCP, ifdata);
4156 if ((err & TCP_FAILED) == TCP_FAILED) {
4157 destroy_udp_listener(ifdata);
4161 index = connman_inet_ifindex("lo");
4162 if (ifdata->index == index) {
4163 if ((err & IPv6_FAILED) != IPv6_FAILED)
4164 __connman_resolvfile_append(index, NULL, "::1");
4166 if ((err & IPv4_FAILED) != IPv4_FAILED)
4167 __connman_resolvfile_append(index, NULL, "127.0.0.1");
4173 static void destroy_listener(struct listener_data *ifdata)
4178 index = connman_inet_ifindex("lo");
4179 if (ifdata->index == index) {
4180 __connman_resolvfile_remove(index, NULL, "127.0.0.1");
4181 __connman_resolvfile_remove(index, NULL, "::1");
4184 for (list = request_list; list; list = list->next) {
4185 struct request_data *req = list->data;
4187 debug("Dropping request (id 0x%04x -> 0x%04x)",
4188 req->srcid, req->dstid);
4189 destroy_request_data(req);
4193 g_slist_free(request_list);
4194 request_list = NULL;
4196 destroy_tcp_listener(ifdata);
4197 destroy_udp_listener(ifdata);
4200 int __connman_dnsproxy_add_listener(int index)
4202 struct listener_data *ifdata;
4205 DBG("index %d", index);
4210 if (!listener_table)
4213 if (g_hash_table_lookup(listener_table, GINT_TO_POINTER(index)))
4216 ifdata = g_try_new0(struct listener_data, 1);
4220 ifdata->index = index;
4221 ifdata->udp4_listener_channel = NULL;
4222 ifdata->udp4_listener_watch = 0;
4223 ifdata->tcp4_listener_channel = NULL;
4224 ifdata->tcp4_listener_watch = 0;
4225 ifdata->udp6_listener_channel = NULL;
4226 ifdata->udp6_listener_watch = 0;
4227 ifdata->tcp6_listener_channel = NULL;
4228 ifdata->tcp6_listener_watch = 0;
4230 err = create_listener(ifdata);
4232 connman_error("Couldn't create listener for index %d err %d",
4237 g_hash_table_insert(listener_table, GINT_TO_POINTER(ifdata->index),
4242 void __connman_dnsproxy_remove_listener(int index)
4244 struct listener_data *ifdata;
4246 DBG("index %d", index);
4248 if (!listener_table)
4251 ifdata = g_hash_table_lookup(listener_table, GINT_TO_POINTER(index));
4255 destroy_listener(ifdata);
4257 g_hash_table_remove(listener_table, GINT_TO_POINTER(index));
4260 static void remove_listener(gpointer key, gpointer value, gpointer user_data)
4262 int index = GPOINTER_TO_INT(key);
4263 struct listener_data *ifdata = value;
4265 DBG("index %d", index);
4267 destroy_listener(ifdata);
4270 static void free_partial_reqs(gpointer value)
4272 struct tcp_partial_client_data *data = value;
4278 int __connman_dnsproxy_init(void)
4284 listener_table = g_hash_table_new_full(g_direct_hash, g_direct_equal,
4287 partial_tcp_req_table = g_hash_table_new_full(g_direct_hash,
4292 index = connman_inet_ifindex("lo");
4293 err = __connman_dnsproxy_add_listener(index);
4297 err = connman_notifier_register(&dnsproxy_notifier);
4304 __connman_dnsproxy_remove_listener(index);
4305 g_hash_table_destroy(listener_table);
4306 g_hash_table_destroy(partial_tcp_req_table);
4311 int __connman_dnsproxy_set_mdns(int index, bool enabled)
4316 void __connman_dnsproxy_cleanup(void)
4321 g_source_remove(cache_timer);
4326 g_hash_table_destroy(cache);
4330 connman_notifier_unregister(&dnsproxy_notifier);
4332 g_hash_table_foreach(listener_table, remove_listener, NULL);
4334 g_hash_table_destroy(listener_table);
4336 g_hash_table_destroy(partial_tcp_req_table);
4339 g_resolv_unref(ipv4_resolve);
4341 g_resolv_unref(ipv6_resolve);