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>
48 #if __BYTE_ORDER == __LITTLE_ENDIAN
63 } __attribute__ ((packed));
64 #elif __BYTE_ORDER == __BIG_ENDIAN
79 } __attribute__ ((packed));
81 #error "Unknown byte order"
84 struct partial_reply {
94 struct sockaddr *server_addr;
95 socklen_t server_addr_len;
102 struct partial_reply *incoming_reply;
105 struct request_data {
107 struct sockaddr_in6 __sin6; /* Only for the length */
126 struct listener_data *ifdata;
130 struct listener_data {
133 GIOChannel *udp4_listener_channel;
134 GIOChannel *tcp4_listener_channel;
135 guint udp4_listener_watch;
136 guint tcp4_listener_watch;
138 GIOChannel *udp6_listener_channel;
139 GIOChannel *tcp6_listener_channel;
140 guint udp6_listener_watch;
141 guint tcp6_listener_watch;
145 * The TCP client requires some extra handling as we need to
146 * be prepared to receive also partial DNS requests.
148 struct tcp_partial_client_data {
150 struct listener_data *ifdata;
154 unsigned int buf_end;
165 unsigned int data_len;
166 unsigned char *data; /* contains DNS header + body */
173 struct cache_data *ipv4;
174 struct cache_data *ipv6;
177 struct domain_question {
180 } __attribute__ ((packed));
187 } __attribute__ ((packed));
190 * Max length of the DNS TCP packet.
192 #define TCP_MAX_BUF_LEN 4096
195 * We limit how long the cached DNS entry stays in the cache.
196 * By default the TTL (time-to-live) of the DNS response is used
197 * when setting the cache entry life time. The value is in seconds.
199 #if defined TIZEN_EXT
200 #define MAX_CACHE_TTL (60 * 60)
202 #define MAX_CACHE_TTL (60 * 30)
205 * Also limit the other end, cache at least for 30 seconds.
207 #define MIN_CACHE_TTL (30)
210 * We limit the cache size to some sane value so that cached data does
211 * not occupy too much memory. Each cached entry occupies on average
212 * about 100 bytes memory (depending on DNS name length).
213 * Example: caching www.connman.net uses 97 bytes memory.
214 * The value is the max amount of cached DNS responses (count).
216 #define MAX_CACHE_SIZE 256
218 static int cache_size;
219 static GHashTable *cache;
220 static int cache_refcount;
221 static GSList *server_list = NULL;
222 #if defined TIZEN_EXT
223 static GSList *server_list_sec = NULL;
225 static GSList *request_list = NULL;
226 static GHashTable *listener_table = NULL;
227 static time_t next_refresh;
228 static GHashTable *partial_tcp_req_table;
229 static guint cache_timer = 0;
231 #if defined TIZEN_EXT
232 static void destroy_server_sec(struct server_data *server);
233 static struct server_data *create_server_sec(int index,
234 const char *domain, const char *server,
238 static guint16 get_id(void)
242 __connman_util_get_random(&rand);
247 static int protocol_offset(int protocol)
263 * There is a power and efficiency benefit to have entries
264 * in our cache expire at the same time. To this extend,
265 * we round down the cache valid time to common boundaries.
267 static time_t round_down_ttl(time_t end_time, int ttl)
272 /* Less than 5 minutes, round to 10 second boundary */
274 end_time = end_time / 10;
275 end_time = end_time * 10;
276 } else { /* 5 or more minutes, round to 30 seconds */
277 end_time = end_time / 30;
278 end_time = end_time * 30;
283 static struct request_data *find_request(guint16 id)
287 for (list = request_list; list; list = list->next) {
288 struct request_data *req = list->data;
290 if (req->dstid == id || req->altid == id)
297 static struct server_data *find_server(int index,
303 DBG("index %d server %s proto %d", index, server, protocol);
305 for (list = server_list; list; list = list->next) {
306 struct server_data *data = list->data;
308 if (index < 0 && data->index < 0 &&
309 g_str_equal(data->server, server) &&
310 data->protocol == protocol)
314 data->index < 0 || !data->server)
317 if (data->index == index &&
318 g_str_equal(data->server, server) &&
319 data->protocol == protocol)
326 /* we can keep using the same resolve's */
327 static GResolv *ipv4_resolve;
328 static GResolv *ipv6_resolve;
330 static void dummy_resolve_func(GResolvResultStatus status,
331 char **results, gpointer user_data)
336 * Refresh a DNS entry, but also age the hit count a bit */
337 static void refresh_dns_entry(struct cache_entry *entry, char *name)
342 ipv4_resolve = g_resolv_new(0);
343 g_resolv_set_address_family(ipv4_resolve, AF_INET);
344 g_resolv_add_nameserver(ipv4_resolve, "127.0.0.1", 53, 0);
348 ipv6_resolve = g_resolv_new(0);
349 g_resolv_set_address_family(ipv6_resolve, AF_INET6);
350 g_resolv_add_nameserver(ipv6_resolve, "::1", 53, 0);
354 DBG("Refresing A record for %s", name);
355 g_resolv_lookup_hostname(ipv4_resolve, name,
356 dummy_resolve_func, NULL);
361 DBG("Refresing AAAA record for %s", name);
362 g_resolv_lookup_hostname(ipv6_resolve, name,
363 dummy_resolve_func, NULL);
372 static int dns_name_length(unsigned char *buf)
374 if ((buf[0] & NS_CMPRSFLGS) == NS_CMPRSFLGS) /* compressed name */
376 return strlen((char *)buf);
379 static void update_cached_ttl(unsigned char *buf, int len, int new_ttl)
385 /* skip the header */
389 /* skip the query, which is a name and 2 16 bit words */
390 l = dns_name_length(c);
396 /* now we get the answer records */
400 l = dns_name_length(c);
405 /* then type + class, 2 bytes each */
411 /* now the 4 byte TTL field */
412 c[0] = new_ttl >> 24 & 0xff;
413 c[1] = new_ttl >> 16 & 0xff;
414 c[2] = new_ttl >> 8 & 0xff;
415 c[3] = new_ttl & 0xff;
421 /* now the 2 byte rdlen field */
422 w = c[0] << 8 | c[1];
428 static void send_cached_response(int sk, unsigned char *buf, int len,
429 const struct sockaddr *to, socklen_t tolen,
430 int protocol, int id, uint16_t answers, int ttl)
432 struct domain_hdr *hdr;
433 unsigned char *ptr = buf;
434 int err, offset, dns_len, adj_len = len - 2;
437 * The cached packet contains always the TCP offset (two bytes)
438 * so skip them for UDP.
449 dns_len = ptr[0] * 256 + ptr[1];
458 hdr = (void *) (ptr + offset);
462 hdr->rcode = ns_r_noerror;
463 hdr->ancount = htons(answers);
467 /* if this is a negative reply, we are authorative */
471 update_cached_ttl((unsigned char *)hdr, adj_len, ttl);
473 DBG("sk %d id 0x%04x answers %d ptr %p length %d dns %d",
474 sk, hdr->id, answers, ptr, len, dns_len);
476 err = sendto(sk, ptr, len, MSG_NOSIGNAL, to, tolen);
478 connman_error("Cannot send cached DNS response: %s",
483 if (err != len || (dns_len != (len - 2) && protocol == IPPROTO_TCP) ||
484 (dns_len != len && protocol == IPPROTO_UDP))
485 DBG("Packet length mismatch, sent %d wanted %d dns %d",
489 static void send_response(int sk, unsigned char *buf, int len,
490 const struct sockaddr *to, socklen_t tolen,
493 struct domain_hdr *hdr;
494 int err, offset = protocol_offset(protocol);
504 hdr = (void *) (buf + offset);
506 DBG("id 0x%04x qr %d opcode %d", hdr->id, hdr->qr, hdr->opcode);
509 hdr->rcode = ns_r_servfail;
515 err = sendto(sk, buf, len, MSG_NOSIGNAL, to, tolen);
517 connman_error("Failed to send DNS response to %d: %s",
518 sk, strerror(errno));
523 static int get_req_udp_socket(struct request_data *req)
527 if (req->family == AF_INET)
528 channel = req->ifdata->udp4_listener_channel;
530 channel = req->ifdata->udp6_listener_channel;
535 return g_io_channel_unix_get_fd(channel);
538 static void destroy_request_data(struct request_data *req)
540 if (req->timeout > 0)
541 g_source_remove(req->timeout);
544 g_free(req->request);
549 static gboolean request_timeout(gpointer user_data)
551 struct request_data *req = user_data;
558 DBG("id 0x%04x", req->srcid);
560 request_list = g_slist_remove(request_list, req);
562 if (req->protocol == IPPROTO_UDP) {
563 sk = get_req_udp_socket(req);
565 } else if (req->protocol == IPPROTO_TCP) {
571 if (req->resplen > 0 && req->resp) {
573 * Here we have received at least one reply (probably telling
574 * "not found" result), so send that back to client instead
575 * of more fatal server failed error.
578 sendto(sk, req->resp, req->resplen, MSG_NOSIGNAL,
581 } else if (req->request) {
583 * There was not reply from server at all.
585 struct domain_hdr *hdr;
587 hdr = (void *)(req->request + protocol_offset(req->protocol));
588 hdr->id = req->srcid;
591 send_response(sk, req->request, req->request_len,
592 sa, req->sa_len, req->protocol);
596 * We cannot leave TCP client hanging so just kick it out
597 * if we get a request timeout from server.
599 if (req->protocol == IPPROTO_TCP) {
600 DBG("client %d removed", req->client_sk);
601 g_hash_table_remove(partial_tcp_req_table,
602 GINT_TO_POINTER(req->client_sk));
607 destroy_request_data(req);
612 static int append_query(unsigned char *buf, unsigned int size,
613 const char *query, const char *domain)
615 unsigned char *ptr = buf;
618 DBG("query %s domain %s", query, domain);
623 tmp = strchr(query, '.');
629 memcpy(ptr + 1, query, len);
635 memcpy(ptr + 1, query, tmp - query);
636 ptr += tmp - query + 1;
644 tmp = strchr(domain, '.');
646 len = strlen(domain);
650 memcpy(ptr + 1, domain, len);
656 memcpy(ptr + 1, domain, tmp - domain);
657 ptr += tmp - domain + 1;
667 static bool cache_check_is_valid(struct cache_data *data,
673 if (data->cache_until < current_time)
680 * remove stale cached entries so that they can be refreshed
682 static void cache_enforce_validity(struct cache_entry *entry)
684 time_t current_time = time(NULL);
686 if (!cache_check_is_valid(entry->ipv4, current_time)
688 DBG("cache timeout \"%s\" type A", entry->key);
689 g_free(entry->ipv4->data);
695 if (!cache_check_is_valid(entry->ipv6, current_time)
697 DBG("cache timeout \"%s\" type AAAA", entry->key);
698 g_free(entry->ipv6->data);
704 static uint16_t cache_check_validity(char *question, uint16_t type,
705 struct cache_entry *entry)
707 time_t current_time = time(NULL);
708 bool want_refresh = false;
711 * if we have a popular entry, we want a refresh instead of
712 * total destruction of the entry.
717 cache_enforce_validity(entry);
721 if (!cache_check_is_valid(entry->ipv4, current_time)) {
722 DBG("cache %s \"%s\" type A", entry->ipv4 ?
723 "timeout" : "entry missing", question);
726 entry->want_refresh = true;
729 * We do not remove cache entry if there is still
730 * valid IPv6 entry found in the cache.
732 if (!cache_check_is_valid(entry->ipv6, current_time) && !want_refresh) {
733 g_hash_table_remove(cache, question);
740 if (!cache_check_is_valid(entry->ipv6, current_time)) {
741 DBG("cache %s \"%s\" type AAAA", entry->ipv6 ?
742 "timeout" : "entry missing", question);
745 entry->want_refresh = true;
747 if (!cache_check_is_valid(entry->ipv4, current_time) && !want_refresh) {
748 g_hash_table_remove(cache, question);
758 static void cache_element_destroy(gpointer value)
760 struct cache_entry *entry = value;
766 g_free(entry->ipv4->data);
771 g_free(entry->ipv6->data);
778 if (--cache_size < 0)
782 static gboolean try_remove_cache(gpointer user_data)
786 if (__sync_fetch_and_sub(&cache_refcount, 1) == 1) {
787 DBG("No cache users, removing it.");
789 g_hash_table_destroy(cache);
796 static void create_cache(void)
798 if (__sync_fetch_and_add(&cache_refcount, 1) == 0)
799 cache = g_hash_table_new_full(g_str_hash,
802 cache_element_destroy);
805 static struct cache_entry *cache_check(gpointer request, int *qtype, int proto)
808 struct cache_entry *entry;
809 struct domain_question *q;
811 int offset, proto_offset;
816 proto_offset = protocol_offset(proto);
817 if (proto_offset < 0)
820 question = request + proto_offset + 12;
822 offset = strlen(question) + 1;
823 q = (void *) (question + offset);
824 type = ntohs(q->type);
826 /* We only cache either A (1) or AAAA (28) requests */
827 if (type != 1 && type != 28)
835 entry = g_hash_table_lookup(cache, question);
839 type = cache_check_validity(question, type, entry);
848 * Get a label/name from DNS resource record. The function decompresses the
849 * label if necessary. The function does not convert the name to presentation
850 * form. This means that the result string will contain label lengths instead
851 * of dots between labels. We intentionally do not want to convert to dotted
852 * format so that we can cache the wire format string directly.
854 static int get_name(int counter,
855 unsigned char *pkt, unsigned char *start, unsigned char *max,
856 unsigned char *output, int output_max, int *output_len,
857 unsigned char **end, char *name, int *name_len)
861 /* Limit recursion to 10 (this means up to 10 labels in domain name) */
867 if ((*p & NS_CMPRSFLGS) == NS_CMPRSFLGS) {
868 uint16_t offset = (*p & 0x3F) * 256 + *(p + 1);
870 if (offset >= max - pkt)
876 return get_name(counter + 1, pkt, pkt + offset, max,
877 output, output_max, output_len, end,
880 unsigned label_len = *p;
882 if (pkt + label_len > max)
885 if (*output_len > output_max)
889 * We need the original name in order to check
890 * if this answer is the correct one.
892 name[(*name_len)++] = label_len;
893 memcpy(name + *name_len, p + 1, label_len + 1);
894 *name_len += label_len;
896 /* We compress the result */
897 output[0] = NS_CMPRSFLGS;
914 static int parse_rr(unsigned char *buf, unsigned char *start,
916 unsigned char *response, unsigned int *response_size,
917 uint16_t *type, uint16_t *class, int *ttl, int *rdlen,
921 struct domain_rr *rr;
923 int name_len = 0, output_len = 0, max_rsp = *response_size;
925 err = get_name(0, buf, start, max, response, max_rsp,
926 &output_len, end, name, &name_len);
932 if ((unsigned int) offset > *response_size)
935 rr = (void *) (*end);
940 *type = ntohs(rr->type);
941 *class = ntohs(rr->class);
942 *ttl = ntohl(rr->ttl);
943 *rdlen = ntohs(rr->rdlen);
948 memcpy(response + offset, *end, sizeof(struct domain_rr));
950 offset += sizeof(struct domain_rr);
951 *end += sizeof(struct domain_rr);
953 if ((unsigned int) (offset + *rdlen) > *response_size)
956 memcpy(response + offset, *end, *rdlen);
960 *response_size = offset + *rdlen;
965 static bool check_alias(GSList *aliases, char *name)
970 for (list = aliases; list; list = list->next) {
971 int len = strlen((char *)list->data);
972 if (strncmp((char *)list->data, name, len) == 0)
980 static int parse_response(unsigned char *buf, int buflen,
981 char *question, int qlen,
982 uint16_t *type, uint16_t *class, int *ttl,
983 unsigned char *response, unsigned int *response_len,
986 struct domain_hdr *hdr = (void *) buf;
987 struct domain_question *q;
989 uint16_t qdcount = ntohs(hdr->qdcount);
990 uint16_t ancount = ntohs(hdr->ancount);
992 uint16_t qtype, qclass;
993 unsigned char *next = NULL;
994 unsigned int maxlen = *response_len;
995 GSList *aliases = NULL, *list;
996 char name[NS_MAXDNAME + 1];
1001 DBG("qr %d qdcount %d", hdr->qr, qdcount);
1003 /* We currently only cache responses where question count is 1 */
1004 if (hdr->qr != 1 || qdcount != 1)
1007 ptr = buf + sizeof(struct domain_hdr);
1009 strncpy(question, (char *) ptr, qlen);
1010 qlen = strlen(question);
1011 ptr += qlen + 1; /* skip \0 */
1014 qtype = ntohs(q->type);
1016 /* We cache only A and AAAA records */
1017 if (qtype != 1 && qtype != 28)
1020 qclass = ntohs(q->class);
1022 ptr += 2 + 2; /* ptr points now to answers */
1028 memset(name, 0, sizeof(name));
1031 * We have a bunch of answers (like A, AAAA, CNAME etc) to
1032 * A or AAAA question. We traverse the answers and parse the
1033 * resource records. Only A and AAAA records are cached, all
1034 * the other records in answers are skipped.
1036 for (i = 0; i < ancount; i++) {
1038 * Get one address at a time to this buffer.
1039 * The max size of the answer is
1040 * 2 (pointer) + 2 (type) + 2 (class) +
1041 * 4 (ttl) + 2 (rdlen) + addr (16 or 4) = 28
1042 * for A or AAAA record.
1043 * For CNAME the size can be bigger.
1045 unsigned char rsp[NS_MAXCDNAME];
1046 unsigned int rsp_len = sizeof(rsp) - 1;
1049 memset(rsp, 0, sizeof(rsp));
1051 ret = parse_rr(buf, ptr, buf + buflen, rsp, &rsp_len,
1052 type, class, ttl, &rdlen, &next, name);
1059 * Now rsp contains compressed or uncompressed resource
1060 * record. Next we check if this record answers the question.
1061 * The name var contains the uncompressed label.
1062 * One tricky bit is the CNAME records as they alias
1063 * the name we might be interested in.
1067 * Go to next answer if the class is not the one we are
1070 if (*class != qclass) {
1077 * Try to resolve aliases also, type is CNAME(5).
1078 * This is important as otherwise the aliased names would not
1079 * be cached at all as the cache would not contain the aliased
1082 * If any CNAME is found in DNS packet, then we cache the alias
1083 * IP address instead of the question (as the server
1084 * said that question has only an alias).
1085 * This means in practice that if e.g., ipv6.google.com is
1086 * queried, DNS server returns CNAME of that name which is
1087 * ipv6.l.google.com. We then cache the address of the CNAME
1088 * but return the question name to client. So the alias
1089 * status of the name is not saved in cache and thus not
1090 * returned to the client. We do not return DNS packets from
1091 * cache to client saying that ipv6.google.com is an alias to
1092 * ipv6.l.google.com but we return instead a DNS packet that
1093 * says ipv6.google.com has address xxx which is in fact the
1094 * address of ipv6.l.google.com. For caching purposes this
1095 * should not cause any issues.
1097 if (*type == 5 && strncmp(question, name, qlen) == 0) {
1099 * So now the alias answered the question. This is
1100 * not very useful from caching point of view as
1101 * the following A or AAAA records will not match the
1102 * question. We need to find the real A/AAAA record
1103 * of the alias and cache that.
1105 unsigned char *end = NULL;
1106 int name_len = 0, output_len = 0;
1108 memset(rsp, 0, sizeof(rsp));
1109 rsp_len = sizeof(rsp) - 1;
1112 * Alias is in rdata part of the message,
1113 * and next-rdlen points to it. So we need to get
1114 * the real name of the alias.
1116 ret = get_name(0, buf, next - rdlen, buf + buflen,
1117 rsp, rsp_len, &output_len, &end,
1120 /* just ignore the error at this point */
1127 * We should now have the alias of the entry we might
1128 * want to cache. Just remember it for a while.
1129 * We check the alias list when we have parsed the
1132 aliases = g_slist_prepend(aliases, g_strdup(name));
1139 if (*type == qtype) {
1141 * We found correct type (A or AAAA)
1143 if (check_alias(aliases, name) ||
1144 (!aliases && strncmp(question, name,
1147 * We found an alias or the name of the rr
1148 * matches the question. If so, we append
1149 * the compressed label to the cache.
1150 * The end result is a response buffer that
1151 * will contain one or more cached and
1152 * compressed resource records.
1154 if (*response_len + rsp_len > maxlen) {
1158 memcpy(response + *response_len, rsp, rsp_len);
1159 *response_len += rsp_len;
1170 for (list = aliases; list; list = list->next)
1172 g_slist_free(aliases);
1177 struct cache_timeout {
1178 time_t current_time;
1183 static gboolean cache_check_entry(gpointer key, gpointer value,
1186 struct cache_timeout *data = user_data;
1187 struct cache_entry *entry = value;
1190 /* Scale the number of hits by half as part of cache aging */
1195 * If either IPv4 or IPv6 cached entry has expired, we
1196 * remove both from the cache.
1199 if (entry->ipv4 && entry->ipv4->timeout > 0) {
1200 max_timeout = entry->ipv4->cache_until;
1201 if (max_timeout > data->max_timeout)
1202 data->max_timeout = max_timeout;
1204 if (entry->ipv4->cache_until < data->current_time)
1208 if (entry->ipv6 && entry->ipv6->timeout > 0) {
1209 max_timeout = entry->ipv6->cache_until;
1210 if (max_timeout > data->max_timeout)
1211 data->max_timeout = max_timeout;
1213 if (entry->ipv6->cache_until < data->current_time)
1218 * if we're asked to try harder, also remove entries that have
1221 if (data->try_harder && entry->hits < 4)
1227 static void cache_cleanup(void)
1229 static int max_timeout;
1230 struct cache_timeout data;
1233 data.current_time = time(NULL);
1234 data.max_timeout = 0;
1235 data.try_harder = 0;
1238 * In the first pass, we only remove entries that have timed out.
1239 * We use a cache of the first time to expire to do this only
1240 * when it makes sense.
1242 if (max_timeout <= data.current_time) {
1243 count = g_hash_table_foreach_remove(cache, cache_check_entry,
1246 DBG("removed %d in the first pass", count);
1249 * In the second pass, if the first pass turned up blank,
1250 * we also expire entries with a low hit count,
1251 * while aging the hit count at the same time.
1253 data.try_harder = 1;
1255 count = g_hash_table_foreach_remove(cache, cache_check_entry,
1260 * If we could not remove anything, then remember
1261 * what is the max timeout and do nothing if we
1262 * have not yet reached it. This will prevent
1263 * constant traversal of the cache if it is full.
1265 max_timeout = data.max_timeout;
1270 static gboolean cache_invalidate_entry(gpointer key, gpointer value,
1273 struct cache_entry *entry = value;
1275 /* first, delete any expired elements */
1276 cache_enforce_validity(entry);
1278 /* if anything is not expired, mark the entry for refresh */
1279 if (entry->hits > 0 && (entry->ipv4 || entry->ipv6))
1280 entry->want_refresh = true;
1282 /* delete the cached data */
1284 g_free(entry->ipv4->data);
1285 g_free(entry->ipv4);
1290 g_free(entry->ipv6->data);
1291 g_free(entry->ipv6);
1295 /* keep the entry if we want it refreshed, delete it otherwise */
1296 if (entry->want_refresh)
1303 * cache_invalidate is called from places where the DNS landscape
1304 * has changed, say because connections are added or we entered a VPN.
1305 * The logic is to wipe all cache data, but mark all non-expired
1306 * parts of the cache for refresh rather than deleting the whole cache.
1308 static void cache_invalidate(void)
1310 DBG("Invalidating the DNS cache %p", cache);
1315 g_hash_table_foreach_remove(cache, cache_invalidate_entry, NULL);
1318 static void cache_refresh_entry(struct cache_entry *entry)
1321 cache_enforce_validity(entry);
1323 if (entry->hits > 2 && !entry->ipv4)
1324 entry->want_refresh = true;
1325 if (entry->hits > 2 && !entry->ipv6)
1326 entry->want_refresh = true;
1328 if (entry->want_refresh) {
1330 char dns_name[NS_MAXDNAME + 1];
1331 entry->want_refresh = false;
1333 /* turn a DNS name into a hostname with dots */
1334 strncpy(dns_name, entry->key, NS_MAXDNAME);
1342 DBG("Refreshing %s\n", dns_name);
1343 /* then refresh the hostname */
1344 refresh_dns_entry(entry, &dns_name[1]);
1348 static void cache_refresh_iterator(gpointer key, gpointer value,
1351 struct cache_entry *entry = value;
1353 cache_refresh_entry(entry);
1356 static void cache_refresh(void)
1361 g_hash_table_foreach(cache, cache_refresh_iterator, NULL);
1364 static int reply_query_type(unsigned char *msg, int len)
1370 /* skip the header */
1371 c = msg + sizeof(struct domain_hdr);
1372 len -= sizeof(struct domain_hdr);
1377 /* now the query, which is a name and 2 16 bit words */
1378 l = dns_name_length(c) + 1;
1380 type = c[0] << 8 | c[1];
1385 static int cache_update(struct server_data *srv, unsigned char *msg,
1386 unsigned int msg_len)
1388 int offset = protocol_offset(srv->protocol);
1389 int err, qlen, ttl = 0;
1390 uint16_t answers = 0, type = 0, class = 0;
1391 struct domain_hdr *hdr = (void *)(msg + offset);
1392 struct domain_question *q;
1393 struct cache_entry *entry;
1394 struct cache_data *data;
1395 char question[NS_MAXDNAME + 1];
1396 unsigned char response[NS_MAXDNAME + 1];
1398 unsigned int rsplen;
1399 bool new_entry = true;
1400 time_t current_time;
1402 if (cache_size >= MAX_CACHE_SIZE) {
1404 if (cache_size >= MAX_CACHE_SIZE)
1408 current_time = time(NULL);
1410 /* don't do a cache refresh more than twice a minute */
1411 if (next_refresh < current_time) {
1413 next_refresh = current_time + 30;
1419 DBG("offset %d hdr %p msg %p rcode %d", offset, hdr, msg, hdr->rcode);
1421 /* Continue only if response code is 0 (=ok) */
1422 if (hdr->rcode != ns_r_noerror)
1428 rsplen = sizeof(response) - 1;
1429 question[sizeof(question) - 1] = '\0';
1431 err = parse_response(msg + offset, msg_len - offset,
1432 question, sizeof(question) - 1,
1433 &type, &class, &ttl,
1434 response, &rsplen, &answers);
1437 * special case: if we do a ipv6 lookup and get no result
1438 * for a record that's already in our ipv4 cache.. we want
1439 * to cache the negative response.
1441 if ((err == -ENOMSG || err == -ENOBUFS) &&
1442 reply_query_type(msg + offset,
1443 msg_len - offset) == 28) {
1444 entry = g_hash_table_lookup(cache, question);
1445 if (entry && entry->ipv4 && !entry->ipv6) {
1446 int cache_offset = 0;
1448 data = g_try_new(struct cache_data, 1);
1451 data->inserted = entry->ipv4->inserted;
1453 data->answers = ntohs(hdr->ancount);
1454 data->timeout = entry->ipv4->timeout;
1455 if (srv->protocol == IPPROTO_UDP)
1457 data->data_len = msg_len + cache_offset;
1458 data->data = ptr = g_malloc(data->data_len);
1459 ptr[0] = (data->data_len - 2) / 256;
1460 ptr[1] = (data->data_len - 2) - ptr[0] * 256;
1461 if (srv->protocol == IPPROTO_UDP)
1463 data->valid_until = entry->ipv4->valid_until;
1464 data->cache_until = entry->ipv4->cache_until;
1465 memcpy(ptr, msg, msg_len);
1468 * we will get a "hit" when we serve the response
1472 if (entry->hits < 0)
1478 if (err < 0 || ttl == 0)
1481 qlen = strlen(question);
1484 * If the cache contains already data, check if the
1485 * type of the cached data is the same and do not add
1486 * to cache if data is already there.
1487 * This is needed so that we can cache both A and AAAA
1488 * records for the same name.
1490 entry = g_hash_table_lookup(cache, question);
1492 entry = g_try_new(struct cache_entry, 1);
1496 data = g_try_new(struct cache_data, 1);
1502 entry->key = g_strdup(question);
1503 entry->ipv4 = entry->ipv6 = NULL;
1504 entry->want_refresh = false;
1512 if (type == 1 && entry->ipv4)
1515 if (type == 28 && entry->ipv6)
1518 data = g_try_new(struct cache_data, 1);
1528 * compensate for the hit we'll get for serving
1529 * the response out of the cache
1532 if (entry->hits < 0)
1538 if (ttl < MIN_CACHE_TTL)
1539 ttl = MIN_CACHE_TTL;
1541 data->inserted = current_time;
1543 data->answers = answers;
1544 data->timeout = ttl;
1546 * The "2" in start of the length is the TCP offset. We allocate it
1547 * here even for UDP packet because it simplifies the sending
1550 data->data_len = 2 + 12 + qlen + 1 + 2 + 2 + rsplen;
1551 data->data = ptr = g_malloc(data->data_len);
1552 data->valid_until = current_time + ttl;
1555 * Restrict the cached DNS record TTL to some sane value
1556 * in order to prevent data staying in the cache too long.
1558 if (ttl > MAX_CACHE_TTL)
1559 ttl = MAX_CACHE_TTL;
1561 data->cache_until = round_down_ttl(current_time + ttl, ttl);
1571 * We cache the two extra bytes at the start of the message
1572 * in a TCP packet. When sending UDP packet, we skip the first
1573 * two bytes. This way we do not need to know the format
1574 * (UDP/TCP) of the cached message.
1576 if (srv->protocol == IPPROTO_UDP)
1577 memcpy(ptr + 2, msg, offset + 12);
1579 memcpy(ptr, msg, offset + 12);
1581 ptr[0] = (data->data_len - 2) / 256;
1582 ptr[1] = (data->data_len - 2) - ptr[0] * 256;
1583 if (srv->protocol == IPPROTO_UDP)
1586 memcpy(ptr + offset + 12, question, qlen + 1); /* copy also the \0 */
1588 q = (void *) (ptr + offset + 12 + qlen + 1);
1589 q->type = htons(type);
1590 q->class = htons(class);
1591 memcpy(ptr + offset + 12 + qlen + 1 + sizeof(struct domain_question),
1595 g_hash_table_replace(cache, entry->key, entry);
1599 DBG("cache %d %squestion \"%s\" type %d ttl %d size %zd packet %u "
1601 cache_size, new_entry ? "new " : "old ",
1602 question, type, ttl,
1603 sizeof(*entry) + sizeof(*data) + data->data_len + qlen,
1605 srv->protocol == IPPROTO_TCP ?
1606 (unsigned int)(data->data[0] * 256 + data->data[1]) :
1612 static int ns_resolv(struct server_data *server, struct request_data *req,
1613 gpointer request, gpointer name)
1616 int sk, err, type = 0;
1617 char *dot, *lookup = (char *) name;
1618 struct cache_entry *entry;
1620 entry = cache_check(request, &type, req->protocol);
1623 struct cache_data *data;
1625 DBG("cache hit %s type %s", lookup, type == 1 ? "A" : "AAAA");
1632 ttl_left = data->valid_until - time(NULL);
1636 if (data && req->protocol == IPPROTO_TCP) {
1637 send_cached_response(req->client_sk, data->data,
1638 data->data_len, NULL, 0, IPPROTO_TCP,
1639 req->srcid, data->answers, ttl_left);
1643 if (data && req->protocol == IPPROTO_UDP) {
1644 int udp_sk = get_req_udp_socket(req);
1649 send_cached_response(udp_sk, data->data,
1650 data->data_len, &req->sa, req->sa_len,
1651 IPPROTO_UDP, req->srcid, data->answers,
1657 #if defined TIZEN_EXT
1658 if (server->protocol == IPPROTO_UDP) {
1660 struct server_data *new_server = NULL;
1662 new_server = create_server_sec(server->index, NULL,
1663 server->server, IPPROTO_UDP);
1665 if (new_server != NULL) {
1666 for (domains = server->domains; domains;
1667 domains = domains->next) {
1668 char *dom = domains->data;
1670 DBG("Adding domain %s to %s",
1671 dom, new_server->server);
1673 new_server->domains = g_list_append(
1674 new_server->domains,
1678 server = new_server;
1682 sk = g_io_channel_unix_get_fd(server->channel);
1684 err = sendto(sk, request, req->request_len, MSG_NOSIGNAL,
1685 server->server_addr, server->server_addr_len);
1687 DBG("Cannot send message to server %s sock %d "
1688 "protocol %d (%s/%d)",
1689 server->server, sk, server->protocol,
1690 strerror(errno), errno);
1696 /* If we have more than one dot, we don't add domains */
1697 dot = strchr(lookup, '.');
1698 if (dot && dot != lookup + strlen(lookup) - 1)
1701 if (server->domains && server->domains->data)
1702 req->append_domain = true;
1704 for (list = server->domains; list; list = list->next) {
1706 unsigned char alt[1024];
1707 struct domain_hdr *hdr = (void *) &alt;
1708 int altlen, domlen, offset;
1710 domain = list->data;
1715 offset = protocol_offset(server->protocol);
1719 domlen = strlen(domain) + 1;
1723 alt[offset] = req->altid & 0xff;
1724 alt[offset + 1] = req->altid >> 8;
1726 memcpy(alt + offset + 2, request + offset + 2, 10);
1727 hdr->qdcount = htons(1);
1729 altlen = append_query(alt + offset + 12, sizeof(alt) - 12,
1736 memcpy(alt + offset + altlen,
1737 request + offset + altlen - domlen,
1738 req->request_len - altlen - offset + domlen);
1740 if (server->protocol == IPPROTO_TCP) {
1741 int req_len = req->request_len + domlen - 2;
1743 alt[0] = (req_len >> 8) & 0xff;
1744 alt[1] = req_len & 0xff;
1747 DBG("req %p dstid 0x%04x altid 0x%04x", req, req->dstid,
1750 err = send(sk, alt, req->request_len + domlen, MSG_NOSIGNAL);
1760 static char *convert_label(char *start, char *end, char *ptr, char *uptr,
1761 int remaining_len, int *used_comp, int *used_uncomp)
1764 char name[NS_MAXLABEL];
1766 pos = dn_expand((u_char *)start, (u_char *)end, (u_char *)ptr,
1769 DBG("uncompress error [%d/%s]", errno, strerror(errno));
1774 * We need to compress back the name so that we get back to internal
1775 * label presentation.
1777 comp_pos = dn_comp(name, (u_char *)uptr, remaining_len, NULL, NULL);
1779 DBG("compress error [%d/%s]", errno, strerror(errno));
1784 *used_uncomp = comp_pos;
1792 static char *uncompress(int16_t field_count, char *start, char *end,
1793 char *ptr, char *uncompressed, int uncomp_len,
1794 char **uncompressed_ptr)
1796 char *uptr = *uncompressed_ptr; /* position in result buffer */
1798 DBG("count %d ptr %p end %p uptr %p", field_count, ptr, end, uptr);
1800 while (field_count-- > 0 && ptr < end) {
1801 int dlen; /* data field length */
1802 int ulen; /* uncompress length */
1803 int pos; /* position in compressed string */
1804 char name[NS_MAXLABEL]; /* tmp label */
1805 uint16_t dns_type, dns_class;
1808 if (!convert_label(start, end, ptr, name, NS_MAXLABEL,
1813 * Copy the uncompressed resource record, type, class and \0 to
1817 ulen = strlen(name);
1818 strncpy(uptr, name, uncomp_len - (uptr - uncompressed));
1820 DBG("pos %d ulen %d left %d name %s", pos, ulen,
1821 (int)(uncomp_len - (uptr - uncompressed)), uptr);
1829 * We copy also the fixed portion of the result (type, class,
1830 * ttl, address length and the address)
1832 memcpy(uptr, ptr, NS_RRFIXEDSZ);
1834 dns_type = uptr[0] << 8 | uptr[1];
1835 dns_class = uptr[2] << 8 | uptr[3];
1837 if (dns_class != ns_c_in)
1840 ptr += NS_RRFIXEDSZ;
1841 uptr += NS_RRFIXEDSZ;
1844 * Then the variable portion of the result (data length).
1845 * Typically this portion is also compressed
1846 * so we need to uncompress it also when necessary.
1848 if (dns_type == ns_t_cname) {
1849 if (!convert_label(start, end, ptr, uptr,
1850 uncomp_len - (uptr - uncompressed),
1854 uptr[-2] = comp_pos << 8;
1855 uptr[-1] = comp_pos & 0xff;
1860 } else if (dns_type == ns_t_a || dns_type == ns_t_aaaa) {
1861 dlen = uptr[-2] << 8 | uptr[-1];
1863 if (ptr + dlen > end) {
1864 DBG("data len %d too long", dlen);
1868 memcpy(uptr, ptr, dlen);
1872 } else if (dns_type == ns_t_soa) {
1876 /* Primary name server expansion */
1877 if (!convert_label(start, end, ptr, uptr,
1878 uncomp_len - (uptr - uncompressed),
1882 total_len += comp_pos;
1883 len_ptr = &uptr[-2];
1887 /* Responsible authority's mailbox */
1888 if (!convert_label(start, end, ptr, uptr,
1889 uncomp_len - (uptr - uncompressed),
1893 total_len += comp_pos;
1898 * Copy rest of the soa fields (serial number,
1899 * refresh interval, retry interval, expiration
1900 * limit and minimum ttl). They are 20 bytes long.
1902 memcpy(uptr, ptr, 20);
1908 * Finally fix the length of the data part
1910 len_ptr[0] = total_len << 8;
1911 len_ptr[1] = total_len & 0xff;
1914 *uncompressed_ptr = uptr;
1923 static int strip_domains(char *name, char *answers, int maxlen)
1926 int name_len = strlen(name);
1927 char *ptr, *start = answers, *end = answers + maxlen;
1929 while (maxlen > 0) {
1930 ptr = strstr(answers, name);
1932 char *domain = ptr + name_len;
1935 int domain_len = strlen(domain);
1937 memmove(answers + name_len,
1938 domain + domain_len,
1939 end - (domain + domain_len));
1942 maxlen -= domain_len;
1946 answers += strlen(answers) + 1;
1947 answers += 2 + 2 + 4; /* skip type, class and ttl fields */
1949 data_len = answers[0] << 8 | answers[1];
1950 answers += 2; /* skip the length field */
1952 if (answers + data_len > end)
1955 answers += data_len;
1956 maxlen -= answers - ptr;
1962 static int forward_dns_reply(unsigned char *reply, int reply_len, int protocol,
1963 struct server_data *data)
1965 struct domain_hdr *hdr;
1966 struct request_data *req;
1967 int dns_id, sk, err, offset = protocol_offset(protocol);
1972 hdr = (void *)(reply + offset);
1973 dns_id = reply[offset] | reply[offset + 1] << 8;
1975 DBG("Received %d bytes (id 0x%04x)", reply_len, dns_id);
1977 req = find_request(dns_id);
1981 DBG("req %p dstid 0x%04x altid 0x%04x rcode %d",
1982 req, req->dstid, req->altid, hdr->rcode);
1984 reply[offset] = req->srcid & 0xff;
1985 reply[offset + 1] = req->srcid >> 8;
1989 if (hdr->rcode == ns_r_noerror || !req->resp) {
1990 unsigned char *new_reply = NULL;
1993 * If the domain name was append
1994 * remove it before forwarding the reply.
1995 * If there were more than one question, then this
1996 * domain name ripping can be hairy so avoid that
1997 * and bail out in that that case.
1999 * The reason we are doing this magic is that if the
2000 * user's DNS client tries to resolv hostname without
2001 * domain part, it also expects to get the result without
2002 * a domain name part.
2004 if (req->append_domain && ntohs(hdr->qdcount) == 1) {
2005 uint16_t domain_len = 0;
2006 uint16_t header_len;
2007 uint16_t dns_type, dns_class;
2008 uint8_t host_len, dns_type_pos;
2009 char uncompressed[NS_MAXDNAME], *uptr;
2010 char *ptr, *eom = (char *)reply + reply_len;
2013 * ptr points to the first char of the hostname.
2014 * ->hostname.domain.net
2016 header_len = offset + sizeof(struct domain_hdr);
2017 ptr = (char *)reply + header_len;
2021 domain_len = strnlen(ptr + 1 + host_len,
2022 reply_len - header_len);
2025 * If the query type is anything other than A or AAAA,
2026 * then bail out and pass the message as is.
2027 * We only want to deal with IPv4 or IPv6 addresses.
2029 dns_type_pos = host_len + 1 + domain_len + 1;
2031 dns_type = ptr[dns_type_pos] << 8 |
2032 ptr[dns_type_pos + 1];
2033 dns_class = ptr[dns_type_pos + 2] << 8 |
2034 ptr[dns_type_pos + 3];
2035 if (dns_type != ns_t_a && dns_type != ns_t_aaaa &&
2036 dns_class != ns_c_in) {
2037 DBG("Pass msg dns type %d class %d",
2038 dns_type, dns_class);
2043 * Remove the domain name and replace it by the end
2044 * of reply. Check if the domain is really there
2045 * before trying to copy the data. We also need to
2046 * uncompress the answers if necessary.
2047 * The domain_len can be 0 because if the original
2048 * query did not contain a domain name, then we are
2049 * sending two packets, first without the domain name
2050 * and the second packet with domain name.
2051 * The append_domain is set to true even if we sent
2052 * the first packet without domain name. In this
2053 * case we end up in this branch.
2055 if (domain_len > 0) {
2056 int len = host_len + 1;
2057 int new_len, fixed_len;
2061 * First copy host (without domain name) into
2064 uptr = &uncompressed[0];
2065 memcpy(uptr, ptr, len);
2067 uptr[len] = '\0'; /* host termination */
2071 * Copy type and class fields of the question.
2073 ptr += len + domain_len + 1;
2074 memcpy(uptr, ptr, NS_QFIXEDSZ);
2077 * ptr points to answers after this
2080 uptr += NS_QFIXEDSZ;
2082 fixed_len = answers - uncompressed;
2085 * We then uncompress the result to buffer
2086 * so that we can rip off the domain name
2087 * part from the question. First answers,
2088 * then name server (authority) information,
2089 * and finally additional record info.
2092 ptr = uncompress(ntohs(hdr->ancount),
2093 (char *)reply + offset, eom,
2094 ptr, uncompressed, NS_MAXDNAME,
2099 ptr = uncompress(ntohs(hdr->nscount),
2100 (char *)reply + offset, eom,
2101 ptr, uncompressed, NS_MAXDNAME,
2106 ptr = uncompress(ntohs(hdr->arcount),
2107 (char *)reply + offset, eom,
2108 ptr, uncompressed, NS_MAXDNAME,
2114 * The uncompressed buffer now contains almost
2115 * valid response. Final step is to get rid of
2116 * the domain name because at least glibc
2117 * gethostbyname() implementation does extra
2118 * checks and expects to find an answer without
2119 * domain name if we asked a query without
2120 * domain part. Note that glibc getaddrinfo()
2121 * works differently and accepts FQDN in answer
2123 new_len = strip_domains(uncompressed, answers,
2126 DBG("Corrupted packet");
2131 * Because we have now uncompressed the answers
2132 * we might have to create a bigger buffer to
2133 * hold all that data.
2136 reply_len = header_len + new_len + fixed_len;
2138 new_reply = g_try_malloc(reply_len);
2142 memcpy(new_reply, reply, header_len);
2143 memcpy(new_reply + header_len, uncompressed,
2144 new_len + fixed_len);
2154 req->resp = g_try_malloc(reply_len);
2158 memcpy(req->resp, reply, reply_len);
2159 req->resplen = reply_len;
2161 cache_update(data, reply, reply_len);
2167 if (req->numresp < req->numserv) {
2168 if (hdr->rcode > ns_r_noerror) {
2170 } else if (hdr->ancount == 0 && req->append_domain) {
2175 request_list = g_slist_remove(request_list, req);
2177 if (protocol == IPPROTO_UDP) {
2178 sk = get_req_udp_socket(req);
2183 err = sendto(sk, req->resp, req->resplen, 0,
2184 &req->sa, req->sa_len);
2186 sk = req->client_sk;
2187 err = send(sk, req->resp, req->resplen, MSG_NOSIGNAL);
2191 DBG("Cannot send msg, sk %d proto %d errno %d/%s", sk,
2192 protocol, errno, strerror(errno));
2194 DBG("proto %d sent %d bytes to %d", protocol, err, sk);
2196 destroy_request_data(req);
2201 static void server_destroy_socket(struct server_data *data)
2203 DBG("index %d server %s proto %d", data->index,
2204 data->server, data->protocol);
2206 if (data->watch > 0) {
2207 g_source_remove(data->watch);
2211 if (data->timeout > 0) {
2212 g_source_remove(data->timeout);
2216 if (data->channel) {
2217 g_io_channel_shutdown(data->channel, TRUE, NULL);
2218 g_io_channel_unref(data->channel);
2219 data->channel = NULL;
2222 g_free(data->incoming_reply);
2223 data->incoming_reply = NULL;
2226 static void destroy_server(struct server_data *server)
2228 DBG("index %d server %s sock %d", server->index, server->server,
2230 g_io_channel_unix_get_fd(server->channel): -1);
2232 server_list = g_slist_remove(server_list, server);
2233 server_destroy_socket(server);
2235 if (server->protocol == IPPROTO_UDP && server->enabled)
2236 DBG("Removing DNS server %s", server->server);
2238 g_free(server->server);
2239 g_list_free_full(server->domains, g_free);
2240 g_free(server->server_addr);
2243 * We do not remove cache right away but delay it few seconds.
2244 * The idea is that when IPv6 DNS server is added via RDNSS, it has a
2245 * lifetime. When the lifetime expires we decrease the refcount so it
2246 * is possible that the cache is then removed. Because a new DNS server
2247 * is usually created almost immediately we would then loose the cache
2248 * without any good reason. The small delay allows the new RDNSS to
2249 * create a new DNS server instance and the refcount does not go to 0.
2251 if (cache && !cache_timer)
2252 cache_timer = g_timeout_add_seconds(3, try_remove_cache, NULL);
2257 static gboolean udp_server_event(GIOChannel *channel, GIOCondition condition,
2260 unsigned char buf[4096];
2262 struct server_data *data = user_data;
2264 if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
2265 connman_error("Error with UDP server %s", data->server);
2266 server_destroy_socket(data);
2270 sk = g_io_channel_unix_get_fd(channel);
2272 len = recv(sk, buf, sizeof(buf), 0);
2276 err = forward_dns_reply(buf, len, IPPROTO_UDP, data);
2280 #if defined TIZEN_EXT
2283 for (list = server_list_sec; list; list = list->next) {
2284 struct server_data *new_data = list->data;
2286 if (new_data == data) {
2287 destroy_server_sec(data);
2296 static gboolean tcp_server_event(GIOChannel *channel, GIOCondition condition,
2300 struct server_data *server = user_data;
2302 sk = g_io_channel_unix_get_fd(channel);
2306 if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
2309 DBG("TCP server channel closed, sk %d", sk);
2312 * Discard any partial response which is buffered; better
2313 * to get a proper response from a working server.
2315 g_free(server->incoming_reply);
2316 server->incoming_reply = NULL;
2318 for (list = request_list; list; list = list->next) {
2319 struct request_data *req = list->data;
2320 struct domain_hdr *hdr;
2322 if (req->protocol == IPPROTO_UDP)
2329 * If we're not waiting for any further response
2330 * from another name server, then we send an error
2331 * response to the client.
2333 if (req->numserv && --(req->numserv))
2336 hdr = (void *) (req->request + 2);
2337 hdr->id = req->srcid;
2338 send_response(req->client_sk, req->request,
2339 req->request_len, NULL, 0, IPPROTO_TCP);
2341 request_list = g_slist_remove(request_list, req);
2344 destroy_server(server);
2349 if ((condition & G_IO_OUT) && !server->connected) {
2352 bool no_request_sent = true;
2353 struct server_data *udp_server;
2355 udp_server = find_server(server->index, server->server,
2358 for (domains = udp_server->domains; domains;
2359 domains = domains->next) {
2360 char *dom = domains->data;
2362 DBG("Adding domain %s to %s",
2363 dom, server->server);
2365 server->domains = g_list_append(server->domains,
2370 server->connected = true;
2371 server_list = g_slist_append(server_list, server);
2373 if (server->timeout > 0) {
2374 g_source_remove(server->timeout);
2375 server->timeout = 0;
2378 for (list = request_list; list; ) {
2379 struct request_data *req = list->data;
2382 if (req->protocol == IPPROTO_UDP) {
2387 DBG("Sending req %s over TCP", (char *)req->name);
2389 status = ns_resolv(server, req,
2390 req->request, req->name);
2393 * A cached result was sent,
2394 * so the request can be released
2397 request_list = g_slist_remove(request_list, req);
2398 destroy_request_data(req);
2407 no_request_sent = false;
2409 if (req->timeout > 0)
2410 g_source_remove(req->timeout);
2412 req->timeout = g_timeout_add_seconds(30,
2413 request_timeout, req);
2417 if (no_request_sent) {
2418 destroy_server(server);
2422 } else if (condition & G_IO_IN) {
2423 struct partial_reply *reply = server->incoming_reply;
2427 unsigned char reply_len_buf[2];
2430 bytes_recv = recv(sk, reply_len_buf, 2, MSG_PEEK);
2433 } else if (bytes_recv < 0) {
2434 if (errno == EAGAIN || errno == EWOULDBLOCK)
2437 connman_error("DNS proxy error %s",
2440 } else if (bytes_recv < 2)
2443 reply_len = reply_len_buf[1] | reply_len_buf[0] << 8;
2446 DBG("TCP reply %d bytes from %d", reply_len, sk);
2448 reply = g_try_malloc(sizeof(*reply) + reply_len + 2);
2452 reply->len = reply_len;
2453 reply->received = 0;
2455 server->incoming_reply = reply;
2458 while (reply->received < reply->len) {
2459 bytes_recv = recv(sk, reply->buf + reply->received,
2460 reply->len - reply->received, 0);
2462 connman_error("DNS proxy TCP disconnect");
2464 } else if (bytes_recv < 0) {
2465 if (errno == EAGAIN || errno == EWOULDBLOCK)
2468 connman_error("DNS proxy error %s",
2472 reply->received += bytes_recv;
2475 forward_dns_reply(reply->buf, reply->received, IPPROTO_TCP,
2479 server->incoming_reply = NULL;
2481 destroy_server(server);
2489 static gboolean tcp_idle_timeout(gpointer user_data)
2491 struct server_data *server = user_data;
2498 destroy_server(server);
2503 static int server_create_socket(struct server_data *data)
2508 DBG("index %d server %s proto %d", data->index,
2509 data->server, data->protocol);
2511 sk = socket(data->server_addr->sa_family,
2512 data->protocol == IPPROTO_TCP ? SOCK_STREAM : SOCK_DGRAM,
2516 connman_error("Failed to create server %s socket",
2518 server_destroy_socket(data);
2524 interface = connman_inet_ifname(data->index);
2526 if (setsockopt(sk, SOL_SOCKET, SO_BINDTODEVICE,
2528 strlen(interface) + 1) < 0) {
2530 connman_error("Failed to bind server %s "
2532 data->server, interface);
2534 server_destroy_socket(data);
2541 data->channel = g_io_channel_unix_new(sk);
2542 if (!data->channel) {
2543 connman_error("Failed to create server %s channel",
2546 server_destroy_socket(data);
2550 g_io_channel_set_close_on_unref(data->channel, TRUE);
2552 if (data->protocol == IPPROTO_TCP) {
2553 g_io_channel_set_flags(data->channel, G_IO_FLAG_NONBLOCK, NULL);
2554 data->watch = g_io_add_watch(data->channel,
2555 G_IO_OUT | G_IO_IN | G_IO_HUP | G_IO_NVAL | G_IO_ERR,
2556 tcp_server_event, data);
2557 data->timeout = g_timeout_add_seconds(30, tcp_idle_timeout,
2560 data->watch = g_io_add_watch(data->channel,
2561 G_IO_IN | G_IO_NVAL | G_IO_ERR | G_IO_HUP,
2562 udp_server_event, data);
2564 if (connect(sk, data->server_addr, data->server_addr_len) < 0) {
2567 if ((data->protocol == IPPROTO_TCP && errno != EINPROGRESS) ||
2568 data->protocol == IPPROTO_UDP) {
2570 connman_error("Failed to connect to server %s",
2572 server_destroy_socket(data);
2582 #if defined TIZEN_EXT
2584 static void destroy_server_sec(struct server_data *server)
2589 if (server->channel)
2590 fd = g_io_channel_unix_get_fd(server->channel);
2594 DBG("index %d server %s sock %d", server->index, server->server, fd);
2596 server_list_sec = g_slist_remove(server_list_sec, server);
2601 server_destroy_socket(server);
2603 if (server->protocol == IPPROTO_UDP && server->enabled)
2604 DBG("Removing DNS server %s", server->server);
2606 g_free(server->server);
2607 for (list = server->domains; list; list = list->next) {
2608 char *domain = list->data;
2610 server->domains = g_list_remove(server->domains, domain);
2613 g_free(server->server_addr);
2616 * We do not remove cache right away but delay it few seconds.
2617 * The idea is that when IPv6 DNS server is added via RDNSS, it has a
2618 * lifetime. When the lifetime expires we decrease the refcount so it
2619 * is possible that the cache is then removed. Because a new DNS server
2620 * is usually created almost immediately we would then loose the cache
2621 * without any good reason. The small delay allows the new RDNSS to
2622 * create a new DNS server instance and the refcount does not go to 0.
2624 /* TODO: Need to check this */
2625 /* g_timeout_add_seconds(3, try_remove_cache, NULL); */
2630 static void destroy_all_server_sec()
2634 DBG("remove all dns server");
2636 for (list = server_list_sec; list; list = list->next) {
2637 struct server_data *server = list->data;
2638 destroy_server_sec(server);
2640 server_list_sec = NULL;
2643 static gboolean sec_udp_idle_timeout(gpointer user_data)
2645 struct server_data *server = user_data;
2652 destroy_server_sec(server);
2657 static struct server_data *create_server_sec(int index,
2658 const char *domain, const char *server,
2661 struct server_data *data;
2662 struct addrinfo hints, *rp;
2665 DBG("index %d server %s", index, server);
2667 data = g_try_new0(struct server_data, 1);
2669 connman_error("Failed to allocate server %s data", server);
2673 data->index = index;
2675 data->domains = g_list_append(data->domains, g_strdup(domain));
2676 data->server = g_strdup(server);
2677 data->protocol = protocol;
2679 memset(&hints, 0, sizeof(hints));
2683 hints.ai_socktype = SOCK_DGRAM;
2687 hints.ai_socktype = SOCK_STREAM;
2691 destroy_server_sec(data);
2694 hints.ai_family = AF_UNSPEC;
2695 hints.ai_flags = AI_NUMERICSERV | AI_NUMERICHOST;
2697 ret = getaddrinfo(data->server, "53", &hints, &rp);
2699 connman_error("Failed to parse server %s address: %s\n",
2700 data->server, gai_strerror(ret));
2702 destroy_server_sec(data);
2706 /* Do not blindly copy this code elsewhere; it doesn't loop over the
2707 results using ->ai_next as it should. That's OK in *this* case
2708 because it was a numeric lookup; we *know* there's only one. */
2710 data->server_addr_len = rp->ai_addrlen;
2712 switch (rp->ai_family) {
2714 data->server_addr = (struct sockaddr *)
2715 g_try_new0(struct sockaddr_in, 1);
2718 data->server_addr = (struct sockaddr *)
2719 g_try_new0(struct sockaddr_in6, 1);
2722 connman_error("Wrong address family %d", rp->ai_family);
2725 if (data->server_addr == NULL) {
2727 destroy_server_sec(data);
2730 memcpy(data->server_addr, rp->ai_addr, rp->ai_addrlen);
2733 if (server_create_socket(data) != 0) {
2734 destroy_server_sec(data);
2738 if (protocol == IPPROTO_UDP) {
2739 /* Enable new servers by default */
2740 data->enabled = TRUE;
2741 DBG("Adding DNS server %s", data->server);
2743 data->timeout = g_timeout_add_seconds(30, sec_udp_idle_timeout,
2746 server_list_sec = g_slist_append(server_list_sec, data);
2753 static struct server_data *create_server(int index,
2754 const char *domain, const char *server,
2757 struct server_data *data;
2758 struct addrinfo hints, *rp;
2761 DBG("index %d server %s", index, server);
2763 data = g_try_new0(struct server_data, 1);
2765 connman_error("Failed to allocate server %s data", server);
2769 data->index = index;
2771 data->domains = g_list_append(data->domains, g_strdup(domain));
2772 data->server = g_strdup(server);
2773 data->protocol = protocol;
2775 memset(&hints, 0, sizeof(hints));
2779 hints.ai_socktype = SOCK_DGRAM;
2783 hints.ai_socktype = SOCK_STREAM;
2787 destroy_server(data);
2790 hints.ai_family = AF_UNSPEC;
2791 hints.ai_flags = AI_NUMERICSERV | AI_NUMERICHOST;
2793 ret = getaddrinfo(data->server, "53", &hints, &rp);
2795 connman_error("Failed to parse server %s address: %s\n",
2796 data->server, gai_strerror(ret));
2797 destroy_server(data);
2801 /* Do not blindly copy this code elsewhere; it doesn't loop over the
2802 results using ->ai_next as it should. That's OK in *this* case
2803 because it was a numeric lookup; we *know* there's only one. */
2805 data->server_addr_len = rp->ai_addrlen;
2807 switch (rp->ai_family) {
2809 data->server_addr = (struct sockaddr *)
2810 g_try_new0(struct sockaddr_in, 1);
2813 data->server_addr = (struct sockaddr *)
2814 g_try_new0(struct sockaddr_in6, 1);
2817 connman_error("Wrong address family %d", rp->ai_family);
2820 if (!data->server_addr) {
2822 destroy_server(data);
2825 memcpy(data->server_addr, rp->ai_addr, rp->ai_addrlen);
2828 if (server_create_socket(data) != 0) {
2829 destroy_server(data);
2833 if (protocol == IPPROTO_UDP) {
2834 if (__connman_service_index_is_default(data->index) ||
2835 __connman_service_index_is_split_routing(
2837 data->enabled = true;
2838 DBG("Adding DNS server %s", data->server);
2841 server_list = g_slist_append(server_list, data);
2847 static bool resolv(struct request_data *req,
2848 gpointer request, gpointer name)
2852 for (list = server_list; list; list = list->next) {
2853 struct server_data *data = list->data;
2855 if (data->protocol == IPPROTO_TCP) {
2856 DBG("server %s ignored proto TCP", data->server);
2860 DBG("server %s enabled %d", data->server, data->enabled);
2865 if (!data->channel && data->protocol == IPPROTO_UDP) {
2866 if (server_create_socket(data) < 0) {
2867 DBG("socket creation failed while resolving");
2872 if (ns_resolv(data, req, request, name) > 0)
2879 static void append_domain(int index, const char *domain)
2883 DBG("index %d domain %s", index, domain);
2888 for (list = server_list; list; list = list->next) {
2889 struct server_data *data = list->data;
2892 bool dom_found = false;
2894 if (data->index < 0)
2897 if (data->index != index)
2900 for (dom_list = data->domains; dom_list;
2901 dom_list = dom_list->next) {
2902 dom = dom_list->data;
2904 if (g_str_equal(dom, domain)) {
2912 g_list_append(data->domains, g_strdup(domain));
2917 static void flush_requests(struct server_data *server)
2921 list = request_list;
2923 struct request_data *req = list->data;
2927 if (ns_resolv(server, req, req->request, req->name)) {
2929 * A cached result was sent,
2930 * so the request can be released
2933 g_slist_remove(request_list, req);
2934 destroy_request_data(req);
2938 if (req->timeout > 0)
2939 g_source_remove(req->timeout);
2941 req->timeout = g_timeout_add_seconds(5, request_timeout, req);
2945 int __connman_dnsproxy_append(int index, const char *domain,
2948 struct server_data *data;
2950 DBG("index %d server %s", index, server);
2952 if (!server && !domain)
2956 append_domain(index, domain);
2961 if (g_str_equal(server, "127.0.0.1"))
2964 if (g_str_equal(server, "::1"))
2967 data = find_server(index, server, IPPROTO_UDP);
2969 append_domain(index, domain);
2973 data = create_server(index, domain, server, IPPROTO_UDP);
2977 flush_requests(data);
2982 static void remove_server(int index, const char *domain,
2983 const char *server, int protocol)
2985 struct server_data *data;
2987 data = find_server(index, server, protocol);
2991 destroy_server(data);
2994 int __connman_dnsproxy_remove(int index, const char *domain,
2997 DBG("index %d server %s", index, server);
3002 if (g_str_equal(server, "127.0.0.1"))
3005 if (g_str_equal(server, "::1"))
3008 remove_server(index, domain, server, IPPROTO_UDP);
3009 remove_server(index, domain, server, IPPROTO_TCP);
3011 #if defined TIZEN_EXT
3012 destroy_all_server_sec();
3018 static void dnsproxy_offline_mode(bool enabled)
3022 DBG("enabled %d", enabled);
3024 for (list = server_list; list; list = list->next) {
3025 struct server_data *data = list->data;
3028 DBG("Enabling DNS server %s", data->server);
3029 data->enabled = true;
3033 DBG("Disabling DNS server %s", data->server);
3034 data->enabled = false;
3040 static void dnsproxy_default_changed(struct connman_service *service)
3045 DBG("service %p", service);
3047 /* DNS has changed, invalidate the cache */
3051 /* When no services are active, then disable DNS proxying */
3052 dnsproxy_offline_mode(true);
3056 index = __connman_service_get_index(service);
3060 for (list = server_list; list; list = list->next) {
3061 struct server_data *data = list->data;
3063 if (data->index == index) {
3064 DBG("Enabling DNS server %s", data->server);
3065 data->enabled = true;
3067 DBG("Disabling DNS server %s", data->server);
3068 data->enabled = false;
3075 static struct connman_notifier dnsproxy_notifier = {
3077 .default_changed = dnsproxy_default_changed,
3078 .offline_mode = dnsproxy_offline_mode,
3081 static unsigned char opt_edns0_type[2] = { 0x00, 0x29 };
3083 static int parse_request(unsigned char *buf, int len,
3084 char *name, unsigned int size)
3086 struct domain_hdr *hdr = (void *) buf;
3087 uint16_t qdcount = ntohs(hdr->qdcount);
3088 uint16_t arcount = ntohs(hdr->arcount);
3090 char *last_label = NULL;
3091 unsigned int remain, used = 0;
3096 DBG("id 0x%04x qr %d opcode %d qdcount %d arcount %d",
3097 hdr->id, hdr->qr, hdr->opcode,
3100 if (hdr->qr != 0 || qdcount != 1)
3105 ptr = buf + sizeof(struct domain_hdr);
3106 remain = len - sizeof(struct domain_hdr);
3108 while (remain > 0) {
3109 uint8_t label_len = *ptr;
3111 if (label_len == 0x00) {
3112 last_label = (char *) (ptr + 1);
3116 if (used + label_len + 1 > size)
3119 strncat(name, (char *) (ptr + 1), label_len);
3122 used += label_len + 1;
3124 ptr += label_len + 1;
3125 remain -= label_len + 1;
3128 #if defined TIZEN_EXT
3129 /* parse DNS query type either A or AAAA
3130 * enforce to drop AAAA temporarily (IPv6 not supported)
3132 if (last_label != NULL) {
3133 uint16_t *type_p = (uint16_t *)last_label;
3134 uint16_t type = ntohs(*type_p);
3137 DBG("query %s is type AAAA(0x%x)", name, type);
3143 if (last_label && arcount && remain >= 9 && last_label[4] == 0 &&
3144 !memcmp(last_label + 5, opt_edns0_type, 2)) {
3145 uint16_t edns0_bufsize;
3147 edns0_bufsize = last_label[7] << 8 | last_label[8];
3149 DBG("EDNS0 buffer size %u", edns0_bufsize);
3151 /* This is an evil hack until full TCP support has been
3154 * Somtimes the EDNS0 request gets send with a too-small
3155 * buffer size. Since glibc doesn't seem to crash when it
3156 * gets a response biffer then it requested, just bump
3157 * the buffer size up to 4KiB.
3159 if (edns0_bufsize < 0x1000) {
3160 last_label[7] = 0x10;
3161 last_label[8] = 0x00;
3165 DBG("query %s", name);
3170 static void client_reset(struct tcp_partial_client_data *client)
3175 if (client->channel) {
3176 DBG("client %d closing",
3177 g_io_channel_unix_get_fd(client->channel));
3179 g_io_channel_unref(client->channel);
3180 client->channel = NULL;
3183 if (client->watch > 0) {
3184 g_source_remove(client->watch);
3188 if (client->timeout > 0) {
3189 g_source_remove(client->timeout);
3190 client->timeout = 0;
3193 g_free(client->buf);
3196 client->buf_end = 0;
3199 static unsigned int get_msg_len(unsigned char *buf)
3201 return buf[0]<<8 | buf[1];
3204 static bool read_tcp_data(struct tcp_partial_client_data *client,
3205 void *client_addr, socklen_t client_addr_len,
3208 char query[TCP_MAX_BUF_LEN];
3209 struct request_data *req;
3211 unsigned int msg_len;
3213 bool waiting_for_connect = false;
3215 struct cache_entry *entry;
3217 client_sk = g_io_channel_unix_get_fd(client->channel);
3219 if (read_len == 0) {
3220 DBG("client %d closed, pending %d bytes",
3221 client_sk, client->buf_end);
3222 g_hash_table_remove(partial_tcp_req_table,
3223 GINT_TO_POINTER(client_sk));
3227 DBG("client %d received %d bytes", client_sk, read_len);
3229 client->buf_end += read_len;
3231 if (client->buf_end < 2)
3234 msg_len = get_msg_len(client->buf);
3235 if (msg_len > TCP_MAX_BUF_LEN) {
3236 DBG("client %d sent too much data %d", client_sk, msg_len);
3237 g_hash_table_remove(partial_tcp_req_table,
3238 GINT_TO_POINTER(client_sk));
3243 DBG("client %d msg len %d end %d past end %d", client_sk, msg_len,
3244 client->buf_end, client->buf_end - (msg_len + 2));
3246 if (client->buf_end < (msg_len + 2)) {
3247 DBG("client %d still missing %d bytes",
3249 msg_len + 2 - client->buf_end);
3253 DBG("client %d all data %d received", client_sk, msg_len);
3255 err = parse_request(client->buf + 2, msg_len,
3256 query, sizeof(query));
3257 if (err < 0 || (g_slist_length(server_list) == 0)) {
3258 send_response(client_sk, client->buf, msg_len + 2,
3259 NULL, 0, IPPROTO_TCP);
3263 req = g_try_new0(struct request_data, 1);
3267 memcpy(&req->sa, client_addr, client_addr_len);
3268 req->sa_len = client_addr_len;
3269 req->client_sk = client_sk;
3270 req->protocol = IPPROTO_TCP;
3271 req->family = client->family;
3273 req->srcid = client->buf[2] | (client->buf[3] << 8);
3274 req->dstid = get_id();
3275 req->altid = get_id();
3276 req->request_len = msg_len + 2;
3278 client->buf[2] = req->dstid & 0xff;
3279 client->buf[3] = req->dstid >> 8;
3282 req->ifdata = client->ifdata;
3283 req->append_domain = false;
3286 * Check if the answer is found in the cache before
3287 * creating sockets to the server.
3289 entry = cache_check(client->buf, &qtype, IPPROTO_TCP);
3292 struct cache_data *data;
3294 DBG("cache hit %s type %s", query, qtype == 1 ? "A" : "AAAA");
3301 ttl_left = data->valid_until - time(NULL);
3304 send_cached_response(client_sk, data->data,
3305 data->data_len, NULL, 0, IPPROTO_TCP,
3306 req->srcid, data->answers, ttl_left);
3311 DBG("data missing, ignoring cache for this query");
3314 for (list = server_list; list; list = list->next) {
3315 struct server_data *data = list->data;
3317 if (data->protocol != IPPROTO_UDP || !data->enabled)
3320 if (!create_server(data->index, NULL, data->server,
3324 waiting_for_connect = true;
3327 if (!waiting_for_connect) {
3328 /* No server is waiting for connect */
3329 send_response(client_sk, client->buf,
3330 req->request_len, NULL, 0, IPPROTO_TCP);
3336 * The server is not connected yet.
3337 * Copy the relevant buffers.
3338 * The request will actually be sent once we're
3339 * properly connected over TCP to the nameserver.
3341 req->request = g_try_malloc0(req->request_len);
3342 if (!req->request) {
3343 send_response(client_sk, client->buf,
3344 req->request_len, NULL, 0, IPPROTO_TCP);
3348 memcpy(req->request, client->buf, req->request_len);
3350 req->name = g_try_malloc0(sizeof(query));
3352 send_response(client_sk, client->buf,
3353 req->request_len, NULL, 0, IPPROTO_TCP);
3354 g_free(req->request);
3358 memcpy(req->name, query, sizeof(query));
3360 req->timeout = g_timeout_add_seconds(30, request_timeout, req);
3362 request_list = g_slist_append(request_list, req);
3365 if (client->buf_end > (msg_len + 2)) {
3366 DBG("client %d buf %p -> %p end %d len %d new %d",
3368 client->buf + msg_len + 2,
3369 client->buf, client->buf_end,
3370 TCP_MAX_BUF_LEN - client->buf_end,
3371 client->buf_end - (msg_len + 2));
3372 memmove(client->buf, client->buf + msg_len + 2,
3373 TCP_MAX_BUF_LEN - client->buf_end);
3374 client->buf_end = client->buf_end - (msg_len + 2);
3377 * If we have a full message waiting, just read it
3380 msg_len = get_msg_len(client->buf);
3381 if ((msg_len + 2) == client->buf_end) {
3382 DBG("client %d reading another %d bytes", client_sk,
3387 DBG("client %d clearing reading buffer", client_sk);
3389 client->buf_end = 0;
3390 memset(client->buf, 0, TCP_MAX_BUF_LEN);
3393 * We received all the packets from client so we must also
3394 * remove the timeout handler here otherwise we might get
3395 * timeout while waiting the results from server.
3397 g_source_remove(client->timeout);
3398 client->timeout = 0;
3404 static gboolean tcp_client_event(GIOChannel *channel, GIOCondition condition,
3407 struct tcp_partial_client_data *client = user_data;
3408 struct sockaddr_in6 client_addr6;
3409 socklen_t client_addr6_len = sizeof(client_addr6);
3410 struct sockaddr_in client_addr4;
3411 socklen_t client_addr4_len = sizeof(client_addr4);
3413 socklen_t *client_addr_len;
3416 client_sk = g_io_channel_unix_get_fd(channel);
3418 if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
3419 g_hash_table_remove(partial_tcp_req_table,
3420 GINT_TO_POINTER(client_sk));
3422 connman_error("Error with TCP client %d channel", client_sk);
3426 switch (client->family) {
3428 client_addr = &client_addr4;
3429 client_addr_len = &client_addr4_len;
3432 client_addr = &client_addr6;
3433 client_addr_len = &client_addr6_len;
3436 g_hash_table_remove(partial_tcp_req_table,
3437 GINT_TO_POINTER(client_sk));
3438 connman_error("client %p corrupted", client);
3442 len = recvfrom(client_sk, client->buf + client->buf_end,
3443 TCP_MAX_BUF_LEN - client->buf_end, 0,
3444 client_addr, client_addr_len);
3446 if (errno == EAGAIN || errno == EWOULDBLOCK)
3449 DBG("client %d cannot read errno %d/%s", client_sk, -errno,
3451 g_hash_table_remove(partial_tcp_req_table,
3452 GINT_TO_POINTER(client_sk));
3456 return read_tcp_data(client, client_addr, *client_addr_len, len);
3459 static gboolean client_timeout(gpointer user_data)
3461 struct tcp_partial_client_data *client = user_data;
3464 sock = g_io_channel_unix_get_fd(client->channel);
3466 DBG("client %d timeout pending %d bytes", sock, client->buf_end);
3468 g_hash_table_remove(partial_tcp_req_table, GINT_TO_POINTER(sock));
3473 #if defined TIZEN_EXT
3474 static void recover_listener(GIOChannel *channel, struct listener_data *ifdata)
3478 index = ifdata->index;
3480 sk = g_io_channel_unix_get_fd(channel);
3483 __connman_dnsproxy_remove_listener(index);
3485 if (__connman_dnsproxy_add_listener(index) == 0)
3486 DBG("listener %d successfully recovered", index);
3490 static bool tcp_listener_event(GIOChannel *channel, GIOCondition condition,
3491 struct listener_data *ifdata, int family,
3492 guint *listener_watch)
3494 int sk, client_sk, len;
3495 unsigned int msg_len;
3496 struct tcp_partial_client_data *client;
3497 struct sockaddr_in6 client_addr6;
3498 socklen_t client_addr6_len = sizeof(client_addr6);
3499 struct sockaddr_in client_addr4;
3500 socklen_t client_addr4_len = sizeof(client_addr4);
3502 socklen_t *client_addr_len;
3506 DBG("condition 0x%02x channel %p ifdata %p family %d",
3507 condition, channel, ifdata, family);
3509 if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
3510 #if defined TIZEN_EXT
3511 connman_error("Error %d with TCP listener channel", condition);
3513 recover_listener(channel, ifdata);
3515 if (*listener_watch > 0)
3516 g_source_remove(*listener_watch);
3517 *listener_watch = 0;
3519 connman_error("Error with TCP listener channel");
3525 sk = g_io_channel_unix_get_fd(channel);
3527 if (family == AF_INET) {
3528 client_addr = &client_addr4;
3529 client_addr_len = &client_addr4_len;
3531 client_addr = &client_addr6;
3532 client_addr_len = &client_addr6_len;
3535 tv.tv_sec = tv.tv_usec = 0;
3537 FD_SET(sk, &readfds);
3539 select(sk + 1, &readfds, NULL, NULL, &tv);
3540 if (FD_ISSET(sk, &readfds)) {
3541 client_sk = accept(sk, client_addr, client_addr_len);
3542 DBG("client %d accepted", client_sk);
3544 DBG("No data to read from master %d, waiting.", sk);
3548 if (client_sk < 0) {
3549 connman_error("Accept failure on TCP listener");
3550 *listener_watch = 0;
3554 fcntl(client_sk, F_SETFL, O_NONBLOCK);
3556 client = g_hash_table_lookup(partial_tcp_req_table,
3557 GINT_TO_POINTER(client_sk));
3559 client = g_try_new0(struct tcp_partial_client_data, 1);
3565 g_hash_table_insert(partial_tcp_req_table,
3566 GINT_TO_POINTER(client_sk),
3569 client->channel = g_io_channel_unix_new(client_sk);
3570 g_io_channel_set_close_on_unref(client->channel, TRUE);
3572 client->watch = g_io_add_watch(client->channel,
3573 G_IO_IN, tcp_client_event,
3576 client->ifdata = ifdata;
3578 DBG("client %d created %p", client_sk, client);
3580 DBG("client %d already exists %p", client_sk, client);
3584 client->buf = g_try_malloc(TCP_MAX_BUF_LEN);
3588 memset(client->buf, 0, TCP_MAX_BUF_LEN);
3589 client->buf_end = 0;
3590 client->family = family;
3592 if (client->timeout == 0)
3593 client->timeout = g_timeout_add_seconds(2, client_timeout,
3597 * Check how much data there is. If all is there, then we can
3598 * proceed normally, otherwise read the bits until everything
3599 * is received or timeout occurs.
3601 len = recv(client_sk, client->buf, TCP_MAX_BUF_LEN, 0);
3603 if (errno == EAGAIN || errno == EWOULDBLOCK) {
3604 DBG("client %d no data to read, waiting", client_sk);
3608 DBG("client %d cannot read errno %d/%s", client_sk, -errno,
3610 g_hash_table_remove(partial_tcp_req_table,
3611 GINT_TO_POINTER(client_sk));
3616 DBG("client %d not enough data to read, waiting", client_sk);
3617 client->buf_end += len;
3621 msg_len = get_msg_len(client->buf);
3622 if (msg_len > TCP_MAX_BUF_LEN) {
3623 DBG("client %d invalid message length %u ignoring packet",
3624 client_sk, msg_len);
3625 g_hash_table_remove(partial_tcp_req_table,
3626 GINT_TO_POINTER(client_sk));
3631 * The packet length bytes do not contain the total message length,
3632 * that is the reason to -2 below.
3634 #if defined TIZEN_EXT
3635 if (msg_len > (unsigned int)(len - 2)) {
3637 if (msg_len != (unsigned int)(len - 2)) {
3639 DBG("client %d sent %d bytes but expecting %u pending %d",
3640 client_sk, len, msg_len + 2, msg_len + 2 - len);
3642 client->buf_end += len;
3646 return read_tcp_data(client, client_addr, *client_addr_len, len);
3649 static gboolean tcp4_listener_event(GIOChannel *channel, GIOCondition condition,
3652 struct listener_data *ifdata = user_data;
3654 return tcp_listener_event(channel, condition, ifdata, AF_INET,
3655 &ifdata->tcp4_listener_watch);
3658 static gboolean tcp6_listener_event(GIOChannel *channel, GIOCondition condition,
3661 struct listener_data *ifdata = user_data;
3663 return tcp_listener_event(channel, condition, user_data, AF_INET6,
3664 &ifdata->tcp6_listener_watch);
3667 #if defined TIZEN_EXT
3668 /* Temporarily disable AAAA type to enhance performance (IPv6 not supported) */
3669 static void __send_response_not_implemented(int sk, unsigned char *buf, int len,
3670 const struct sockaddr *to, socklen_t tolen,
3673 struct domain_hdr *hdr;
3674 int err, offset = protocol_offset(protocol);
3684 hdr = (void *) (buf + offset);
3686 DBG("id 0x%04x qr %d opcode %d", hdr->id, hdr->qr, hdr->opcode);
3695 err = sendto(sk, buf, len, MSG_NOSIGNAL, to, tolen);
3697 connman_error("Failed to send DNS response to %d: %s",
3698 sk, strerror(errno));
3702 static bool udp_listener_event(GIOChannel *channel, GIOCondition condition,
3703 struct listener_data *ifdata, int family,
3704 guint *listener_watch)
3706 unsigned char buf[768];
3708 struct request_data *req;
3709 struct sockaddr_in6 client_addr6;
3710 socklen_t client_addr6_len = sizeof(client_addr6);
3711 struct sockaddr_in client_addr4;
3712 socklen_t client_addr4_len = sizeof(client_addr4);
3714 socklen_t *client_addr_len;
3717 if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
3718 #if defined TIZEN_EXT
3719 connman_error("Error %d with UDP listener channel", condition);
3721 recover_listener(channel, ifdata);
3723 connman_error("Error with UDP listener channel");
3724 *listener_watch = 0;
3729 sk = g_io_channel_unix_get_fd(channel);
3731 if (family == AF_INET) {
3732 client_addr = &client_addr4;
3733 client_addr_len = &client_addr4_len;
3735 client_addr = &client_addr6;
3736 client_addr_len = &client_addr6_len;
3739 memset(client_addr, 0, *client_addr_len);
3740 len = recvfrom(sk, buf, sizeof(buf), 0, client_addr, client_addr_len);
3744 DBG("Received %d bytes (id 0x%04x)", len, buf[0] | buf[1] << 8);
3746 err = parse_request(buf, len, query, sizeof(query));
3747 if (err < 0 || (g_slist_length(server_list) == 0)) {
3748 #if defined TIZEN_EXT
3749 if (err == -ENOENT) {
3750 /* Temporarily disable AAAA type to enhance performance
3751 * (IPv6 not supported)
3753 __send_response_not_implemented(sk, buf, len, client_addr,
3754 *client_addr_len, IPPROTO_UDP);
3758 send_response(sk, buf, len, client_addr,
3759 *client_addr_len, IPPROTO_UDP);
3763 req = g_try_new0(struct request_data, 1);
3767 memcpy(&req->sa, client_addr, *client_addr_len);
3768 req->sa_len = *client_addr_len;
3770 req->protocol = IPPROTO_UDP;
3771 req->family = family;
3773 req->srcid = buf[0] | (buf[1] << 8);
3774 req->dstid = get_id();
3775 req->altid = get_id();
3776 req->request_len = len;
3778 buf[0] = req->dstid & 0xff;
3779 buf[1] = req->dstid >> 8;
3782 req->ifdata = ifdata;
3783 req->append_domain = false;
3785 if (resolv(req, buf, query)) {
3786 /* a cached result was sent, so the request can be released */
3791 req->name = g_strdup(query);
3792 req->request = g_malloc(len);
3793 memcpy(req->request, buf, len);
3794 #if defined TIZEN_EXT
3795 DBG("req %p dstid 0x%04x altid 0x%04x", req, req->dstid, req->altid);
3796 req->timeout = g_timeout_add_seconds(30, request_timeout, req);
3798 req->timeout = g_timeout_add_seconds(5, request_timeout, req);
3800 request_list = g_slist_append(request_list, req);
3805 static gboolean udp4_listener_event(GIOChannel *channel, GIOCondition condition,
3808 struct listener_data *ifdata = user_data;
3810 return udp_listener_event(channel, condition, ifdata, AF_INET,
3811 &ifdata->udp4_listener_watch);
3814 static gboolean udp6_listener_event(GIOChannel *channel, GIOCondition condition,
3817 struct listener_data *ifdata = user_data;
3819 return udp_listener_event(channel, condition, user_data, AF_INET6,
3820 &ifdata->udp6_listener_watch);
3823 static GIOChannel *get_listener(int family, int protocol, int index)
3825 GIOChannel *channel;
3829 struct sockaddr_in6 sin6;
3830 struct sockaddr_in sin;
3834 #if !defined TIZEN_EXT
3837 #if defined TIZEN_EXT
3841 DBG("family %d protocol %d index %d", family, protocol, index);
3846 type = SOCK_DGRAM | SOCK_CLOEXEC;
3851 type = SOCK_STREAM | SOCK_CLOEXEC;
3858 sk = socket(family, type, protocol);
3859 if (sk < 0 && family == AF_INET6 && errno == EAFNOSUPPORT) {
3860 connman_error("No IPv6 support");
3865 connman_error("Failed to create %s listener socket", proto);
3869 #if !defined TIZEN_EXT
3870 /* ConnMan listens DNS from multiple interfaces
3871 * E.g. various technology based and tethering interfaces
3873 interface = connman_inet_ifname(index);
3874 if (!interface || setsockopt(sk, SOL_SOCKET, SO_BINDTODEVICE,
3876 strlen(interface) + 1) < 0) {
3877 connman_error("Failed to bind %s listener interface "
3879 proto, family == AF_INET ? "IPv4" : "IPv6",
3880 -errno, strerror(errno));
3888 if (family == AF_INET6) {
3889 memset(&s.sin6, 0, sizeof(s.sin6));
3890 s.sin6.sin6_family = AF_INET6;
3891 s.sin6.sin6_port = htons(53);
3892 slen = sizeof(s.sin6);
3893 #if defined TIZEN_EXT
3894 s.sin6.sin6_addr = in6addr_any;
3896 if (__connman_inet_get_interface_address(index,
3898 &s.sin6.sin6_addr) < 0) {
3899 /* So we could not find suitable IPv6 address for
3900 * the interface. This could happen if we have
3901 * disabled IPv6 for the interface.
3908 } else if (family == AF_INET) {
3909 memset(&s.sin, 0, sizeof(s.sin));
3910 s.sin.sin_family = AF_INET;
3911 s.sin.sin_port = htons(53);
3912 slen = sizeof(s.sin);
3913 #if defined TIZEN_EXT
3914 s.sin.sin_addr.s_addr = htonl(INADDR_ANY);
3916 if (__connman_inet_get_interface_address(index,
3918 &s.sin.sin_addr) < 0) {
3928 #if defined TIZEN_EXT
3929 /* When ConnMan crashed,
3930 * probably DNS listener cannot bind existing address */
3932 setsockopt(sk, SOL_SOCKET, SO_REUSEADDR, &option, sizeof(option));
3934 if (bind(sk, &s.sa, slen) < 0) {
3935 connman_error("Failed to bind %s listener socket", proto);
3940 if (protocol == IPPROTO_TCP) {
3942 if (listen(sk, 10) < 0) {
3943 connman_error("Failed to listen on TCP socket %d/%s",
3944 -errno, strerror(errno));
3949 fcntl(sk, F_SETFL, O_NONBLOCK);
3952 channel = g_io_channel_unix_new(sk);
3954 connman_error("Failed to create %s listener channel", proto);
3959 g_io_channel_set_close_on_unref(channel, TRUE);
3964 #define UDP_IPv4_FAILED 0x01
3965 #define TCP_IPv4_FAILED 0x02
3966 #define UDP_IPv6_FAILED 0x04
3967 #define TCP_IPv6_FAILED 0x08
3968 #define UDP_FAILED (UDP_IPv4_FAILED | UDP_IPv6_FAILED)
3969 #define TCP_FAILED (TCP_IPv4_FAILED | TCP_IPv6_FAILED)
3970 #define IPv6_FAILED (UDP_IPv6_FAILED | TCP_IPv6_FAILED)
3971 #define IPv4_FAILED (UDP_IPv4_FAILED | TCP_IPv4_FAILED)
3973 static int create_dns_listener(int protocol, struct listener_data *ifdata)
3977 if (protocol == IPPROTO_TCP) {
3978 ifdata->tcp4_listener_channel = get_listener(AF_INET, protocol,
3980 if (ifdata->tcp4_listener_channel)
3981 #if defined TIZEN_EXT
3982 ifdata->tcp4_listener_watch =
3983 g_io_add_watch(ifdata->tcp4_listener_channel,
3984 G_IO_IN | G_IO_ERR | G_IO_HUP | G_IO_NVAL,
3985 tcp4_listener_event, (gpointer)ifdata);
3987 ifdata->tcp4_listener_watch =
3988 g_io_add_watch(ifdata->tcp4_listener_channel,
3989 G_IO_IN, tcp4_listener_event,
3993 ret |= TCP_IPv4_FAILED;
3995 ifdata->tcp6_listener_channel = get_listener(AF_INET6, protocol,
3997 if (ifdata->tcp6_listener_channel)
3998 #if defined TIZEN_EXT
3999 ifdata->tcp6_listener_watch =
4000 g_io_add_watch(ifdata->tcp6_listener_channel,
4001 G_IO_IN | G_IO_ERR | G_IO_HUP | G_IO_NVAL,
4002 tcp6_listener_event, (gpointer)ifdata);
4004 ifdata->tcp6_listener_watch =
4005 g_io_add_watch(ifdata->tcp6_listener_channel,
4006 G_IO_IN, tcp6_listener_event,
4010 ret |= TCP_IPv6_FAILED;
4012 ifdata->udp4_listener_channel = get_listener(AF_INET, protocol,
4014 if (ifdata->udp4_listener_channel)
4015 #if defined TIZEN_EXT
4016 ifdata->udp4_listener_watch =
4017 g_io_add_watch(ifdata->udp4_listener_channel,
4018 G_IO_IN | G_IO_ERR | G_IO_HUP | G_IO_NVAL,
4019 udp4_listener_event, (gpointer)ifdata);
4021 ifdata->udp4_listener_watch =
4022 g_io_add_watch(ifdata->udp4_listener_channel,
4023 G_IO_IN, udp4_listener_event,
4027 ret |= UDP_IPv4_FAILED;
4029 ifdata->udp6_listener_channel = get_listener(AF_INET6, protocol,
4031 if (ifdata->udp6_listener_channel)
4032 #if defined TIZEN_EXT
4033 ifdata->udp6_listener_watch =
4034 g_io_add_watch(ifdata->udp6_listener_channel,
4035 G_IO_IN | G_IO_ERR | G_IO_HUP | G_IO_NVAL,
4036 udp6_listener_event, (gpointer)ifdata);
4038 ifdata->udp6_listener_watch =
4039 g_io_add_watch(ifdata->udp6_listener_channel,
4040 G_IO_IN, udp6_listener_event,
4044 ret |= UDP_IPv6_FAILED;
4050 static void destroy_udp_listener(struct listener_data *ifdata)
4052 DBG("index %d", ifdata->index);
4054 if (ifdata->udp4_listener_watch > 0)
4055 g_source_remove(ifdata->udp4_listener_watch);
4057 if (ifdata->udp6_listener_watch > 0)
4058 g_source_remove(ifdata->udp6_listener_watch);
4060 if (ifdata->udp4_listener_channel)
4061 g_io_channel_unref(ifdata->udp4_listener_channel);
4062 if (ifdata->udp6_listener_channel)
4063 g_io_channel_unref(ifdata->udp6_listener_channel);
4066 static void destroy_tcp_listener(struct listener_data *ifdata)
4068 DBG("index %d", ifdata->index);
4070 if (ifdata->tcp4_listener_watch > 0)
4071 g_source_remove(ifdata->tcp4_listener_watch);
4072 if (ifdata->tcp6_listener_watch > 0)
4073 g_source_remove(ifdata->tcp6_listener_watch);
4075 if (ifdata->tcp4_listener_channel)
4076 g_io_channel_unref(ifdata->tcp4_listener_channel);
4077 if (ifdata->tcp6_listener_channel)
4078 g_io_channel_unref(ifdata->tcp6_listener_channel);
4081 static int create_listener(struct listener_data *ifdata)
4085 err = create_dns_listener(IPPROTO_UDP, ifdata);
4086 if ((err & UDP_FAILED) == UDP_FAILED)
4089 err |= create_dns_listener(IPPROTO_TCP, ifdata);
4090 if ((err & TCP_FAILED) == TCP_FAILED) {
4091 destroy_udp_listener(ifdata);
4095 index = connman_inet_ifindex("lo");
4096 if (ifdata->index == index) {
4097 if ((err & IPv6_FAILED) != IPv6_FAILED)
4098 __connman_resolvfile_append(index, NULL, "::1");
4100 if ((err & IPv4_FAILED) != IPv4_FAILED)
4101 __connman_resolvfile_append(index, NULL, "127.0.0.1");
4107 static void destroy_listener(struct listener_data *ifdata)
4112 index = connman_inet_ifindex("lo");
4113 if (ifdata->index == index) {
4114 __connman_resolvfile_remove(index, NULL, "127.0.0.1");
4115 __connman_resolvfile_remove(index, NULL, "::1");
4118 for (list = request_list; list; list = list->next) {
4119 struct request_data *req = list->data;
4121 DBG("Dropping request (id 0x%04x -> 0x%04x)",
4122 req->srcid, req->dstid);
4123 destroy_request_data(req);
4127 g_slist_free(request_list);
4128 request_list = NULL;
4130 destroy_tcp_listener(ifdata);
4131 destroy_udp_listener(ifdata);
4134 int __connman_dnsproxy_add_listener(int index)
4136 struct listener_data *ifdata;
4139 DBG("index %d", index);
4144 if (!listener_table)
4147 if (g_hash_table_lookup(listener_table, GINT_TO_POINTER(index)))
4150 ifdata = g_try_new0(struct listener_data, 1);
4154 ifdata->index = index;
4155 ifdata->udp4_listener_channel = NULL;
4156 ifdata->udp4_listener_watch = 0;
4157 ifdata->tcp4_listener_channel = NULL;
4158 ifdata->tcp4_listener_watch = 0;
4159 ifdata->udp6_listener_channel = NULL;
4160 ifdata->udp6_listener_watch = 0;
4161 ifdata->tcp6_listener_channel = NULL;
4162 ifdata->tcp6_listener_watch = 0;
4164 err = create_listener(ifdata);
4166 connman_error("Couldn't create listener for index %d err %d",
4171 g_hash_table_insert(listener_table, GINT_TO_POINTER(ifdata->index),
4176 void __connman_dnsproxy_remove_listener(int index)
4178 struct listener_data *ifdata;
4180 DBG("index %d", index);
4182 if (!listener_table)
4185 ifdata = g_hash_table_lookup(listener_table, GINT_TO_POINTER(index));
4189 destroy_listener(ifdata);
4191 g_hash_table_remove(listener_table, GINT_TO_POINTER(index));
4194 static void remove_listener(gpointer key, gpointer value, gpointer user_data)
4196 int index = GPOINTER_TO_INT(key);
4197 struct listener_data *ifdata = value;
4199 DBG("index %d", index);
4201 destroy_listener(ifdata);
4204 static void free_partial_reqs(gpointer value)
4206 struct tcp_partial_client_data *data = value;
4212 int __connman_dnsproxy_init(void)
4218 listener_table = g_hash_table_new_full(g_direct_hash, g_direct_equal,
4221 partial_tcp_req_table = g_hash_table_new_full(g_direct_hash,
4226 index = connman_inet_ifindex("lo");
4227 err = __connman_dnsproxy_add_listener(index);
4231 err = connman_notifier_register(&dnsproxy_notifier);
4238 __connman_dnsproxy_remove_listener(index);
4239 g_hash_table_destroy(listener_table);
4240 g_hash_table_destroy(partial_tcp_req_table);
4245 void __connman_dnsproxy_cleanup(void)
4250 g_source_remove(cache_timer);
4255 g_hash_table_destroy(cache);
4259 connman_notifier_unregister(&dnsproxy_notifier);
4261 g_hash_table_foreach(listener_table, remove_listener, NULL);
4263 g_hash_table_destroy(listener_table);
4265 g_hash_table_destroy(partial_tcp_req_table);