5 * Copyright (C) 2007-2014 Intel Corporation. All rights reserved.
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License version 2 as
9 * published by the Free Software Foundation.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
31 #include <arpa/inet.h>
32 #include <netinet/in.h>
33 #include <sys/types.h>
34 #include <sys/socket.h>
38 #include <gweb/gresolv.h>
44 #if __BYTE_ORDER == __LITTLE_ENDIAN
59 } __attribute__ ((packed));
60 #elif __BYTE_ORDER == __BIG_ENDIAN
75 } __attribute__ ((packed));
77 #error "Unknown byte order"
80 struct partial_reply {
90 struct sockaddr *server_addr;
91 socklen_t server_addr_len;
98 struct partial_reply *incoming_reply;
101 struct request_data {
103 struct sockaddr_in6 __sin6; /* Only for the length */
122 struct listener_data *ifdata;
126 struct listener_data {
129 GIOChannel *udp4_listener_channel;
130 GIOChannel *tcp4_listener_channel;
131 guint udp4_listener_watch;
132 guint tcp4_listener_watch;
134 GIOChannel *udp6_listener_channel;
135 GIOChannel *tcp6_listener_channel;
136 guint udp6_listener_watch;
137 guint tcp6_listener_watch;
141 * The TCP client requires some extra handling as we need to
142 * be prepared to receive also partial DNS requests.
144 struct tcp_partial_client_data {
146 struct listener_data *ifdata;
150 unsigned int buf_end;
161 unsigned int data_len;
162 unsigned char *data; /* contains DNS header + body */
169 struct cache_data *ipv4;
170 struct cache_data *ipv6;
173 struct domain_question {
176 } __attribute__ ((packed));
183 } __attribute__ ((packed));
186 * Max length of the DNS TCP packet.
188 #define TCP_MAX_BUF_LEN 4096
191 * We limit how long the cached DNS entry stays in the cache.
192 * By default the TTL (time-to-live) of the DNS response is used
193 * when setting the cache entry life time. The value is in seconds.
195 #if defined TIZEN_EXT
196 #define MAX_CACHE_TTL (60 * 60)
198 #define MAX_CACHE_TTL (60 * 30)
201 * Also limit the other end, cache at least for 30 seconds.
203 #define MIN_CACHE_TTL (30)
206 * We limit the cache size to some sane value so that cached data does
207 * not occupy too much memory. Each cached entry occupies on average
208 * about 100 bytes memory (depending on DNS name length).
209 * Example: caching www.connman.net uses 97 bytes memory.
210 * The value is the max amount of cached DNS responses (count).
212 #define MAX_CACHE_SIZE 256
214 static int cache_size;
215 static GHashTable *cache;
216 static int cache_refcount;
217 static GSList *server_list = NULL;
218 #if defined TIZEN_EXT
219 static GSList *server_list_sec = NULL;
221 static GSList *request_list = NULL;
222 static GHashTable *listener_table = NULL;
223 static time_t next_refresh;
224 static GHashTable *partial_tcp_req_table;
225 static guint cache_timer = 0;
227 #if defined TIZEN_EXT
228 static void destroy_server_sec(struct server_data *server);
229 static struct server_data *create_server_sec(int index,
230 const char *domain, const char *server,
234 static guint16 get_id(void)
239 static int protocol_offset(int protocol)
255 * There is a power and efficiency benefit to have entries
256 * in our cache expire at the same time. To this extend,
257 * we round down the cache valid time to common boundaries.
259 static time_t round_down_ttl(time_t end_time, int ttl)
264 /* Less than 5 minutes, round to 10 second boundary */
266 end_time = end_time / 10;
267 end_time = end_time * 10;
268 } else { /* 5 or more minutes, round to 30 seconds */
269 end_time = end_time / 30;
270 end_time = end_time * 30;
275 static struct request_data *find_request(guint16 id)
279 for (list = request_list; list; list = list->next) {
280 struct request_data *req = list->data;
282 if (req->dstid == id || req->altid == id)
289 static struct server_data *find_server(int index,
295 DBG("index %d server %s proto %d", index, server, protocol);
297 for (list = server_list; list; list = list->next) {
298 struct server_data *data = list->data;
300 if (index < 0 && data->index < 0 &&
301 g_str_equal(data->server, server) &&
302 data->protocol == protocol)
306 data->index < 0 || !data->server)
309 if (data->index == index &&
310 g_str_equal(data->server, server) &&
311 data->protocol == protocol)
318 /* we can keep using the same resolve's */
319 static GResolv *ipv4_resolve;
320 static GResolv *ipv6_resolve;
322 static void dummy_resolve_func(GResolvResultStatus status,
323 char **results, gpointer user_data)
328 * Refresh a DNS entry, but also age the hit count a bit */
329 static void refresh_dns_entry(struct cache_entry *entry, char *name)
334 ipv4_resolve = g_resolv_new(0);
335 g_resolv_set_address_family(ipv4_resolve, AF_INET);
336 g_resolv_add_nameserver(ipv4_resolve, "127.0.0.1", 53, 0);
340 ipv6_resolve = g_resolv_new(0);
341 g_resolv_set_address_family(ipv6_resolve, AF_INET6);
342 g_resolv_add_nameserver(ipv6_resolve, "::1", 53, 0);
346 DBG("Refresing A record for %s", name);
347 g_resolv_lookup_hostname(ipv4_resolve, name,
348 dummy_resolve_func, NULL);
353 DBG("Refresing AAAA record for %s", name);
354 g_resolv_lookup_hostname(ipv6_resolve, name,
355 dummy_resolve_func, NULL);
364 static int dns_name_length(unsigned char *buf)
366 if ((buf[0] & NS_CMPRSFLGS) == NS_CMPRSFLGS) /* compressed name */
368 return strlen((char *)buf);
371 static void update_cached_ttl(unsigned char *buf, int len, int new_ttl)
377 /* skip the header */
381 /* skip the query, which is a name and 2 16 bit words */
382 l = dns_name_length(c);
388 /* now we get the answer records */
392 l = dns_name_length(c);
397 /* then type + class, 2 bytes each */
403 /* now the 4 byte TTL field */
404 c[0] = new_ttl >> 24 & 0xff;
405 c[1] = new_ttl >> 16 & 0xff;
406 c[2] = new_ttl >> 8 & 0xff;
407 c[3] = new_ttl & 0xff;
413 /* now the 2 byte rdlen field */
414 w = c[0] << 8 | c[1];
420 static void send_cached_response(int sk, unsigned char *buf, int len,
421 const struct sockaddr *to, socklen_t tolen,
422 int protocol, int id, uint16_t answers, int ttl)
424 struct domain_hdr *hdr;
425 unsigned char *ptr = buf;
426 int err, offset, dns_len, adj_len = len - 2;
429 * The cached packet contains always the TCP offset (two bytes)
430 * so skip them for UDP.
441 dns_len = ptr[0] * 256 + ptr[1];
450 hdr = (void *) (ptr + offset);
454 hdr->rcode = ns_r_noerror;
455 hdr->ancount = htons(answers);
459 /* if this is a negative reply, we are authorative */
463 update_cached_ttl((unsigned char *)hdr, adj_len, ttl);
465 DBG("sk %d id 0x%04x answers %d ptr %p length %d dns %d",
466 sk, hdr->id, answers, ptr, len, dns_len);
468 err = sendto(sk, ptr, len, MSG_NOSIGNAL, to, tolen);
470 connman_error("Cannot send cached DNS response: %s",
475 if (err != len || (dns_len != (len - 2) && protocol == IPPROTO_TCP) ||
476 (dns_len != len && protocol == IPPROTO_UDP))
477 DBG("Packet length mismatch, sent %d wanted %d dns %d",
481 static void send_response(int sk, unsigned char *buf, int len,
482 const struct sockaddr *to, socklen_t tolen,
485 struct domain_hdr *hdr;
486 int err, offset = protocol_offset(protocol);
496 hdr = (void *) (buf + offset);
498 DBG("id 0x%04x qr %d opcode %d", hdr->id, hdr->qr, hdr->opcode);
501 hdr->rcode = ns_r_servfail;
507 err = sendto(sk, buf, len, MSG_NOSIGNAL, to, tolen);
509 connman_error("Failed to send DNS response to %d: %s",
510 sk, strerror(errno));
515 static int get_req_udp_socket(struct request_data *req)
519 if (req->family == AF_INET)
520 channel = req->ifdata->udp4_listener_channel;
522 channel = req->ifdata->udp6_listener_channel;
527 return g_io_channel_unix_get_fd(channel);
530 static void destroy_request_data(struct request_data *req)
532 if (req->timeout > 0)
533 g_source_remove(req->timeout);
536 g_free(req->request);
541 static gboolean request_timeout(gpointer user_data)
543 struct request_data *req = user_data;
548 DBG("id 0x%04x", req->srcid);
550 request_list = g_slist_remove(request_list, req);
553 if (req->resplen > 0 && req->resp) {
556 if (req->protocol == IPPROTO_UDP) {
557 sk = get_req_udp_socket(req);
561 err = sendto(sk, req->resp, req->resplen, MSG_NOSIGNAL,
562 &req->sa, req->sa_len);
565 err = send(sk, req->resp, req->resplen, MSG_NOSIGNAL);
571 } else if (req->request && req->numserv == 0) {
572 struct domain_hdr *hdr;
574 if (req->protocol == IPPROTO_TCP) {
575 hdr = (void *) (req->request + 2);
576 hdr->id = req->srcid;
577 send_response(req->client_sk, req->request,
578 req->request_len, NULL, 0, IPPROTO_TCP);
580 } else if (req->protocol == IPPROTO_UDP) {
583 hdr = (void *) (req->request);
584 hdr->id = req->srcid;
586 sk = get_req_udp_socket(req);
588 send_response(sk, req->request,
589 req->request_len, &req->sa,
590 req->sa_len, IPPROTO_UDP);
595 * We cannot leave TCP client hanging so just kick it out
596 * if we get a request timeout from server.
598 if (req->protocol == IPPROTO_TCP) {
599 DBG("client %d removed", req->client_sk);
600 g_hash_table_remove(partial_tcp_req_table,
601 GINT_TO_POINTER(req->client_sk));
605 destroy_request_data(req);
610 static int append_query(unsigned char *buf, unsigned int size,
611 const char *query, const char *domain)
613 unsigned char *ptr = buf;
616 DBG("query %s domain %s", query, domain);
621 tmp = strchr(query, '.');
627 memcpy(ptr + 1, query, len);
633 memcpy(ptr + 1, query, tmp - query);
634 ptr += tmp - query + 1;
642 tmp = strchr(domain, '.');
644 len = strlen(domain);
648 memcpy(ptr + 1, domain, len);
654 memcpy(ptr + 1, domain, tmp - domain);
655 ptr += tmp - domain + 1;
665 static bool cache_check_is_valid(struct cache_data *data,
671 if (data->cache_until < current_time)
678 * remove stale cached entries so that they can be refreshed
680 static void cache_enforce_validity(struct cache_entry *entry)
682 time_t current_time = time(NULL);
684 if (!cache_check_is_valid(entry->ipv4, current_time)
686 DBG("cache timeout \"%s\" type A", entry->key);
687 g_free(entry->ipv4->data);
693 if (!cache_check_is_valid(entry->ipv6, current_time)
695 DBG("cache timeout \"%s\" type AAAA", entry->key);
696 g_free(entry->ipv6->data);
702 static uint16_t cache_check_validity(char *question, uint16_t type,
703 struct cache_entry *entry)
705 time_t current_time = time(NULL);
706 bool want_refresh = false;
709 * if we have a popular entry, we want a refresh instead of
710 * total destruction of the entry.
715 cache_enforce_validity(entry);
719 if (!cache_check_is_valid(entry->ipv4, current_time)) {
720 DBG("cache %s \"%s\" type A", entry->ipv4 ?
721 "timeout" : "entry missing", question);
724 entry->want_refresh = true;
727 * We do not remove cache entry if there is still
728 * valid IPv6 entry found in the cache.
730 if (!cache_check_is_valid(entry->ipv6, current_time) && !want_refresh) {
731 g_hash_table_remove(cache, question);
738 if (!cache_check_is_valid(entry->ipv6, current_time)) {
739 DBG("cache %s \"%s\" type AAAA", entry->ipv6 ?
740 "timeout" : "entry missing", question);
743 entry->want_refresh = true;
745 if (!cache_check_is_valid(entry->ipv4, current_time) && !want_refresh) {
746 g_hash_table_remove(cache, question);
756 static void cache_element_destroy(gpointer value)
758 struct cache_entry *entry = value;
764 g_free(entry->ipv4->data);
769 g_free(entry->ipv6->data);
776 if (--cache_size < 0)
780 static gboolean try_remove_cache(gpointer user_data)
782 if (__sync_fetch_and_sub(&cache_refcount, 1) == 1) {
783 DBG("No cache users, removing it.");
785 g_hash_table_destroy(cache);
792 static void create_cache(void)
794 if (__sync_fetch_and_add(&cache_refcount, 1) == 0)
795 cache = g_hash_table_new_full(g_str_hash,
798 cache_element_destroy);
801 static struct cache_entry *cache_check(gpointer request, int *qtype, int proto)
804 struct cache_entry *entry;
805 struct domain_question *q;
807 int offset, proto_offset;
812 proto_offset = protocol_offset(proto);
813 if (proto_offset < 0)
816 question = request + proto_offset + 12;
818 offset = strlen(question) + 1;
819 q = (void *) (question + offset);
820 type = ntohs(q->type);
822 /* We only cache either A (1) or AAAA (28) requests */
823 if (type != 1 && type != 28)
831 entry = g_hash_table_lookup(cache, question);
835 type = cache_check_validity(question, type, entry);
844 * Get a label/name from DNS resource record. The function decompresses the
845 * label if necessary. The function does not convert the name to presentation
846 * form. This means that the result string will contain label lengths instead
847 * of dots between labels. We intentionally do not want to convert to dotted
848 * format so that we can cache the wire format string directly.
850 static int get_name(int counter,
851 unsigned char *pkt, unsigned char *start, unsigned char *max,
852 unsigned char *output, int output_max, int *output_len,
853 unsigned char **end, char *name, int *name_len)
857 /* Limit recursion to 10 (this means up to 10 labels in domain name) */
863 if ((*p & NS_CMPRSFLGS) == NS_CMPRSFLGS) {
864 uint16_t offset = (*p & 0x3F) * 256 + *(p + 1);
866 if (offset >= max - pkt)
872 return get_name(counter + 1, pkt, pkt + offset, max,
873 output, output_max, output_len, end,
876 unsigned label_len = *p;
878 if (pkt + label_len > max)
881 if (*output_len > output_max)
885 * We need the original name in order to check
886 * if this answer is the correct one.
888 name[(*name_len)++] = label_len;
889 memcpy(name + *name_len, p + 1, label_len + 1);
890 *name_len += label_len;
892 /* We compress the result */
893 output[0] = NS_CMPRSFLGS;
910 static int parse_rr(unsigned char *buf, unsigned char *start,
912 unsigned char *response, unsigned int *response_size,
913 uint16_t *type, uint16_t *class, int *ttl, int *rdlen,
917 struct domain_rr *rr;
919 int name_len = 0, output_len = 0, max_rsp = *response_size;
921 err = get_name(0, buf, start, max, response, max_rsp,
922 &output_len, end, name, &name_len);
928 if ((unsigned int) offset > *response_size)
931 rr = (void *) (*end);
936 *type = ntohs(rr->type);
937 *class = ntohs(rr->class);
938 *ttl = ntohl(rr->ttl);
939 *rdlen = ntohs(rr->rdlen);
944 memcpy(response + offset, *end, sizeof(struct domain_rr));
946 offset += sizeof(struct domain_rr);
947 *end += sizeof(struct domain_rr);
949 if ((unsigned int) (offset + *rdlen) > *response_size)
952 memcpy(response + offset, *end, *rdlen);
956 *response_size = offset + *rdlen;
961 static bool check_alias(GSList *aliases, char *name)
966 for (list = aliases; list; list = list->next) {
967 int len = strlen((char *)list->data);
968 if (strncmp((char *)list->data, name, len) == 0)
976 static int parse_response(unsigned char *buf, int buflen,
977 char *question, int qlen,
978 uint16_t *type, uint16_t *class, int *ttl,
979 unsigned char *response, unsigned int *response_len,
982 struct domain_hdr *hdr = (void *) buf;
983 struct domain_question *q;
985 uint16_t qdcount = ntohs(hdr->qdcount);
986 uint16_t ancount = ntohs(hdr->ancount);
988 uint16_t qtype, qclass;
989 unsigned char *next = NULL;
990 unsigned int maxlen = *response_len;
991 GSList *aliases = NULL, *list;
992 char name[NS_MAXDNAME + 1];
997 DBG("qr %d qdcount %d", hdr->qr, qdcount);
999 /* We currently only cache responses where question count is 1 */
1000 if (hdr->qr != 1 || qdcount != 1)
1003 ptr = buf + sizeof(struct domain_hdr);
1005 strncpy(question, (char *) ptr, qlen);
1006 qlen = strlen(question);
1007 ptr += qlen + 1; /* skip \0 */
1010 qtype = ntohs(q->type);
1012 /* We cache only A and AAAA records */
1013 if (qtype != 1 && qtype != 28)
1016 qclass = ntohs(q->class);
1018 ptr += 2 + 2; /* ptr points now to answers */
1024 memset(name, 0, sizeof(name));
1027 * We have a bunch of answers (like A, AAAA, CNAME etc) to
1028 * A or AAAA question. We traverse the answers and parse the
1029 * resource records. Only A and AAAA records are cached, all
1030 * the other records in answers are skipped.
1032 for (i = 0; i < ancount; i++) {
1034 * Get one address at a time to this buffer.
1035 * The max size of the answer is
1036 * 2 (pointer) + 2 (type) + 2 (class) +
1037 * 4 (ttl) + 2 (rdlen) + addr (16 or 4) = 28
1038 * for A or AAAA record.
1039 * For CNAME the size can be bigger.
1041 unsigned char rsp[NS_MAXCDNAME];
1042 unsigned int rsp_len = sizeof(rsp) - 1;
1045 memset(rsp, 0, sizeof(rsp));
1047 ret = parse_rr(buf, ptr, buf + buflen, rsp, &rsp_len,
1048 type, class, ttl, &rdlen, &next, name);
1055 * Now rsp contains compressed or uncompressed resource
1056 * record. Next we check if this record answers the question.
1057 * The name var contains the uncompressed label.
1058 * One tricky bit is the CNAME records as they alias
1059 * the name we might be interested in.
1063 * Go to next answer if the class is not the one we are
1066 if (*class != qclass) {
1073 * Try to resolve aliases also, type is CNAME(5).
1074 * This is important as otherwise the aliased names would not
1075 * be cached at all as the cache would not contain the aliased
1078 * If any CNAME is found in DNS packet, then we cache the alias
1079 * IP address instead of the question (as the server
1080 * said that question has only an alias).
1081 * This means in practice that if e.g., ipv6.google.com is
1082 * queried, DNS server returns CNAME of that name which is
1083 * ipv6.l.google.com. We then cache the address of the CNAME
1084 * but return the question name to client. So the alias
1085 * status of the name is not saved in cache and thus not
1086 * returned to the client. We do not return DNS packets from
1087 * cache to client saying that ipv6.google.com is an alias to
1088 * ipv6.l.google.com but we return instead a DNS packet that
1089 * says ipv6.google.com has address xxx which is in fact the
1090 * address of ipv6.l.google.com. For caching purposes this
1091 * should not cause any issues.
1093 if (*type == 5 && strncmp(question, name, qlen) == 0) {
1095 * So now the alias answered the question. This is
1096 * not very useful from caching point of view as
1097 * the following A or AAAA records will not match the
1098 * question. We need to find the real A/AAAA record
1099 * of the alias and cache that.
1101 unsigned char *end = NULL;
1102 int name_len = 0, output_len = 0;
1104 memset(rsp, 0, sizeof(rsp));
1105 rsp_len = sizeof(rsp) - 1;
1108 * Alias is in rdata part of the message,
1109 * and next-rdlen points to it. So we need to get
1110 * the real name of the alias.
1112 ret = get_name(0, buf, next - rdlen, buf + buflen,
1113 rsp, rsp_len, &output_len, &end,
1116 /* just ignore the error at this point */
1123 * We should now have the alias of the entry we might
1124 * want to cache. Just remember it for a while.
1125 * We check the alias list when we have parsed the
1128 aliases = g_slist_prepend(aliases, g_strdup(name));
1135 if (*type == qtype) {
1137 * We found correct type (A or AAAA)
1139 if (check_alias(aliases, name) ||
1140 (!aliases && strncmp(question, name,
1143 * We found an alias or the name of the rr
1144 * matches the question. If so, we append
1145 * the compressed label to the cache.
1146 * The end result is a response buffer that
1147 * will contain one or more cached and
1148 * compressed resource records.
1150 if (*response_len + rsp_len > maxlen) {
1154 memcpy(response + *response_len, rsp, rsp_len);
1155 *response_len += rsp_len;
1166 for (list = aliases; list; list = list->next)
1168 g_slist_free(aliases);
1173 struct cache_timeout {
1174 time_t current_time;
1179 static gboolean cache_check_entry(gpointer key, gpointer value,
1182 struct cache_timeout *data = user_data;
1183 struct cache_entry *entry = value;
1186 /* Scale the number of hits by half as part of cache aging */
1191 * If either IPv4 or IPv6 cached entry has expired, we
1192 * remove both from the cache.
1195 if (entry->ipv4 && entry->ipv4->timeout > 0) {
1196 max_timeout = entry->ipv4->cache_until;
1197 if (max_timeout > data->max_timeout)
1198 data->max_timeout = max_timeout;
1200 if (entry->ipv4->cache_until < data->current_time)
1204 if (entry->ipv6 && entry->ipv6->timeout > 0) {
1205 max_timeout = entry->ipv6->cache_until;
1206 if (max_timeout > data->max_timeout)
1207 data->max_timeout = max_timeout;
1209 if (entry->ipv6->cache_until < data->current_time)
1214 * if we're asked to try harder, also remove entries that have
1217 if (data->try_harder && entry->hits < 4)
1223 static void cache_cleanup(void)
1225 static int max_timeout;
1226 struct cache_timeout data;
1229 data.current_time = time(NULL);
1230 data.max_timeout = 0;
1231 data.try_harder = 0;
1234 * In the first pass, we only remove entries that have timed out.
1235 * We use a cache of the first time to expire to do this only
1236 * when it makes sense.
1238 if (max_timeout <= data.current_time) {
1239 count = g_hash_table_foreach_remove(cache, cache_check_entry,
1242 DBG("removed %d in the first pass", count);
1245 * In the second pass, if the first pass turned up blank,
1246 * we also expire entries with a low hit count,
1247 * while aging the hit count at the same time.
1249 data.try_harder = 1;
1251 count = g_hash_table_foreach_remove(cache, cache_check_entry,
1256 * If we could not remove anything, then remember
1257 * what is the max timeout and do nothing if we
1258 * have not yet reached it. This will prevent
1259 * constant traversal of the cache if it is full.
1261 max_timeout = data.max_timeout;
1266 static gboolean cache_invalidate_entry(gpointer key, gpointer value,
1269 struct cache_entry *entry = value;
1271 /* first, delete any expired elements */
1272 cache_enforce_validity(entry);
1274 /* if anything is not expired, mark the entry for refresh */
1275 if (entry->hits > 0 && (entry->ipv4 || entry->ipv6))
1276 entry->want_refresh = true;
1278 /* delete the cached data */
1280 g_free(entry->ipv4->data);
1281 g_free(entry->ipv4);
1286 g_free(entry->ipv6->data);
1287 g_free(entry->ipv6);
1291 /* keep the entry if we want it refreshed, delete it otherwise */
1292 if (entry->want_refresh)
1299 * cache_invalidate is called from places where the DNS landscape
1300 * has changed, say because connections are added or we entered a VPN.
1301 * The logic is to wipe all cache data, but mark all non-expired
1302 * parts of the cache for refresh rather than deleting the whole cache.
1304 static void cache_invalidate(void)
1306 DBG("Invalidating the DNS cache %p", cache);
1311 g_hash_table_foreach_remove(cache, cache_invalidate_entry, NULL);
1314 static void cache_refresh_entry(struct cache_entry *entry)
1317 cache_enforce_validity(entry);
1319 if (entry->hits > 2 && !entry->ipv4)
1320 entry->want_refresh = true;
1321 if (entry->hits > 2 && !entry->ipv6)
1322 entry->want_refresh = true;
1324 if (entry->want_refresh) {
1326 char dns_name[NS_MAXDNAME + 1];
1327 entry->want_refresh = false;
1329 /* turn a DNS name into a hostname with dots */
1330 strncpy(dns_name, entry->key, NS_MAXDNAME);
1338 DBG("Refreshing %s\n", dns_name);
1339 /* then refresh the hostname */
1340 refresh_dns_entry(entry, &dns_name[1]);
1344 static void cache_refresh_iterator(gpointer key, gpointer value,
1347 struct cache_entry *entry = value;
1349 cache_refresh_entry(entry);
1352 static void cache_refresh(void)
1357 g_hash_table_foreach(cache, cache_refresh_iterator, NULL);
1360 static int reply_query_type(unsigned char *msg, int len)
1366 /* skip the header */
1367 c = msg + sizeof(struct domain_hdr);
1368 len -= sizeof(struct domain_hdr);
1373 /* now the query, which is a name and 2 16 bit words */
1374 l = dns_name_length(c) + 1;
1376 type = c[0] << 8 | c[1];
1381 static int cache_update(struct server_data *srv, unsigned char *msg,
1382 unsigned int msg_len)
1384 int offset = protocol_offset(srv->protocol);
1385 int err, qlen, ttl = 0;
1386 uint16_t answers = 0, type = 0, class = 0;
1387 struct domain_hdr *hdr = (void *)(msg + offset);
1388 struct domain_question *q;
1389 struct cache_entry *entry;
1390 struct cache_data *data;
1391 char question[NS_MAXDNAME + 1];
1392 unsigned char response[NS_MAXDNAME + 1];
1394 unsigned int rsplen;
1395 bool new_entry = true;
1396 time_t current_time;
1398 if (cache_size >= MAX_CACHE_SIZE) {
1400 if (cache_size >= MAX_CACHE_SIZE)
1404 current_time = time(NULL);
1406 /* don't do a cache refresh more than twice a minute */
1407 if (next_refresh < current_time) {
1409 next_refresh = current_time + 30;
1415 DBG("offset %d hdr %p msg %p rcode %d", offset, hdr, msg, hdr->rcode);
1417 /* Continue only if response code is 0 (=ok) */
1418 if (hdr->rcode != ns_r_noerror)
1424 rsplen = sizeof(response) - 1;
1425 question[sizeof(question) - 1] = '\0';
1427 err = parse_response(msg + offset, msg_len - offset,
1428 question, sizeof(question) - 1,
1429 &type, &class, &ttl,
1430 response, &rsplen, &answers);
1433 * special case: if we do a ipv6 lookup and get no result
1434 * for a record that's already in our ipv4 cache.. we want
1435 * to cache the negative response.
1437 if ((err == -ENOMSG || err == -ENOBUFS) &&
1438 reply_query_type(msg + offset,
1439 msg_len - offset) == 28) {
1440 entry = g_hash_table_lookup(cache, question);
1441 if (entry && entry->ipv4 && !entry->ipv6) {
1442 int cache_offset = 0;
1444 data = g_try_new(struct cache_data, 1);
1447 data->inserted = entry->ipv4->inserted;
1449 data->answers = ntohs(hdr->ancount);
1450 data->timeout = entry->ipv4->timeout;
1451 if (srv->protocol == IPPROTO_UDP)
1453 data->data_len = msg_len + cache_offset;
1454 data->data = ptr = g_malloc(data->data_len);
1455 ptr[0] = (data->data_len - 2) / 256;
1456 ptr[1] = (data->data_len - 2) - ptr[0] * 256;
1457 if (srv->protocol == IPPROTO_UDP)
1459 data->valid_until = entry->ipv4->valid_until;
1460 data->cache_until = entry->ipv4->cache_until;
1461 memcpy(ptr, msg, msg_len);
1464 * we will get a "hit" when we serve the response
1468 if (entry->hits < 0)
1474 if (err < 0 || ttl == 0)
1477 qlen = strlen(question);
1480 * If the cache contains already data, check if the
1481 * type of the cached data is the same and do not add
1482 * to cache if data is already there.
1483 * This is needed so that we can cache both A and AAAA
1484 * records for the same name.
1486 entry = g_hash_table_lookup(cache, question);
1488 entry = g_try_new(struct cache_entry, 1);
1492 data = g_try_new(struct cache_data, 1);
1498 entry->key = g_strdup(question);
1499 entry->ipv4 = entry->ipv6 = NULL;
1500 entry->want_refresh = false;
1508 if (type == 1 && entry->ipv4)
1511 if (type == 28 && entry->ipv6)
1514 data = g_try_new(struct cache_data, 1);
1524 * compensate for the hit we'll get for serving
1525 * the response out of the cache
1528 if (entry->hits < 0)
1534 if (ttl < MIN_CACHE_TTL)
1535 ttl = MIN_CACHE_TTL;
1537 data->inserted = current_time;
1539 data->answers = answers;
1540 data->timeout = ttl;
1542 * The "2" in start of the length is the TCP offset. We allocate it
1543 * here even for UDP packet because it simplifies the sending
1546 data->data_len = 2 + 12 + qlen + 1 + 2 + 2 + rsplen;
1547 data->data = ptr = g_malloc(data->data_len);
1548 data->valid_until = current_time + ttl;
1551 * Restrict the cached DNS record TTL to some sane value
1552 * in order to prevent data staying in the cache too long.
1554 if (ttl > MAX_CACHE_TTL)
1555 ttl = MAX_CACHE_TTL;
1557 data->cache_until = round_down_ttl(current_time + ttl, ttl);
1567 * We cache the two extra bytes at the start of the message
1568 * in a TCP packet. When sending UDP packet, we skip the first
1569 * two bytes. This way we do not need to know the format
1570 * (UDP/TCP) of the cached message.
1572 if (srv->protocol == IPPROTO_UDP)
1573 memcpy(ptr + 2, msg, offset + 12);
1575 memcpy(ptr, msg, offset + 12);
1577 ptr[0] = (data->data_len - 2) / 256;
1578 ptr[1] = (data->data_len - 2) - ptr[0] * 256;
1579 if (srv->protocol == IPPROTO_UDP)
1582 memcpy(ptr + offset + 12, question, qlen + 1); /* copy also the \0 */
1584 q = (void *) (ptr + offset + 12 + qlen + 1);
1585 q->type = htons(type);
1586 q->class = htons(class);
1587 memcpy(ptr + offset + 12 + qlen + 1 + sizeof(struct domain_question),
1591 g_hash_table_replace(cache, entry->key, entry);
1595 DBG("cache %d %squestion \"%s\" type %d ttl %d size %zd packet %u "
1597 cache_size, new_entry ? "new " : "old ",
1598 question, type, ttl,
1599 sizeof(*entry) + sizeof(*data) + data->data_len + qlen,
1601 srv->protocol == IPPROTO_TCP ?
1602 (unsigned int)(data->data[0] * 256 + data->data[1]) :
1608 static int ns_resolv(struct server_data *server, struct request_data *req,
1609 gpointer request, gpointer name)
1612 int sk, err, type = 0;
1613 char *dot, *lookup = (char *) name;
1614 struct cache_entry *entry;
1616 entry = cache_check(request, &type, req->protocol);
1619 struct cache_data *data;
1621 DBG("cache hit %s type %s", lookup, type == 1 ? "A" : "AAAA");
1628 ttl_left = data->valid_until - time(NULL);
1632 if (data && req->protocol == IPPROTO_TCP) {
1633 send_cached_response(req->client_sk, data->data,
1634 data->data_len, NULL, 0, IPPROTO_TCP,
1635 req->srcid, data->answers, ttl_left);
1639 if (data && req->protocol == IPPROTO_UDP) {
1640 int udp_sk = get_req_udp_socket(req);
1645 send_cached_response(udp_sk, data->data,
1646 data->data_len, &req->sa, req->sa_len,
1647 IPPROTO_UDP, req->srcid, data->answers,
1653 #if defined TIZEN_EXT
1654 if (server->protocol == IPPROTO_UDP) {
1656 struct server_data *new_server = NULL;
1658 new_server = create_server_sec(server->index, NULL,
1659 server->server, IPPROTO_UDP);
1661 if (new_server != NULL) {
1662 for (domains = server->domains; domains;
1663 domains = domains->next) {
1664 char *dom = domains->data;
1666 DBG("Adding domain %s to %s",
1667 dom, new_server->server);
1669 new_server->domains = g_list_append(
1670 new_server->domains,
1674 server = new_server;
1678 sk = g_io_channel_unix_get_fd(server->channel);
1680 err = sendto(sk, request, req->request_len, MSG_NOSIGNAL,
1681 server->server_addr, server->server_addr_len);
1683 DBG("Cannot send message to server %s sock %d "
1684 "protocol %d (%s/%d)",
1685 server->server, sk, server->protocol,
1686 strerror(errno), errno);
1692 /* If we have more than one dot, we don't add domains */
1693 dot = strchr(lookup, '.');
1694 if (dot && dot != lookup + strlen(lookup) - 1)
1697 if (server->domains && server->domains->data)
1698 req->append_domain = true;
1700 for (list = server->domains; list; list = list->next) {
1702 unsigned char alt[1024];
1703 struct domain_hdr *hdr = (void *) &alt;
1704 int altlen, domlen, offset;
1706 domain = list->data;
1711 offset = protocol_offset(server->protocol);
1715 domlen = strlen(domain) + 1;
1719 alt[offset] = req->altid & 0xff;
1720 alt[offset + 1] = req->altid >> 8;
1722 memcpy(alt + offset + 2, request + offset + 2, 10);
1723 hdr->qdcount = htons(1);
1725 altlen = append_query(alt + offset + 12, sizeof(alt) - 12,
1732 memcpy(alt + offset + altlen,
1733 request + offset + altlen - domlen,
1734 req->request_len - altlen - offset + domlen);
1736 if (server->protocol == IPPROTO_TCP) {
1737 int req_len = req->request_len + domlen - 2;
1739 alt[0] = (req_len >> 8) & 0xff;
1740 alt[1] = req_len & 0xff;
1743 DBG("req %p dstid 0x%04x altid 0x%04x", req, req->dstid,
1746 err = send(sk, alt, req->request_len + domlen, MSG_NOSIGNAL);
1756 static char *convert_label(char *start, char *end, char *ptr, char *uptr,
1757 int remaining_len, int *used_comp, int *used_uncomp)
1760 char name[NS_MAXLABEL];
1762 pos = dn_expand((u_char *)start, (u_char *)end, (u_char *)ptr,
1765 DBG("uncompress error [%d/%s]", errno, strerror(errno));
1770 * We need to compress back the name so that we get back to internal
1771 * label presentation.
1773 comp_pos = dn_comp(name, (u_char *)uptr, remaining_len, NULL, NULL);
1775 DBG("compress error [%d/%s]", errno, strerror(errno));
1780 *used_uncomp = comp_pos;
1788 static char *uncompress(int16_t field_count, char *start, char *end,
1789 char *ptr, char *uncompressed, int uncomp_len,
1790 char **uncompressed_ptr)
1792 char *uptr = *uncompressed_ptr; /* position in result buffer */
1794 DBG("count %d ptr %p end %p uptr %p", field_count, ptr, end, uptr);
1796 while (field_count-- > 0 && ptr < end) {
1797 int dlen; /* data field length */
1798 int ulen; /* uncompress length */
1799 int pos; /* position in compressed string */
1800 char name[NS_MAXLABEL]; /* tmp label */
1801 uint16_t dns_type, dns_class;
1804 if (!convert_label(start, end, ptr, name, NS_MAXLABEL,
1809 * Copy the uncompressed resource record, type, class and \0 to
1813 ulen = strlen(name);
1814 strncpy(uptr, name, uncomp_len - (uptr - uncompressed));
1816 DBG("pos %d ulen %d left %d name %s", pos, ulen,
1817 (int)(uncomp_len - (uptr - uncompressed)), uptr);
1825 * We copy also the fixed portion of the result (type, class,
1826 * ttl, address length and the address)
1828 memcpy(uptr, ptr, NS_RRFIXEDSZ);
1830 dns_type = uptr[0] << 8 | uptr[1];
1831 dns_class = uptr[2] << 8 | uptr[3];
1833 if (dns_class != ns_c_in)
1836 ptr += NS_RRFIXEDSZ;
1837 uptr += NS_RRFIXEDSZ;
1840 * Then the variable portion of the result (data length).
1841 * Typically this portion is also compressed
1842 * so we need to uncompress it also when necessary.
1844 if (dns_type == ns_t_cname) {
1845 if (!convert_label(start, end, ptr, uptr,
1846 uncomp_len - (uptr - uncompressed),
1850 uptr[-2] = comp_pos << 8;
1851 uptr[-1] = comp_pos & 0xff;
1856 } else if (dns_type == ns_t_a || dns_type == ns_t_aaaa) {
1857 dlen = uptr[-2] << 8 | uptr[-1];
1859 if (ptr + dlen > end) {
1860 DBG("data len %d too long", dlen);
1864 memcpy(uptr, ptr, dlen);
1868 } else if (dns_type == ns_t_soa) {
1872 /* Primary name server expansion */
1873 if (!convert_label(start, end, ptr, uptr,
1874 uncomp_len - (uptr - uncompressed),
1878 total_len += comp_pos;
1879 len_ptr = &uptr[-2];
1883 /* Responsible authority's mailbox */
1884 if (!convert_label(start, end, ptr, uptr,
1885 uncomp_len - (uptr - uncompressed),
1889 total_len += comp_pos;
1894 * Copy rest of the soa fields (serial number,
1895 * refresh interval, retry interval, expiration
1896 * limit and minimum ttl). They are 20 bytes long.
1898 memcpy(uptr, ptr, 20);
1904 * Finally fix the length of the data part
1906 len_ptr[0] = total_len << 8;
1907 len_ptr[1] = total_len & 0xff;
1910 *uncompressed_ptr = uptr;
1919 static int strip_domains(char *name, char *answers, int maxlen)
1922 int name_len = strlen(name);
1923 char *ptr, *start = answers, *end = answers + maxlen;
1925 while (maxlen > 0) {
1926 ptr = strstr(answers, name);
1928 char *domain = ptr + name_len;
1931 int domain_len = strlen(domain);
1933 memmove(answers + name_len,
1934 domain + domain_len,
1935 end - (domain + domain_len));
1938 maxlen -= domain_len;
1942 answers += strlen(answers) + 1;
1943 answers += 2 + 2 + 4; /* skip type, class and ttl fields */
1945 data_len = answers[0] << 8 | answers[1];
1946 answers += 2; /* skip the length field */
1948 if (answers + data_len > end)
1951 answers += data_len;
1952 maxlen -= answers - ptr;
1958 static int forward_dns_reply(unsigned char *reply, int reply_len, int protocol,
1959 struct server_data *data)
1961 struct domain_hdr *hdr;
1962 struct request_data *req;
1963 int dns_id, sk, err, offset = protocol_offset(protocol);
1968 hdr = (void *)(reply + offset);
1969 dns_id = reply[offset] | reply[offset + 1] << 8;
1971 DBG("Received %d bytes (id 0x%04x)", reply_len, dns_id);
1973 req = find_request(dns_id);
1977 DBG("req %p dstid 0x%04x altid 0x%04x rcode %d",
1978 req, req->dstid, req->altid, hdr->rcode);
1980 reply[offset] = req->srcid & 0xff;
1981 reply[offset + 1] = req->srcid >> 8;
1985 if (hdr->rcode == ns_r_noerror || !req->resp) {
1986 unsigned char *new_reply = NULL;
1989 * If the domain name was append
1990 * remove it before forwarding the reply.
1991 * If there were more than one question, then this
1992 * domain name ripping can be hairy so avoid that
1993 * and bail out in that that case.
1995 * The reason we are doing this magic is that if the
1996 * user's DNS client tries to resolv hostname without
1997 * domain part, it also expects to get the result without
1998 * a domain name part.
2000 if (req->append_domain && ntohs(hdr->qdcount) == 1) {
2001 uint16_t domain_len = 0;
2002 uint16_t header_len;
2003 uint16_t dns_type, dns_class;
2004 uint8_t host_len, dns_type_pos;
2005 char uncompressed[NS_MAXDNAME], *uptr;
2006 char *ptr, *eom = (char *)reply + reply_len;
2009 * ptr points to the first char of the hostname.
2010 * ->hostname.domain.net
2012 header_len = offset + sizeof(struct domain_hdr);
2013 ptr = (char *)reply + header_len;
2017 domain_len = strnlen(ptr + 1 + host_len,
2018 reply_len - header_len);
2021 * If the query type is anything other than A or AAAA,
2022 * then bail out and pass the message as is.
2023 * We only want to deal with IPv4 or IPv6 addresses.
2025 dns_type_pos = host_len + 1 + domain_len + 1;
2027 dns_type = ptr[dns_type_pos] << 8 |
2028 ptr[dns_type_pos + 1];
2029 dns_class = ptr[dns_type_pos + 2] << 8 |
2030 ptr[dns_type_pos + 3];
2031 if (dns_type != ns_t_a && dns_type != ns_t_aaaa &&
2032 dns_class != ns_c_in) {
2033 DBG("Pass msg dns type %d class %d",
2034 dns_type, dns_class);
2039 * Remove the domain name and replace it by the end
2040 * of reply. Check if the domain is really there
2041 * before trying to copy the data. We also need to
2042 * uncompress the answers if necessary.
2043 * The domain_len can be 0 because if the original
2044 * query did not contain a domain name, then we are
2045 * sending two packets, first without the domain name
2046 * and the second packet with domain name.
2047 * The append_domain is set to true even if we sent
2048 * the first packet without domain name. In this
2049 * case we end up in this branch.
2051 if (domain_len > 0) {
2052 int len = host_len + 1;
2053 int new_len, fixed_len;
2057 * First copy host (without domain name) into
2060 uptr = &uncompressed[0];
2061 memcpy(uptr, ptr, len);
2063 uptr[len] = '\0'; /* host termination */
2067 * Copy type and class fields of the question.
2069 ptr += len + domain_len + 1;
2070 memcpy(uptr, ptr, NS_QFIXEDSZ);
2073 * ptr points to answers after this
2076 uptr += NS_QFIXEDSZ;
2078 fixed_len = answers - uncompressed;
2081 * We then uncompress the result to buffer
2082 * so that we can rip off the domain name
2083 * part from the question. First answers,
2084 * then name server (authority) information,
2085 * and finally additional record info.
2088 ptr = uncompress(ntohs(hdr->ancount),
2089 (char *)reply + offset, eom,
2090 ptr, uncompressed, NS_MAXDNAME,
2095 ptr = uncompress(ntohs(hdr->nscount),
2096 (char *)reply + offset, eom,
2097 ptr, uncompressed, NS_MAXDNAME,
2102 ptr = uncompress(ntohs(hdr->arcount),
2103 (char *)reply + offset, eom,
2104 ptr, uncompressed, NS_MAXDNAME,
2110 * The uncompressed buffer now contains almost
2111 * valid response. Final step is to get rid of
2112 * the domain name because at least glibc
2113 * gethostbyname() implementation does extra
2114 * checks and expects to find an answer without
2115 * domain name if we asked a query without
2116 * domain part. Note that glibc getaddrinfo()
2117 * works differently and accepts FQDN in answer
2119 new_len = strip_domains(uncompressed, answers,
2122 DBG("Corrupted packet");
2127 * Because we have now uncompressed the answers
2128 * we might have to create a bigger buffer to
2129 * hold all that data.
2132 reply_len = header_len + new_len + fixed_len;
2134 new_reply = g_try_malloc(reply_len);
2138 memcpy(new_reply, reply, header_len);
2139 memcpy(new_reply + header_len, uncompressed,
2140 new_len + fixed_len);
2150 req->resp = g_try_malloc(reply_len);
2154 memcpy(req->resp, reply, reply_len);
2155 req->resplen = reply_len;
2157 cache_update(data, reply, reply_len);
2163 if (req->numresp < req->numserv) {
2164 if (hdr->rcode > ns_r_noerror) {
2166 } else if (hdr->ancount == 0 && req->append_domain) {
2171 request_list = g_slist_remove(request_list, req);
2173 if (protocol == IPPROTO_UDP) {
2174 sk = get_req_udp_socket(req);
2179 err = sendto(sk, req->resp, req->resplen, 0,
2180 &req->sa, req->sa_len);
2182 sk = req->client_sk;
2183 err = send(sk, req->resp, req->resplen, MSG_NOSIGNAL);
2187 DBG("Cannot send msg, sk %d proto %d errno %d/%s", sk,
2188 protocol, errno, strerror(errno));
2190 DBG("proto %d sent %d bytes to %d", protocol, err, sk);
2192 destroy_request_data(req);
2197 static void server_destroy_socket(struct server_data *data)
2199 DBG("index %d server %s proto %d", data->index,
2200 data->server, data->protocol);
2202 if (data->watch > 0) {
2203 g_source_remove(data->watch);
2207 if (data->timeout > 0) {
2208 g_source_remove(data->timeout);
2212 if (data->channel) {
2213 g_io_channel_shutdown(data->channel, TRUE, NULL);
2214 g_io_channel_unref(data->channel);
2215 data->channel = NULL;
2218 g_free(data->incoming_reply);
2219 data->incoming_reply = NULL;
2222 static void destroy_server(struct server_data *server)
2224 DBG("index %d server %s sock %d", server->index, server->server,
2226 g_io_channel_unix_get_fd(server->channel): -1);
2228 server_list = g_slist_remove(server_list, server);
2229 server_destroy_socket(server);
2231 if (server->protocol == IPPROTO_UDP && server->enabled)
2232 DBG("Removing DNS server %s", server->server);
2234 g_free(server->server);
2235 g_list_free_full(server->domains, g_free);
2236 g_free(server->server_addr);
2239 * We do not remove cache right away but delay it few seconds.
2240 * The idea is that when IPv6 DNS server is added via RDNSS, it has a
2241 * lifetime. When the lifetime expires we decrease the refcount so it
2242 * is possible that the cache is then removed. Because a new DNS server
2243 * is usually created almost immediately we would then loose the cache
2244 * without any good reason. The small delay allows the new RDNSS to
2245 * create a new DNS server instance and the refcount does not go to 0.
2248 g_timeout_add_seconds(3, try_remove_cache, NULL);
2253 static gboolean udp_server_event(GIOChannel *channel, GIOCondition condition,
2256 unsigned char buf[4096];
2258 struct server_data *data = user_data;
2260 if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
2261 connman_error("Error with UDP server %s", data->server);
2262 server_destroy_socket(data);
2266 sk = g_io_channel_unix_get_fd(channel);
2268 len = recv(sk, buf, sizeof(buf), 0);
2272 err = forward_dns_reply(buf, len, IPPROTO_UDP, data);
2276 #if defined TIZEN_EXT
2279 for (list = server_list_sec; list; list = list->next) {
2280 struct server_data *new_data = list->data;
2282 if (new_data == data) {
2283 destroy_server_sec(data);
2292 static gboolean tcp_server_event(GIOChannel *channel, GIOCondition condition,
2296 struct server_data *server = user_data;
2298 sk = g_io_channel_unix_get_fd(channel);
2302 if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
2305 DBG("TCP server channel closed, sk %d", sk);
2308 * Discard any partial response which is buffered; better
2309 * to get a proper response from a working server.
2311 g_free(server->incoming_reply);
2312 server->incoming_reply = NULL;
2314 for (list = request_list; list; list = list->next) {
2315 struct request_data *req = list->data;
2316 struct domain_hdr *hdr;
2318 if (req->protocol == IPPROTO_UDP)
2325 * If we're not waiting for any further response
2326 * from another name server, then we send an error
2327 * response to the client.
2329 if (req->numserv && --(req->numserv))
2332 hdr = (void *) (req->request + 2);
2333 hdr->id = req->srcid;
2334 send_response(req->client_sk, req->request,
2335 req->request_len, NULL, 0, IPPROTO_TCP);
2337 request_list = g_slist_remove(request_list, req);
2340 destroy_server(server);
2345 if ((condition & G_IO_OUT) && !server->connected) {
2348 bool no_request_sent = true;
2349 struct server_data *udp_server;
2351 udp_server = find_server(server->index, server->server,
2354 for (domains = udp_server->domains; domains;
2355 domains = domains->next) {
2356 char *dom = domains->data;
2358 DBG("Adding domain %s to %s",
2359 dom, server->server);
2361 server->domains = g_list_append(server->domains,
2366 server->connected = true;
2367 server_list = g_slist_append(server_list, server);
2369 if (server->timeout > 0) {
2370 g_source_remove(server->timeout);
2371 server->timeout = 0;
2374 for (list = request_list; list; ) {
2375 struct request_data *req = list->data;
2378 if (req->protocol == IPPROTO_UDP) {
2383 DBG("Sending req %s over TCP", (char *)req->name);
2385 status = ns_resolv(server, req,
2386 req->request, req->name);
2389 * A cached result was sent,
2390 * so the request can be released
2393 request_list = g_slist_remove(request_list, req);
2394 destroy_request_data(req);
2403 no_request_sent = false;
2405 if (req->timeout > 0)
2406 g_source_remove(req->timeout);
2408 req->timeout = g_timeout_add_seconds(30,
2409 request_timeout, req);
2413 if (no_request_sent) {
2414 destroy_server(server);
2418 } else if (condition & G_IO_IN) {
2419 struct partial_reply *reply = server->incoming_reply;
2423 unsigned char reply_len_buf[2];
2426 bytes_recv = recv(sk, reply_len_buf, 2, MSG_PEEK);
2429 } else if (bytes_recv < 0) {
2430 if (errno == EAGAIN || errno == EWOULDBLOCK)
2433 connman_error("DNS proxy error %s",
2436 } else if (bytes_recv < 2)
2439 reply_len = reply_len_buf[1] | reply_len_buf[0] << 8;
2442 DBG("TCP reply %d bytes from %d", reply_len, sk);
2444 reply = g_try_malloc(sizeof(*reply) + reply_len + 2);
2448 reply->len = reply_len;
2449 reply->received = 0;
2451 server->incoming_reply = reply;
2454 while (reply->received < reply->len) {
2455 bytes_recv = recv(sk, reply->buf + reply->received,
2456 reply->len - reply->received, 0);
2458 connman_error("DNS proxy TCP disconnect");
2460 } else if (bytes_recv < 0) {
2461 if (errno == EAGAIN || errno == EWOULDBLOCK)
2464 connman_error("DNS proxy error %s",
2468 reply->received += bytes_recv;
2471 forward_dns_reply(reply->buf, reply->received, IPPROTO_TCP,
2475 server->incoming_reply = NULL;
2477 destroy_server(server);
2485 static gboolean tcp_idle_timeout(gpointer user_data)
2487 struct server_data *server = user_data;
2494 destroy_server(server);
2499 static int server_create_socket(struct server_data *data)
2504 DBG("index %d server %s proto %d", data->index,
2505 data->server, data->protocol);
2507 sk = socket(data->server_addr->sa_family,
2508 data->protocol == IPPROTO_TCP ? SOCK_STREAM : SOCK_DGRAM,
2512 connman_error("Failed to create server %s socket",
2514 server_destroy_socket(data);
2520 interface = connman_inet_ifname(data->index);
2522 if (setsockopt(sk, SOL_SOCKET, SO_BINDTODEVICE,
2524 strlen(interface) + 1) < 0) {
2526 connman_error("Failed to bind server %s "
2528 data->server, interface);
2530 server_destroy_socket(data);
2537 data->channel = g_io_channel_unix_new(sk);
2538 if (!data->channel) {
2539 connman_error("Failed to create server %s channel",
2542 server_destroy_socket(data);
2546 g_io_channel_set_close_on_unref(data->channel, TRUE);
2548 if (data->protocol == IPPROTO_TCP) {
2549 g_io_channel_set_flags(data->channel, G_IO_FLAG_NONBLOCK, NULL);
2550 data->watch = g_io_add_watch(data->channel,
2551 G_IO_OUT | G_IO_IN | G_IO_HUP | G_IO_NVAL | G_IO_ERR,
2552 tcp_server_event, data);
2553 data->timeout = g_timeout_add_seconds(30, tcp_idle_timeout,
2556 data->watch = g_io_add_watch(data->channel,
2557 G_IO_IN | G_IO_NVAL | G_IO_ERR | G_IO_HUP,
2558 udp_server_event, data);
2560 if (connect(sk, data->server_addr, data->server_addr_len) < 0) {
2563 if ((data->protocol == IPPROTO_TCP && errno != EINPROGRESS) ||
2564 data->protocol == IPPROTO_UDP) {
2566 connman_error("Failed to connect to server %s",
2568 server_destroy_socket(data);
2578 #if defined TIZEN_EXT
2580 static void destroy_server_sec(struct server_data *server)
2584 DBG("index %d server %s sock %d", server->index, server->server,
2585 server->channel != NULL ?
2586 g_io_channel_unix_get_fd(server->channel): -1);
2588 server_list_sec = g_slist_remove(server_list_sec, server);
2589 close(g_io_channel_unix_get_fd(server->channel));
2590 server_destroy_socket(server);
2592 if (server->protocol == IPPROTO_UDP && server->enabled)
2593 DBG("Removing DNS server %s", server->server);
2595 g_free(server->server);
2596 for (list = server->domains; list; list = list->next) {
2597 char *domain = list->data;
2599 server->domains = g_list_remove(server->domains, domain);
2602 g_free(server->server_addr);
2605 * We do not remove cache right away but delay it few seconds.
2606 * The idea is that when IPv6 DNS server is added via RDNSS, it has a
2607 * lifetime. When the lifetime expires we decrease the refcount so it
2608 * is possible that the cache is then removed. Because a new DNS server
2609 * is usually created almost immediately we would then loose the cache
2610 * without any good reason. The small delay allows the new RDNSS to
2611 * create a new DNS server instance and the refcount does not go to 0.
2613 /* TODO: Need to check this */
2614 /* g_timeout_add_seconds(3, try_remove_cache, NULL); */
2619 static void destroy_all_server_sec()
2623 DBG("remove all dns server");
2625 for (list = server_list_sec; list; list = list->next) {
2626 struct server_data *server = list->data;
2627 destroy_server_sec(server);
2629 server_list_sec = NULL;
2632 static gboolean sec_udp_idle_timeout(gpointer user_data)
2634 struct server_data *server = user_data;
2641 destroy_server_sec(server);
2646 static struct server_data *create_server_sec(int index,
2647 const char *domain, const char *server,
2650 struct server_data *data;
2651 struct addrinfo hints, *rp;
2654 DBG("index %d server %s", index, server);
2656 data = g_try_new0(struct server_data, 1);
2658 connman_error("Failed to allocate server %s data", server);
2662 data->index = index;
2664 data->domains = g_list_append(data->domains, g_strdup(domain));
2665 data->server = g_strdup(server);
2666 data->protocol = protocol;
2668 memset(&hints, 0, sizeof(hints));
2672 hints.ai_socktype = SOCK_DGRAM;
2676 hints.ai_socktype = SOCK_STREAM;
2680 destroy_server_sec(data);
2683 hints.ai_family = AF_UNSPEC;
2684 hints.ai_flags = AI_NUMERICSERV | AI_NUMERICHOST;
2686 ret = getaddrinfo(data->server, "53", &hints, &rp);
2688 connman_error("Failed to parse server %s address: %s\n",
2689 data->server, gai_strerror(ret));
2690 destroy_server_sec(data);
2694 /* Do not blindly copy this code elsewhere; it doesn't loop over the
2695 results using ->ai_next as it should. That's OK in *this* case
2696 because it was a numeric lookup; we *know* there's only one. */
2698 data->server_addr_len = rp->ai_addrlen;
2700 switch (rp->ai_family) {
2702 data->server_addr = (struct sockaddr *)
2703 g_try_new0(struct sockaddr_in, 1);
2706 data->server_addr = (struct sockaddr *)
2707 g_try_new0(struct sockaddr_in6, 1);
2710 connman_error("Wrong address family %d", rp->ai_family);
2713 if (data->server_addr == NULL) {
2715 destroy_server_sec(data);
2718 memcpy(data->server_addr, rp->ai_addr, rp->ai_addrlen);
2721 if (server_create_socket(data) != 0) {
2722 destroy_server_sec(data);
2726 if (protocol == IPPROTO_UDP) {
2727 /* Enable new servers by default */
2728 data->enabled = TRUE;
2729 DBG("Adding DNS server %s", data->server);
2731 data->timeout = g_timeout_add_seconds(30, sec_udp_idle_timeout,
2734 server_list_sec = g_slist_append(server_list_sec, data);
2741 static struct server_data *create_server(int index,
2742 const char *domain, const char *server,
2745 struct server_data *data;
2746 struct addrinfo hints, *rp;
2749 DBG("index %d server %s", index, server);
2751 data = g_try_new0(struct server_data, 1);
2753 connman_error("Failed to allocate server %s data", server);
2757 data->index = index;
2759 data->domains = g_list_append(data->domains, g_strdup(domain));
2760 data->server = g_strdup(server);
2761 data->protocol = protocol;
2763 memset(&hints, 0, sizeof(hints));
2767 hints.ai_socktype = SOCK_DGRAM;
2771 hints.ai_socktype = SOCK_STREAM;
2775 destroy_server(data);
2778 hints.ai_family = AF_UNSPEC;
2779 hints.ai_flags = AI_NUMERICSERV | AI_NUMERICHOST;
2781 ret = getaddrinfo(data->server, "53", &hints, &rp);
2783 connman_error("Failed to parse server %s address: %s\n",
2784 data->server, gai_strerror(ret));
2785 destroy_server(data);
2789 /* Do not blindly copy this code elsewhere; it doesn't loop over the
2790 results using ->ai_next as it should. That's OK in *this* case
2791 because it was a numeric lookup; we *know* there's only one. */
2793 data->server_addr_len = rp->ai_addrlen;
2795 switch (rp->ai_family) {
2797 data->server_addr = (struct sockaddr *)
2798 g_try_new0(struct sockaddr_in, 1);
2801 data->server_addr = (struct sockaddr *)
2802 g_try_new0(struct sockaddr_in6, 1);
2805 connman_error("Wrong address family %d", rp->ai_family);
2808 if (!data->server_addr) {
2810 destroy_server(data);
2813 memcpy(data->server_addr, rp->ai_addr, rp->ai_addrlen);
2816 if (server_create_socket(data) != 0) {
2817 destroy_server(data);
2821 if (protocol == IPPROTO_UDP) {
2822 if (__connman_service_index_is_default(data->index) ||
2823 __connman_service_index_is_split_routing(
2825 data->enabled = true;
2826 DBG("Adding DNS server %s", data->server);
2829 server_list = g_slist_append(server_list, data);
2835 static bool resolv(struct request_data *req,
2836 gpointer request, gpointer name)
2840 for (list = server_list; list; list = list->next) {
2841 struct server_data *data = list->data;
2843 if (data->protocol == IPPROTO_TCP) {
2844 DBG("server %s ignored proto TCP", data->server);
2848 DBG("server %s enabled %d", data->server, data->enabled);
2853 if (!data->channel && data->protocol == IPPROTO_UDP) {
2854 if (server_create_socket(data) < 0) {
2855 DBG("socket creation failed while resolving");
2860 if (ns_resolv(data, req, request, name) > 0)
2867 static void append_domain(int index, const char *domain)
2871 DBG("index %d domain %s", index, domain);
2876 for (list = server_list; list; list = list->next) {
2877 struct server_data *data = list->data;
2880 bool dom_found = false;
2882 if (data->index < 0)
2885 if (data->index != index)
2888 for (dom_list = data->domains; dom_list;
2889 dom_list = dom_list->next) {
2890 dom = dom_list->data;
2892 if (g_str_equal(dom, domain)) {
2900 g_list_append(data->domains, g_strdup(domain));
2905 int __connman_dnsproxy_append(int index, const char *domain,
2908 struct server_data *data;
2910 DBG("index %d server %s", index, server);
2912 if (!server && !domain)
2916 append_domain(index, domain);
2921 if (g_str_equal(server, "127.0.0.1"))
2924 if (g_str_equal(server, "::1"))
2927 data = find_server(index, server, IPPROTO_UDP);
2929 append_domain(index, domain);
2933 data = create_server(index, domain, server, IPPROTO_UDP);
2940 static void remove_server(int index, const char *domain,
2941 const char *server, int protocol)
2943 struct server_data *data;
2945 data = find_server(index, server, protocol);
2949 destroy_server(data);
2952 int __connman_dnsproxy_remove(int index, const char *domain,
2955 DBG("index %d server %s", index, server);
2960 if (g_str_equal(server, "127.0.0.1"))
2963 if (g_str_equal(server, "::1"))
2966 remove_server(index, domain, server, IPPROTO_UDP);
2967 remove_server(index, domain, server, IPPROTO_TCP);
2969 #if defined TIZEN_EXT
2970 destroy_all_server_sec();
2976 void __connman_dnsproxy_flush(void)
2980 list = request_list;
2982 struct request_data *req = list->data;
2986 if (resolv(req, req->request, req->name)) {
2988 * A cached result was sent,
2989 * so the request can be released
2992 g_slist_remove(request_list, req);
2993 destroy_request_data(req);
2997 if (req->timeout > 0)
2998 g_source_remove(req->timeout);
2999 req->timeout = g_timeout_add_seconds(5, request_timeout, req);
3003 static void dnsproxy_offline_mode(bool enabled)
3007 DBG("enabled %d", enabled);
3009 for (list = server_list; list; list = list->next) {
3010 struct server_data *data = list->data;
3013 DBG("Enabling DNS server %s", data->server);
3014 data->enabled = true;
3018 DBG("Disabling DNS server %s", data->server);
3019 data->enabled = false;
3025 static void dnsproxy_default_changed(struct connman_service *service)
3030 DBG("service %p", service);
3032 /* DNS has changed, invalidate the cache */
3036 /* When no services are active, then disable DNS proxying */
3037 dnsproxy_offline_mode(true);
3041 index = __connman_service_get_index(service);
3045 for (list = server_list; list; list = list->next) {
3046 struct server_data *data = list->data;
3048 if (data->index == index) {
3049 DBG("Enabling DNS server %s", data->server);
3050 data->enabled = true;
3052 DBG("Disabling DNS server %s", data->server);
3053 data->enabled = false;
3060 static struct connman_notifier dnsproxy_notifier = {
3062 .default_changed = dnsproxy_default_changed,
3063 .offline_mode = dnsproxy_offline_mode,
3066 static unsigned char opt_edns0_type[2] = { 0x00, 0x29 };
3068 static int parse_request(unsigned char *buf, int len,
3069 char *name, unsigned int size)
3071 struct domain_hdr *hdr = (void *) buf;
3072 uint16_t qdcount = ntohs(hdr->qdcount);
3073 uint16_t arcount = ntohs(hdr->arcount);
3075 char *last_label = NULL;
3076 unsigned int remain, used = 0;
3081 DBG("id 0x%04x qr %d opcode %d qdcount %d arcount %d",
3082 hdr->id, hdr->qr, hdr->opcode,
3085 if (hdr->qr != 0 || qdcount != 1)
3090 ptr = buf + sizeof(struct domain_hdr);
3091 remain = len - sizeof(struct domain_hdr);
3093 while (remain > 0) {
3094 uint8_t label_len = *ptr;
3096 if (label_len == 0x00) {
3097 last_label = (char *) (ptr + 1);
3101 if (used + label_len + 1 > size)
3104 strncat(name, (char *) (ptr + 1), label_len);
3107 used += label_len + 1;
3109 ptr += label_len + 1;
3110 remain -= label_len + 1;
3113 #if defined TIZEN_EXT
3114 /* parse DNS query type either A or AAAA
3115 * enforce to drop AAAA temporarily (IPv6 not supported)
3117 if (last_label != NULL) {
3118 uint16_t *type_p = (uint16_t *)last_label;
3119 uint16_t type = ntohs(*type_p);
3122 DBG("query %s is type AAAA(0x%x)", name, type);
3128 if (last_label && arcount && remain >= 9 && last_label[4] == 0 &&
3129 !memcmp(last_label + 5, opt_edns0_type, 2)) {
3130 uint16_t edns0_bufsize;
3132 edns0_bufsize = last_label[7] << 8 | last_label[8];
3134 DBG("EDNS0 buffer size %u", edns0_bufsize);
3136 /* This is an evil hack until full TCP support has been
3139 * Somtimes the EDNS0 request gets send with a too-small
3140 * buffer size. Since glibc doesn't seem to crash when it
3141 * gets a response biffer then it requested, just bump
3142 * the buffer size up to 4KiB.
3144 if (edns0_bufsize < 0x1000) {
3145 last_label[7] = 0x10;
3146 last_label[8] = 0x00;
3150 DBG("query %s", name);
3155 static void client_reset(struct tcp_partial_client_data *client)
3160 if (client->channel) {
3161 DBG("client %d closing",
3162 g_io_channel_unix_get_fd(client->channel));
3164 g_io_channel_unref(client->channel);
3165 client->channel = NULL;
3168 if (client->watch > 0) {
3169 g_source_remove(client->watch);
3173 if (client->timeout > 0) {
3174 g_source_remove(client->timeout);
3175 client->timeout = 0;
3178 g_free(client->buf);
3181 client->buf_end = 0;
3184 static unsigned int get_msg_len(unsigned char *buf)
3186 return buf[0]<<8 | buf[1];
3189 static bool read_tcp_data(struct tcp_partial_client_data *client,
3190 void *client_addr, socklen_t client_addr_len,
3193 char query[TCP_MAX_BUF_LEN];
3194 struct request_data *req;
3196 unsigned int msg_len;
3198 bool waiting_for_connect = false;
3200 struct cache_entry *entry;
3202 client_sk = g_io_channel_unix_get_fd(client->channel);
3204 if (read_len == 0) {
3205 DBG("client %d closed, pending %d bytes",
3206 client_sk, client->buf_end);
3207 g_hash_table_remove(partial_tcp_req_table,
3208 GINT_TO_POINTER(client_sk));
3212 DBG("client %d received %d bytes", client_sk, read_len);
3214 client->buf_end += read_len;
3216 if (client->buf_end < 2)
3219 msg_len = get_msg_len(client->buf);
3220 if (msg_len > TCP_MAX_BUF_LEN) {
3221 DBG("client %d sent too much data %d", client_sk, msg_len);
3222 g_hash_table_remove(partial_tcp_req_table,
3223 GINT_TO_POINTER(client_sk));
3228 DBG("client %d msg len %d end %d past end %d", client_sk, msg_len,
3229 client->buf_end, client->buf_end - (msg_len + 2));
3231 if (client->buf_end < (msg_len + 2)) {
3232 DBG("client %d still missing %d bytes",
3234 msg_len + 2 - client->buf_end);
3238 DBG("client %d all data %d received", client_sk, msg_len);
3240 err = parse_request(client->buf + 2, msg_len,
3241 query, sizeof(query));
3242 if (err < 0 || (g_slist_length(server_list) == 0)) {
3243 send_response(client_sk, client->buf, msg_len + 2,
3244 NULL, 0, IPPROTO_TCP);
3248 req = g_try_new0(struct request_data, 1);
3252 memcpy(&req->sa, client_addr, client_addr_len);
3253 req->sa_len = client_addr_len;
3254 req->client_sk = client_sk;
3255 req->protocol = IPPROTO_TCP;
3256 req->family = client->family;
3258 req->srcid = client->buf[2] | (client->buf[3] << 8);
3259 req->dstid = get_id();
3260 req->altid = get_id();
3261 req->request_len = msg_len + 2;
3263 client->buf[2] = req->dstid & 0xff;
3264 client->buf[3] = req->dstid >> 8;
3267 req->ifdata = client->ifdata;
3268 req->append_domain = false;
3271 * Check if the answer is found in the cache before
3272 * creating sockets to the server.
3274 entry = cache_check(client->buf, &qtype, IPPROTO_TCP);
3277 struct cache_data *data;
3279 DBG("cache hit %s type %s", query, qtype == 1 ? "A" : "AAAA");
3286 ttl_left = data->valid_until - time(NULL);
3289 send_cached_response(client_sk, data->data,
3290 data->data_len, NULL, 0, IPPROTO_TCP,
3291 req->srcid, data->answers, ttl_left);
3296 DBG("data missing, ignoring cache for this query");
3299 for (list = server_list; list; list = list->next) {
3300 struct server_data *data = list->data;
3302 if (data->protocol != IPPROTO_UDP || !data->enabled)
3305 if (!create_server(data->index, NULL, data->server,
3309 waiting_for_connect = true;
3312 if (!waiting_for_connect) {
3313 /* No server is waiting for connect */
3314 send_response(client_sk, client->buf,
3315 req->request_len, NULL, 0, IPPROTO_TCP);
3321 * The server is not connected yet.
3322 * Copy the relevant buffers.
3323 * The request will actually be sent once we're
3324 * properly connected over TCP to the nameserver.
3326 req->request = g_try_malloc0(req->request_len);
3327 if (!req->request) {
3328 send_response(client_sk, client->buf,
3329 req->request_len, NULL, 0, IPPROTO_TCP);
3333 memcpy(req->request, client->buf, req->request_len);
3335 req->name = g_try_malloc0(sizeof(query));
3337 send_response(client_sk, client->buf,
3338 req->request_len, NULL, 0, IPPROTO_TCP);
3339 g_free(req->request);
3343 memcpy(req->name, query, sizeof(query));
3345 req->timeout = g_timeout_add_seconds(30, request_timeout, req);
3347 request_list = g_slist_append(request_list, req);
3350 if (client->buf_end > (msg_len + 2)) {
3351 DBG("client %d buf %p -> %p end %d len %d new %d",
3353 client->buf + msg_len + 2,
3354 client->buf, client->buf_end,
3355 TCP_MAX_BUF_LEN - client->buf_end,
3356 client->buf_end - (msg_len + 2));
3357 memmove(client->buf, client->buf + msg_len + 2,
3358 TCP_MAX_BUF_LEN - client->buf_end);
3359 client->buf_end = client->buf_end - (msg_len + 2);
3362 * If we have a full message waiting, just read it
3365 msg_len = get_msg_len(client->buf);
3366 if ((msg_len + 2) == client->buf_end) {
3367 DBG("client %d reading another %d bytes", client_sk,
3372 DBG("client %d clearing reading buffer", client_sk);
3374 client->buf_end = 0;
3375 memset(client->buf, 0, TCP_MAX_BUF_LEN);
3378 * We received all the packets from client so we must also
3379 * remove the timeout handler here otherwise we might get
3380 * timeout while waiting the results from server.
3382 g_source_remove(client->timeout);
3383 client->timeout = 0;
3389 static gboolean tcp_client_event(GIOChannel *channel, GIOCondition condition,
3392 struct tcp_partial_client_data *client = user_data;
3393 struct sockaddr_in6 client_addr6;
3394 socklen_t client_addr6_len = sizeof(client_addr6);
3395 struct sockaddr_in client_addr4;
3396 socklen_t client_addr4_len = sizeof(client_addr4);
3398 socklen_t *client_addr_len;
3401 client_sk = g_io_channel_unix_get_fd(channel);
3403 if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
3404 g_hash_table_remove(partial_tcp_req_table,
3405 GINT_TO_POINTER(client_sk));
3407 connman_error("Error with TCP client %d channel", client_sk);
3411 switch (client->family) {
3413 client_addr = &client_addr4;
3414 client_addr_len = &client_addr4_len;
3417 client_addr = &client_addr6;
3418 client_addr_len = &client_addr6_len;
3421 g_hash_table_remove(partial_tcp_req_table,
3422 GINT_TO_POINTER(client_sk));
3423 connman_error("client %p corrupted", client);
3427 len = recvfrom(client_sk, client->buf + client->buf_end,
3428 TCP_MAX_BUF_LEN - client->buf_end, 0,
3429 client_addr, client_addr_len);
3431 if (errno == EAGAIN || errno == EWOULDBLOCK)
3434 DBG("client %d cannot read errno %d/%s", client_sk, -errno,
3436 g_hash_table_remove(partial_tcp_req_table,
3437 GINT_TO_POINTER(client_sk));
3441 return read_tcp_data(client, client_addr, *client_addr_len, len);
3444 static gboolean client_timeout(gpointer user_data)
3446 struct tcp_partial_client_data *client = user_data;
3449 sock = g_io_channel_unix_get_fd(client->channel);
3451 DBG("client %d timeout pending %d bytes", sock, client->buf_end);
3453 g_hash_table_remove(partial_tcp_req_table, GINT_TO_POINTER(sock));
3458 #if defined TIZEN_EXT
3459 static void recover_listener(GIOChannel *channel, struct listener_data *ifdata)
3463 index = ifdata->index;
3465 sk = g_io_channel_unix_get_fd(channel);
3468 __connman_dnsproxy_remove_listener(index);
3470 if (__connman_dnsproxy_add_listener(index) == 0)
3471 DBG("listener %d successfully recovered", index);
3475 static bool tcp_listener_event(GIOChannel *channel, GIOCondition condition,
3476 struct listener_data *ifdata, int family,
3477 guint *listener_watch)
3479 int sk, client_sk, len;
3480 unsigned int msg_len;
3481 struct tcp_partial_client_data *client;
3482 struct sockaddr_in6 client_addr6;
3483 socklen_t client_addr6_len = sizeof(client_addr6);
3484 struct sockaddr_in client_addr4;
3485 socklen_t client_addr4_len = sizeof(client_addr4);
3487 socklen_t *client_addr_len;
3491 DBG("condition 0x%02x channel %p ifdata %p family %d",
3492 condition, channel, ifdata, family);
3494 if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
3495 #if defined TIZEN_EXT
3496 connman_error("Error %d with TCP listener channel", condition);
3498 recover_listener(channel, ifdata);
3500 if (*listener_watch > 0)
3501 g_source_remove(*listener_watch);
3502 *listener_watch = 0;
3504 connman_error("Error with TCP listener channel");
3510 sk = g_io_channel_unix_get_fd(channel);
3512 if (family == AF_INET) {
3513 client_addr = &client_addr4;
3514 client_addr_len = &client_addr4_len;
3516 client_addr = &client_addr6;
3517 client_addr_len = &client_addr6_len;
3520 tv.tv_sec = tv.tv_usec = 0;
3522 FD_SET(sk, &readfds);
3524 select(sk + 1, &readfds, NULL, NULL, &tv);
3525 if (FD_ISSET(sk, &readfds)) {
3526 client_sk = accept(sk, client_addr, client_addr_len);
3527 DBG("client %d accepted", client_sk);
3529 DBG("No data to read from master %d, waiting.", sk);
3533 if (client_sk < 0) {
3534 connman_error("Accept failure on TCP listener");
3535 *listener_watch = 0;
3539 fcntl(client_sk, F_SETFL, O_NONBLOCK);
3541 client = g_hash_table_lookup(partial_tcp_req_table,
3542 GINT_TO_POINTER(client_sk));
3544 client = g_try_new0(struct tcp_partial_client_data, 1);
3550 g_hash_table_insert(partial_tcp_req_table,
3551 GINT_TO_POINTER(client_sk),
3554 client->channel = g_io_channel_unix_new(client_sk);
3555 g_io_channel_set_close_on_unref(client->channel, TRUE);
3557 client->watch = g_io_add_watch(client->channel,
3558 G_IO_IN, tcp_client_event,
3561 client->ifdata = ifdata;
3563 DBG("client %d created %p", client_sk, client);
3565 DBG("client %d already exists %p", client_sk, client);
3569 client->buf = g_try_malloc(TCP_MAX_BUF_LEN);
3573 memset(client->buf, 0, TCP_MAX_BUF_LEN);
3574 client->buf_end = 0;
3575 client->family = family;
3577 if (client->timeout == 0)
3578 client->timeout = g_timeout_add_seconds(2, client_timeout,
3582 * Check how much data there is. If all is there, then we can
3583 * proceed normally, otherwise read the bits until everything
3584 * is received or timeout occurs.
3586 len = recv(client_sk, client->buf, TCP_MAX_BUF_LEN, 0);
3588 if (errno == EAGAIN || errno == EWOULDBLOCK) {
3589 DBG("client %d no data to read, waiting", client_sk);
3593 DBG("client %d cannot read errno %d/%s", client_sk, -errno,
3595 g_hash_table_remove(partial_tcp_req_table,
3596 GINT_TO_POINTER(client_sk));
3601 DBG("client %d not enough data to read, waiting", client_sk);
3602 client->buf_end += len;
3606 msg_len = get_msg_len(client->buf);
3607 if (msg_len > TCP_MAX_BUF_LEN) {
3608 DBG("client %d invalid message length %u ignoring packet",
3609 client_sk, msg_len);
3610 g_hash_table_remove(partial_tcp_req_table,
3611 GINT_TO_POINTER(client_sk));
3616 * The packet length bytes do not contain the total message length,
3617 * that is the reason to -2 below.
3619 #if defined TIZEN_EXT
3620 if (msg_len > (unsigned int)(len - 2)) {
3622 if (msg_len != (unsigned int)(len - 2)) {
3624 DBG("client %d sent %d bytes but expecting %u pending %d",
3625 client_sk, len, msg_len + 2, msg_len + 2 - len);
3627 client->buf_end += len;
3631 return read_tcp_data(client, client_addr, *client_addr_len, len);
3634 static gboolean tcp4_listener_event(GIOChannel *channel, GIOCondition condition,
3637 struct listener_data *ifdata = user_data;
3639 return tcp_listener_event(channel, condition, ifdata, AF_INET,
3640 &ifdata->tcp4_listener_watch);
3643 static gboolean tcp6_listener_event(GIOChannel *channel, GIOCondition condition,
3646 struct listener_data *ifdata = user_data;
3648 return tcp_listener_event(channel, condition, user_data, AF_INET6,
3649 &ifdata->tcp6_listener_watch);
3652 #if defined TIZEN_EXT
3653 /* Temporarily disable AAAA type to enhance performance (IPv6 not supported) */
3654 static void __send_response_not_implemented(int sk, unsigned char *buf, int len,
3655 const struct sockaddr *to, socklen_t tolen,
3658 struct domain_hdr *hdr;
3659 int err, offset = protocol_offset(protocol);
3669 hdr = (void *) (buf + offset);
3671 DBG("id 0x%04x qr %d opcode %d", hdr->id, hdr->qr, hdr->opcode);
3680 err = sendto(sk, buf, len, MSG_NOSIGNAL, to, tolen);
3682 connman_error("Failed to send DNS response to %d: %s",
3683 sk, strerror(errno));
3687 static bool udp_listener_event(GIOChannel *channel, GIOCondition condition,
3688 struct listener_data *ifdata, int family,
3689 guint *listener_watch)
3691 unsigned char buf[768];
3693 struct request_data *req;
3694 struct sockaddr_in6 client_addr6;
3695 socklen_t client_addr6_len = sizeof(client_addr6);
3696 struct sockaddr_in client_addr4;
3697 socklen_t client_addr4_len = sizeof(client_addr4);
3699 socklen_t *client_addr_len;
3702 if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
3703 #if defined TIZEN_EXT
3704 connman_error("Error %d with UDP listener channel", condition);
3706 recover_listener(channel, ifdata);
3708 connman_error("Error with UDP listener channel");
3709 *listener_watch = 0;
3714 sk = g_io_channel_unix_get_fd(channel);
3716 if (family == AF_INET) {
3717 client_addr = &client_addr4;
3718 client_addr_len = &client_addr4_len;
3720 client_addr = &client_addr6;
3721 client_addr_len = &client_addr6_len;
3724 memset(client_addr, 0, *client_addr_len);
3725 len = recvfrom(sk, buf, sizeof(buf), 0, client_addr, client_addr_len);
3729 DBG("Received %d bytes (id 0x%04x)", len, buf[0] | buf[1] << 8);
3731 err = parse_request(buf, len, query, sizeof(query));
3732 if (err < 0 || (g_slist_length(server_list) == 0)) {
3733 #if defined TIZEN_EXT
3734 if (err == -ENOENT) {
3735 /* Temporarily disable AAAA type to enhance performance
3736 * (IPv6 not supported)
3738 __send_response_not_implemented(sk, buf, len, client_addr,
3739 *client_addr_len, IPPROTO_UDP);
3743 send_response(sk, buf, len, client_addr,
3744 *client_addr_len, IPPROTO_UDP);
3748 req = g_try_new0(struct request_data, 1);
3752 memcpy(&req->sa, client_addr, *client_addr_len);
3753 req->sa_len = *client_addr_len;
3755 req->protocol = IPPROTO_UDP;
3756 req->family = family;
3758 req->srcid = buf[0] | (buf[1] << 8);
3759 req->dstid = get_id();
3760 req->altid = get_id();
3761 req->request_len = len;
3763 buf[0] = req->dstid & 0xff;
3764 buf[1] = req->dstid >> 8;
3767 req->ifdata = ifdata;
3768 req->append_domain = false;
3770 if (resolv(req, buf, query)) {
3771 /* a cached result was sent, so the request can be released */
3776 req->name = g_strdup(query);
3777 req->request = g_malloc(len);
3778 memcpy(req->request, buf, len);
3779 #if defined TIZEN_EXT
3780 DBG("req %p dstid 0x%04x altid 0x%04x", req, req->dstid, req->altid);
3781 req->timeout = g_timeout_add_seconds(30, request_timeout, req);
3783 req->timeout = g_timeout_add_seconds(5, request_timeout, req);
3785 request_list = g_slist_append(request_list, req);
3790 static gboolean udp4_listener_event(GIOChannel *channel, GIOCondition condition,
3793 struct listener_data *ifdata = user_data;
3795 return udp_listener_event(channel, condition, ifdata, AF_INET,
3796 &ifdata->udp4_listener_watch);
3799 static gboolean udp6_listener_event(GIOChannel *channel, GIOCondition condition,
3802 struct listener_data *ifdata = user_data;
3804 return udp_listener_event(channel, condition, user_data, AF_INET6,
3805 &ifdata->udp6_listener_watch);
3808 static GIOChannel *get_listener(int family, int protocol, int index)
3810 GIOChannel *channel;
3814 struct sockaddr_in6 sin6;
3815 struct sockaddr_in sin;
3819 #if !defined TIZEN_EXT
3822 #if defined TIZEN_EXT
3826 DBG("family %d protocol %d index %d", family, protocol, index);
3831 type = SOCK_DGRAM | SOCK_CLOEXEC;
3836 type = SOCK_STREAM | SOCK_CLOEXEC;
3843 sk = socket(family, type, protocol);
3844 if (sk < 0 && family == AF_INET6 && errno == EAFNOSUPPORT) {
3845 connman_error("No IPv6 support");
3850 connman_error("Failed to create %s listener socket", proto);
3854 #if !defined TIZEN_EXT
3855 /* ConnMan listens DNS from multiple interfaces
3856 * E.g. various technology based and tethering interfaces
3858 interface = connman_inet_ifname(index);
3859 if (!interface || setsockopt(sk, SOL_SOCKET, SO_BINDTODEVICE,
3861 strlen(interface) + 1) < 0) {
3862 connman_error("Failed to bind %s listener interface "
3864 proto, family == AF_INET ? "IPv4" : "IPv6",
3865 -errno, strerror(errno));
3873 if (family == AF_INET6) {
3874 memset(&s.sin6, 0, sizeof(s.sin6));
3875 s.sin6.sin6_family = AF_INET6;
3876 s.sin6.sin6_port = htons(53);
3877 slen = sizeof(s.sin6);
3878 #if defined TIZEN_EXT
3879 s.sin6.sin6_addr = in6addr_any;
3881 if (__connman_inet_get_interface_address(index,
3883 &s.sin6.sin6_addr) < 0) {
3884 /* So we could not find suitable IPv6 address for
3885 * the interface. This could happen if we have
3886 * disabled IPv6 for the interface.
3893 } else if (family == AF_INET) {
3894 memset(&s.sin, 0, sizeof(s.sin));
3895 s.sin.sin_family = AF_INET;
3896 s.sin.sin_port = htons(53);
3897 slen = sizeof(s.sin);
3898 #if defined TIZEN_EXT
3899 s.sin.sin_addr.s_addr = htonl(INADDR_ANY);
3901 if (__connman_inet_get_interface_address(index,
3903 &s.sin.sin_addr) < 0) {
3913 #if defined TIZEN_EXT
3914 /* When ConnMan crashed,
3915 * probably DNS listener cannot bind existing address */
3917 setsockopt(sk, SOL_SOCKET, SO_REUSEADDR, &option, sizeof(option));
3919 if (bind(sk, &s.sa, slen) < 0) {
3920 connman_error("Failed to bind %s listener socket", proto);
3925 if (protocol == IPPROTO_TCP) {
3927 if (listen(sk, 10) < 0) {
3928 connman_error("Failed to listen on TCP socket %d/%s",
3929 -errno, strerror(errno));
3934 fcntl(sk, F_SETFL, O_NONBLOCK);
3937 channel = g_io_channel_unix_new(sk);
3939 connman_error("Failed to create %s listener channel", proto);
3944 g_io_channel_set_close_on_unref(channel, TRUE);
3949 #define UDP_IPv4_FAILED 0x01
3950 #define TCP_IPv4_FAILED 0x02
3951 #define UDP_IPv6_FAILED 0x04
3952 #define TCP_IPv6_FAILED 0x08
3953 #define UDP_FAILED (UDP_IPv4_FAILED | UDP_IPv6_FAILED)
3954 #define TCP_FAILED (TCP_IPv4_FAILED | TCP_IPv6_FAILED)
3955 #define IPv6_FAILED (UDP_IPv6_FAILED | TCP_IPv6_FAILED)
3956 #define IPv4_FAILED (UDP_IPv4_FAILED | TCP_IPv4_FAILED)
3958 static int create_dns_listener(int protocol, struct listener_data *ifdata)
3962 if (protocol == IPPROTO_TCP) {
3963 ifdata->tcp4_listener_channel = get_listener(AF_INET, protocol,
3965 if (ifdata->tcp4_listener_channel)
3966 #if defined TIZEN_EXT
3967 ifdata->tcp4_listener_watch =
3968 g_io_add_watch(ifdata->tcp4_listener_channel,
3969 G_IO_IN | G_IO_ERR | G_IO_HUP | G_IO_NVAL,
3970 tcp4_listener_event, (gpointer)ifdata);
3972 ifdata->tcp4_listener_watch =
3973 g_io_add_watch(ifdata->tcp4_listener_channel,
3974 G_IO_IN, tcp4_listener_event,
3978 ret |= TCP_IPv4_FAILED;
3980 ifdata->tcp6_listener_channel = get_listener(AF_INET6, protocol,
3982 if (ifdata->tcp6_listener_channel)
3983 #if defined TIZEN_EXT
3984 ifdata->tcp6_listener_watch =
3985 g_io_add_watch(ifdata->tcp6_listener_channel,
3986 G_IO_IN | G_IO_ERR | G_IO_HUP | G_IO_NVAL,
3987 tcp6_listener_event, (gpointer)ifdata);
3989 ifdata->tcp6_listener_watch =
3990 g_io_add_watch(ifdata->tcp6_listener_channel,
3991 G_IO_IN, tcp6_listener_event,
3995 ret |= TCP_IPv6_FAILED;
3997 ifdata->udp4_listener_channel = get_listener(AF_INET, protocol,
3999 if (ifdata->udp4_listener_channel)
4000 #if defined TIZEN_EXT
4001 ifdata->udp4_listener_watch =
4002 g_io_add_watch(ifdata->udp4_listener_channel,
4003 G_IO_IN | G_IO_ERR | G_IO_HUP | G_IO_NVAL,
4004 udp4_listener_event, (gpointer)ifdata);
4006 ifdata->udp4_listener_watch =
4007 g_io_add_watch(ifdata->udp4_listener_channel,
4008 G_IO_IN, udp4_listener_event,
4012 ret |= UDP_IPv4_FAILED;
4014 ifdata->udp6_listener_channel = get_listener(AF_INET6, protocol,
4016 if (ifdata->udp6_listener_channel)
4017 #if defined TIZEN_EXT
4018 ifdata->udp6_listener_watch =
4019 g_io_add_watch(ifdata->udp6_listener_channel,
4020 G_IO_IN | G_IO_ERR | G_IO_HUP | G_IO_NVAL,
4021 udp6_listener_event, (gpointer)ifdata);
4023 ifdata->udp6_listener_watch =
4024 g_io_add_watch(ifdata->udp6_listener_channel,
4025 G_IO_IN, udp6_listener_event,
4029 ret |= UDP_IPv6_FAILED;
4035 static void destroy_udp_listener(struct listener_data *ifdata)
4037 DBG("index %d", ifdata->index);
4039 if (ifdata->udp4_listener_watch > 0)
4040 g_source_remove(ifdata->udp4_listener_watch);
4042 if (ifdata->udp6_listener_watch > 0)
4043 g_source_remove(ifdata->udp6_listener_watch);
4045 if (ifdata->udp4_listener_channel)
4046 g_io_channel_unref(ifdata->udp4_listener_channel);
4047 if (ifdata->udp6_listener_channel)
4048 g_io_channel_unref(ifdata->udp6_listener_channel);
4051 static void destroy_tcp_listener(struct listener_data *ifdata)
4053 DBG("index %d", ifdata->index);
4055 if (ifdata->tcp4_listener_watch > 0)
4056 g_source_remove(ifdata->tcp4_listener_watch);
4057 if (ifdata->tcp6_listener_watch > 0)
4058 g_source_remove(ifdata->tcp6_listener_watch);
4060 if (ifdata->tcp4_listener_channel)
4061 g_io_channel_unref(ifdata->tcp4_listener_channel);
4062 if (ifdata->tcp6_listener_channel)
4063 g_io_channel_unref(ifdata->tcp6_listener_channel);
4066 static int create_listener(struct listener_data *ifdata)
4070 err = create_dns_listener(IPPROTO_UDP, ifdata);
4071 if ((err & UDP_FAILED) == UDP_FAILED)
4074 err |= create_dns_listener(IPPROTO_TCP, ifdata);
4075 if ((err & TCP_FAILED) == TCP_FAILED) {
4076 destroy_udp_listener(ifdata);
4080 index = connman_inet_ifindex("lo");
4081 if (ifdata->index == index) {
4082 if ((err & IPv6_FAILED) != IPv6_FAILED)
4083 __connman_resolvfile_append(index, NULL, "::1");
4085 if ((err & IPv4_FAILED) != IPv4_FAILED)
4086 __connman_resolvfile_append(index, NULL, "127.0.0.1");
4092 static void destroy_listener(struct listener_data *ifdata)
4097 index = connman_inet_ifindex("lo");
4098 if (ifdata->index == index) {
4099 __connman_resolvfile_remove(index, NULL, "127.0.0.1");
4100 __connman_resolvfile_remove(index, NULL, "::1");
4103 for (list = request_list; list; list = list->next) {
4104 struct request_data *req = list->data;
4106 DBG("Dropping request (id 0x%04x -> 0x%04x)",
4107 req->srcid, req->dstid);
4108 destroy_request_data(req);
4112 g_slist_free(request_list);
4113 request_list = NULL;
4115 destroy_tcp_listener(ifdata);
4116 destroy_udp_listener(ifdata);
4119 int __connman_dnsproxy_add_listener(int index)
4121 struct listener_data *ifdata;
4124 DBG("index %d", index);
4129 if (!listener_table)
4132 if (g_hash_table_lookup(listener_table, GINT_TO_POINTER(index)))
4135 ifdata = g_try_new0(struct listener_data, 1);
4139 ifdata->index = index;
4140 ifdata->udp4_listener_channel = NULL;
4141 ifdata->udp4_listener_watch = 0;
4142 ifdata->tcp4_listener_channel = NULL;
4143 ifdata->tcp4_listener_watch = 0;
4144 ifdata->udp6_listener_channel = NULL;
4145 ifdata->udp6_listener_watch = 0;
4146 ifdata->tcp6_listener_channel = NULL;
4147 ifdata->tcp6_listener_watch = 0;
4149 err = create_listener(ifdata);
4151 connman_error("Couldn't create listener for index %d err %d",
4156 g_hash_table_insert(listener_table, GINT_TO_POINTER(ifdata->index),
4161 void __connman_dnsproxy_remove_listener(int index)
4163 struct listener_data *ifdata;
4165 DBG("index %d", index);
4167 if (!listener_table)
4170 ifdata = g_hash_table_lookup(listener_table, GINT_TO_POINTER(index));
4174 destroy_listener(ifdata);
4176 g_hash_table_remove(listener_table, GINT_TO_POINTER(index));
4179 static void remove_listener(gpointer key, gpointer value, gpointer user_data)
4181 int index = GPOINTER_TO_INT(key);
4182 struct listener_data *ifdata = value;
4184 DBG("index %d", index);
4186 destroy_listener(ifdata);
4189 static void free_partial_reqs(gpointer value)
4191 struct tcp_partial_client_data *data = value;
4197 int __connman_dnsproxy_init(void)
4203 srandom(time(NULL));
4205 listener_table = g_hash_table_new_full(g_direct_hash, g_direct_equal,
4208 partial_tcp_req_table = g_hash_table_new_full(g_direct_hash,
4213 index = connman_inet_ifindex("lo");
4214 err = __connman_dnsproxy_add_listener(index);
4218 err = connman_notifier_register(&dnsproxy_notifier);
4225 __connman_dnsproxy_remove_listener(index);
4226 g_hash_table_destroy(listener_table);
4227 g_hash_table_destroy(partial_tcp_req_table);
4232 void __connman_dnsproxy_cleanup(void)
4236 connman_notifier_unregister(&dnsproxy_notifier);
4238 g_hash_table_foreach(listener_table, remove_listener, NULL);
4240 g_hash_table_destroy(listener_table);
4242 g_hash_table_destroy(partial_tcp_req_table);