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 #if __BYTE_ORDER == __LITTLE_ENDIAN
64 } __attribute__ ((packed));
65 #elif __BYTE_ORDER == __BIG_ENDIAN
80 } __attribute__ ((packed));
82 #error "Unknown byte order"
85 struct partial_reply {
95 struct sockaddr *server_addr;
96 socklen_t server_addr_len;
103 struct partial_reply *incoming_reply;
106 struct request_data {
108 struct sockaddr_in6 __sin6; /* Only for the length */
127 struct listener_data *ifdata;
131 struct listener_data {
134 GIOChannel *udp4_listener_channel;
135 GIOChannel *tcp4_listener_channel;
136 guint udp4_listener_watch;
137 guint tcp4_listener_watch;
139 GIOChannel *udp6_listener_channel;
140 GIOChannel *tcp6_listener_channel;
141 guint udp6_listener_watch;
142 guint tcp6_listener_watch;
146 * The TCP client requires some extra handling as we need to
147 * be prepared to receive also partial DNS requests.
149 struct tcp_partial_client_data {
151 struct listener_data *ifdata;
155 unsigned int buf_end;
166 unsigned int data_len;
167 unsigned char *data; /* contains DNS header + body */
174 struct cache_data *ipv4;
175 struct cache_data *ipv6;
178 struct domain_question {
181 } __attribute__ ((packed));
188 } __attribute__ ((packed));
191 * Max length of the DNS TCP packet.
193 #define TCP_MAX_BUF_LEN 4096
196 * We limit how long the cached DNS entry stays in the cache.
197 * By default the TTL (time-to-live) of the DNS response is used
198 * when setting the cache entry life time. The value is in seconds.
200 #if defined TIZEN_EXT
201 #define MAX_CACHE_TTL (60 * 60)
203 #define MAX_CACHE_TTL (60 * 30)
206 * Also limit the other end, cache at least for 30 seconds.
208 #define MIN_CACHE_TTL (30)
211 * We limit the cache size to some sane value so that cached data does
212 * not occupy too much memory. Each cached entry occupies on average
213 * about 100 bytes memory (depending on DNS name length).
214 * Example: caching www.connman.net uses 97 bytes memory.
215 * The value is the max amount of cached DNS responses (count).
217 #define MAX_CACHE_SIZE 256
219 static int cache_size;
220 static GHashTable *cache;
221 static int cache_refcount;
222 static GSList *server_list = NULL;
223 #if defined TIZEN_EXT
224 static GSList *server_list_sec = NULL;
226 static GSList *request_list = NULL;
227 static GHashTable *listener_table = NULL;
228 static time_t next_refresh;
229 static GHashTable *partial_tcp_req_table;
230 static guint cache_timer = 0;
232 #if defined TIZEN_EXT
233 static void destroy_server_sec(struct server_data *server);
234 static struct server_data *create_server_sec(int index,
235 const char *domain, const char *server,
239 static guint16 get_id(void)
243 __connman_util_get_random(&rand);
248 static int protocol_offset(int protocol)
264 * There is a power and efficiency benefit to have entries
265 * in our cache expire at the same time. To this extend,
266 * we round down the cache valid time to common boundaries.
268 static time_t round_down_ttl(time_t end_time, int ttl)
273 /* Less than 5 minutes, round to 10 second boundary */
275 end_time = end_time / 10;
276 end_time = end_time * 10;
277 } else { /* 5 or more minutes, round to 30 seconds */
278 end_time = end_time / 30;
279 end_time = end_time * 30;
284 static struct request_data *find_request(guint16 id)
288 for (list = request_list; list; list = list->next) {
289 struct request_data *req = list->data;
291 if (req->dstid == id || req->altid == id)
298 static struct server_data *find_server(int index,
304 DBG("index %d server %s proto %d", index, server, protocol);
306 for (list = server_list; list; list = list->next) {
307 struct server_data *data = list->data;
309 if (index < 0 && data->index < 0 &&
310 g_str_equal(data->server, server) &&
311 data->protocol == protocol)
315 data->index < 0 || !data->server)
318 if (data->index == index &&
319 g_str_equal(data->server, server) &&
320 data->protocol == protocol)
327 /* we can keep using the same resolve's */
328 static GResolv *ipv4_resolve;
329 static GResolv *ipv6_resolve;
331 static void dummy_resolve_func(GResolvResultStatus status,
332 char **results, gpointer user_data)
337 * Refresh a DNS entry, but also age the hit count a bit */
338 static void refresh_dns_entry(struct cache_entry *entry, char *name)
343 ipv4_resolve = g_resolv_new(0);
344 g_resolv_set_address_family(ipv4_resolve, AF_INET);
345 g_resolv_add_nameserver(ipv4_resolve, "127.0.0.1", 53, 0);
349 ipv6_resolve = g_resolv_new(0);
350 g_resolv_set_address_family(ipv6_resolve, AF_INET6);
351 g_resolv_add_nameserver(ipv6_resolve, "::1", 53, 0);
355 DBG("Refresing A record for %s", name);
356 g_resolv_lookup_hostname(ipv4_resolve, name,
357 dummy_resolve_func, NULL);
362 DBG("Refresing AAAA record for %s", name);
363 g_resolv_lookup_hostname(ipv6_resolve, name,
364 dummy_resolve_func, NULL);
373 static int dns_name_length(unsigned char *buf)
375 if ((buf[0] & NS_CMPRSFLGS) == NS_CMPRSFLGS) /* compressed name */
377 return strlen((char *)buf);
380 static void update_cached_ttl(unsigned char *buf, int len, int new_ttl)
386 /* skip the header */
390 /* skip the query, which is a name and 2 16 bit words */
391 l = dns_name_length(c);
397 /* now we get the answer records */
401 l = dns_name_length(c);
406 /* then type + class, 2 bytes each */
412 /* now the 4 byte TTL field */
413 c[0] = new_ttl >> 24 & 0xff;
414 c[1] = new_ttl >> 16 & 0xff;
415 c[2] = new_ttl >> 8 & 0xff;
416 c[3] = new_ttl & 0xff;
422 /* now the 2 byte rdlen field */
423 w = c[0] << 8 | c[1];
429 static void send_cached_response(int sk, unsigned char *buf, int len,
430 const struct sockaddr *to, socklen_t tolen,
431 int protocol, int id, uint16_t answers, int ttl)
433 struct domain_hdr *hdr;
434 unsigned char *ptr = buf;
435 int err, offset, dns_len, adj_len = len - 2;
438 * The cached packet contains always the TCP offset (two bytes)
439 * so skip them for UDP.
450 dns_len = ptr[0] * 256 + ptr[1];
459 hdr = (void *) (ptr + offset);
463 hdr->rcode = ns_r_noerror;
464 hdr->ancount = htons(answers);
468 /* if this is a negative reply, we are authorative */
472 update_cached_ttl((unsigned char *)hdr, adj_len, ttl);
474 DBG("sk %d id 0x%04x answers %d ptr %p length %d dns %d",
475 sk, hdr->id, answers, ptr, len, dns_len);
477 err = sendto(sk, ptr, len, MSG_NOSIGNAL, to, tolen);
479 connman_error("Cannot send cached DNS response: %s",
484 if (err != len || (dns_len != (len - 2) && protocol == IPPROTO_TCP) ||
485 (dns_len != len && protocol == IPPROTO_UDP))
486 DBG("Packet length mismatch, sent %d wanted %d dns %d",
490 static void send_response(int sk, unsigned char *buf, int len,
491 const struct sockaddr *to, socklen_t tolen,
494 struct domain_hdr *hdr;
495 int err, offset = protocol_offset(protocol);
505 hdr = (void *) (buf + offset);
507 DBG("id 0x%04x qr %d opcode %d", hdr->id, hdr->qr, hdr->opcode);
510 hdr->rcode = ns_r_servfail;
516 err = sendto(sk, buf, len, MSG_NOSIGNAL, to, tolen);
518 connman_error("Failed to send DNS response to %d: %s",
519 sk, strerror(errno));
524 static int get_req_udp_socket(struct request_data *req)
528 if (req->family == AF_INET)
529 channel = req->ifdata->udp4_listener_channel;
531 channel = req->ifdata->udp6_listener_channel;
536 return g_io_channel_unix_get_fd(channel);
539 static void destroy_request_data(struct request_data *req)
541 if (req->timeout > 0)
542 g_source_remove(req->timeout);
545 g_free(req->request);
550 static gboolean request_timeout(gpointer user_data)
552 struct request_data *req = user_data;
559 DBG("id 0x%04x", req->srcid);
561 request_list = g_slist_remove(request_list, req);
563 if (req->protocol == IPPROTO_UDP) {
564 sk = get_req_udp_socket(req);
566 } else if (req->protocol == IPPROTO_TCP) {
572 if (req->resplen > 0 && req->resp) {
574 * Here we have received at least one reply (probably telling
575 * "not found" result), so send that back to client instead
576 * of more fatal server failed error.
579 sendto(sk, req->resp, req->resplen, MSG_NOSIGNAL,
582 } else if (req->request) {
584 * There was not reply from server at all.
586 struct domain_hdr *hdr;
588 hdr = (void *)(req->request + protocol_offset(req->protocol));
589 hdr->id = req->srcid;
592 send_response(sk, req->request, req->request_len,
593 sa, req->sa_len, req->protocol);
597 * We cannot leave TCP client hanging so just kick it out
598 * if we get a request timeout from server.
600 if (req->protocol == IPPROTO_TCP) {
601 DBG("client %d removed", req->client_sk);
602 g_hash_table_remove(partial_tcp_req_table,
603 GINT_TO_POINTER(req->client_sk));
608 destroy_request_data(req);
613 static int append_query(unsigned char *buf, unsigned int size,
614 const char *query, const char *domain)
616 unsigned char *ptr = buf;
619 DBG("query %s domain %s", query, domain);
624 tmp = strchr(query, '.');
630 memcpy(ptr + 1, query, len);
636 memcpy(ptr + 1, query, tmp - query);
637 ptr += tmp - query + 1;
645 tmp = strchr(domain, '.');
647 len = strlen(domain);
651 memcpy(ptr + 1, domain, len);
657 memcpy(ptr + 1, domain, tmp - domain);
658 ptr += tmp - domain + 1;
668 static bool cache_check_is_valid(struct cache_data *data,
674 if (data->cache_until < current_time)
681 * remove stale cached entries so that they can be refreshed
683 static void cache_enforce_validity(struct cache_entry *entry)
685 time_t current_time = time(NULL);
687 if (!cache_check_is_valid(entry->ipv4, current_time)
689 DBG("cache timeout \"%s\" type A", entry->key);
690 g_free(entry->ipv4->data);
696 if (!cache_check_is_valid(entry->ipv6, current_time)
698 DBG("cache timeout \"%s\" type AAAA", entry->key);
699 g_free(entry->ipv6->data);
705 static uint16_t cache_check_validity(char *question, uint16_t type,
706 struct cache_entry *entry)
708 time_t current_time = time(NULL);
709 bool want_refresh = false;
712 * if we have a popular entry, we want a refresh instead of
713 * total destruction of the entry.
718 cache_enforce_validity(entry);
722 if (!cache_check_is_valid(entry->ipv4, current_time)) {
723 DBG("cache %s \"%s\" type A", entry->ipv4 ?
724 "timeout" : "entry missing", question);
727 entry->want_refresh = true;
730 * We do not remove cache entry if there is still
731 * valid IPv6 entry found in the cache.
733 if (!cache_check_is_valid(entry->ipv6, current_time) && !want_refresh) {
734 g_hash_table_remove(cache, question);
741 if (!cache_check_is_valid(entry->ipv6, current_time)) {
742 DBG("cache %s \"%s\" type AAAA", entry->ipv6 ?
743 "timeout" : "entry missing", question);
746 entry->want_refresh = true;
748 if (!cache_check_is_valid(entry->ipv4, current_time) && !want_refresh) {
749 g_hash_table_remove(cache, question);
759 static void cache_element_destroy(gpointer value)
761 struct cache_entry *entry = value;
767 g_free(entry->ipv4->data);
772 g_free(entry->ipv6->data);
779 if (--cache_size < 0)
783 static gboolean try_remove_cache(gpointer user_data)
787 if (__sync_fetch_and_sub(&cache_refcount, 1) == 1) {
788 DBG("No cache users, removing it.");
790 g_hash_table_destroy(cache);
797 static void create_cache(void)
799 if (__sync_fetch_and_add(&cache_refcount, 1) == 0)
800 cache = g_hash_table_new_full(g_str_hash,
803 cache_element_destroy);
806 static struct cache_entry *cache_check(gpointer request, int *qtype, int proto)
809 struct cache_entry *entry;
810 struct domain_question *q;
812 int offset, proto_offset;
817 proto_offset = protocol_offset(proto);
818 if (proto_offset < 0)
821 question = request + proto_offset + 12;
823 offset = strlen(question) + 1;
824 q = (void *) (question + offset);
825 type = ntohs(q->type);
827 /* We only cache either A (1) or AAAA (28) requests */
828 if (type != 1 && type != 28)
836 entry = g_hash_table_lookup(cache, question);
840 type = cache_check_validity(question, type, entry);
849 * Get a label/name from DNS resource record. The function decompresses the
850 * label if necessary. The function does not convert the name to presentation
851 * form. This means that the result string will contain label lengths instead
852 * of dots between labels. We intentionally do not want to convert to dotted
853 * format so that we can cache the wire format string directly.
855 static int get_name(int counter,
856 unsigned char *pkt, unsigned char *start, unsigned char *max,
857 unsigned char *output, int output_max, int *output_len,
858 unsigned char **end, char *name, int *name_len)
862 /* Limit recursion to 10 (this means up to 10 labels in domain name) */
868 if ((*p & NS_CMPRSFLGS) == NS_CMPRSFLGS) {
869 uint16_t offset = (*p & 0x3F) * 256 + *(p + 1);
871 if (offset >= max - pkt)
877 return get_name(counter + 1, pkt, pkt + offset, max,
878 output, output_max, output_len, end,
881 unsigned label_len = *p;
883 if (pkt + label_len > max)
886 if (*output_len > output_max)
890 * We need the original name in order to check
891 * if this answer is the correct one.
893 name[(*name_len)++] = label_len;
894 memcpy(name + *name_len, p + 1, label_len + 1);
895 *name_len += label_len;
897 /* We compress the result */
898 output[0] = NS_CMPRSFLGS;
915 static int parse_rr(unsigned char *buf, unsigned char *start,
917 unsigned char *response, unsigned int *response_size,
918 uint16_t *type, uint16_t *class, int *ttl, int *rdlen,
922 struct domain_rr *rr;
924 int name_len = 0, output_len = 0, max_rsp = *response_size;
926 err = get_name(0, buf, start, max, response, max_rsp,
927 &output_len, end, name, &name_len);
933 if ((unsigned int) offset > *response_size)
936 rr = (void *) (*end);
941 *type = ntohs(rr->type);
942 *class = ntohs(rr->class);
943 *ttl = ntohl(rr->ttl);
944 *rdlen = ntohs(rr->rdlen);
949 memcpy(response + offset, *end, sizeof(struct domain_rr));
951 offset += sizeof(struct domain_rr);
952 *end += sizeof(struct domain_rr);
954 if ((unsigned int) (offset + *rdlen) > *response_size)
957 memcpy(response + offset, *end, *rdlen);
961 *response_size = offset + *rdlen;
966 static bool check_alias(GSList *aliases, char *name)
971 for (list = aliases; list; list = list->next) {
972 int len = strlen((char *)list->data);
973 if (strncmp((char *)list->data, name, len) == 0)
981 static int parse_response(unsigned char *buf, int buflen,
982 char *question, int qlen,
983 uint16_t *type, uint16_t *class, int *ttl,
984 unsigned char *response, unsigned int *response_len,
987 struct domain_hdr *hdr = (void *) buf;
988 struct domain_question *q;
990 uint16_t qdcount = ntohs(hdr->qdcount);
991 uint16_t ancount = ntohs(hdr->ancount);
993 uint16_t qtype, qclass;
994 unsigned char *next = NULL;
995 unsigned int maxlen = *response_len;
996 GSList *aliases = NULL, *list;
997 char name[NS_MAXDNAME + 1];
1002 DBG("qr %d qdcount %d", hdr->qr, qdcount);
1004 /* We currently only cache responses where question count is 1 */
1005 if (hdr->qr != 1 || qdcount != 1)
1008 ptr = buf + sizeof(struct domain_hdr);
1010 strncpy(question, (char *) ptr, qlen);
1011 qlen = strlen(question);
1012 ptr += qlen + 1; /* skip \0 */
1015 qtype = ntohs(q->type);
1017 /* We cache only A and AAAA records */
1018 if (qtype != 1 && qtype != 28)
1021 qclass = ntohs(q->class);
1023 ptr += 2 + 2; /* ptr points now to answers */
1029 memset(name, 0, sizeof(name));
1032 * We have a bunch of answers (like A, AAAA, CNAME etc) to
1033 * A or AAAA question. We traverse the answers and parse the
1034 * resource records. Only A and AAAA records are cached, all
1035 * the other records in answers are skipped.
1037 for (i = 0; i < ancount; i++) {
1039 * Get one address at a time to this buffer.
1040 * The max size of the answer is
1041 * 2 (pointer) + 2 (type) + 2 (class) +
1042 * 4 (ttl) + 2 (rdlen) + addr (16 or 4) = 28
1043 * for A or AAAA record.
1044 * For CNAME the size can be bigger.
1046 unsigned char rsp[NS_MAXCDNAME];
1047 unsigned int rsp_len = sizeof(rsp) - 1;
1050 memset(rsp, 0, sizeof(rsp));
1052 ret = parse_rr(buf, ptr, buf + buflen, rsp, &rsp_len,
1053 type, class, ttl, &rdlen, &next, name);
1060 * Now rsp contains compressed or uncompressed resource
1061 * record. Next we check if this record answers the question.
1062 * The name var contains the uncompressed label.
1063 * One tricky bit is the CNAME records as they alias
1064 * the name we might be interested in.
1068 * Go to next answer if the class is not the one we are
1071 if (*class != qclass) {
1078 * Try to resolve aliases also, type is CNAME(5).
1079 * This is important as otherwise the aliased names would not
1080 * be cached at all as the cache would not contain the aliased
1083 * If any CNAME is found in DNS packet, then we cache the alias
1084 * IP address instead of the question (as the server
1085 * said that question has only an alias).
1086 * This means in practice that if e.g., ipv6.google.com is
1087 * queried, DNS server returns CNAME of that name which is
1088 * ipv6.l.google.com. We then cache the address of the CNAME
1089 * but return the question name to client. So the alias
1090 * status of the name is not saved in cache and thus not
1091 * returned to the client. We do not return DNS packets from
1092 * cache to client saying that ipv6.google.com is an alias to
1093 * ipv6.l.google.com but we return instead a DNS packet that
1094 * says ipv6.google.com has address xxx which is in fact the
1095 * address of ipv6.l.google.com. For caching purposes this
1096 * should not cause any issues.
1098 if (*type == 5 && strncmp(question, name, qlen) == 0) {
1100 * So now the alias answered the question. This is
1101 * not very useful from caching point of view as
1102 * the following A or AAAA records will not match the
1103 * question. We need to find the real A/AAAA record
1104 * of the alias and cache that.
1106 unsigned char *end = NULL;
1107 int name_len = 0, output_len = 0;
1109 memset(rsp, 0, sizeof(rsp));
1110 rsp_len = sizeof(rsp) - 1;
1113 * Alias is in rdata part of the message,
1114 * and next-rdlen points to it. So we need to get
1115 * the real name of the alias.
1117 ret = get_name(0, buf, next - rdlen, buf + buflen,
1118 rsp, rsp_len, &output_len, &end,
1121 /* just ignore the error at this point */
1128 * We should now have the alias of the entry we might
1129 * want to cache. Just remember it for a while.
1130 * We check the alias list when we have parsed the
1133 aliases = g_slist_prepend(aliases, g_strdup(name));
1140 if (*type == qtype) {
1142 * We found correct type (A or AAAA)
1144 if (check_alias(aliases, name) ||
1145 (!aliases && strncmp(question, name,
1148 * We found an alias or the name of the rr
1149 * matches the question. If so, we append
1150 * the compressed label to the cache.
1151 * The end result is a response buffer that
1152 * will contain one or more cached and
1153 * compressed resource records.
1155 if (*response_len + rsp_len > maxlen) {
1159 memcpy(response + *response_len, rsp, rsp_len);
1160 *response_len += rsp_len;
1171 for (list = aliases; list; list = list->next)
1173 g_slist_free(aliases);
1178 struct cache_timeout {
1179 time_t current_time;
1184 static gboolean cache_check_entry(gpointer key, gpointer value,
1187 struct cache_timeout *data = user_data;
1188 struct cache_entry *entry = value;
1191 /* Scale the number of hits by half as part of cache aging */
1196 * If either IPv4 or IPv6 cached entry has expired, we
1197 * remove both from the cache.
1200 if (entry->ipv4 && entry->ipv4->timeout > 0) {
1201 max_timeout = entry->ipv4->cache_until;
1202 if (max_timeout > data->max_timeout)
1203 data->max_timeout = max_timeout;
1205 if (entry->ipv4->cache_until < data->current_time)
1209 if (entry->ipv6 && entry->ipv6->timeout > 0) {
1210 max_timeout = entry->ipv6->cache_until;
1211 if (max_timeout > data->max_timeout)
1212 data->max_timeout = max_timeout;
1214 if (entry->ipv6->cache_until < data->current_time)
1219 * if we're asked to try harder, also remove entries that have
1222 if (data->try_harder && entry->hits < 4)
1228 static void cache_cleanup(void)
1230 static int max_timeout;
1231 struct cache_timeout data;
1234 data.current_time = time(NULL);
1235 data.max_timeout = 0;
1236 data.try_harder = 0;
1239 * In the first pass, we only remove entries that have timed out.
1240 * We use a cache of the first time to expire to do this only
1241 * when it makes sense.
1243 if (max_timeout <= data.current_time) {
1244 count = g_hash_table_foreach_remove(cache, cache_check_entry,
1247 DBG("removed %d in the first pass", count);
1250 * In the second pass, if the first pass turned up blank,
1251 * we also expire entries with a low hit count,
1252 * while aging the hit count at the same time.
1254 data.try_harder = 1;
1256 count = g_hash_table_foreach_remove(cache, cache_check_entry,
1261 * If we could not remove anything, then remember
1262 * what is the max timeout and do nothing if we
1263 * have not yet reached it. This will prevent
1264 * constant traversal of the cache if it is full.
1266 max_timeout = data.max_timeout;
1271 static gboolean cache_invalidate_entry(gpointer key, gpointer value,
1274 struct cache_entry *entry = value;
1276 /* first, delete any expired elements */
1277 cache_enforce_validity(entry);
1279 /* if anything is not expired, mark the entry for refresh */
1280 if (entry->hits > 0 && (entry->ipv4 || entry->ipv6))
1281 entry->want_refresh = true;
1283 /* delete the cached data */
1285 g_free(entry->ipv4->data);
1286 g_free(entry->ipv4);
1291 g_free(entry->ipv6->data);
1292 g_free(entry->ipv6);
1296 /* keep the entry if we want it refreshed, delete it otherwise */
1297 if (entry->want_refresh)
1304 * cache_invalidate is called from places where the DNS landscape
1305 * has changed, say because connections are added or we entered a VPN.
1306 * The logic is to wipe all cache data, but mark all non-expired
1307 * parts of the cache for refresh rather than deleting the whole cache.
1309 static void cache_invalidate(void)
1311 DBG("Invalidating the DNS cache %p", cache);
1316 g_hash_table_foreach_remove(cache, cache_invalidate_entry, NULL);
1319 static void cache_refresh_entry(struct cache_entry *entry)
1322 cache_enforce_validity(entry);
1324 if (entry->hits > 2 && !entry->ipv4)
1325 entry->want_refresh = true;
1326 if (entry->hits > 2 && !entry->ipv6)
1327 entry->want_refresh = true;
1329 if (entry->want_refresh) {
1331 char dns_name[NS_MAXDNAME + 1];
1332 entry->want_refresh = false;
1334 /* turn a DNS name into a hostname with dots */
1335 strncpy(dns_name, entry->key, NS_MAXDNAME);
1343 DBG("Refreshing %s\n", dns_name);
1344 /* then refresh the hostname */
1345 refresh_dns_entry(entry, &dns_name[1]);
1349 static void cache_refresh_iterator(gpointer key, gpointer value,
1352 struct cache_entry *entry = value;
1354 cache_refresh_entry(entry);
1357 static void cache_refresh(void)
1362 g_hash_table_foreach(cache, cache_refresh_iterator, NULL);
1365 static int reply_query_type(unsigned char *msg, int len)
1371 /* skip the header */
1372 c = msg + sizeof(struct domain_hdr);
1373 len -= sizeof(struct domain_hdr);
1378 /* now the query, which is a name and 2 16 bit words */
1379 l = dns_name_length(c) + 1;
1381 type = c[0] << 8 | c[1];
1386 static int cache_update(struct server_data *srv, unsigned char *msg,
1387 unsigned int msg_len)
1389 int offset = protocol_offset(srv->protocol);
1390 int err, qlen, ttl = 0;
1391 uint16_t answers = 0, type = 0, class = 0;
1392 struct domain_hdr *hdr = (void *)(msg + offset);
1393 struct domain_question *q;
1394 struct cache_entry *entry;
1395 struct cache_data *data;
1396 char question[NS_MAXDNAME + 1];
1397 unsigned char response[NS_MAXDNAME + 1];
1399 unsigned int rsplen;
1400 bool new_entry = true;
1401 time_t current_time;
1403 if (cache_size >= MAX_CACHE_SIZE) {
1405 if (cache_size >= MAX_CACHE_SIZE)
1409 current_time = time(NULL);
1411 /* don't do a cache refresh more than twice a minute */
1412 if (next_refresh < current_time) {
1414 next_refresh = current_time + 30;
1420 DBG("offset %d hdr %p msg %p rcode %d", offset, hdr, msg, hdr->rcode);
1422 /* Continue only if response code is 0 (=ok) */
1423 if (hdr->rcode != ns_r_noerror)
1429 rsplen = sizeof(response) - 1;
1430 question[sizeof(question) - 1] = '\0';
1432 err = parse_response(msg + offset, msg_len - offset,
1433 question, sizeof(question) - 1,
1434 &type, &class, &ttl,
1435 response, &rsplen, &answers);
1438 * special case: if we do a ipv6 lookup and get no result
1439 * for a record that's already in our ipv4 cache.. we want
1440 * to cache the negative response.
1442 if ((err == -ENOMSG || err == -ENOBUFS) &&
1443 reply_query_type(msg + offset,
1444 msg_len - offset) == 28) {
1445 entry = g_hash_table_lookup(cache, question);
1446 if (entry && entry->ipv4 && !entry->ipv6) {
1447 int cache_offset = 0;
1449 data = g_try_new(struct cache_data, 1);
1452 data->inserted = entry->ipv4->inserted;
1454 data->answers = ntohs(hdr->ancount);
1455 data->timeout = entry->ipv4->timeout;
1456 if (srv->protocol == IPPROTO_UDP)
1458 data->data_len = msg_len + cache_offset;
1459 data->data = ptr = g_malloc(data->data_len);
1460 ptr[0] = (data->data_len - 2) / 256;
1461 ptr[1] = (data->data_len - 2) - ptr[0] * 256;
1462 if (srv->protocol == IPPROTO_UDP)
1464 data->valid_until = entry->ipv4->valid_until;
1465 data->cache_until = entry->ipv4->cache_until;
1466 memcpy(ptr, msg, msg_len);
1469 * we will get a "hit" when we serve the response
1473 if (entry->hits < 0)
1479 if (err < 0 || ttl == 0)
1482 qlen = strlen(question);
1485 * If the cache contains already data, check if the
1486 * type of the cached data is the same and do not add
1487 * to cache if data is already there.
1488 * This is needed so that we can cache both A and AAAA
1489 * records for the same name.
1491 entry = g_hash_table_lookup(cache, question);
1493 entry = g_try_new(struct cache_entry, 1);
1497 data = g_try_new(struct cache_data, 1);
1503 entry->key = g_strdup(question);
1504 entry->ipv4 = entry->ipv6 = NULL;
1505 entry->want_refresh = false;
1513 if (type == 1 && entry->ipv4)
1516 if (type == 28 && entry->ipv6)
1519 data = g_try_new(struct cache_data, 1);
1529 * compensate for the hit we'll get for serving
1530 * the response out of the cache
1533 if (entry->hits < 0)
1539 if (ttl < MIN_CACHE_TTL)
1540 ttl = MIN_CACHE_TTL;
1542 data->inserted = current_time;
1544 data->answers = answers;
1545 data->timeout = ttl;
1547 * The "2" in start of the length is the TCP offset. We allocate it
1548 * here even for UDP packet because it simplifies the sending
1551 data->data_len = 2 + 12 + qlen + 1 + 2 + 2 + rsplen;
1552 data->data = ptr = g_malloc(data->data_len);
1553 data->valid_until = current_time + ttl;
1556 * Restrict the cached DNS record TTL to some sane value
1557 * in order to prevent data staying in the cache too long.
1559 if (ttl > MAX_CACHE_TTL)
1560 ttl = MAX_CACHE_TTL;
1562 data->cache_until = round_down_ttl(current_time + ttl, ttl);
1572 * We cache the two extra bytes at the start of the message
1573 * in a TCP packet. When sending UDP packet, we skip the first
1574 * two bytes. This way we do not need to know the format
1575 * (UDP/TCP) of the cached message.
1577 if (srv->protocol == IPPROTO_UDP)
1578 memcpy(ptr + 2, msg, offset + 12);
1580 memcpy(ptr, msg, offset + 12);
1582 ptr[0] = (data->data_len - 2) / 256;
1583 ptr[1] = (data->data_len - 2) - ptr[0] * 256;
1584 if (srv->protocol == IPPROTO_UDP)
1587 memcpy(ptr + offset + 12, question, qlen + 1); /* copy also the \0 */
1589 q = (void *) (ptr + offset + 12 + qlen + 1);
1590 q->type = htons(type);
1591 q->class = htons(class);
1592 memcpy(ptr + offset + 12 + qlen + 1 + sizeof(struct domain_question),
1596 g_hash_table_replace(cache, entry->key, entry);
1600 DBG("cache %d %squestion \"%s\" type %d ttl %d size %zd packet %u "
1602 cache_size, new_entry ? "new " : "old ",
1603 question, type, ttl,
1604 sizeof(*entry) + sizeof(*data) + data->data_len + qlen,
1606 srv->protocol == IPPROTO_TCP ?
1607 (unsigned int)(data->data[0] * 256 + data->data[1]) :
1613 static int ns_resolv(struct server_data *server, struct request_data *req,
1614 gpointer request, gpointer name)
1617 int sk, err, type = 0;
1618 char *dot, *lookup = (char *) name;
1619 struct cache_entry *entry;
1621 entry = cache_check(request, &type, req->protocol);
1624 struct cache_data *data;
1626 DBG("cache hit %s type %s", lookup, type == 1 ? "A" : "AAAA");
1633 ttl_left = data->valid_until - time(NULL);
1637 if (data && req->protocol == IPPROTO_TCP) {
1638 send_cached_response(req->client_sk, data->data,
1639 data->data_len, NULL, 0, IPPROTO_TCP,
1640 req->srcid, data->answers, ttl_left);
1644 if (data && req->protocol == IPPROTO_UDP) {
1645 int udp_sk = get_req_udp_socket(req);
1650 send_cached_response(udp_sk, data->data,
1651 data->data_len, &req->sa, req->sa_len,
1652 IPPROTO_UDP, req->srcid, data->answers,
1658 #if defined TIZEN_EXT
1659 if (server->protocol == IPPROTO_UDP) {
1661 struct server_data *new_server = NULL;
1663 new_server = create_server_sec(server->index, NULL,
1664 server->server, IPPROTO_UDP);
1666 if (new_server != NULL) {
1667 for (domains = server->domains; domains;
1668 domains = domains->next) {
1669 char *dom = domains->data;
1671 DBG("Adding domain %s to %s",
1672 dom, new_server->server);
1674 new_server->domains = g_list_append(
1675 new_server->domains,
1679 server = new_server;
1683 sk = g_io_channel_unix_get_fd(server->channel);
1685 err = sendto(sk, request, req->request_len, MSG_NOSIGNAL,
1686 server->server_addr, server->server_addr_len);
1688 DBG("Cannot send message to server %s sock %d "
1689 "protocol %d (%s/%d)",
1690 server->server, sk, server->protocol,
1691 strerror(errno), errno);
1697 /* If we have more than one dot, we don't add domains */
1698 dot = strchr(lookup, '.');
1699 if (dot && dot != lookup + strlen(lookup) - 1)
1702 if (server->domains && server->domains->data)
1703 req->append_domain = true;
1705 for (list = server->domains; list; list = list->next) {
1707 unsigned char alt[1024];
1708 struct domain_hdr *hdr = (void *) &alt;
1709 int altlen, domlen, offset;
1711 domain = list->data;
1716 offset = protocol_offset(server->protocol);
1720 domlen = strlen(domain) + 1;
1724 alt[offset] = req->altid & 0xff;
1725 alt[offset + 1] = req->altid >> 8;
1727 memcpy(alt + offset + 2, request + offset + 2, 10);
1728 hdr->qdcount = htons(1);
1730 altlen = append_query(alt + offset + 12, sizeof(alt) - 12,
1737 memcpy(alt + offset + altlen,
1738 request + offset + altlen - domlen,
1739 req->request_len - altlen - offset + domlen);
1741 if (server->protocol == IPPROTO_TCP) {
1742 int req_len = req->request_len + domlen - 2;
1744 alt[0] = (req_len >> 8) & 0xff;
1745 alt[1] = req_len & 0xff;
1748 DBG("req %p dstid 0x%04x altid 0x%04x", req, req->dstid,
1751 err = send(sk, alt, req->request_len + domlen, MSG_NOSIGNAL);
1761 static char *convert_label(char *start, char *end, char *ptr, char *uptr,
1762 int remaining_len, int *used_comp, int *used_uncomp)
1765 char name[NS_MAXLABEL];
1767 pos = dn_expand((u_char *)start, (u_char *)end, (u_char *)ptr,
1770 DBG("uncompress error [%d/%s]", errno, strerror(errno));
1775 * We need to compress back the name so that we get back to internal
1776 * label presentation.
1778 comp_pos = dn_comp(name, (u_char *)uptr, remaining_len, NULL, NULL);
1780 DBG("compress error [%d/%s]", errno, strerror(errno));
1785 *used_uncomp = comp_pos;
1793 static char *uncompress(int16_t field_count, char *start, char *end,
1794 char *ptr, char *uncompressed, int uncomp_len,
1795 char **uncompressed_ptr)
1797 char *uptr = *uncompressed_ptr; /* position in result buffer */
1799 DBG("count %d ptr %p end %p uptr %p", field_count, ptr, end, uptr);
1801 while (field_count-- > 0 && ptr < end) {
1802 int dlen; /* data field length */
1803 int ulen; /* uncompress length */
1804 int pos; /* position in compressed string */
1805 char name[NS_MAXLABEL]; /* tmp label */
1806 uint16_t dns_type, dns_class;
1809 if (!convert_label(start, end, ptr, name, NS_MAXLABEL,
1814 * Copy the uncompressed resource record, type, class and \0 to
1818 ulen = strlen(name);
1819 strncpy(uptr, name, uncomp_len - (uptr - uncompressed));
1821 DBG("pos %d ulen %d left %d name %s", pos, ulen,
1822 (int)(uncomp_len - (uptr - uncompressed)), uptr);
1830 * We copy also the fixed portion of the result (type, class,
1831 * ttl, address length and the address)
1833 memcpy(uptr, ptr, NS_RRFIXEDSZ);
1835 dns_type = uptr[0] << 8 | uptr[1];
1836 dns_class = uptr[2] << 8 | uptr[3];
1838 if (dns_class != ns_c_in)
1841 ptr += NS_RRFIXEDSZ;
1842 uptr += NS_RRFIXEDSZ;
1845 * Then the variable portion of the result (data length).
1846 * Typically this portion is also compressed
1847 * so we need to uncompress it also when necessary.
1849 if (dns_type == ns_t_cname) {
1850 if (!convert_label(start, end, ptr, uptr,
1851 uncomp_len - (uptr - uncompressed),
1855 uptr[-2] = comp_pos << 8;
1856 uptr[-1] = comp_pos & 0xff;
1861 } else if (dns_type == ns_t_a || dns_type == ns_t_aaaa) {
1862 dlen = uptr[-2] << 8 | uptr[-1];
1864 if (ptr + dlen > end) {
1865 DBG("data len %d too long", dlen);
1869 memcpy(uptr, ptr, dlen);
1873 } else if (dns_type == ns_t_soa) {
1877 /* Primary name server expansion */
1878 if (!convert_label(start, end, ptr, uptr,
1879 uncomp_len - (uptr - uncompressed),
1883 total_len += comp_pos;
1884 len_ptr = &uptr[-2];
1888 /* Responsible authority's mailbox */
1889 if (!convert_label(start, end, ptr, uptr,
1890 uncomp_len - (uptr - uncompressed),
1894 total_len += comp_pos;
1899 * Copy rest of the soa fields (serial number,
1900 * refresh interval, retry interval, expiration
1901 * limit and minimum ttl). They are 20 bytes long.
1903 memcpy(uptr, ptr, 20);
1909 * Finally fix the length of the data part
1911 len_ptr[0] = total_len << 8;
1912 len_ptr[1] = total_len & 0xff;
1915 *uncompressed_ptr = uptr;
1924 static int strip_domains(char *name, char *answers, int maxlen)
1927 int name_len = strlen(name);
1928 char *ptr, *start = answers, *end = answers + maxlen;
1930 while (maxlen > 0) {
1931 ptr = strstr(answers, name);
1933 char *domain = ptr + name_len;
1936 int domain_len = strlen(domain);
1938 memmove(answers + name_len,
1939 domain + domain_len,
1940 end - (domain + domain_len));
1943 maxlen -= domain_len;
1947 answers += strlen(answers) + 1;
1948 answers += 2 + 2 + 4; /* skip type, class and ttl fields */
1950 data_len = answers[0] << 8 | answers[1];
1951 answers += 2; /* skip the length field */
1953 if (answers + data_len > end)
1956 answers += data_len;
1957 maxlen -= answers - ptr;
1963 static int forward_dns_reply(unsigned char *reply, int reply_len, int protocol,
1964 struct server_data *data)
1966 struct domain_hdr *hdr;
1967 struct request_data *req;
1968 int dns_id, sk, err, offset = protocol_offset(protocol);
1973 hdr = (void *)(reply + offset);
1974 dns_id = reply[offset] | reply[offset + 1] << 8;
1976 DBG("Received %d bytes (id 0x%04x)", reply_len, dns_id);
1978 req = find_request(dns_id);
1982 DBG("req %p dstid 0x%04x altid 0x%04x rcode %d",
1983 req, req->dstid, req->altid, hdr->rcode);
1985 reply[offset] = req->srcid & 0xff;
1986 reply[offset + 1] = req->srcid >> 8;
1990 if (hdr->rcode == ns_r_noerror || !req->resp) {
1991 unsigned char *new_reply = NULL;
1994 * If the domain name was append
1995 * remove it before forwarding the reply.
1996 * If there were more than one question, then this
1997 * domain name ripping can be hairy so avoid that
1998 * and bail out in that that case.
2000 * The reason we are doing this magic is that if the
2001 * user's DNS client tries to resolv hostname without
2002 * domain part, it also expects to get the result without
2003 * a domain name part.
2005 if (req->append_domain && ntohs(hdr->qdcount) == 1) {
2006 uint16_t domain_len = 0;
2007 uint16_t header_len;
2008 uint16_t dns_type, dns_class;
2009 uint8_t host_len, dns_type_pos;
2010 char uncompressed[NS_MAXDNAME], *uptr;
2011 char *ptr, *eom = (char *)reply + reply_len;
2014 * ptr points to the first char of the hostname.
2015 * ->hostname.domain.net
2017 header_len = offset + sizeof(struct domain_hdr);
2018 ptr = (char *)reply + header_len;
2022 domain_len = strnlen(ptr + 1 + host_len,
2023 reply_len - header_len);
2026 * If the query type is anything other than A or AAAA,
2027 * then bail out and pass the message as is.
2028 * We only want to deal with IPv4 or IPv6 addresses.
2030 dns_type_pos = host_len + 1 + domain_len + 1;
2032 dns_type = ptr[dns_type_pos] << 8 |
2033 ptr[dns_type_pos + 1];
2034 dns_class = ptr[dns_type_pos + 2] << 8 |
2035 ptr[dns_type_pos + 3];
2036 if (dns_type != ns_t_a && dns_type != ns_t_aaaa &&
2037 dns_class != ns_c_in) {
2038 DBG("Pass msg dns type %d class %d",
2039 dns_type, dns_class);
2044 * Remove the domain name and replace it by the end
2045 * of reply. Check if the domain is really there
2046 * before trying to copy the data. We also need to
2047 * uncompress the answers if necessary.
2048 * The domain_len can be 0 because if the original
2049 * query did not contain a domain name, then we are
2050 * sending two packets, first without the domain name
2051 * and the second packet with domain name.
2052 * The append_domain is set to true even if we sent
2053 * the first packet without domain name. In this
2054 * case we end up in this branch.
2056 if (domain_len > 0) {
2057 int len = host_len + 1;
2058 int new_len, fixed_len;
2062 * First copy host (without domain name) into
2065 uptr = &uncompressed[0];
2066 memcpy(uptr, ptr, len);
2068 uptr[len] = '\0'; /* host termination */
2072 * Copy type and class fields of the question.
2074 ptr += len + domain_len + 1;
2075 memcpy(uptr, ptr, NS_QFIXEDSZ);
2078 * ptr points to answers after this
2081 uptr += NS_QFIXEDSZ;
2083 fixed_len = answers - uncompressed;
2086 * We then uncompress the result to buffer
2087 * so that we can rip off the domain name
2088 * part from the question. First answers,
2089 * then name server (authority) information,
2090 * and finally additional record info.
2093 ptr = uncompress(ntohs(hdr->ancount),
2094 (char *)reply + offset, eom,
2095 ptr, uncompressed, NS_MAXDNAME,
2100 ptr = uncompress(ntohs(hdr->nscount),
2101 (char *)reply + offset, eom,
2102 ptr, uncompressed, NS_MAXDNAME,
2107 ptr = uncompress(ntohs(hdr->arcount),
2108 (char *)reply + offset, eom,
2109 ptr, uncompressed, NS_MAXDNAME,
2115 * The uncompressed buffer now contains almost
2116 * valid response. Final step is to get rid of
2117 * the domain name because at least glibc
2118 * gethostbyname() implementation does extra
2119 * checks and expects to find an answer without
2120 * domain name if we asked a query without
2121 * domain part. Note that glibc getaddrinfo()
2122 * works differently and accepts FQDN in answer
2124 new_len = strip_domains(uncompressed, answers,
2127 DBG("Corrupted packet");
2132 * Because we have now uncompressed the answers
2133 * we might have to create a bigger buffer to
2134 * hold all that data.
2137 reply_len = header_len + new_len + fixed_len;
2139 new_reply = g_try_malloc(reply_len);
2143 memcpy(new_reply, reply, header_len);
2144 memcpy(new_reply + header_len, uncompressed,
2145 new_len + fixed_len);
2155 req->resp = g_try_malloc(reply_len);
2159 memcpy(req->resp, reply, reply_len);
2160 req->resplen = reply_len;
2162 cache_update(data, reply, reply_len);
2168 if (req->numresp < req->numserv) {
2169 if (hdr->rcode > ns_r_noerror) {
2171 } else if (hdr->ancount == 0 && req->append_domain) {
2176 request_list = g_slist_remove(request_list, req);
2178 if (protocol == IPPROTO_UDP) {
2179 sk = get_req_udp_socket(req);
2184 err = sendto(sk, req->resp, req->resplen, 0,
2185 &req->sa, req->sa_len);
2187 sk = req->client_sk;
2188 err = send(sk, req->resp, req->resplen, MSG_NOSIGNAL);
2192 DBG("Cannot send msg, sk %d proto %d errno %d/%s", sk,
2193 protocol, errno, strerror(errno));
2195 DBG("proto %d sent %d bytes to %d", protocol, err, sk);
2197 destroy_request_data(req);
2202 static void server_destroy_socket(struct server_data *data)
2204 DBG("index %d server %s proto %d", data->index,
2205 data->server, data->protocol);
2207 if (data->watch > 0) {
2208 g_source_remove(data->watch);
2212 if (data->timeout > 0) {
2213 g_source_remove(data->timeout);
2217 if (data->channel) {
2218 g_io_channel_shutdown(data->channel, TRUE, NULL);
2219 g_io_channel_unref(data->channel);
2220 data->channel = NULL;
2223 g_free(data->incoming_reply);
2224 data->incoming_reply = NULL;
2227 static void destroy_server(struct server_data *server)
2229 DBG("index %d server %s sock %d", server->index, server->server,
2231 g_io_channel_unix_get_fd(server->channel): -1);
2233 server_list = g_slist_remove(server_list, server);
2234 server_destroy_socket(server);
2236 if (server->protocol == IPPROTO_UDP && server->enabled)
2237 DBG("Removing DNS server %s", server->server);
2239 g_free(server->server);
2240 g_list_free_full(server->domains, g_free);
2241 g_free(server->server_addr);
2244 * We do not remove cache right away but delay it few seconds.
2245 * The idea is that when IPv6 DNS server is added via RDNSS, it has a
2246 * lifetime. When the lifetime expires we decrease the refcount so it
2247 * is possible that the cache is then removed. Because a new DNS server
2248 * is usually created almost immediately we would then loose the cache
2249 * without any good reason. The small delay allows the new RDNSS to
2250 * create a new DNS server instance and the refcount does not go to 0.
2252 if (cache && !cache_timer)
2253 cache_timer = g_timeout_add_seconds(3, try_remove_cache, NULL);
2258 static gboolean udp_server_event(GIOChannel *channel, GIOCondition condition,
2261 unsigned char buf[4096];
2263 struct server_data *data = user_data;
2265 if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
2266 connman_error("Error with UDP server %s", data->server);
2267 server_destroy_socket(data);
2271 sk = g_io_channel_unix_get_fd(channel);
2273 len = recv(sk, buf, sizeof(buf), 0);
2277 err = forward_dns_reply(buf, len, IPPROTO_UDP, data);
2281 #if defined TIZEN_EXT
2284 for (list = server_list_sec; list; list = list->next) {
2285 struct server_data *new_data = list->data;
2287 if (new_data == data) {
2288 destroy_server_sec(data);
2297 static gboolean tcp_server_event(GIOChannel *channel, GIOCondition condition,
2301 struct server_data *server = user_data;
2303 sk = g_io_channel_unix_get_fd(channel);
2307 if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
2310 DBG("TCP server channel closed, sk %d", sk);
2313 * Discard any partial response which is buffered; better
2314 * to get a proper response from a working server.
2316 g_free(server->incoming_reply);
2317 server->incoming_reply = NULL;
2319 for (list = request_list; list; list = list->next) {
2320 struct request_data *req = list->data;
2321 struct domain_hdr *hdr;
2323 if (req->protocol == IPPROTO_UDP)
2330 * If we're not waiting for any further response
2331 * from another name server, then we send an error
2332 * response to the client.
2334 if (req->numserv && --(req->numserv))
2337 hdr = (void *) (req->request + 2);
2338 hdr->id = req->srcid;
2339 send_response(req->client_sk, req->request,
2340 req->request_len, NULL, 0, IPPROTO_TCP);
2342 request_list = g_slist_remove(request_list, req);
2345 destroy_server(server);
2350 if ((condition & G_IO_OUT) && !server->connected) {
2353 bool no_request_sent = true;
2354 struct server_data *udp_server;
2356 udp_server = find_server(server->index, server->server,
2359 for (domains = udp_server->domains; domains;
2360 domains = domains->next) {
2361 char *dom = domains->data;
2363 DBG("Adding domain %s to %s",
2364 dom, server->server);
2366 server->domains = g_list_append(server->domains,
2371 server->connected = true;
2372 server_list = g_slist_append(server_list, server);
2374 if (server->timeout > 0) {
2375 g_source_remove(server->timeout);
2376 server->timeout = 0;
2379 for (list = request_list; list; ) {
2380 struct request_data *req = list->data;
2383 if (req->protocol == IPPROTO_UDP) {
2388 DBG("Sending req %s over TCP", (char *)req->name);
2390 status = ns_resolv(server, req,
2391 req->request, req->name);
2394 * A cached result was sent,
2395 * so the request can be released
2398 request_list = g_slist_remove(request_list, req);
2399 destroy_request_data(req);
2408 no_request_sent = false;
2410 if (req->timeout > 0)
2411 g_source_remove(req->timeout);
2413 req->timeout = g_timeout_add_seconds(30,
2414 request_timeout, req);
2418 if (no_request_sent) {
2419 destroy_server(server);
2423 } else if (condition & G_IO_IN) {
2424 struct partial_reply *reply = server->incoming_reply;
2428 unsigned char reply_len_buf[2];
2431 bytes_recv = recv(sk, reply_len_buf, 2, MSG_PEEK);
2434 } else if (bytes_recv < 0) {
2435 if (errno == EAGAIN || errno == EWOULDBLOCK)
2438 connman_error("DNS proxy error %s",
2441 } else if (bytes_recv < 2)
2444 reply_len = reply_len_buf[1] | reply_len_buf[0] << 8;
2447 DBG("TCP reply %d bytes from %d", reply_len, sk);
2449 reply = g_try_malloc(sizeof(*reply) + reply_len + 2);
2453 reply->len = reply_len;
2454 reply->received = 0;
2456 server->incoming_reply = reply;
2459 while (reply->received < reply->len) {
2460 bytes_recv = recv(sk, reply->buf + reply->received,
2461 reply->len - reply->received, 0);
2463 connman_error("DNS proxy TCP disconnect");
2465 } else if (bytes_recv < 0) {
2466 if (errno == EAGAIN || errno == EWOULDBLOCK)
2469 connman_error("DNS proxy error %s",
2473 reply->received += bytes_recv;
2476 forward_dns_reply(reply->buf, reply->received, IPPROTO_TCP,
2480 server->incoming_reply = NULL;
2482 destroy_server(server);
2490 static gboolean tcp_idle_timeout(gpointer user_data)
2492 struct server_data *server = user_data;
2499 destroy_server(server);
2504 static int server_create_socket(struct server_data *data)
2509 DBG("index %d server %s proto %d", data->index,
2510 data->server, data->protocol);
2512 sk = socket(data->server_addr->sa_family,
2513 data->protocol == IPPROTO_TCP ? SOCK_STREAM : SOCK_DGRAM,
2517 connman_error("Failed to create server %s socket",
2519 server_destroy_socket(data);
2525 interface = connman_inet_ifname(data->index);
2527 if (setsockopt(sk, SOL_SOCKET, SO_BINDTODEVICE,
2529 strlen(interface) + 1) < 0) {
2531 connman_error("Failed to bind server %s "
2533 data->server, interface);
2535 server_destroy_socket(data);
2542 data->channel = g_io_channel_unix_new(sk);
2543 if (!data->channel) {
2544 connman_error("Failed to create server %s channel",
2547 server_destroy_socket(data);
2551 g_io_channel_set_close_on_unref(data->channel, TRUE);
2553 if (data->protocol == IPPROTO_TCP) {
2554 g_io_channel_set_flags(data->channel, G_IO_FLAG_NONBLOCK, NULL);
2555 data->watch = g_io_add_watch(data->channel,
2556 G_IO_OUT | G_IO_IN | G_IO_HUP | G_IO_NVAL | G_IO_ERR,
2557 tcp_server_event, data);
2558 data->timeout = g_timeout_add_seconds(30, tcp_idle_timeout,
2561 data->watch = g_io_add_watch(data->channel,
2562 G_IO_IN | G_IO_NVAL | G_IO_ERR | G_IO_HUP,
2563 udp_server_event, data);
2565 if (connect(sk, data->server_addr, data->server_addr_len) < 0) {
2568 if ((data->protocol == IPPROTO_TCP && errno != EINPROGRESS) ||
2569 data->protocol == IPPROTO_UDP) {
2571 connman_error("Failed to connect to server %s",
2573 server_destroy_socket(data);
2583 #if defined TIZEN_EXT
2585 static void destroy_server_sec(struct server_data *server)
2590 if (server->channel)
2591 fd = g_io_channel_unix_get_fd(server->channel);
2595 DBG("index %d server %s sock %d", server->index, server->server, fd);
2597 server_list_sec = g_slist_remove(server_list_sec, server);
2602 server_destroy_socket(server);
2604 if (server->protocol == IPPROTO_UDP && server->enabled)
2605 DBG("Removing DNS server %s", server->server);
2607 g_free(server->server);
2608 for (list = server->domains; list; list = list->next) {
2609 char *domain = list->data;
2611 server->domains = g_list_remove(server->domains, domain);
2614 g_free(server->server_addr);
2617 * We do not remove cache right away but delay it few seconds.
2618 * The idea is that when IPv6 DNS server is added via RDNSS, it has a
2619 * lifetime. When the lifetime expires we decrease the refcount so it
2620 * is possible that the cache is then removed. Because a new DNS server
2621 * is usually created almost immediately we would then loose the cache
2622 * without any good reason. The small delay allows the new RDNSS to
2623 * create a new DNS server instance and the refcount does not go to 0.
2625 /* TODO: Need to check this */
2626 /* g_timeout_add_seconds(3, try_remove_cache, NULL); */
2631 static void destroy_all_server_sec()
2635 DBG("remove all dns server");
2637 for (list = server_list_sec; list; list = list->next) {
2638 struct server_data *server = list->data;
2639 destroy_server_sec(server);
2641 server_list_sec = NULL;
2644 static gboolean sec_udp_idle_timeout(gpointer user_data)
2646 struct server_data *server = user_data;
2653 destroy_server_sec(server);
2658 static struct server_data *create_server_sec(int index,
2659 const char *domain, const char *server,
2662 struct server_data *data;
2663 struct addrinfo hints, *rp;
2666 DBG("index %d server %s", index, server);
2668 data = g_try_new0(struct server_data, 1);
2670 connman_error("Failed to allocate server %s data", server);
2674 data->index = index;
2676 data->domains = g_list_append(data->domains, g_strdup(domain));
2677 data->server = g_strdup(server);
2678 data->protocol = protocol;
2680 memset(&hints, 0, sizeof(hints));
2684 hints.ai_socktype = SOCK_DGRAM;
2688 hints.ai_socktype = SOCK_STREAM;
2692 destroy_server_sec(data);
2695 hints.ai_family = AF_UNSPEC;
2696 hints.ai_flags = AI_NUMERICSERV | AI_NUMERICHOST;
2698 ret = getaddrinfo(data->server, "53", &hints, &rp);
2700 connman_error("Failed to parse server %s address: %s\n",
2701 data->server, gai_strerror(ret));
2703 destroy_server_sec(data);
2707 /* Do not blindly copy this code elsewhere; it doesn't loop over the
2708 results using ->ai_next as it should. That's OK in *this* case
2709 because it was a numeric lookup; we *know* there's only one. */
2711 data->server_addr_len = rp->ai_addrlen;
2713 switch (rp->ai_family) {
2715 data->server_addr = (struct sockaddr *)
2716 g_try_new0(struct sockaddr_in, 1);
2719 data->server_addr = (struct sockaddr *)
2720 g_try_new0(struct sockaddr_in6, 1);
2723 connman_error("Wrong address family %d", rp->ai_family);
2726 if (data->server_addr == NULL) {
2728 destroy_server_sec(data);
2731 memcpy(data->server_addr, rp->ai_addr, rp->ai_addrlen);
2734 if (server_create_socket(data) != 0) {
2735 destroy_server_sec(data);
2739 if (protocol == IPPROTO_UDP) {
2740 /* Enable new servers by default */
2741 data->enabled = TRUE;
2742 DBG("Adding DNS server %s", data->server);
2744 data->timeout = g_timeout_add_seconds(30, sec_udp_idle_timeout,
2747 server_list_sec = g_slist_append(server_list_sec, data);
2754 static struct server_data *create_server(int index,
2755 const char *domain, const char *server,
2758 struct server_data *data;
2759 struct addrinfo hints, *rp;
2762 DBG("index %d server %s", index, server);
2764 data = g_try_new0(struct server_data, 1);
2766 connman_error("Failed to allocate server %s data", server);
2770 data->index = index;
2772 data->domains = g_list_append(data->domains, g_strdup(domain));
2773 data->server = g_strdup(server);
2774 data->protocol = protocol;
2776 memset(&hints, 0, sizeof(hints));
2780 hints.ai_socktype = SOCK_DGRAM;
2784 hints.ai_socktype = SOCK_STREAM;
2788 destroy_server(data);
2791 hints.ai_family = AF_UNSPEC;
2792 hints.ai_flags = AI_NUMERICSERV | AI_NUMERICHOST;
2794 ret = getaddrinfo(data->server, "53", &hints, &rp);
2796 connman_error("Failed to parse server %s address: %s\n",
2797 data->server, gai_strerror(ret));
2798 destroy_server(data);
2802 /* Do not blindly copy this code elsewhere; it doesn't loop over the
2803 results using ->ai_next as it should. That's OK in *this* case
2804 because it was a numeric lookup; we *know* there's only one. */
2806 data->server_addr_len = rp->ai_addrlen;
2808 switch (rp->ai_family) {
2810 data->server_addr = (struct sockaddr *)
2811 g_try_new0(struct sockaddr_in, 1);
2814 data->server_addr = (struct sockaddr *)
2815 g_try_new0(struct sockaddr_in6, 1);
2818 connman_error("Wrong address family %d", rp->ai_family);
2821 if (!data->server_addr) {
2823 destroy_server(data);
2826 memcpy(data->server_addr, rp->ai_addr, rp->ai_addrlen);
2829 if (server_create_socket(data) != 0) {
2830 destroy_server(data);
2834 if (protocol == IPPROTO_UDP) {
2835 if (__connman_service_index_is_default(data->index) ||
2836 __connman_service_index_is_split_routing(
2838 data->enabled = true;
2839 DBG("Adding DNS server %s", data->server);
2842 server_list = g_slist_append(server_list, data);
2848 static bool resolv(struct request_data *req,
2849 gpointer request, gpointer name)
2853 for (list = server_list; list; list = list->next) {
2854 struct server_data *data = list->data;
2856 if (data->protocol == IPPROTO_TCP) {
2857 DBG("server %s ignored proto TCP", data->server);
2861 DBG("server %s enabled %d", data->server, data->enabled);
2866 if (!data->channel && data->protocol == IPPROTO_UDP) {
2867 if (server_create_socket(data) < 0) {
2868 DBG("socket creation failed while resolving");
2873 if (ns_resolv(data, req, request, name) > 0)
2880 static void append_domain(int index, const char *domain)
2884 DBG("index %d domain %s", index, domain);
2889 for (list = server_list; list; list = list->next) {
2890 struct server_data *data = list->data;
2893 bool dom_found = false;
2895 if (data->index < 0)
2898 if (data->index != index)
2901 for (dom_list = data->domains; dom_list;
2902 dom_list = dom_list->next) {
2903 dom = dom_list->data;
2905 if (g_str_equal(dom, domain)) {
2913 g_list_append(data->domains, g_strdup(domain));
2918 static void flush_requests(struct server_data *server)
2922 list = request_list;
2924 struct request_data *req = list->data;
2928 if (ns_resolv(server, req, req->request, req->name)) {
2930 * A cached result was sent,
2931 * so the request can be released
2934 g_slist_remove(request_list, req);
2935 destroy_request_data(req);
2939 if (req->timeout > 0)
2940 g_source_remove(req->timeout);
2942 req->timeout = g_timeout_add_seconds(5, request_timeout, req);
2946 int __connman_dnsproxy_append(int index, const char *domain,
2949 struct server_data *data;
2951 DBG("index %d server %s", index, server);
2953 if (!server && !domain)
2957 append_domain(index, domain);
2962 if (g_str_equal(server, "127.0.0.1"))
2965 if (g_str_equal(server, "::1"))
2968 data = find_server(index, server, IPPROTO_UDP);
2970 append_domain(index, domain);
2974 data = create_server(index, domain, server, IPPROTO_UDP);
2978 flush_requests(data);
2983 static void remove_server(int index, const char *domain,
2984 const char *server, int protocol)
2986 struct server_data *data;
2988 data = find_server(index, server, protocol);
2992 destroy_server(data);
2995 int __connman_dnsproxy_remove(int index, const char *domain,
2998 DBG("index %d server %s", index, server);
3003 if (g_str_equal(server, "127.0.0.1"))
3006 if (g_str_equal(server, "::1"))
3009 remove_server(index, domain, server, IPPROTO_UDP);
3010 remove_server(index, domain, server, IPPROTO_TCP);
3012 #if defined TIZEN_EXT
3013 destroy_all_server_sec();
3019 static void dnsproxy_offline_mode(bool enabled)
3023 DBG("enabled %d", enabled);
3025 for (list = server_list; list; list = list->next) {
3026 struct server_data *data = list->data;
3029 DBG("Enabling DNS server %s", data->server);
3030 data->enabled = true;
3034 DBG("Disabling DNS server %s", data->server);
3035 data->enabled = false;
3041 static void dnsproxy_default_changed(struct connman_service *service)
3046 DBG("service %p", service);
3048 /* DNS has changed, invalidate the cache */
3052 /* When no services are active, then disable DNS proxying */
3053 dnsproxy_offline_mode(true);
3057 index = __connman_service_get_index(service);
3061 for (list = server_list; list; list = list->next) {
3062 struct server_data *data = list->data;
3064 if (data->index == index) {
3065 DBG("Enabling DNS server %s", data->server);
3066 data->enabled = true;
3068 DBG("Disabling DNS server %s", data->server);
3069 data->enabled = false;
3076 static struct connman_notifier dnsproxy_notifier = {
3078 .default_changed = dnsproxy_default_changed,
3079 .offline_mode = dnsproxy_offline_mode,
3082 static unsigned char opt_edns0_type[2] = { 0x00, 0x29 };
3084 static int parse_request(unsigned char *buf, int len,
3085 char *name, unsigned int size)
3087 struct domain_hdr *hdr = (void *) buf;
3088 uint16_t qdcount = ntohs(hdr->qdcount);
3089 uint16_t arcount = ntohs(hdr->arcount);
3091 char *last_label = NULL;
3092 unsigned int remain, used = 0;
3097 DBG("id 0x%04x qr %d opcode %d qdcount %d arcount %d",
3098 hdr->id, hdr->qr, hdr->opcode,
3101 if (hdr->qr != 0 || qdcount != 1)
3106 ptr = buf + sizeof(struct domain_hdr);
3107 remain = len - sizeof(struct domain_hdr);
3109 while (remain > 0) {
3110 uint8_t label_len = *ptr;
3112 if (label_len == 0x00) {
3113 last_label = (char *) (ptr + 1);
3117 if (used + label_len + 1 > size)
3120 strncat(name, (char *) (ptr + 1), label_len);
3123 used += label_len + 1;
3125 ptr += label_len + 1;
3126 remain -= label_len + 1;
3129 #if defined TIZEN_EXT
3130 /* parse DNS query type either A or AAAA
3131 * enforce to drop AAAA temporarily (IPv6 not supported)
3133 if (last_label != NULL) {
3134 uint16_t *type_p = (uint16_t *)last_label;
3135 uint16_t type = ntohs(*type_p);
3138 DBG("query %s is type AAAA(0x%x)", name, type);
3144 if (last_label && arcount && remain >= 9 && last_label[4] == 0 &&
3145 !memcmp(last_label + 5, opt_edns0_type, 2)) {
3146 uint16_t edns0_bufsize;
3148 edns0_bufsize = last_label[7] << 8 | last_label[8];
3150 DBG("EDNS0 buffer size %u", edns0_bufsize);
3152 /* This is an evil hack until full TCP support has been
3155 * Somtimes the EDNS0 request gets send with a too-small
3156 * buffer size. Since glibc doesn't seem to crash when it
3157 * gets a response biffer then it requested, just bump
3158 * the buffer size up to 4KiB.
3160 if (edns0_bufsize < 0x1000) {
3161 last_label[7] = 0x10;
3162 last_label[8] = 0x00;
3166 DBG("query %s", name);
3171 static void client_reset(struct tcp_partial_client_data *client)
3176 if (client->channel) {
3177 DBG("client %d closing",
3178 g_io_channel_unix_get_fd(client->channel));
3180 g_io_channel_unref(client->channel);
3181 client->channel = NULL;
3184 if (client->watch > 0) {
3185 g_source_remove(client->watch);
3189 if (client->timeout > 0) {
3190 g_source_remove(client->timeout);
3191 client->timeout = 0;
3194 g_free(client->buf);
3197 client->buf_end = 0;
3200 static unsigned int get_msg_len(unsigned char *buf)
3202 return buf[0]<<8 | buf[1];
3205 static bool read_tcp_data(struct tcp_partial_client_data *client,
3206 void *client_addr, socklen_t client_addr_len,
3209 char query[TCP_MAX_BUF_LEN];
3210 struct request_data *req;
3212 unsigned int msg_len;
3214 bool waiting_for_connect = false;
3216 struct cache_entry *entry;
3218 client_sk = g_io_channel_unix_get_fd(client->channel);
3220 if (read_len == 0) {
3221 DBG("client %d closed, pending %d bytes",
3222 client_sk, client->buf_end);
3223 g_hash_table_remove(partial_tcp_req_table,
3224 GINT_TO_POINTER(client_sk));
3228 DBG("client %d received %d bytes", client_sk, read_len);
3230 client->buf_end += read_len;
3232 if (client->buf_end < 2)
3235 msg_len = get_msg_len(client->buf);
3236 if (msg_len > TCP_MAX_BUF_LEN) {
3237 DBG("client %d sent too much data %d", client_sk, msg_len);
3238 g_hash_table_remove(partial_tcp_req_table,
3239 GINT_TO_POINTER(client_sk));
3244 DBG("client %d msg len %d end %d past end %d", client_sk, msg_len,
3245 client->buf_end, client->buf_end - (msg_len + 2));
3247 if (client->buf_end < (msg_len + 2)) {
3248 DBG("client %d still missing %d bytes",
3250 msg_len + 2 - client->buf_end);
3254 DBG("client %d all data %d received", client_sk, msg_len);
3256 err = parse_request(client->buf + 2, msg_len,
3257 query, sizeof(query));
3258 if (err < 0 || (g_slist_length(server_list) == 0)) {
3259 send_response(client_sk, client->buf, msg_len + 2,
3260 NULL, 0, IPPROTO_TCP);
3264 req = g_try_new0(struct request_data, 1);
3268 memcpy(&req->sa, client_addr, client_addr_len);
3269 req->sa_len = client_addr_len;
3270 req->client_sk = client_sk;
3271 req->protocol = IPPROTO_TCP;
3272 req->family = client->family;
3274 req->srcid = client->buf[2] | (client->buf[3] << 8);
3275 req->dstid = get_id();
3276 req->altid = get_id();
3277 req->request_len = msg_len + 2;
3279 client->buf[2] = req->dstid & 0xff;
3280 client->buf[3] = req->dstid >> 8;
3283 req->ifdata = client->ifdata;
3284 req->append_domain = false;
3287 * Check if the answer is found in the cache before
3288 * creating sockets to the server.
3290 entry = cache_check(client->buf, &qtype, IPPROTO_TCP);
3293 struct cache_data *data;
3295 DBG("cache hit %s type %s", query, qtype == 1 ? "A" : "AAAA");
3302 ttl_left = data->valid_until - time(NULL);
3305 send_cached_response(client_sk, data->data,
3306 data->data_len, NULL, 0, IPPROTO_TCP,
3307 req->srcid, data->answers, ttl_left);
3312 DBG("data missing, ignoring cache for this query");
3315 for (list = server_list; list; list = list->next) {
3316 struct server_data *data = list->data;
3318 if (data->protocol != IPPROTO_UDP || !data->enabled)
3321 if (!create_server(data->index, NULL, data->server,
3325 waiting_for_connect = true;
3328 if (!waiting_for_connect) {
3329 /* No server is waiting for connect */
3330 send_response(client_sk, client->buf,
3331 req->request_len, NULL, 0, IPPROTO_TCP);
3337 * The server is not connected yet.
3338 * Copy the relevant buffers.
3339 * The request will actually be sent once we're
3340 * properly connected over TCP to the nameserver.
3342 req->request = g_try_malloc0(req->request_len);
3343 if (!req->request) {
3344 send_response(client_sk, client->buf,
3345 req->request_len, NULL, 0, IPPROTO_TCP);
3349 memcpy(req->request, client->buf, req->request_len);
3351 req->name = g_try_malloc0(sizeof(query));
3353 send_response(client_sk, client->buf,
3354 req->request_len, NULL, 0, IPPROTO_TCP);
3355 g_free(req->request);
3359 memcpy(req->name, query, sizeof(query));
3361 req->timeout = g_timeout_add_seconds(30, request_timeout, req);
3363 request_list = g_slist_append(request_list, req);
3366 if (client->buf_end > (msg_len + 2)) {
3367 DBG("client %d buf %p -> %p end %d len %d new %d",
3369 client->buf + msg_len + 2,
3370 client->buf, client->buf_end,
3371 TCP_MAX_BUF_LEN - client->buf_end,
3372 client->buf_end - (msg_len + 2));
3373 memmove(client->buf, client->buf + msg_len + 2,
3374 TCP_MAX_BUF_LEN - client->buf_end);
3375 client->buf_end = client->buf_end - (msg_len + 2);
3378 * If we have a full message waiting, just read it
3381 msg_len = get_msg_len(client->buf);
3382 if ((msg_len + 2) == client->buf_end) {
3383 DBG("client %d reading another %d bytes", client_sk,
3388 DBG("client %d clearing reading buffer", client_sk);
3390 client->buf_end = 0;
3391 memset(client->buf, 0, TCP_MAX_BUF_LEN);
3394 * We received all the packets from client so we must also
3395 * remove the timeout handler here otherwise we might get
3396 * timeout while waiting the results from server.
3398 g_source_remove(client->timeout);
3399 client->timeout = 0;
3405 static gboolean tcp_client_event(GIOChannel *channel, GIOCondition condition,
3408 struct tcp_partial_client_data *client = user_data;
3409 struct sockaddr_in6 client_addr6;
3410 socklen_t client_addr6_len = sizeof(client_addr6);
3411 struct sockaddr_in client_addr4;
3412 socklen_t client_addr4_len = sizeof(client_addr4);
3414 socklen_t *client_addr_len;
3417 client_sk = g_io_channel_unix_get_fd(channel);
3419 if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
3420 g_hash_table_remove(partial_tcp_req_table,
3421 GINT_TO_POINTER(client_sk));
3423 connman_error("Error with TCP client %d channel", client_sk);
3427 switch (client->family) {
3429 client_addr = &client_addr4;
3430 client_addr_len = &client_addr4_len;
3433 client_addr = &client_addr6;
3434 client_addr_len = &client_addr6_len;
3437 g_hash_table_remove(partial_tcp_req_table,
3438 GINT_TO_POINTER(client_sk));
3439 connman_error("client %p corrupted", client);
3443 len = recvfrom(client_sk, client->buf + client->buf_end,
3444 TCP_MAX_BUF_LEN - client->buf_end, 0,
3445 client_addr, client_addr_len);
3447 if (errno == EAGAIN || errno == EWOULDBLOCK)
3450 DBG("client %d cannot read errno %d/%s", client_sk, -errno,
3452 g_hash_table_remove(partial_tcp_req_table,
3453 GINT_TO_POINTER(client_sk));
3457 return read_tcp_data(client, client_addr, *client_addr_len, len);
3460 static gboolean client_timeout(gpointer user_data)
3462 struct tcp_partial_client_data *client = user_data;
3465 sock = g_io_channel_unix_get_fd(client->channel);
3467 DBG("client %d timeout pending %d bytes", sock, client->buf_end);
3469 g_hash_table_remove(partial_tcp_req_table, GINT_TO_POINTER(sock));
3474 #if defined TIZEN_EXT
3475 static void recover_listener(GIOChannel *channel, struct listener_data *ifdata)
3479 index = ifdata->index;
3481 sk = g_io_channel_unix_get_fd(channel);
3484 __connman_dnsproxy_remove_listener(index);
3486 if (__connman_dnsproxy_add_listener(index) == 0)
3487 DBG("listener %d successfully recovered", index);
3491 static bool tcp_listener_event(GIOChannel *channel, GIOCondition condition,
3492 struct listener_data *ifdata, int family,
3493 guint *listener_watch)
3495 int sk, client_sk, len;
3496 unsigned int msg_len;
3497 struct tcp_partial_client_data *client;
3498 struct sockaddr_in6 client_addr6;
3499 socklen_t client_addr6_len = sizeof(client_addr6);
3500 struct sockaddr_in client_addr4;
3501 socklen_t client_addr4_len = sizeof(client_addr4);
3503 socklen_t *client_addr_len;
3507 DBG("condition 0x%02x channel %p ifdata %p family %d",
3508 condition, channel, ifdata, family);
3510 if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
3511 #if defined TIZEN_EXT
3512 connman_error("Error %d with TCP listener channel", condition);
3514 recover_listener(channel, ifdata);
3516 if (*listener_watch > 0)
3517 g_source_remove(*listener_watch);
3518 *listener_watch = 0;
3520 connman_error("Error with TCP listener channel");
3526 sk = g_io_channel_unix_get_fd(channel);
3528 if (family == AF_INET) {
3529 client_addr = &client_addr4;
3530 client_addr_len = &client_addr4_len;
3532 client_addr = &client_addr6;
3533 client_addr_len = &client_addr6_len;
3536 tv.tv_sec = tv.tv_usec = 0;
3538 FD_SET(sk, &readfds);
3540 select(sk + 1, &readfds, NULL, NULL, &tv);
3541 if (FD_ISSET(sk, &readfds)) {
3542 client_sk = accept(sk, client_addr, client_addr_len);
3543 DBG("client %d accepted", client_sk);
3545 DBG("No data to read from master %d, waiting.", sk);
3549 if (client_sk < 0) {
3550 connman_error("Accept failure on TCP listener");
3551 *listener_watch = 0;
3555 fcntl(client_sk, F_SETFL, O_NONBLOCK);
3557 client = g_hash_table_lookup(partial_tcp_req_table,
3558 GINT_TO_POINTER(client_sk));
3560 client = g_try_new0(struct tcp_partial_client_data, 1);
3566 g_hash_table_insert(partial_tcp_req_table,
3567 GINT_TO_POINTER(client_sk),
3570 client->channel = g_io_channel_unix_new(client_sk);
3571 g_io_channel_set_close_on_unref(client->channel, TRUE);
3573 client->watch = g_io_add_watch(client->channel,
3574 G_IO_IN, tcp_client_event,
3577 client->ifdata = ifdata;
3579 DBG("client %d created %p", client_sk, client);
3581 DBG("client %d already exists %p", client_sk, client);
3585 client->buf = g_try_malloc(TCP_MAX_BUF_LEN);
3589 memset(client->buf, 0, TCP_MAX_BUF_LEN);
3590 client->buf_end = 0;
3591 client->family = family;
3593 if (client->timeout == 0)
3594 client->timeout = g_timeout_add_seconds(2, client_timeout,
3598 * Check how much data there is. If all is there, then we can
3599 * proceed normally, otherwise read the bits until everything
3600 * is received or timeout occurs.
3602 len = recv(client_sk, client->buf, TCP_MAX_BUF_LEN, 0);
3604 if (errno == EAGAIN || errno == EWOULDBLOCK) {
3605 DBG("client %d no data to read, waiting", client_sk);
3609 DBG("client %d cannot read errno %d/%s", client_sk, -errno,
3611 g_hash_table_remove(partial_tcp_req_table,
3612 GINT_TO_POINTER(client_sk));
3617 DBG("client %d not enough data to read, waiting", client_sk);
3618 client->buf_end += len;
3622 msg_len = get_msg_len(client->buf);
3623 if (msg_len > TCP_MAX_BUF_LEN) {
3624 DBG("client %d invalid message length %u ignoring packet",
3625 client_sk, msg_len);
3626 g_hash_table_remove(partial_tcp_req_table,
3627 GINT_TO_POINTER(client_sk));
3632 * The packet length bytes do not contain the total message length,
3633 * that is the reason to -2 below.
3635 #if defined TIZEN_EXT
3636 if (msg_len > (unsigned int)(len - 2)) {
3638 if (msg_len != (unsigned int)(len - 2)) {
3640 DBG("client %d sent %d bytes but expecting %u pending %d",
3641 client_sk, len, msg_len + 2, msg_len + 2 - len);
3643 client->buf_end += len;
3647 return read_tcp_data(client, client_addr, *client_addr_len, len);
3650 static gboolean tcp4_listener_event(GIOChannel *channel, GIOCondition condition,
3653 struct listener_data *ifdata = user_data;
3655 return tcp_listener_event(channel, condition, ifdata, AF_INET,
3656 &ifdata->tcp4_listener_watch);
3659 static gboolean tcp6_listener_event(GIOChannel *channel, GIOCondition condition,
3662 struct listener_data *ifdata = user_data;
3664 return tcp_listener_event(channel, condition, user_data, AF_INET6,
3665 &ifdata->tcp6_listener_watch);
3668 #if defined TIZEN_EXT
3669 /* Temporarily disable AAAA type to enhance performance (IPv6 not supported) */
3670 static void __send_response_not_implemented(int sk, unsigned char *buf, int len,
3671 const struct sockaddr *to, socklen_t tolen,
3674 struct domain_hdr *hdr;
3675 int err, offset = protocol_offset(protocol);
3685 hdr = (void *) (buf + offset);
3687 DBG("id 0x%04x qr %d opcode %d", hdr->id, hdr->qr, hdr->opcode);
3696 err = sendto(sk, buf, len, MSG_NOSIGNAL, to, tolen);
3698 connman_error("Failed to send DNS response to %d: %s",
3699 sk, strerror(errno));
3703 static bool udp_listener_event(GIOChannel *channel, GIOCondition condition,
3704 struct listener_data *ifdata, int family,
3705 guint *listener_watch)
3707 unsigned char buf[768];
3709 struct request_data *req;
3710 struct sockaddr_in6 client_addr6;
3711 socklen_t client_addr6_len = sizeof(client_addr6);
3712 struct sockaddr_in client_addr4;
3713 socklen_t client_addr4_len = sizeof(client_addr4);
3715 socklen_t *client_addr_len;
3718 if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
3719 #if defined TIZEN_EXT
3720 connman_error("Error %d with UDP listener channel", condition);
3722 recover_listener(channel, ifdata);
3724 connman_error("Error with UDP listener channel");
3725 *listener_watch = 0;
3730 sk = g_io_channel_unix_get_fd(channel);
3732 if (family == AF_INET) {
3733 client_addr = &client_addr4;
3734 client_addr_len = &client_addr4_len;
3736 client_addr = &client_addr6;
3737 client_addr_len = &client_addr6_len;
3740 memset(client_addr, 0, *client_addr_len);
3741 len = recvfrom(sk, buf, sizeof(buf), 0, client_addr, client_addr_len);
3745 DBG("Received %d bytes (id 0x%04x)", len, buf[0] | buf[1] << 8);
3747 err = parse_request(buf, len, query, sizeof(query));
3748 if (err < 0 || (g_slist_length(server_list) == 0)) {
3749 #if defined TIZEN_EXT
3750 if (err == -ENOENT) {
3751 /* Temporarily disable AAAA type to enhance performance
3752 * (IPv6 not supported)
3754 __send_response_not_implemented(sk, buf, len, client_addr,
3755 *client_addr_len, IPPROTO_UDP);
3759 send_response(sk, buf, len, client_addr,
3760 *client_addr_len, IPPROTO_UDP);
3764 req = g_try_new0(struct request_data, 1);
3768 memcpy(&req->sa, client_addr, *client_addr_len);
3769 req->sa_len = *client_addr_len;
3771 req->protocol = IPPROTO_UDP;
3772 req->family = family;
3774 req->srcid = buf[0] | (buf[1] << 8);
3775 req->dstid = get_id();
3776 req->altid = get_id();
3777 req->request_len = len;
3779 buf[0] = req->dstid & 0xff;
3780 buf[1] = req->dstid >> 8;
3783 req->ifdata = ifdata;
3784 req->append_domain = false;
3786 if (resolv(req, buf, query)) {
3787 /* a cached result was sent, so the request can be released */
3792 req->name = g_strdup(query);
3793 req->request = g_malloc(len);
3794 memcpy(req->request, buf, len);
3795 #if defined TIZEN_EXT
3796 DBG("req %p dstid 0x%04x altid 0x%04x", req, req->dstid, req->altid);
3797 req->timeout = g_timeout_add_seconds(30, request_timeout, req);
3799 req->timeout = g_timeout_add_seconds(5, request_timeout, req);
3801 request_list = g_slist_append(request_list, req);
3806 static gboolean udp4_listener_event(GIOChannel *channel, GIOCondition condition,
3809 struct listener_data *ifdata = user_data;
3811 return udp_listener_event(channel, condition, ifdata, AF_INET,
3812 &ifdata->udp4_listener_watch);
3815 static gboolean udp6_listener_event(GIOChannel *channel, GIOCondition condition,
3818 struct listener_data *ifdata = user_data;
3820 return udp_listener_event(channel, condition, user_data, AF_INET6,
3821 &ifdata->udp6_listener_watch);
3824 static GIOChannel *get_listener(int family, int protocol, int index)
3826 GIOChannel *channel;
3828 #if !defined TIZEN_EXT
3831 struct sockaddr_in6 sin6;
3832 struct sockaddr_in sin;
3837 #if !defined TIZEN_EXT
3840 #if defined TIZEN_EXT
3846 DBG("family %d protocol %d index %d", family, protocol, index);
3851 type = SOCK_DGRAM | SOCK_CLOEXEC;
3856 type = SOCK_STREAM | SOCK_CLOEXEC;
3862 #if defined TIZEN_EXT
3863 sd_num = sd_listen_fds(0);
3864 DBG("socket type(%s) systemd number of fds(%d)", proto, sd_num);
3866 DBG("fail to get the fd from systemd");
3870 if(protocol == IPPROTO_TCP)
3875 for(sk = SD_LISTEN_FDS_START; sk < SD_LISTEN_FDS_START+sd_num; ++sk){
3876 rv = sd_is_socket_inet(sk, family, type, -1, 53);
3878 DBG("socket fd (%d) is passed by systemd", sk);
3883 if(sk >= SD_LISTEN_FDS_START+sd_num){
3884 DBG("socket fd is not matched what connman requests");
3888 sk = socket(family, type, protocol);
3889 if (sk < 0 && family == AF_INET6 && errno == EAFNOSUPPORT) {
3890 connman_error("No IPv6 support");
3895 connman_error("Failed to create %s listener socket", proto);
3899 /* ConnMan listens DNS from multiple interfaces
3900 * E.g. various technology based and tethering interfaces
3902 interface = connman_inet_ifname(index);
3903 if (!interface || setsockopt(sk, SOL_SOCKET, SO_BINDTODEVICE,
3905 strlen(interface) + 1) < 0) {
3906 connman_error("Failed to bind %s listener interface "
3908 proto, family == AF_INET ? "IPv4" : "IPv6",
3909 -errno, strerror(errno));
3916 if (family == AF_INET6) {
3917 memset(&s.sin6, 0, sizeof(s.sin6));
3918 s.sin6.sin6_family = AF_INET6;
3919 s.sin6.sin6_port = htons(53);
3920 slen = sizeof(s.sin6);
3922 if (__connman_inet_get_interface_address(index,
3924 &s.sin6.sin6_addr) < 0) {
3925 /* So we could not find suitable IPv6 address for
3926 * the interface. This could happen if we have
3927 * disabled IPv6 for the interface.
3933 } else if (family == AF_INET) {
3934 memset(&s.sin, 0, sizeof(s.sin));
3935 s.sin.sin_family = AF_INET;
3936 s.sin.sin_port = htons(53);
3937 slen = sizeof(s.sin);
3938 if (__connman_inet_get_interface_address(index,
3940 &s.sin.sin_addr) < 0) {
3949 #if defined TIZEN_EXT
3950 /* When ConnMan crashed,
3951 * probably DNS listener cannot bind existing address */
3953 setsockopt(sk, SOL_SOCKET, SO_REUSEADDR, &option, sizeof(option));
3955 #if !defined TIZEN_EXT
3956 if (bind(sk, &s.sa, slen) < 0) {
3957 connman_error("Failed to bind %s listener socket", proto);
3963 if (protocol == IPPROTO_TCP) {
3964 #if !defined TIZEN_EXT
3965 if (listen(sk, 10) < 0) {
3966 connman_error("Failed to listen on TCP socket %d/%s",
3967 -errno, strerror(errno));
3972 fcntl(sk, F_SETFL, O_NONBLOCK);
3975 channel = g_io_channel_unix_new(sk);
3977 connman_error("Failed to create %s listener channel", proto);
3982 g_io_channel_set_close_on_unref(channel, TRUE);
3987 #define UDP_IPv4_FAILED 0x01
3988 #define TCP_IPv4_FAILED 0x02
3989 #define UDP_IPv6_FAILED 0x04
3990 #define TCP_IPv6_FAILED 0x08
3991 #define UDP_FAILED (UDP_IPv4_FAILED | UDP_IPv6_FAILED)
3992 #define TCP_FAILED (TCP_IPv4_FAILED | TCP_IPv6_FAILED)
3993 #define IPv6_FAILED (UDP_IPv6_FAILED | TCP_IPv6_FAILED)
3994 #define IPv4_FAILED (UDP_IPv4_FAILED | TCP_IPv4_FAILED)
3996 static int create_dns_listener(int protocol, struct listener_data *ifdata)
4000 if (protocol == IPPROTO_TCP) {
4001 ifdata->tcp4_listener_channel = get_listener(AF_INET, protocol,
4003 if (ifdata->tcp4_listener_channel)
4004 #if defined TIZEN_EXT
4005 ifdata->tcp4_listener_watch =
4006 g_io_add_watch(ifdata->tcp4_listener_channel,
4007 G_IO_IN | G_IO_ERR | G_IO_HUP | G_IO_NVAL,
4008 tcp4_listener_event, (gpointer)ifdata);
4010 ifdata->tcp4_listener_watch =
4011 g_io_add_watch(ifdata->tcp4_listener_channel,
4012 G_IO_IN, tcp4_listener_event,
4016 ret |= TCP_IPv4_FAILED;
4018 ifdata->tcp6_listener_channel = get_listener(AF_INET6, protocol,
4020 if (ifdata->tcp6_listener_channel)
4021 #if defined TIZEN_EXT
4022 ifdata->tcp6_listener_watch =
4023 g_io_add_watch(ifdata->tcp6_listener_channel,
4024 G_IO_IN | G_IO_ERR | G_IO_HUP | G_IO_NVAL,
4025 tcp6_listener_event, (gpointer)ifdata);
4027 ifdata->tcp6_listener_watch =
4028 g_io_add_watch(ifdata->tcp6_listener_channel,
4029 G_IO_IN, tcp6_listener_event,
4033 ret |= TCP_IPv6_FAILED;
4035 ifdata->udp4_listener_channel = get_listener(AF_INET, protocol,
4037 if (ifdata->udp4_listener_channel)
4038 #if defined TIZEN_EXT
4039 ifdata->udp4_listener_watch =
4040 g_io_add_watch(ifdata->udp4_listener_channel,
4041 G_IO_IN | G_IO_ERR | G_IO_HUP | G_IO_NVAL,
4042 udp4_listener_event, (gpointer)ifdata);
4044 ifdata->udp4_listener_watch =
4045 g_io_add_watch(ifdata->udp4_listener_channel,
4046 G_IO_IN, udp4_listener_event,
4050 ret |= UDP_IPv4_FAILED;
4052 ifdata->udp6_listener_channel = get_listener(AF_INET6, protocol,
4054 if (ifdata->udp6_listener_channel)
4055 #if defined TIZEN_EXT
4056 ifdata->udp6_listener_watch =
4057 g_io_add_watch(ifdata->udp6_listener_channel,
4058 G_IO_IN | G_IO_ERR | G_IO_HUP | G_IO_NVAL,
4059 udp6_listener_event, (gpointer)ifdata);
4061 ifdata->udp6_listener_watch =
4062 g_io_add_watch(ifdata->udp6_listener_channel,
4063 G_IO_IN, udp6_listener_event,
4067 ret |= UDP_IPv6_FAILED;
4073 static void destroy_udp_listener(struct listener_data *ifdata)
4075 DBG("index %d", ifdata->index);
4077 if (ifdata->udp4_listener_watch > 0)
4078 g_source_remove(ifdata->udp4_listener_watch);
4080 if (ifdata->udp6_listener_watch > 0)
4081 g_source_remove(ifdata->udp6_listener_watch);
4083 if (ifdata->udp4_listener_channel)
4084 g_io_channel_unref(ifdata->udp4_listener_channel);
4085 if (ifdata->udp6_listener_channel)
4086 g_io_channel_unref(ifdata->udp6_listener_channel);
4089 static void destroy_tcp_listener(struct listener_data *ifdata)
4091 DBG("index %d", ifdata->index);
4093 if (ifdata->tcp4_listener_watch > 0)
4094 g_source_remove(ifdata->tcp4_listener_watch);
4095 if (ifdata->tcp6_listener_watch > 0)
4096 g_source_remove(ifdata->tcp6_listener_watch);
4098 if (ifdata->tcp4_listener_channel)
4099 g_io_channel_unref(ifdata->tcp4_listener_channel);
4100 if (ifdata->tcp6_listener_channel)
4101 g_io_channel_unref(ifdata->tcp6_listener_channel);
4104 static int create_listener(struct listener_data *ifdata)
4108 err = create_dns_listener(IPPROTO_UDP, ifdata);
4109 if ((err & UDP_FAILED) == UDP_FAILED)
4112 err |= create_dns_listener(IPPROTO_TCP, ifdata);
4113 if ((err & TCP_FAILED) == TCP_FAILED) {
4114 destroy_udp_listener(ifdata);
4118 index = connman_inet_ifindex("lo");
4119 if (ifdata->index == index) {
4120 if ((err & IPv6_FAILED) != IPv6_FAILED)
4121 __connman_resolvfile_append(index, NULL, "::1");
4123 if ((err & IPv4_FAILED) != IPv4_FAILED)
4124 __connman_resolvfile_append(index, NULL, "127.0.0.1");
4130 static void destroy_listener(struct listener_data *ifdata)
4135 index = connman_inet_ifindex("lo");
4136 if (ifdata->index == index) {
4137 __connman_resolvfile_remove(index, NULL, "127.0.0.1");
4138 __connman_resolvfile_remove(index, NULL, "::1");
4141 for (list = request_list; list; list = list->next) {
4142 struct request_data *req = list->data;
4144 DBG("Dropping request (id 0x%04x -> 0x%04x)",
4145 req->srcid, req->dstid);
4146 destroy_request_data(req);
4150 g_slist_free(request_list);
4151 request_list = NULL;
4153 destroy_tcp_listener(ifdata);
4154 destroy_udp_listener(ifdata);
4157 int __connman_dnsproxy_add_listener(int index)
4159 struct listener_data *ifdata;
4162 DBG("index %d", index);
4167 if (!listener_table)
4170 if (g_hash_table_lookup(listener_table, GINT_TO_POINTER(index)))
4173 ifdata = g_try_new0(struct listener_data, 1);
4177 ifdata->index = index;
4178 ifdata->udp4_listener_channel = NULL;
4179 ifdata->udp4_listener_watch = 0;
4180 ifdata->tcp4_listener_channel = NULL;
4181 ifdata->tcp4_listener_watch = 0;
4182 ifdata->udp6_listener_channel = NULL;
4183 ifdata->udp6_listener_watch = 0;
4184 ifdata->tcp6_listener_channel = NULL;
4185 ifdata->tcp6_listener_watch = 0;
4187 err = create_listener(ifdata);
4189 connman_error("Couldn't create listener for index %d err %d",
4194 g_hash_table_insert(listener_table, GINT_TO_POINTER(ifdata->index),
4199 void __connman_dnsproxy_remove_listener(int index)
4201 struct listener_data *ifdata;
4203 DBG("index %d", index);
4205 if (!listener_table)
4208 ifdata = g_hash_table_lookup(listener_table, GINT_TO_POINTER(index));
4212 destroy_listener(ifdata);
4214 g_hash_table_remove(listener_table, GINT_TO_POINTER(index));
4217 static void remove_listener(gpointer key, gpointer value, gpointer user_data)
4219 int index = GPOINTER_TO_INT(key);
4220 struct listener_data *ifdata = value;
4222 DBG("index %d", index);
4224 destroy_listener(ifdata);
4227 static void free_partial_reqs(gpointer value)
4229 struct tcp_partial_client_data *data = value;
4235 int __connman_dnsproxy_init(void)
4241 listener_table = g_hash_table_new_full(g_direct_hash, g_direct_equal,
4244 partial_tcp_req_table = g_hash_table_new_full(g_direct_hash,
4249 index = connman_inet_ifindex("lo");
4250 err = __connman_dnsproxy_add_listener(index);
4254 err = connman_notifier_register(&dnsproxy_notifier);
4261 __connman_dnsproxy_remove_listener(index);
4262 g_hash_table_destroy(listener_table);
4263 g_hash_table_destroy(partial_tcp_req_table);
4268 void __connman_dnsproxy_cleanup(void)
4273 g_source_remove(cache_timer);
4278 g_hash_table_destroy(cache);
4282 connman_notifier_unregister(&dnsproxy_notifier);
4284 g_hash_table_foreach(listener_table, remove_listener, NULL);
4286 g_hash_table_destroy(listener_table);
4288 g_hash_table_destroy(partial_tcp_req_table);