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, size_t max_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,
879 name, max_name, name_len);
881 unsigned label_len = *p;
883 if (pkt + label_len > max)
886 if (*output_len > output_max)
889 if ((*name_len + 1 + label_len + 1) > max_name)
893 * We need the original name in order to check
894 * if this answer is the correct one.
896 name[(*name_len)++] = label_len;
897 memcpy(name + *name_len, p + 1, label_len + 1);
898 *name_len += label_len;
900 /* We compress the result */
901 output[0] = NS_CMPRSFLGS;
918 static int parse_rr(unsigned char *buf, unsigned char *start,
920 unsigned char *response, unsigned int *response_size,
921 uint16_t *type, uint16_t *class, int *ttl, int *rdlen,
923 char *name, size_t max_name)
925 struct domain_rr *rr;
927 int name_len = 0, output_len = 0, max_rsp = *response_size;
929 err = get_name(0, buf, start, max, response, max_rsp,
930 &output_len, end, name, max_name, &name_len);
936 if ((unsigned int) offset > *response_size)
939 rr = (void *) (*end);
944 *type = ntohs(rr->type);
945 *class = ntohs(rr->class);
946 *ttl = ntohl(rr->ttl);
947 *rdlen = ntohs(rr->rdlen);
952 memcpy(response + offset, *end, sizeof(struct domain_rr));
954 offset += sizeof(struct domain_rr);
955 *end += sizeof(struct domain_rr);
957 if ((unsigned int) (offset + *rdlen) > *response_size)
960 memcpy(response + offset, *end, *rdlen);
964 *response_size = offset + *rdlen;
969 static bool check_alias(GSList *aliases, char *name)
974 for (list = aliases; list; list = list->next) {
975 int len = strlen((char *)list->data);
976 if (strncmp((char *)list->data, name, len) == 0)
984 static int parse_response(unsigned char *buf, int buflen,
985 char *question, int qlen,
986 uint16_t *type, uint16_t *class, int *ttl,
987 unsigned char *response, unsigned int *response_len,
990 struct domain_hdr *hdr = (void *) buf;
991 struct domain_question *q;
993 uint16_t qdcount = ntohs(hdr->qdcount);
994 uint16_t ancount = ntohs(hdr->ancount);
996 uint16_t qtype, qclass;
997 unsigned char *next = NULL;
998 unsigned int maxlen = *response_len;
999 GSList *aliases = NULL, *list;
1000 char name[NS_MAXDNAME + 1];
1005 DBG("qr %d qdcount %d", hdr->qr, qdcount);
1007 /* We currently only cache responses where question count is 1 */
1008 if (hdr->qr != 1 || qdcount != 1)
1011 ptr = buf + sizeof(struct domain_hdr);
1013 strncpy(question, (char *) ptr, qlen);
1014 qlen = strlen(question);
1015 ptr += qlen + 1; /* skip \0 */
1018 qtype = ntohs(q->type);
1020 /* We cache only A and AAAA records */
1021 if (qtype != 1 && qtype != 28)
1024 qclass = ntohs(q->class);
1026 ptr += 2 + 2; /* ptr points now to answers */
1032 memset(name, 0, sizeof(name));
1035 * We have a bunch of answers (like A, AAAA, CNAME etc) to
1036 * A or AAAA question. We traverse the answers and parse the
1037 * resource records. Only A and AAAA records are cached, all
1038 * the other records in answers are skipped.
1040 for (i = 0; i < ancount; i++) {
1042 * Get one address at a time to this buffer.
1043 * The max size of the answer is
1044 * 2 (pointer) + 2 (type) + 2 (class) +
1045 * 4 (ttl) + 2 (rdlen) + addr (16 or 4) = 28
1046 * for A or AAAA record.
1047 * For CNAME the size can be bigger.
1049 unsigned char rsp[NS_MAXCDNAME];
1050 unsigned int rsp_len = sizeof(rsp) - 1;
1053 memset(rsp, 0, sizeof(rsp));
1055 ret = parse_rr(buf, ptr, buf + buflen, rsp, &rsp_len,
1056 type, class, ttl, &rdlen, &next, name,
1064 * Now rsp contains compressed or uncompressed resource
1065 * record. Next we check if this record answers the question.
1066 * The name var contains the uncompressed label.
1067 * One tricky bit is the CNAME records as they alias
1068 * the name we might be interested in.
1072 * Go to next answer if the class is not the one we are
1075 if (*class != qclass) {
1082 * Try to resolve aliases also, type is CNAME(5).
1083 * This is important as otherwise the aliased names would not
1084 * be cached at all as the cache would not contain the aliased
1087 * If any CNAME is found in DNS packet, then we cache the alias
1088 * IP address instead of the question (as the server
1089 * said that question has only an alias).
1090 * This means in practice that if e.g., ipv6.google.com is
1091 * queried, DNS server returns CNAME of that name which is
1092 * ipv6.l.google.com. We then cache the address of the CNAME
1093 * but return the question name to client. So the alias
1094 * status of the name is not saved in cache and thus not
1095 * returned to the client. We do not return DNS packets from
1096 * cache to client saying that ipv6.google.com is an alias to
1097 * ipv6.l.google.com but we return instead a DNS packet that
1098 * says ipv6.google.com has address xxx which is in fact the
1099 * address of ipv6.l.google.com. For caching purposes this
1100 * should not cause any issues.
1102 if (*type == 5 && strncmp(question, name, qlen) == 0) {
1104 * So now the alias answered the question. This is
1105 * not very useful from caching point of view as
1106 * the following A or AAAA records will not match the
1107 * question. We need to find the real A/AAAA record
1108 * of the alias and cache that.
1110 unsigned char *end = NULL;
1111 int name_len = 0, output_len = 0;
1113 memset(rsp, 0, sizeof(rsp));
1114 rsp_len = sizeof(rsp) - 1;
1117 * Alias is in rdata part of the message,
1118 * and next-rdlen points to it. So we need to get
1119 * the real name of the alias.
1121 ret = get_name(0, buf, next - rdlen, buf + buflen,
1122 rsp, rsp_len, &output_len, &end,
1123 name, sizeof(name) - 1, &name_len);
1125 /* just ignore the error at this point */
1132 * We should now have the alias of the entry we might
1133 * want to cache. Just remember it for a while.
1134 * We check the alias list when we have parsed the
1137 aliases = g_slist_prepend(aliases, g_strdup(name));
1144 if (*type == qtype) {
1146 * We found correct type (A or AAAA)
1148 if (check_alias(aliases, name) ||
1149 (!aliases && strncmp(question, name,
1152 * We found an alias or the name of the rr
1153 * matches the question. If so, we append
1154 * the compressed label to the cache.
1155 * The end result is a response buffer that
1156 * will contain one or more cached and
1157 * compressed resource records.
1159 if (*response_len + rsp_len > maxlen) {
1163 memcpy(response + *response_len, rsp, rsp_len);
1164 *response_len += rsp_len;
1175 for (list = aliases; list; list = list->next)
1177 g_slist_free(aliases);
1182 struct cache_timeout {
1183 time_t current_time;
1188 static gboolean cache_check_entry(gpointer key, gpointer value,
1191 struct cache_timeout *data = user_data;
1192 struct cache_entry *entry = value;
1195 /* Scale the number of hits by half as part of cache aging */
1200 * If either IPv4 or IPv6 cached entry has expired, we
1201 * remove both from the cache.
1204 if (entry->ipv4 && entry->ipv4->timeout > 0) {
1205 max_timeout = entry->ipv4->cache_until;
1206 if (max_timeout > data->max_timeout)
1207 data->max_timeout = max_timeout;
1209 if (entry->ipv4->cache_until < data->current_time)
1213 if (entry->ipv6 && entry->ipv6->timeout > 0) {
1214 max_timeout = entry->ipv6->cache_until;
1215 if (max_timeout > data->max_timeout)
1216 data->max_timeout = max_timeout;
1218 if (entry->ipv6->cache_until < data->current_time)
1223 * if we're asked to try harder, also remove entries that have
1226 if (data->try_harder && entry->hits < 4)
1232 static void cache_cleanup(void)
1234 static int max_timeout;
1235 struct cache_timeout data;
1238 data.current_time = time(NULL);
1239 data.max_timeout = 0;
1240 data.try_harder = 0;
1243 * In the first pass, we only remove entries that have timed out.
1244 * We use a cache of the first time to expire to do this only
1245 * when it makes sense.
1247 if (max_timeout <= data.current_time) {
1248 count = g_hash_table_foreach_remove(cache, cache_check_entry,
1251 DBG("removed %d in the first pass", count);
1254 * In the second pass, if the first pass turned up blank,
1255 * we also expire entries with a low hit count,
1256 * while aging the hit count at the same time.
1258 data.try_harder = 1;
1260 count = g_hash_table_foreach_remove(cache, cache_check_entry,
1265 * If we could not remove anything, then remember
1266 * what is the max timeout and do nothing if we
1267 * have not yet reached it. This will prevent
1268 * constant traversal of the cache if it is full.
1270 max_timeout = data.max_timeout;
1275 static gboolean cache_invalidate_entry(gpointer key, gpointer value,
1278 struct cache_entry *entry = value;
1280 /* first, delete any expired elements */
1281 cache_enforce_validity(entry);
1283 /* if anything is not expired, mark the entry for refresh */
1284 if (entry->hits > 0 && (entry->ipv4 || entry->ipv6))
1285 entry->want_refresh = true;
1287 /* delete the cached data */
1289 g_free(entry->ipv4->data);
1290 g_free(entry->ipv4);
1295 g_free(entry->ipv6->data);
1296 g_free(entry->ipv6);
1300 /* keep the entry if we want it refreshed, delete it otherwise */
1301 if (entry->want_refresh)
1308 * cache_invalidate is called from places where the DNS landscape
1309 * has changed, say because connections are added or we entered a VPN.
1310 * The logic is to wipe all cache data, but mark all non-expired
1311 * parts of the cache for refresh rather than deleting the whole cache.
1313 static void cache_invalidate(void)
1315 DBG("Invalidating the DNS cache %p", cache);
1320 g_hash_table_foreach_remove(cache, cache_invalidate_entry, NULL);
1323 static void cache_refresh_entry(struct cache_entry *entry)
1326 cache_enforce_validity(entry);
1328 if (entry->hits > 2 && !entry->ipv4)
1329 entry->want_refresh = true;
1330 if (entry->hits > 2 && !entry->ipv6)
1331 entry->want_refresh = true;
1333 if (entry->want_refresh) {
1335 char dns_name[NS_MAXDNAME + 1];
1336 entry->want_refresh = false;
1338 /* turn a DNS name into a hostname with dots */
1339 strncpy(dns_name, entry->key, NS_MAXDNAME);
1347 DBG("Refreshing %s\n", dns_name);
1348 /* then refresh the hostname */
1349 refresh_dns_entry(entry, &dns_name[1]);
1353 static void cache_refresh_iterator(gpointer key, gpointer value,
1356 struct cache_entry *entry = value;
1358 cache_refresh_entry(entry);
1361 static void cache_refresh(void)
1366 g_hash_table_foreach(cache, cache_refresh_iterator, NULL);
1369 static int reply_query_type(unsigned char *msg, int len)
1375 /* skip the header */
1376 c = msg + sizeof(struct domain_hdr);
1377 len -= sizeof(struct domain_hdr);
1382 /* now the query, which is a name and 2 16 bit words */
1383 l = dns_name_length(c) + 1;
1385 type = c[0] << 8 | c[1];
1390 static int cache_update(struct server_data *srv, unsigned char *msg,
1391 unsigned int msg_len)
1393 int offset = protocol_offset(srv->protocol);
1394 int err, qlen, ttl = 0;
1395 uint16_t answers = 0, type = 0, class = 0;
1396 struct domain_hdr *hdr = (void *)(msg + offset);
1397 struct domain_question *q;
1398 struct cache_entry *entry;
1399 struct cache_data *data;
1400 char question[NS_MAXDNAME + 1];
1401 unsigned char response[NS_MAXDNAME + 1];
1403 unsigned int rsplen;
1404 bool new_entry = true;
1405 time_t current_time;
1407 if (cache_size >= MAX_CACHE_SIZE) {
1409 if (cache_size >= MAX_CACHE_SIZE)
1413 current_time = time(NULL);
1415 /* don't do a cache refresh more than twice a minute */
1416 if (next_refresh < current_time) {
1418 next_refresh = current_time + 30;
1424 DBG("offset %d hdr %p msg %p rcode %d", offset, hdr, msg, hdr->rcode);
1426 /* Continue only if response code is 0 (=ok) */
1427 if (hdr->rcode != ns_r_noerror)
1433 rsplen = sizeof(response) - 1;
1434 question[sizeof(question) - 1] = '\0';
1436 err = parse_response(msg + offset, msg_len - offset,
1437 question, sizeof(question) - 1,
1438 &type, &class, &ttl,
1439 response, &rsplen, &answers);
1442 * special case: if we do a ipv6 lookup and get no result
1443 * for a record that's already in our ipv4 cache.. we want
1444 * to cache the negative response.
1446 if ((err == -ENOMSG || err == -ENOBUFS) &&
1447 reply_query_type(msg + offset,
1448 msg_len - offset) == 28) {
1449 entry = g_hash_table_lookup(cache, question);
1450 if (entry && entry->ipv4 && !entry->ipv6) {
1451 int cache_offset = 0;
1453 data = g_try_new(struct cache_data, 1);
1456 data->inserted = entry->ipv4->inserted;
1458 data->answers = ntohs(hdr->ancount);
1459 data->timeout = entry->ipv4->timeout;
1460 if (srv->protocol == IPPROTO_UDP)
1462 data->data_len = msg_len + cache_offset;
1463 data->data = ptr = g_malloc(data->data_len);
1464 ptr[0] = (data->data_len - 2) / 256;
1465 ptr[1] = (data->data_len - 2) - ptr[0] * 256;
1466 if (srv->protocol == IPPROTO_UDP)
1468 data->valid_until = entry->ipv4->valid_until;
1469 data->cache_until = entry->ipv4->cache_until;
1470 memcpy(ptr, msg, msg_len);
1473 * we will get a "hit" when we serve the response
1477 if (entry->hits < 0)
1483 if (err < 0 || ttl == 0)
1486 qlen = strlen(question);
1489 * If the cache contains already data, check if the
1490 * type of the cached data is the same and do not add
1491 * to cache if data is already there.
1492 * This is needed so that we can cache both A and AAAA
1493 * records for the same name.
1495 entry = g_hash_table_lookup(cache, question);
1497 entry = g_try_new(struct cache_entry, 1);
1501 data = g_try_new(struct cache_data, 1);
1507 entry->key = g_strdup(question);
1508 entry->ipv4 = entry->ipv6 = NULL;
1509 entry->want_refresh = false;
1517 if (type == 1 && entry->ipv4)
1520 if (type == 28 && entry->ipv6)
1523 data = g_try_new(struct cache_data, 1);
1533 * compensate for the hit we'll get for serving
1534 * the response out of the cache
1537 if (entry->hits < 0)
1543 if (ttl < MIN_CACHE_TTL)
1544 ttl = MIN_CACHE_TTL;
1546 data->inserted = current_time;
1548 data->answers = answers;
1549 data->timeout = ttl;
1551 * The "2" in start of the length is the TCP offset. We allocate it
1552 * here even for UDP packet because it simplifies the sending
1555 data->data_len = 2 + 12 + qlen + 1 + 2 + 2 + rsplen;
1556 data->data = ptr = g_malloc(data->data_len);
1557 data->valid_until = current_time + ttl;
1560 * Restrict the cached DNS record TTL to some sane value
1561 * in order to prevent data staying in the cache too long.
1563 if (ttl > MAX_CACHE_TTL)
1564 ttl = MAX_CACHE_TTL;
1566 data->cache_until = round_down_ttl(current_time + ttl, ttl);
1576 * We cache the two extra bytes at the start of the message
1577 * in a TCP packet. When sending UDP packet, we skip the first
1578 * two bytes. This way we do not need to know the format
1579 * (UDP/TCP) of the cached message.
1581 if (srv->protocol == IPPROTO_UDP)
1582 memcpy(ptr + 2, msg, offset + 12);
1584 memcpy(ptr, msg, offset + 12);
1586 ptr[0] = (data->data_len - 2) / 256;
1587 ptr[1] = (data->data_len - 2) - ptr[0] * 256;
1588 if (srv->protocol == IPPROTO_UDP)
1591 memcpy(ptr + offset + 12, question, qlen + 1); /* copy also the \0 */
1593 q = (void *) (ptr + offset + 12 + qlen + 1);
1594 q->type = htons(type);
1595 q->class = htons(class);
1596 memcpy(ptr + offset + 12 + qlen + 1 + sizeof(struct domain_question),
1600 g_hash_table_replace(cache, entry->key, entry);
1604 DBG("cache %d %squestion \"%s\" type %d ttl %d size %zd packet %u "
1606 cache_size, new_entry ? "new " : "old ",
1607 question, type, ttl,
1608 sizeof(*entry) + sizeof(*data) + data->data_len + qlen,
1610 srv->protocol == IPPROTO_TCP ?
1611 (unsigned int)(data->data[0] * 256 + data->data[1]) :
1617 static int ns_resolv(struct server_data *server, struct request_data *req,
1618 gpointer request, gpointer name)
1621 int sk, err, type = 0;
1622 char *dot, *lookup = (char *) name;
1623 struct cache_entry *entry;
1625 entry = cache_check(request, &type, req->protocol);
1628 struct cache_data *data;
1630 DBG("cache hit %s type %s", lookup, type == 1 ? "A" : "AAAA");
1637 ttl_left = data->valid_until - time(NULL);
1641 if (data && req->protocol == IPPROTO_TCP) {
1642 send_cached_response(req->client_sk, data->data,
1643 data->data_len, NULL, 0, IPPROTO_TCP,
1644 req->srcid, data->answers, ttl_left);
1648 if (data && req->protocol == IPPROTO_UDP) {
1649 int udp_sk = get_req_udp_socket(req);
1654 send_cached_response(udp_sk, data->data,
1655 data->data_len, &req->sa, req->sa_len,
1656 IPPROTO_UDP, req->srcid, data->answers,
1662 #if defined TIZEN_EXT
1663 if (server->protocol == IPPROTO_UDP) {
1665 struct server_data *new_server = NULL;
1667 new_server = create_server_sec(server->index, NULL,
1668 server->server, IPPROTO_UDP);
1670 if (new_server != NULL) {
1671 for (domains = server->domains; domains;
1672 domains = domains->next) {
1673 char *dom = domains->data;
1675 DBG("Adding domain %s to %s",
1676 dom, new_server->server);
1678 new_server->domains = g_list_append(
1679 new_server->domains,
1683 server = new_server;
1687 sk = g_io_channel_unix_get_fd(server->channel);
1689 err = sendto(sk, request, req->request_len, MSG_NOSIGNAL,
1690 server->server_addr, server->server_addr_len);
1692 DBG("Cannot send message to server %s sock %d "
1693 "protocol %d (%s/%d)",
1694 server->server, sk, server->protocol,
1695 strerror(errno), errno);
1701 /* If we have more than one dot, we don't add domains */
1702 dot = strchr(lookup, '.');
1703 if (dot && dot != lookup + strlen(lookup) - 1)
1706 if (server->domains && server->domains->data)
1707 req->append_domain = true;
1709 for (list = server->domains; list; list = list->next) {
1711 unsigned char alt[1024];
1712 struct domain_hdr *hdr = (void *) &alt;
1713 int altlen, domlen, offset;
1715 domain = list->data;
1720 offset = protocol_offset(server->protocol);
1724 domlen = strlen(domain) + 1;
1728 alt[offset] = req->altid & 0xff;
1729 alt[offset + 1] = req->altid >> 8;
1731 memcpy(alt + offset + 2, request + offset + 2, 10);
1732 hdr->qdcount = htons(1);
1734 altlen = append_query(alt + offset + 12, sizeof(alt) - 12,
1741 memcpy(alt + offset + altlen,
1742 request + offset + altlen - domlen,
1743 req->request_len - altlen - offset + domlen);
1745 if (server->protocol == IPPROTO_TCP) {
1746 int req_len = req->request_len + domlen - 2;
1748 alt[0] = (req_len >> 8) & 0xff;
1749 alt[1] = req_len & 0xff;
1752 DBG("req %p dstid 0x%04x altid 0x%04x", req, req->dstid,
1755 err = send(sk, alt, req->request_len + domlen, MSG_NOSIGNAL);
1765 static char *convert_label(char *start, char *end, char *ptr, char *uptr,
1766 int remaining_len, int *used_comp, int *used_uncomp)
1769 char name[NS_MAXLABEL];
1771 pos = dn_expand((u_char *)start, (u_char *)end, (u_char *)ptr,
1774 DBG("uncompress error [%d/%s]", errno, strerror(errno));
1779 * We need to compress back the name so that we get back to internal
1780 * label presentation.
1782 comp_pos = dn_comp(name, (u_char *)uptr, remaining_len, NULL, NULL);
1784 DBG("compress error [%d/%s]", errno, strerror(errno));
1789 *used_uncomp = comp_pos;
1797 static char *uncompress(int16_t field_count, char *start, char *end,
1798 char *ptr, char *uncompressed, int uncomp_len,
1799 char **uncompressed_ptr)
1801 char *uptr = *uncompressed_ptr; /* position in result buffer */
1803 DBG("count %d ptr %p end %p uptr %p", field_count, ptr, end, uptr);
1805 while (field_count-- > 0 && ptr < end) {
1806 int dlen; /* data field length */
1807 int ulen; /* uncompress length */
1808 int pos; /* position in compressed string */
1809 char name[NS_MAXLABEL]; /* tmp label */
1810 uint16_t dns_type, dns_class;
1813 if (!convert_label(start, end, ptr, name, NS_MAXLABEL,
1818 * Copy the uncompressed resource record, type, class and \0 to
1822 ulen = strlen(name);
1823 strncpy(uptr, name, uncomp_len - (uptr - uncompressed));
1825 DBG("pos %d ulen %d left %d name %s", pos, ulen,
1826 (int)(uncomp_len - (uptr - uncompressed)), uptr);
1834 * We copy also the fixed portion of the result (type, class,
1835 * ttl, address length and the address)
1837 memcpy(uptr, ptr, NS_RRFIXEDSZ);
1839 dns_type = uptr[0] << 8 | uptr[1];
1840 dns_class = uptr[2] << 8 | uptr[3];
1842 if (dns_class != ns_c_in)
1845 ptr += NS_RRFIXEDSZ;
1846 uptr += NS_RRFIXEDSZ;
1849 * Then the variable portion of the result (data length).
1850 * Typically this portion is also compressed
1851 * so we need to uncompress it also when necessary.
1853 if (dns_type == ns_t_cname) {
1854 if (!convert_label(start, end, ptr, uptr,
1855 uncomp_len - (uptr - uncompressed),
1859 uptr[-2] = comp_pos << 8;
1860 uptr[-1] = comp_pos & 0xff;
1865 } else if (dns_type == ns_t_a || dns_type == ns_t_aaaa) {
1866 dlen = uptr[-2] << 8 | uptr[-1];
1868 if (ptr + dlen > end) {
1869 DBG("data len %d too long", dlen);
1873 memcpy(uptr, ptr, dlen);
1877 } else if (dns_type == ns_t_soa) {
1881 /* Primary name server expansion */
1882 if (!convert_label(start, end, ptr, uptr,
1883 uncomp_len - (uptr - uncompressed),
1887 total_len += comp_pos;
1888 len_ptr = &uptr[-2];
1892 /* Responsible authority's mailbox */
1893 if (!convert_label(start, end, ptr, uptr,
1894 uncomp_len - (uptr - uncompressed),
1898 total_len += comp_pos;
1903 * Copy rest of the soa fields (serial number,
1904 * refresh interval, retry interval, expiration
1905 * limit and minimum ttl). They are 20 bytes long.
1907 memcpy(uptr, ptr, 20);
1913 * Finally fix the length of the data part
1915 len_ptr[0] = total_len << 8;
1916 len_ptr[1] = total_len & 0xff;
1919 *uncompressed_ptr = uptr;
1928 static int strip_domains(char *name, char *answers, int maxlen)
1931 int name_len = strlen(name);
1932 char *ptr, *start = answers, *end = answers + maxlen;
1934 while (maxlen > 0) {
1935 ptr = strstr(answers, name);
1937 char *domain = ptr + name_len;
1940 int domain_len = strlen(domain);
1942 memmove(answers + name_len,
1943 domain + domain_len,
1944 end - (domain + domain_len));
1947 maxlen -= domain_len;
1951 answers += strlen(answers) + 1;
1952 answers += 2 + 2 + 4; /* skip type, class and ttl fields */
1954 data_len = answers[0] << 8 | answers[1];
1955 answers += 2; /* skip the length field */
1957 if (answers + data_len > end)
1960 answers += data_len;
1961 maxlen -= answers - ptr;
1967 static int forward_dns_reply(unsigned char *reply, int reply_len, int protocol,
1968 struct server_data *data)
1970 struct domain_hdr *hdr;
1971 struct request_data *req;
1972 int dns_id, sk, err, offset = protocol_offset(protocol);
1977 hdr = (void *)(reply + offset);
1978 dns_id = reply[offset] | reply[offset + 1] << 8;
1980 DBG("Received %d bytes (id 0x%04x)", reply_len, dns_id);
1982 req = find_request(dns_id);
1986 DBG("req %p dstid 0x%04x altid 0x%04x rcode %d",
1987 req, req->dstid, req->altid, hdr->rcode);
1989 reply[offset] = req->srcid & 0xff;
1990 reply[offset + 1] = req->srcid >> 8;
1994 if (hdr->rcode == ns_r_noerror || !req->resp) {
1995 unsigned char *new_reply = NULL;
1998 * If the domain name was append
1999 * remove it before forwarding the reply.
2000 * If there were more than one question, then this
2001 * domain name ripping can be hairy so avoid that
2002 * and bail out in that that case.
2004 * The reason we are doing this magic is that if the
2005 * user's DNS client tries to resolv hostname without
2006 * domain part, it also expects to get the result without
2007 * a domain name part.
2009 if (req->append_domain && ntohs(hdr->qdcount) == 1) {
2010 uint16_t domain_len = 0;
2011 uint16_t header_len;
2012 uint16_t dns_type, dns_class;
2013 uint8_t host_len, dns_type_pos;
2014 char uncompressed[NS_MAXDNAME], *uptr;
2015 char *ptr, *eom = (char *)reply + reply_len;
2018 * ptr points to the first char of the hostname.
2019 * ->hostname.domain.net
2021 header_len = offset + sizeof(struct domain_hdr);
2022 ptr = (char *)reply + header_len;
2026 domain_len = strnlen(ptr + 1 + host_len,
2027 reply_len - header_len);
2030 * If the query type is anything other than A or AAAA,
2031 * then bail out and pass the message as is.
2032 * We only want to deal with IPv4 or IPv6 addresses.
2034 dns_type_pos = host_len + 1 + domain_len + 1;
2036 dns_type = ptr[dns_type_pos] << 8 |
2037 ptr[dns_type_pos + 1];
2038 dns_class = ptr[dns_type_pos + 2] << 8 |
2039 ptr[dns_type_pos + 3];
2040 if (dns_type != ns_t_a && dns_type != ns_t_aaaa &&
2041 dns_class != ns_c_in) {
2042 DBG("Pass msg dns type %d class %d",
2043 dns_type, dns_class);
2048 * Remove the domain name and replace it by the end
2049 * of reply. Check if the domain is really there
2050 * before trying to copy the data. We also need to
2051 * uncompress the answers if necessary.
2052 * The domain_len can be 0 because if the original
2053 * query did not contain a domain name, then we are
2054 * sending two packets, first without the domain name
2055 * and the second packet with domain name.
2056 * The append_domain is set to true even if we sent
2057 * the first packet without domain name. In this
2058 * case we end up in this branch.
2060 if (domain_len > 0) {
2061 int len = host_len + 1;
2062 int new_len, fixed_len;
2066 * First copy host (without domain name) into
2069 uptr = &uncompressed[0];
2070 memcpy(uptr, ptr, len);
2072 uptr[len] = '\0'; /* host termination */
2076 * Copy type and class fields of the question.
2078 ptr += len + domain_len + 1;
2079 memcpy(uptr, ptr, NS_QFIXEDSZ);
2082 * ptr points to answers after this
2085 uptr += NS_QFIXEDSZ;
2087 fixed_len = answers - uncompressed;
2090 * We then uncompress the result to buffer
2091 * so that we can rip off the domain name
2092 * part from the question. First answers,
2093 * then name server (authority) information,
2094 * and finally additional record info.
2097 ptr = uncompress(ntohs(hdr->ancount),
2098 (char *)reply + offset, eom,
2099 ptr, uncompressed, NS_MAXDNAME,
2104 ptr = uncompress(ntohs(hdr->nscount),
2105 (char *)reply + offset, eom,
2106 ptr, uncompressed, NS_MAXDNAME,
2111 ptr = uncompress(ntohs(hdr->arcount),
2112 (char *)reply + offset, eom,
2113 ptr, uncompressed, NS_MAXDNAME,
2119 * The uncompressed buffer now contains almost
2120 * valid response. Final step is to get rid of
2121 * the domain name because at least glibc
2122 * gethostbyname() implementation does extra
2123 * checks and expects to find an answer without
2124 * domain name if we asked a query without
2125 * domain part. Note that glibc getaddrinfo()
2126 * works differently and accepts FQDN in answer
2128 new_len = strip_domains(uncompressed, answers,
2131 DBG("Corrupted packet");
2136 * Because we have now uncompressed the answers
2137 * we might have to create a bigger buffer to
2138 * hold all that data.
2141 reply_len = header_len + new_len + fixed_len;
2143 new_reply = g_try_malloc(reply_len);
2147 memcpy(new_reply, reply, header_len);
2148 memcpy(new_reply + header_len, uncompressed,
2149 new_len + fixed_len);
2159 req->resp = g_try_malloc(reply_len);
2163 memcpy(req->resp, reply, reply_len);
2164 req->resplen = reply_len;
2166 cache_update(data, reply, reply_len);
2172 if (req->numresp < req->numserv) {
2173 if (hdr->rcode > ns_r_noerror) {
2175 } else if (hdr->ancount == 0 && req->append_domain) {
2180 request_list = g_slist_remove(request_list, req);
2182 if (protocol == IPPROTO_UDP) {
2183 sk = get_req_udp_socket(req);
2188 err = sendto(sk, req->resp, req->resplen, 0,
2189 &req->sa, req->sa_len);
2191 sk = req->client_sk;
2192 err = send(sk, req->resp, req->resplen, MSG_NOSIGNAL);
2196 DBG("Cannot send msg, sk %d proto %d errno %d/%s", sk,
2197 protocol, errno, strerror(errno));
2199 DBG("proto %d sent %d bytes to %d", protocol, err, sk);
2201 destroy_request_data(req);
2206 static void server_destroy_socket(struct server_data *data)
2208 DBG("index %d server %s proto %d", data->index,
2209 data->server, data->protocol);
2211 if (data->watch > 0) {
2212 g_source_remove(data->watch);
2216 if (data->timeout > 0) {
2217 g_source_remove(data->timeout);
2221 if (data->channel) {
2222 g_io_channel_shutdown(data->channel, TRUE, NULL);
2223 g_io_channel_unref(data->channel);
2224 data->channel = NULL;
2227 g_free(data->incoming_reply);
2228 data->incoming_reply = NULL;
2231 static void destroy_server(struct server_data *server)
2233 DBG("index %d server %s sock %d", server->index, server->server,
2235 g_io_channel_unix_get_fd(server->channel): -1);
2237 server_list = g_slist_remove(server_list, server);
2238 server_destroy_socket(server);
2240 if (server->protocol == IPPROTO_UDP && server->enabled)
2241 DBG("Removing DNS server %s", server->server);
2243 g_free(server->server);
2244 g_list_free_full(server->domains, g_free);
2245 g_free(server->server_addr);
2248 * We do not remove cache right away but delay it few seconds.
2249 * The idea is that when IPv6 DNS server is added via RDNSS, it has a
2250 * lifetime. When the lifetime expires we decrease the refcount so it
2251 * is possible that the cache is then removed. Because a new DNS server
2252 * is usually created almost immediately we would then loose the cache
2253 * without any good reason. The small delay allows the new RDNSS to
2254 * create a new DNS server instance and the refcount does not go to 0.
2256 if (cache && !cache_timer)
2257 cache_timer = g_timeout_add_seconds(3, try_remove_cache, NULL);
2262 static gboolean udp_server_event(GIOChannel *channel, GIOCondition condition,
2265 unsigned char buf[4096];
2267 struct server_data *data = user_data;
2269 if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
2270 connman_error("Error with UDP server %s", data->server);
2271 server_destroy_socket(data);
2275 sk = g_io_channel_unix_get_fd(channel);
2277 len = recv(sk, buf, sizeof(buf), 0);
2281 err = forward_dns_reply(buf, len, IPPROTO_UDP, data);
2285 #if defined TIZEN_EXT
2288 for (list = server_list_sec; list; list = list->next) {
2289 struct server_data *new_data = list->data;
2291 if (new_data == data) {
2292 destroy_server_sec(data);
2301 static gboolean tcp_server_event(GIOChannel *channel, GIOCondition condition,
2305 struct server_data *server = user_data;
2307 sk = g_io_channel_unix_get_fd(channel);
2311 if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
2314 DBG("TCP server channel closed, sk %d", sk);
2317 * Discard any partial response which is buffered; better
2318 * to get a proper response from a working server.
2320 g_free(server->incoming_reply);
2321 server->incoming_reply = NULL;
2323 for (list = request_list; list; list = list->next) {
2324 struct request_data *req = list->data;
2325 struct domain_hdr *hdr;
2327 if (req->protocol == IPPROTO_UDP)
2334 * If we're not waiting for any further response
2335 * from another name server, then we send an error
2336 * response to the client.
2338 if (req->numserv && --(req->numserv))
2341 hdr = (void *) (req->request + 2);
2342 hdr->id = req->srcid;
2343 send_response(req->client_sk, req->request,
2344 req->request_len, NULL, 0, IPPROTO_TCP);
2346 request_list = g_slist_remove(request_list, req);
2349 destroy_server(server);
2354 if ((condition & G_IO_OUT) && !server->connected) {
2357 bool no_request_sent = true;
2358 struct server_data *udp_server;
2360 udp_server = find_server(server->index, server->server,
2363 for (domains = udp_server->domains; domains;
2364 domains = domains->next) {
2365 char *dom = domains->data;
2367 DBG("Adding domain %s to %s",
2368 dom, server->server);
2370 server->domains = g_list_append(server->domains,
2375 server->connected = true;
2376 server_list = g_slist_append(server_list, server);
2378 if (server->timeout > 0) {
2379 g_source_remove(server->timeout);
2380 server->timeout = 0;
2383 for (list = request_list; list; ) {
2384 struct request_data *req = list->data;
2387 if (req->protocol == IPPROTO_UDP) {
2392 DBG("Sending req %s over TCP", (char *)req->name);
2394 status = ns_resolv(server, req,
2395 req->request, req->name);
2398 * A cached result was sent,
2399 * so the request can be released
2402 request_list = g_slist_remove(request_list, req);
2403 destroy_request_data(req);
2412 no_request_sent = false;
2414 if (req->timeout > 0)
2415 g_source_remove(req->timeout);
2417 req->timeout = g_timeout_add_seconds(30,
2418 request_timeout, req);
2422 if (no_request_sent) {
2423 destroy_server(server);
2427 } else if (condition & G_IO_IN) {
2428 struct partial_reply *reply = server->incoming_reply;
2432 unsigned char reply_len_buf[2];
2435 bytes_recv = recv(sk, reply_len_buf, 2, MSG_PEEK);
2438 } else if (bytes_recv < 0) {
2439 if (errno == EAGAIN || errno == EWOULDBLOCK)
2442 connman_error("DNS proxy error %s",
2445 } else if (bytes_recv < 2)
2448 reply_len = reply_len_buf[1] | reply_len_buf[0] << 8;
2451 DBG("TCP reply %d bytes from %d", reply_len, sk);
2453 reply = g_try_malloc(sizeof(*reply) + reply_len + 2);
2457 reply->len = reply_len;
2458 reply->received = 0;
2460 server->incoming_reply = reply;
2463 while (reply->received < reply->len) {
2464 bytes_recv = recv(sk, reply->buf + reply->received,
2465 reply->len - reply->received, 0);
2467 connman_error("DNS proxy TCP disconnect");
2469 } else if (bytes_recv < 0) {
2470 if (errno == EAGAIN || errno == EWOULDBLOCK)
2473 connman_error("DNS proxy error %s",
2477 reply->received += bytes_recv;
2480 forward_dns_reply(reply->buf, reply->received, IPPROTO_TCP,
2484 server->incoming_reply = NULL;
2486 destroy_server(server);
2494 static gboolean tcp_idle_timeout(gpointer user_data)
2496 struct server_data *server = user_data;
2503 destroy_server(server);
2508 static int server_create_socket(struct server_data *data)
2513 DBG("index %d server %s proto %d", data->index,
2514 data->server, data->protocol);
2516 sk = socket(data->server_addr->sa_family,
2517 data->protocol == IPPROTO_TCP ? SOCK_STREAM : SOCK_DGRAM,
2521 connman_error("Failed to create server %s socket",
2523 server_destroy_socket(data);
2529 interface = connman_inet_ifname(data->index);
2531 if (setsockopt(sk, SOL_SOCKET, SO_BINDTODEVICE,
2533 strlen(interface) + 1) < 0) {
2535 connman_error("Failed to bind server %s "
2537 data->server, interface);
2539 server_destroy_socket(data);
2546 data->channel = g_io_channel_unix_new(sk);
2547 if (!data->channel) {
2548 connman_error("Failed to create server %s channel",
2551 server_destroy_socket(data);
2555 g_io_channel_set_close_on_unref(data->channel, TRUE);
2557 if (data->protocol == IPPROTO_TCP) {
2558 g_io_channel_set_flags(data->channel, G_IO_FLAG_NONBLOCK, NULL);
2559 data->watch = g_io_add_watch(data->channel,
2560 G_IO_OUT | G_IO_IN | G_IO_HUP | G_IO_NVAL | G_IO_ERR,
2561 tcp_server_event, data);
2562 data->timeout = g_timeout_add_seconds(30, tcp_idle_timeout,
2565 data->watch = g_io_add_watch(data->channel,
2566 G_IO_IN | G_IO_NVAL | G_IO_ERR | G_IO_HUP,
2567 udp_server_event, data);
2569 if (connect(sk, data->server_addr, data->server_addr_len) < 0) {
2572 if ((data->protocol == IPPROTO_TCP && errno != EINPROGRESS) ||
2573 data->protocol == IPPROTO_UDP) {
2575 connman_error("Failed to connect to server %s",
2577 server_destroy_socket(data);
2587 #if defined TIZEN_EXT
2589 static void destroy_server_sec(struct server_data *server)
2594 if (server->channel)
2595 fd = g_io_channel_unix_get_fd(server->channel);
2599 DBG("index %d server %s sock %d", server->index, server->server, fd);
2601 server_list_sec = g_slist_remove(server_list_sec, server);
2606 server_destroy_socket(server);
2608 if (server->protocol == IPPROTO_UDP && server->enabled)
2609 DBG("Removing DNS server %s", server->server);
2611 g_free(server->server);
2612 for (list = server->domains; list; list = list->next) {
2613 char *domain = list->data;
2615 server->domains = g_list_remove(server->domains, domain);
2618 g_free(server->server_addr);
2621 * We do not remove cache right away but delay it few seconds.
2622 * The idea is that when IPv6 DNS server is added via RDNSS, it has a
2623 * lifetime. When the lifetime expires we decrease the refcount so it
2624 * is possible that the cache is then removed. Because a new DNS server
2625 * is usually created almost immediately we would then loose the cache
2626 * without any good reason. The small delay allows the new RDNSS to
2627 * create a new DNS server instance and the refcount does not go to 0.
2629 /* TODO: Need to check this */
2630 /* g_timeout_add_seconds(3, try_remove_cache, NULL); */
2635 static void destroy_all_server_sec()
2639 DBG("remove all dns server");
2641 for (list = server_list_sec; list; list = list->next) {
2642 struct server_data *server = list->data;
2643 destroy_server_sec(server);
2645 server_list_sec = NULL;
2648 static gboolean sec_udp_idle_timeout(gpointer user_data)
2650 struct server_data *server = user_data;
2657 destroy_server_sec(server);
2662 static struct server_data *create_server_sec(int index,
2663 const char *domain, const char *server,
2666 struct server_data *data;
2667 struct addrinfo hints, *rp;
2670 DBG("index %d server %s", index, server);
2672 data = g_try_new0(struct server_data, 1);
2674 connman_error("Failed to allocate server %s data", server);
2678 data->index = index;
2680 data->domains = g_list_append(data->domains, g_strdup(domain));
2681 data->server = g_strdup(server);
2682 data->protocol = protocol;
2684 memset(&hints, 0, sizeof(hints));
2688 hints.ai_socktype = SOCK_DGRAM;
2692 hints.ai_socktype = SOCK_STREAM;
2696 destroy_server_sec(data);
2699 hints.ai_family = AF_UNSPEC;
2700 hints.ai_flags = AI_NUMERICSERV | AI_NUMERICHOST;
2702 ret = getaddrinfo(data->server, "53", &hints, &rp);
2704 connman_error("Failed to parse server %s address: %s\n",
2705 data->server, gai_strerror(ret));
2707 destroy_server_sec(data);
2711 /* Do not blindly copy this code elsewhere; it doesn't loop over the
2712 results using ->ai_next as it should. That's OK in *this* case
2713 because it was a numeric lookup; we *know* there's only one. */
2715 data->server_addr_len = rp->ai_addrlen;
2717 switch (rp->ai_family) {
2719 data->server_addr = (struct sockaddr *)
2720 g_try_new0(struct sockaddr_in, 1);
2723 data->server_addr = (struct sockaddr *)
2724 g_try_new0(struct sockaddr_in6, 1);
2727 connman_error("Wrong address family %d", rp->ai_family);
2730 if (data->server_addr == NULL) {
2732 destroy_server_sec(data);
2735 memcpy(data->server_addr, rp->ai_addr, rp->ai_addrlen);
2738 if (server_create_socket(data) != 0) {
2739 destroy_server_sec(data);
2743 if (protocol == IPPROTO_UDP) {
2744 /* Enable new servers by default */
2745 data->enabled = TRUE;
2746 DBG("Adding DNS server %s", data->server);
2748 data->timeout = g_timeout_add_seconds(30, sec_udp_idle_timeout,
2751 server_list_sec = g_slist_append(server_list_sec, data);
2758 static struct server_data *create_server(int index,
2759 const char *domain, const char *server,
2762 struct server_data *data;
2763 struct addrinfo hints, *rp;
2766 DBG("index %d server %s", index, server);
2768 data = g_try_new0(struct server_data, 1);
2770 connman_error("Failed to allocate server %s data", server);
2774 data->index = index;
2776 data->domains = g_list_append(data->domains, g_strdup(domain));
2777 data->server = g_strdup(server);
2778 data->protocol = protocol;
2780 memset(&hints, 0, sizeof(hints));
2784 hints.ai_socktype = SOCK_DGRAM;
2788 hints.ai_socktype = SOCK_STREAM;
2792 destroy_server(data);
2795 hints.ai_family = AF_UNSPEC;
2796 hints.ai_flags = AI_NUMERICSERV | AI_NUMERICHOST;
2798 ret = getaddrinfo(data->server, "53", &hints, &rp);
2800 connman_error("Failed to parse server %s address: %s\n",
2801 data->server, gai_strerror(ret));
2802 destroy_server(data);
2806 /* Do not blindly copy this code elsewhere; it doesn't loop over the
2807 results using ->ai_next as it should. That's OK in *this* case
2808 because it was a numeric lookup; we *know* there's only one. */
2810 data->server_addr_len = rp->ai_addrlen;
2812 switch (rp->ai_family) {
2814 data->server_addr = (struct sockaddr *)
2815 g_try_new0(struct sockaddr_in, 1);
2818 data->server_addr = (struct sockaddr *)
2819 g_try_new0(struct sockaddr_in6, 1);
2822 connman_error("Wrong address family %d", rp->ai_family);
2825 if (!data->server_addr) {
2827 destroy_server(data);
2830 memcpy(data->server_addr, rp->ai_addr, rp->ai_addrlen);
2833 if (server_create_socket(data) != 0) {
2834 destroy_server(data);
2838 if (protocol == IPPROTO_UDP) {
2839 if (__connman_service_index_is_default(data->index) ||
2840 __connman_service_index_is_split_routing(
2842 data->enabled = true;
2843 DBG("Adding DNS server %s", data->server);
2846 server_list = g_slist_append(server_list, data);
2852 static bool resolv(struct request_data *req,
2853 gpointer request, gpointer name)
2857 for (list = server_list; list; list = list->next) {
2858 struct server_data *data = list->data;
2860 if (data->protocol == IPPROTO_TCP) {
2861 DBG("server %s ignored proto TCP", data->server);
2865 DBG("server %s enabled %d", data->server, data->enabled);
2870 if (!data->channel && data->protocol == IPPROTO_UDP) {
2871 if (server_create_socket(data) < 0) {
2872 DBG("socket creation failed while resolving");
2877 if (ns_resolv(data, req, request, name) > 0)
2884 static void append_domain(int index, const char *domain)
2888 DBG("index %d domain %s", index, domain);
2893 for (list = server_list; list; list = list->next) {
2894 struct server_data *data = list->data;
2897 bool dom_found = false;
2899 if (data->index < 0)
2902 if (data->index != index)
2905 for (dom_list = data->domains; dom_list;
2906 dom_list = dom_list->next) {
2907 dom = dom_list->data;
2909 if (g_str_equal(dom, domain)) {
2917 g_list_append(data->domains, g_strdup(domain));
2922 static void flush_requests(struct server_data *server)
2926 list = request_list;
2928 struct request_data *req = list->data;
2932 if (ns_resolv(server, req, req->request, req->name)) {
2934 * A cached result was sent,
2935 * so the request can be released
2938 g_slist_remove(request_list, req);
2939 destroy_request_data(req);
2943 if (req->timeout > 0)
2944 g_source_remove(req->timeout);
2946 req->timeout = g_timeout_add_seconds(5, request_timeout, req);
2950 int __connman_dnsproxy_append(int index, const char *domain,
2953 struct server_data *data;
2955 DBG("index %d server %s", index, server);
2957 if (!server && !domain)
2961 append_domain(index, domain);
2966 if (g_str_equal(server, "127.0.0.1"))
2969 if (g_str_equal(server, "::1"))
2972 data = find_server(index, server, IPPROTO_UDP);
2974 append_domain(index, domain);
2978 data = create_server(index, domain, server, IPPROTO_UDP);
2982 flush_requests(data);
2987 static void remove_server(int index, const char *domain,
2988 const char *server, int protocol)
2990 struct server_data *data;
2992 data = find_server(index, server, protocol);
2996 destroy_server(data);
2999 int __connman_dnsproxy_remove(int index, const char *domain,
3002 DBG("index %d server %s", index, server);
3007 if (g_str_equal(server, "127.0.0.1"))
3010 if (g_str_equal(server, "::1"))
3013 remove_server(index, domain, server, IPPROTO_UDP);
3014 remove_server(index, domain, server, IPPROTO_TCP);
3016 #if defined TIZEN_EXT
3017 destroy_all_server_sec();
3023 static void dnsproxy_offline_mode(bool enabled)
3027 DBG("enabled %d", enabled);
3029 for (list = server_list; list; list = list->next) {
3030 struct server_data *data = list->data;
3033 DBG("Enabling DNS server %s", data->server);
3034 data->enabled = true;
3038 DBG("Disabling DNS server %s", data->server);
3039 data->enabled = false;
3045 static void dnsproxy_default_changed(struct connman_service *service)
3050 DBG("service %p", service);
3052 /* DNS has changed, invalidate the cache */
3056 /* When no services are active, then disable DNS proxying */
3057 dnsproxy_offline_mode(true);
3061 index = __connman_service_get_index(service);
3065 for (list = server_list; list; list = list->next) {
3066 struct server_data *data = list->data;
3068 if (data->index == index) {
3069 DBG("Enabling DNS server %s", data->server);
3070 data->enabled = true;
3072 DBG("Disabling DNS server %s", data->server);
3073 data->enabled = false;
3080 static struct connman_notifier dnsproxy_notifier = {
3082 .default_changed = dnsproxy_default_changed,
3083 .offline_mode = dnsproxy_offline_mode,
3086 static unsigned char opt_edns0_type[2] = { 0x00, 0x29 };
3088 static int parse_request(unsigned char *buf, int len,
3089 char *name, unsigned int size)
3091 struct domain_hdr *hdr = (void *) buf;
3092 uint16_t qdcount = ntohs(hdr->qdcount);
3093 uint16_t arcount = ntohs(hdr->arcount);
3095 char *last_label = NULL;
3096 unsigned int remain, used = 0;
3101 DBG("id 0x%04x qr %d opcode %d qdcount %d arcount %d",
3102 hdr->id, hdr->qr, hdr->opcode,
3105 if (hdr->qr != 0 || qdcount != 1)
3110 ptr = buf + sizeof(struct domain_hdr);
3111 remain = len - sizeof(struct domain_hdr);
3113 while (remain > 0) {
3114 uint8_t label_len = *ptr;
3116 if (label_len == 0x00) {
3117 last_label = (char *) (ptr + 1);
3121 if (used + label_len + 1 > size)
3124 strncat(name, (char *) (ptr + 1), label_len);
3127 used += label_len + 1;
3129 ptr += label_len + 1;
3130 remain -= label_len + 1;
3133 if (last_label && arcount && remain >= 9 && last_label[4] == 0 &&
3134 !memcmp(last_label + 5, opt_edns0_type, 2)) {
3135 uint16_t edns0_bufsize;
3137 edns0_bufsize = last_label[7] << 8 | last_label[8];
3139 DBG("EDNS0 buffer size %u", edns0_bufsize);
3141 /* This is an evil hack until full TCP support has been
3144 * Somtimes the EDNS0 request gets send with a too-small
3145 * buffer size. Since glibc doesn't seem to crash when it
3146 * gets a response biffer then it requested, just bump
3147 * the buffer size up to 4KiB.
3149 if (edns0_bufsize < 0x1000) {
3150 last_label[7] = 0x10;
3151 last_label[8] = 0x00;
3155 DBG("query %s", name);
3160 static void client_reset(struct tcp_partial_client_data *client)
3165 if (client->channel) {
3166 DBG("client %d closing",
3167 g_io_channel_unix_get_fd(client->channel));
3169 g_io_channel_unref(client->channel);
3170 client->channel = NULL;
3173 if (client->watch > 0) {
3174 g_source_remove(client->watch);
3178 if (client->timeout > 0) {
3179 g_source_remove(client->timeout);
3180 client->timeout = 0;
3183 g_free(client->buf);
3186 client->buf_end = 0;
3189 static unsigned int get_msg_len(unsigned char *buf)
3191 return buf[0]<<8 | buf[1];
3194 static bool read_tcp_data(struct tcp_partial_client_data *client,
3195 void *client_addr, socklen_t client_addr_len,
3198 char query[TCP_MAX_BUF_LEN];
3199 struct request_data *req;
3201 unsigned int msg_len;
3203 bool waiting_for_connect = false;
3205 struct cache_entry *entry;
3207 client_sk = g_io_channel_unix_get_fd(client->channel);
3209 if (read_len == 0) {
3210 DBG("client %d closed, pending %d bytes",
3211 client_sk, client->buf_end);
3212 g_hash_table_remove(partial_tcp_req_table,
3213 GINT_TO_POINTER(client_sk));
3217 DBG("client %d received %d bytes", client_sk, read_len);
3219 client->buf_end += read_len;
3221 if (client->buf_end < 2)
3224 msg_len = get_msg_len(client->buf);
3225 if (msg_len > TCP_MAX_BUF_LEN) {
3226 DBG("client %d sent too much data %d", client_sk, msg_len);
3227 g_hash_table_remove(partial_tcp_req_table,
3228 GINT_TO_POINTER(client_sk));
3233 DBG("client %d msg len %d end %d past end %d", client_sk, msg_len,
3234 client->buf_end, client->buf_end - (msg_len + 2));
3236 if (client->buf_end < (msg_len + 2)) {
3237 DBG("client %d still missing %d bytes",
3239 msg_len + 2 - client->buf_end);
3243 DBG("client %d all data %d received", client_sk, msg_len);
3245 err = parse_request(client->buf + 2, msg_len,
3246 query, sizeof(query));
3247 if (err < 0 || (g_slist_length(server_list) == 0)) {
3248 send_response(client_sk, client->buf, msg_len + 2,
3249 NULL, 0, IPPROTO_TCP);
3253 req = g_try_new0(struct request_data, 1);
3257 memcpy(&req->sa, client_addr, client_addr_len);
3258 req->sa_len = client_addr_len;
3259 req->client_sk = client_sk;
3260 req->protocol = IPPROTO_TCP;
3261 req->family = client->family;
3263 req->srcid = client->buf[2] | (client->buf[3] << 8);
3264 req->dstid = get_id();
3265 req->altid = get_id();
3266 req->request_len = msg_len + 2;
3268 client->buf[2] = req->dstid & 0xff;
3269 client->buf[3] = req->dstid >> 8;
3272 req->ifdata = client->ifdata;
3273 req->append_domain = false;
3276 * Check if the answer is found in the cache before
3277 * creating sockets to the server.
3279 entry = cache_check(client->buf, &qtype, IPPROTO_TCP);
3282 struct cache_data *data;
3284 DBG("cache hit %s type %s", query, qtype == 1 ? "A" : "AAAA");
3291 ttl_left = data->valid_until - time(NULL);
3294 send_cached_response(client_sk, data->data,
3295 data->data_len, NULL, 0, IPPROTO_TCP,
3296 req->srcid, data->answers, ttl_left);
3301 DBG("data missing, ignoring cache for this query");
3304 for (list = server_list; list; list = list->next) {
3305 struct server_data *data = list->data;
3307 if (data->protocol != IPPROTO_UDP || !data->enabled)
3310 if (!create_server(data->index, NULL, data->server,
3314 waiting_for_connect = true;
3317 if (!waiting_for_connect) {
3318 /* No server is waiting for connect */
3319 send_response(client_sk, client->buf,
3320 req->request_len, NULL, 0, IPPROTO_TCP);
3326 * The server is not connected yet.
3327 * Copy the relevant buffers.
3328 * The request will actually be sent once we're
3329 * properly connected over TCP to the nameserver.
3331 req->request = g_try_malloc0(req->request_len);
3332 if (!req->request) {
3333 send_response(client_sk, client->buf,
3334 req->request_len, NULL, 0, IPPROTO_TCP);
3338 memcpy(req->request, client->buf, req->request_len);
3340 req->name = g_try_malloc0(sizeof(query));
3342 send_response(client_sk, client->buf,
3343 req->request_len, NULL, 0, IPPROTO_TCP);
3344 g_free(req->request);
3348 memcpy(req->name, query, sizeof(query));
3350 req->timeout = g_timeout_add_seconds(30, request_timeout, req);
3352 request_list = g_slist_append(request_list, req);
3355 if (client->buf_end > (msg_len + 2)) {
3356 DBG("client %d buf %p -> %p end %d len %d new %d",
3358 client->buf + msg_len + 2,
3359 client->buf, client->buf_end,
3360 TCP_MAX_BUF_LEN - client->buf_end,
3361 client->buf_end - (msg_len + 2));
3362 memmove(client->buf, client->buf + msg_len + 2,
3363 TCP_MAX_BUF_LEN - client->buf_end);
3364 client->buf_end = client->buf_end - (msg_len + 2);
3367 * If we have a full message waiting, just read it
3370 msg_len = get_msg_len(client->buf);
3371 if ((msg_len + 2) == client->buf_end) {
3372 DBG("client %d reading another %d bytes", client_sk,
3377 DBG("client %d clearing reading buffer", client_sk);
3379 client->buf_end = 0;
3380 memset(client->buf, 0, TCP_MAX_BUF_LEN);
3383 * We received all the packets from client so we must also
3384 * remove the timeout handler here otherwise we might get
3385 * timeout while waiting the results from server.
3387 g_source_remove(client->timeout);
3388 client->timeout = 0;
3394 static gboolean tcp_client_event(GIOChannel *channel, GIOCondition condition,
3397 struct tcp_partial_client_data *client = user_data;
3398 struct sockaddr_in6 client_addr6;
3399 socklen_t client_addr6_len = sizeof(client_addr6);
3400 struct sockaddr_in client_addr4;
3401 socklen_t client_addr4_len = sizeof(client_addr4);
3403 socklen_t *client_addr_len;
3406 client_sk = g_io_channel_unix_get_fd(channel);
3408 if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
3409 g_hash_table_remove(partial_tcp_req_table,
3410 GINT_TO_POINTER(client_sk));
3412 connman_error("Error with TCP client %d channel", client_sk);
3416 switch (client->family) {
3418 client_addr = &client_addr4;
3419 client_addr_len = &client_addr4_len;
3422 client_addr = &client_addr6;
3423 client_addr_len = &client_addr6_len;
3426 g_hash_table_remove(partial_tcp_req_table,
3427 GINT_TO_POINTER(client_sk));
3428 connman_error("client %p corrupted", client);
3432 len = recvfrom(client_sk, client->buf + client->buf_end,
3433 TCP_MAX_BUF_LEN - client->buf_end, 0,
3434 client_addr, client_addr_len);
3436 if (errno == EAGAIN || errno == EWOULDBLOCK)
3439 DBG("client %d cannot read errno %d/%s", client_sk, -errno,
3441 g_hash_table_remove(partial_tcp_req_table,
3442 GINT_TO_POINTER(client_sk));
3446 return read_tcp_data(client, client_addr, *client_addr_len, len);
3449 static gboolean client_timeout(gpointer user_data)
3451 struct tcp_partial_client_data *client = user_data;
3454 sock = g_io_channel_unix_get_fd(client->channel);
3456 DBG("client %d timeout pending %d bytes", sock, client->buf_end);
3458 g_hash_table_remove(partial_tcp_req_table, GINT_TO_POINTER(sock));
3463 #if defined TIZEN_EXT
3464 static void recover_listener(GIOChannel *channel, struct listener_data *ifdata)
3468 index = ifdata->index;
3470 sk = g_io_channel_unix_get_fd(channel);
3473 __connman_dnsproxy_remove_listener(index);
3475 if (__connman_dnsproxy_add_listener(index) == 0)
3476 DBG("listener %d successfully recovered", index);
3480 static bool tcp_listener_event(GIOChannel *channel, GIOCondition condition,
3481 struct listener_data *ifdata, int family,
3482 guint *listener_watch)
3484 int sk, client_sk, len;
3485 unsigned int msg_len;
3486 struct tcp_partial_client_data *client;
3487 struct sockaddr_in6 client_addr6;
3488 socklen_t client_addr6_len = sizeof(client_addr6);
3489 struct sockaddr_in client_addr4;
3490 socklen_t client_addr4_len = sizeof(client_addr4);
3492 socklen_t *client_addr_len;
3496 DBG("condition 0x%02x channel %p ifdata %p family %d",
3497 condition, channel, ifdata, family);
3499 if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
3500 #if defined TIZEN_EXT
3501 connman_error("Error %d with TCP listener channel", condition);
3503 recover_listener(channel, ifdata);
3505 if (*listener_watch > 0)
3506 g_source_remove(*listener_watch);
3507 *listener_watch = 0;
3509 connman_error("Error with TCP listener channel");
3515 sk = g_io_channel_unix_get_fd(channel);
3517 if (family == AF_INET) {
3518 client_addr = &client_addr4;
3519 client_addr_len = &client_addr4_len;
3521 client_addr = &client_addr6;
3522 client_addr_len = &client_addr6_len;
3525 tv.tv_sec = tv.tv_usec = 0;
3527 FD_SET(sk, &readfds);
3529 select(sk + 1, &readfds, NULL, NULL, &tv);
3530 if (FD_ISSET(sk, &readfds)) {
3531 client_sk = accept(sk, client_addr, client_addr_len);
3532 DBG("client %d accepted", client_sk);
3534 DBG("No data to read from master %d, waiting.", sk);
3538 if (client_sk < 0) {
3539 connman_error("Accept failure on TCP listener");
3540 *listener_watch = 0;
3544 fcntl(client_sk, F_SETFL, O_NONBLOCK);
3546 client = g_hash_table_lookup(partial_tcp_req_table,
3547 GINT_TO_POINTER(client_sk));
3549 client = g_try_new0(struct tcp_partial_client_data, 1);
3555 g_hash_table_insert(partial_tcp_req_table,
3556 GINT_TO_POINTER(client_sk),
3559 client->channel = g_io_channel_unix_new(client_sk);
3560 g_io_channel_set_close_on_unref(client->channel, TRUE);
3562 client->watch = g_io_add_watch(client->channel,
3563 G_IO_IN, tcp_client_event,
3566 client->ifdata = ifdata;
3568 DBG("client %d created %p", client_sk, client);
3570 DBG("client %d already exists %p", client_sk, client);
3574 client->buf = g_try_malloc(TCP_MAX_BUF_LEN);
3578 memset(client->buf, 0, TCP_MAX_BUF_LEN);
3579 client->buf_end = 0;
3580 client->family = family;
3582 if (client->timeout == 0)
3583 client->timeout = g_timeout_add_seconds(2, client_timeout,
3587 * Check how much data there is. If all is there, then we can
3588 * proceed normally, otherwise read the bits until everything
3589 * is received or timeout occurs.
3591 len = recv(client_sk, client->buf, TCP_MAX_BUF_LEN, 0);
3593 if (errno == EAGAIN || errno == EWOULDBLOCK) {
3594 DBG("client %d no data to read, waiting", client_sk);
3598 DBG("client %d cannot read errno %d/%s", client_sk, -errno,
3600 g_hash_table_remove(partial_tcp_req_table,
3601 GINT_TO_POINTER(client_sk));
3606 DBG("client %d not enough data to read, waiting", client_sk);
3607 client->buf_end += len;
3611 msg_len = get_msg_len(client->buf);
3612 if (msg_len > TCP_MAX_BUF_LEN) {
3613 DBG("client %d invalid message length %u ignoring packet",
3614 client_sk, msg_len);
3615 g_hash_table_remove(partial_tcp_req_table,
3616 GINT_TO_POINTER(client_sk));
3621 * The packet length bytes do not contain the total message length,
3622 * that is the reason to -2 below.
3624 #if defined TIZEN_EXT
3625 if (msg_len > (unsigned int)(len - 2)) {
3627 if (msg_len != (unsigned int)(len - 2)) {
3629 DBG("client %d sent %d bytes but expecting %u pending %d",
3630 client_sk, len, msg_len + 2, msg_len + 2 - len);
3632 client->buf_end += len;
3636 return read_tcp_data(client, client_addr, *client_addr_len, len);
3639 static gboolean tcp4_listener_event(GIOChannel *channel, GIOCondition condition,
3642 struct listener_data *ifdata = user_data;
3644 return tcp_listener_event(channel, condition, ifdata, AF_INET,
3645 &ifdata->tcp4_listener_watch);
3648 static gboolean tcp6_listener_event(GIOChannel *channel, GIOCondition condition,
3651 struct listener_data *ifdata = user_data;
3653 return tcp_listener_event(channel, condition, user_data, AF_INET6,
3654 &ifdata->tcp6_listener_watch);
3657 static bool udp_listener_event(GIOChannel *channel, GIOCondition condition,
3658 struct listener_data *ifdata, int family,
3659 guint *listener_watch)
3661 unsigned char buf[768];
3663 struct request_data *req;
3664 struct sockaddr_in6 client_addr6;
3665 socklen_t client_addr6_len = sizeof(client_addr6);
3666 struct sockaddr_in client_addr4;
3667 socklen_t client_addr4_len = sizeof(client_addr4);
3669 socklen_t *client_addr_len;
3672 if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
3673 #if defined TIZEN_EXT
3674 connman_error("Error %d with UDP listener channel", condition);
3676 recover_listener(channel, ifdata);
3678 connman_error("Error with UDP listener channel");
3679 *listener_watch = 0;
3684 sk = g_io_channel_unix_get_fd(channel);
3686 if (family == AF_INET) {
3687 client_addr = &client_addr4;
3688 client_addr_len = &client_addr4_len;
3690 client_addr = &client_addr6;
3691 client_addr_len = &client_addr6_len;
3694 memset(client_addr, 0, *client_addr_len);
3695 len = recvfrom(sk, buf, sizeof(buf), 0, client_addr, client_addr_len);
3699 DBG("Received %d bytes (id 0x%04x)", len, buf[0] | buf[1] << 8);
3701 err = parse_request(buf, len, query, sizeof(query));
3702 if (err < 0 || (g_slist_length(server_list) == 0)) {
3703 send_response(sk, buf, len, client_addr,
3704 *client_addr_len, IPPROTO_UDP);
3708 req = g_try_new0(struct request_data, 1);
3712 memcpy(&req->sa, client_addr, *client_addr_len);
3713 req->sa_len = *client_addr_len;
3715 req->protocol = IPPROTO_UDP;
3716 req->family = family;
3718 req->srcid = buf[0] | (buf[1] << 8);
3719 req->dstid = get_id();
3720 req->altid = get_id();
3721 req->request_len = len;
3723 buf[0] = req->dstid & 0xff;
3724 buf[1] = req->dstid >> 8;
3727 req->ifdata = ifdata;
3728 req->append_domain = false;
3730 if (resolv(req, buf, query)) {
3731 /* a cached result was sent, so the request can be released */
3736 req->name = g_strdup(query);
3737 req->request = g_malloc(len);
3738 memcpy(req->request, buf, len);
3739 #if defined TIZEN_EXT
3740 DBG("req %p dstid 0x%04x altid 0x%04x", req, req->dstid, req->altid);
3741 req->timeout = g_timeout_add_seconds(30, request_timeout, req);
3743 req->timeout = g_timeout_add_seconds(5, request_timeout, req);
3745 request_list = g_slist_append(request_list, req);
3750 static gboolean udp4_listener_event(GIOChannel *channel, GIOCondition condition,
3753 struct listener_data *ifdata = user_data;
3755 return udp_listener_event(channel, condition, ifdata, AF_INET,
3756 &ifdata->udp4_listener_watch);
3759 static gboolean udp6_listener_event(GIOChannel *channel, GIOCondition condition,
3762 struct listener_data *ifdata = user_data;
3764 return udp_listener_event(channel, condition, user_data, AF_INET6,
3765 &ifdata->udp6_listener_watch);
3768 static GIOChannel *get_listener(int family, int protocol, int index)
3770 GIOChannel *channel;
3772 #if !defined TIZEN_EXT
3775 struct sockaddr_in6 sin6;
3776 struct sockaddr_in sin;
3781 #if !defined TIZEN_EXT
3784 #if defined TIZEN_EXT
3788 int is_socket_inet = 0;
3791 DBG("family %d protocol %d index %d", family, protocol, index);
3796 type = SOCK_DGRAM | SOCK_CLOEXEC;
3801 type = SOCK_STREAM | SOCK_CLOEXEC;
3807 #if defined TIZEN_EXT
3808 sd_num = sd_listen_fds(0);
3809 DBG("socket type(%s) systemd number of fds(%d)", proto, sd_num);
3811 DBG("fail to get the fd from systemd");
3815 if(protocol == IPPROTO_TCP)
3820 for(sk = SD_LISTEN_FDS_START; sk < SD_LISTEN_FDS_START+sd_num; ++sk){
3821 rv = sd_is_socket_inet(sk, family, type, -1, 53);
3823 DBG("socket fd (%d) is passed by systemd", sk);
3829 if (!is_socket_inet) {
3830 DBG("socket fd is not matched what connman requests");
3834 sk = socket(family, type, protocol);
3835 if (sk < 0 && family == AF_INET6 && errno == EAFNOSUPPORT) {
3836 connman_error("No IPv6 support");
3841 connman_error("Failed to create %s listener socket", proto);
3845 /* ConnMan listens DNS from multiple interfaces
3846 * E.g. various technology based and tethering interfaces
3848 interface = connman_inet_ifname(index);
3849 if (!interface || setsockopt(sk, SOL_SOCKET, SO_BINDTODEVICE,
3851 strlen(interface) + 1) < 0) {
3852 connman_error("Failed to bind %s listener interface "
3854 proto, family == AF_INET ? "IPv4" : "IPv6",
3855 -errno, strerror(errno));
3862 if (family == AF_INET6) {
3863 memset(&s.sin6, 0, sizeof(s.sin6));
3864 s.sin6.sin6_family = AF_INET6;
3865 s.sin6.sin6_port = htons(53);
3866 slen = sizeof(s.sin6);
3868 if (__connman_inet_get_interface_address(index,
3870 &s.sin6.sin6_addr) < 0) {
3871 /* So we could not find suitable IPv6 address for
3872 * the interface. This could happen if we have
3873 * disabled IPv6 for the interface.
3879 } else if (family == AF_INET) {
3880 memset(&s.sin, 0, sizeof(s.sin));
3881 s.sin.sin_family = AF_INET;
3882 s.sin.sin_port = htons(53);
3883 slen = sizeof(s.sin);
3884 if (__connman_inet_get_interface_address(index,
3886 &s.sin.sin_addr) < 0) {
3895 #if defined TIZEN_EXT
3896 /* When ConnMan crashed,
3897 * probably DNS listener cannot bind existing address */
3899 setsockopt(sk, SOL_SOCKET, SO_REUSEADDR, &option, sizeof(option));
3901 #if !defined TIZEN_EXT
3902 if (bind(sk, &s.sa, slen) < 0) {
3903 connman_error("Failed to bind %s listener socket", proto);
3909 if (protocol == IPPROTO_TCP) {
3910 #if !defined TIZEN_EXT
3911 if (listen(sk, 10) < 0) {
3912 connman_error("Failed to listen on TCP socket %d/%s",
3913 -errno, strerror(errno));
3918 fcntl(sk, F_SETFL, O_NONBLOCK);
3921 channel = g_io_channel_unix_new(sk);
3923 connman_error("Failed to create %s listener channel", proto);
3928 g_io_channel_set_close_on_unref(channel, TRUE);
3933 #define UDP_IPv4_FAILED 0x01
3934 #define TCP_IPv4_FAILED 0x02
3935 #define UDP_IPv6_FAILED 0x04
3936 #define TCP_IPv6_FAILED 0x08
3937 #define UDP_FAILED (UDP_IPv4_FAILED | UDP_IPv6_FAILED)
3938 #define TCP_FAILED (TCP_IPv4_FAILED | TCP_IPv6_FAILED)
3939 #define IPv6_FAILED (UDP_IPv6_FAILED | TCP_IPv6_FAILED)
3940 #define IPv4_FAILED (UDP_IPv4_FAILED | TCP_IPv4_FAILED)
3942 static int create_dns_listener(int protocol, struct listener_data *ifdata)
3946 if (protocol == IPPROTO_TCP) {
3947 ifdata->tcp4_listener_channel = get_listener(AF_INET, protocol,
3949 if (ifdata->tcp4_listener_channel)
3950 #if defined TIZEN_EXT
3951 ifdata->tcp4_listener_watch =
3952 g_io_add_watch(ifdata->tcp4_listener_channel,
3953 G_IO_IN | G_IO_ERR | G_IO_HUP | G_IO_NVAL,
3954 tcp4_listener_event, (gpointer)ifdata);
3956 ifdata->tcp4_listener_watch =
3957 g_io_add_watch(ifdata->tcp4_listener_channel,
3958 G_IO_IN, tcp4_listener_event,
3962 ret |= TCP_IPv4_FAILED;
3964 ifdata->tcp6_listener_channel = get_listener(AF_INET6, protocol,
3966 if (ifdata->tcp6_listener_channel)
3967 #if defined TIZEN_EXT
3968 ifdata->tcp6_listener_watch =
3969 g_io_add_watch(ifdata->tcp6_listener_channel,
3970 G_IO_IN | G_IO_ERR | G_IO_HUP | G_IO_NVAL,
3971 tcp6_listener_event, (gpointer)ifdata);
3973 ifdata->tcp6_listener_watch =
3974 g_io_add_watch(ifdata->tcp6_listener_channel,
3975 G_IO_IN, tcp6_listener_event,
3979 ret |= TCP_IPv6_FAILED;
3981 ifdata->udp4_listener_channel = get_listener(AF_INET, protocol,
3983 if (ifdata->udp4_listener_channel)
3984 #if defined TIZEN_EXT
3985 ifdata->udp4_listener_watch =
3986 g_io_add_watch(ifdata->udp4_listener_channel,
3987 G_IO_IN | G_IO_ERR | G_IO_HUP | G_IO_NVAL,
3988 udp4_listener_event, (gpointer)ifdata);
3990 ifdata->udp4_listener_watch =
3991 g_io_add_watch(ifdata->udp4_listener_channel,
3992 G_IO_IN, udp4_listener_event,
3996 ret |= UDP_IPv4_FAILED;
3998 ifdata->udp6_listener_channel = get_listener(AF_INET6, protocol,
4000 if (ifdata->udp6_listener_channel)
4001 #if defined TIZEN_EXT
4002 ifdata->udp6_listener_watch =
4003 g_io_add_watch(ifdata->udp6_listener_channel,
4004 G_IO_IN | G_IO_ERR | G_IO_HUP | G_IO_NVAL,
4005 udp6_listener_event, (gpointer)ifdata);
4007 ifdata->udp6_listener_watch =
4008 g_io_add_watch(ifdata->udp6_listener_channel,
4009 G_IO_IN, udp6_listener_event,
4013 ret |= UDP_IPv6_FAILED;
4019 static void destroy_udp_listener(struct listener_data *ifdata)
4021 DBG("index %d", ifdata->index);
4023 if (ifdata->udp4_listener_watch > 0)
4024 g_source_remove(ifdata->udp4_listener_watch);
4026 if (ifdata->udp6_listener_watch > 0)
4027 g_source_remove(ifdata->udp6_listener_watch);
4029 if (ifdata->udp4_listener_channel)
4030 g_io_channel_unref(ifdata->udp4_listener_channel);
4031 if (ifdata->udp6_listener_channel)
4032 g_io_channel_unref(ifdata->udp6_listener_channel);
4035 static void destroy_tcp_listener(struct listener_data *ifdata)
4037 DBG("index %d", ifdata->index);
4039 if (ifdata->tcp4_listener_watch > 0)
4040 g_source_remove(ifdata->tcp4_listener_watch);
4041 if (ifdata->tcp6_listener_watch > 0)
4042 g_source_remove(ifdata->tcp6_listener_watch);
4044 if (ifdata->tcp4_listener_channel)
4045 g_io_channel_unref(ifdata->tcp4_listener_channel);
4046 if (ifdata->tcp6_listener_channel)
4047 g_io_channel_unref(ifdata->tcp6_listener_channel);
4050 static int create_listener(struct listener_data *ifdata)
4054 err = create_dns_listener(IPPROTO_UDP, ifdata);
4055 if ((err & UDP_FAILED) == UDP_FAILED)
4058 err |= create_dns_listener(IPPROTO_TCP, ifdata);
4059 if ((err & TCP_FAILED) == TCP_FAILED) {
4060 destroy_udp_listener(ifdata);
4064 index = connman_inet_ifindex("lo");
4065 if (ifdata->index == index) {
4066 if ((err & IPv6_FAILED) != IPv6_FAILED)
4067 __connman_resolvfile_append(index, NULL, "::1");
4069 if ((err & IPv4_FAILED) != IPv4_FAILED)
4070 __connman_resolvfile_append(index, NULL, "127.0.0.1");
4076 static void destroy_listener(struct listener_data *ifdata)
4081 index = connman_inet_ifindex("lo");
4082 if (ifdata->index == index) {
4083 __connman_resolvfile_remove(index, NULL, "127.0.0.1");
4084 __connman_resolvfile_remove(index, NULL, "::1");
4087 for (list = request_list; list; list = list->next) {
4088 struct request_data *req = list->data;
4090 DBG("Dropping request (id 0x%04x -> 0x%04x)",
4091 req->srcid, req->dstid);
4092 destroy_request_data(req);
4096 g_slist_free(request_list);
4097 request_list = NULL;
4099 destroy_tcp_listener(ifdata);
4100 destroy_udp_listener(ifdata);
4103 int __connman_dnsproxy_add_listener(int index)
4105 struct listener_data *ifdata;
4108 DBG("index %d", index);
4113 if (!listener_table)
4116 if (g_hash_table_lookup(listener_table, GINT_TO_POINTER(index)))
4119 ifdata = g_try_new0(struct listener_data, 1);
4123 ifdata->index = index;
4124 ifdata->udp4_listener_channel = NULL;
4125 ifdata->udp4_listener_watch = 0;
4126 ifdata->tcp4_listener_channel = NULL;
4127 ifdata->tcp4_listener_watch = 0;
4128 ifdata->udp6_listener_channel = NULL;
4129 ifdata->udp6_listener_watch = 0;
4130 ifdata->tcp6_listener_channel = NULL;
4131 ifdata->tcp6_listener_watch = 0;
4133 err = create_listener(ifdata);
4135 connman_error("Couldn't create listener for index %d err %d",
4140 g_hash_table_insert(listener_table, GINT_TO_POINTER(ifdata->index),
4145 void __connman_dnsproxy_remove_listener(int index)
4147 struct listener_data *ifdata;
4149 DBG("index %d", index);
4151 if (!listener_table)
4154 ifdata = g_hash_table_lookup(listener_table, GINT_TO_POINTER(index));
4158 destroy_listener(ifdata);
4160 g_hash_table_remove(listener_table, GINT_TO_POINTER(index));
4163 static void remove_listener(gpointer key, gpointer value, gpointer user_data)
4165 int index = GPOINTER_TO_INT(key);
4166 struct listener_data *ifdata = value;
4168 DBG("index %d", index);
4170 destroy_listener(ifdata);
4173 static void free_partial_reqs(gpointer value)
4175 struct tcp_partial_client_data *data = value;
4181 int __connman_dnsproxy_init(void)
4187 listener_table = g_hash_table_new_full(g_direct_hash, g_direct_equal,
4190 partial_tcp_req_table = g_hash_table_new_full(g_direct_hash,
4195 index = connman_inet_ifindex("lo");
4196 err = __connman_dnsproxy_add_listener(index);
4200 err = connman_notifier_register(&dnsproxy_notifier);
4207 __connman_dnsproxy_remove_listener(index);
4208 g_hash_table_destroy(listener_table);
4209 g_hash_table_destroy(partial_tcp_req_table);
4214 void __connman_dnsproxy_cleanup(void)
4219 g_source_remove(cache_timer);
4224 g_hash_table_destroy(cache);
4228 connman_notifier_unregister(&dnsproxy_notifier);
4230 g_hash_table_foreach(listener_table, remove_listener, NULL);
4232 g_hash_table_destroy(listener_table);
4234 g_hash_table_destroy(partial_tcp_req_table);