5 * Copyright (C) 2007-2014 Intel Corporation. All rights reserved.
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License version 2 as
9 * published by the Free Software Foundation.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
31 #include <arpa/inet.h>
32 #include <netinet/in.h>
33 #include <sys/types.h>
34 #include <sys/socket.h>
38 #include <gweb/gresolv.h>
45 #include <sys/smack.h>
46 #include <systemd/sd-daemon.h>
49 #define debug(fmt...) do { } while (0)
51 #if __BYTE_ORDER == __LITTLE_ENDIAN
66 } __attribute__ ((packed));
67 #elif __BYTE_ORDER == __BIG_ENDIAN
82 } __attribute__ ((packed));
84 #error "Unknown byte order"
87 struct partial_reply {
97 struct sockaddr *server_addr;
98 socklen_t server_addr_len;
105 struct partial_reply *incoming_reply;
108 struct request_data {
110 struct sockaddr_in6 __sin6; /* Only for the length */
129 struct listener_data *ifdata;
133 struct listener_data {
136 GIOChannel *udp4_listener_channel;
137 GIOChannel *tcp4_listener_channel;
138 guint udp4_listener_watch;
139 guint tcp4_listener_watch;
141 GIOChannel *udp6_listener_channel;
142 GIOChannel *tcp6_listener_channel;
143 guint udp6_listener_watch;
144 guint tcp6_listener_watch;
148 * The TCP client requires some extra handling as we need to
149 * be prepared to receive also partial DNS requests.
151 struct tcp_partial_client_data {
153 struct listener_data *ifdata;
157 unsigned int buf_end;
168 unsigned int data_len;
169 unsigned char *data; /* contains DNS header + body */
176 struct cache_data *ipv4;
177 struct cache_data *ipv6;
180 struct domain_question {
183 } __attribute__ ((packed));
190 } __attribute__ ((packed));
193 * Max length of the DNS TCP packet.
195 #define TCP_MAX_BUF_LEN 4096
198 * We limit how long the cached DNS entry stays in the cache.
199 * By default the TTL (time-to-live) of the DNS response is used
200 * when setting the cache entry life time. The value is in seconds.
202 #if defined TIZEN_EXT
203 #define MAX_CACHE_TTL (60 * 60)
205 #define MAX_CACHE_TTL (60 * 30)
208 * Also limit the other end, cache at least for 30 seconds.
210 #define MIN_CACHE_TTL (30)
213 * We limit the cache size to some sane value so that cached data does
214 * not occupy too much memory. Each cached entry occupies on average
215 * about 100 bytes memory (depending on DNS name length).
216 * Example: caching www.connman.net uses 97 bytes memory.
217 * The value is the max amount of cached DNS responses (count).
219 #define MAX_CACHE_SIZE 256
221 static int cache_size;
222 static GHashTable *cache;
223 static int cache_refcount;
224 static GSList *server_list = NULL;
225 #if defined TIZEN_EXT
226 static GSList *server_list_sec = NULL;
228 static GSList *request_list = NULL;
229 static GHashTable *listener_table = NULL;
230 static time_t next_refresh;
231 static GHashTable *partial_tcp_req_table;
232 static guint cache_timer = 0;
234 #if defined TIZEN_EXT
235 static void destroy_server_sec(struct server_data *server);
236 static struct server_data *create_server_sec(int index,
237 const char *domain, const char *server,
241 static guint16 get_id(void)
245 __connman_util_get_random(&rand);
250 static int protocol_offset(int protocol)
266 * There is a power and efficiency benefit to have entries
267 * in our cache expire at the same time. To this extend,
268 * we round down the cache valid time to common boundaries.
270 static time_t round_down_ttl(time_t end_time, int ttl)
275 /* Less than 5 minutes, round to 10 second boundary */
277 end_time = end_time / 10;
278 end_time = end_time * 10;
279 } else { /* 5 or more minutes, round to 30 seconds */
280 end_time = end_time / 30;
281 end_time = end_time * 30;
286 static struct request_data *find_request(guint16 id)
290 for (list = request_list; list; list = list->next) {
291 struct request_data *req = list->data;
293 if (req->dstid == id || req->altid == id)
300 static struct server_data *find_server(int index,
306 debug("index %d server %s proto %d", index, server, protocol);
308 for (list = server_list; list; list = list->next) {
309 struct server_data *data = list->data;
311 if (index < 0 && data->index < 0 &&
312 g_str_equal(data->server, server) &&
313 data->protocol == protocol)
317 data->index < 0 || !data->server)
320 if (data->index == index &&
321 g_str_equal(data->server, server) &&
322 data->protocol == protocol)
329 /* we can keep using the same resolve's */
330 static GResolv *ipv4_resolve;
331 static GResolv *ipv6_resolve;
333 static void dummy_resolve_func(GResolvResultStatus status,
334 char **results, gpointer user_data)
339 * Refresh a DNS entry, but also age the hit count a bit */
340 static void refresh_dns_entry(struct cache_entry *entry, char *name)
345 ipv4_resolve = g_resolv_new(0);
346 g_resolv_set_address_family(ipv4_resolve, AF_INET);
347 g_resolv_add_nameserver(ipv4_resolve, "127.0.0.1", 53, 0);
351 ipv6_resolve = g_resolv_new(0);
352 g_resolv_set_address_family(ipv6_resolve, AF_INET6);
353 g_resolv_add_nameserver(ipv6_resolve, "::1", 53, 0);
357 debug("Refreshing A record for %s", name);
358 g_resolv_lookup_hostname(ipv4_resolve, name,
359 dummy_resolve_func, NULL);
364 debug("Refreshing AAAA record for %s", name);
365 g_resolv_lookup_hostname(ipv6_resolve, name,
366 dummy_resolve_func, NULL);
375 static int dns_name_length(unsigned char *buf)
377 if ((buf[0] & NS_CMPRSFLGS) == NS_CMPRSFLGS) /* compressed name */
379 return strlen((char *)buf) + 1;
382 static void update_cached_ttl(unsigned char *buf, int len, int new_ttl)
388 /* skip the header */
392 /* skip the query, which is a name and 2 16 bit words */
393 l = dns_name_length(c);
399 /* now we get the answer records */
403 l = dns_name_length(c);
408 /* then type + class, 2 bytes each */
414 /* now the 4 byte TTL field */
415 c[0] = new_ttl >> 24 & 0xff;
416 c[1] = new_ttl >> 16 & 0xff;
417 c[2] = new_ttl >> 8 & 0xff;
418 c[3] = new_ttl & 0xff;
424 /* now the 2 byte rdlen field */
425 w = c[0] << 8 | c[1];
431 static void send_cached_response(int sk, unsigned char *buf, int len,
432 const struct sockaddr *to, socklen_t tolen,
433 int protocol, int id, uint16_t answers, int ttl)
435 struct domain_hdr *hdr;
436 unsigned char *ptr = buf;
437 int err, offset, dns_len, adj_len = len - 2;
440 * The cached packet contains always the TCP offset (two bytes)
441 * so skip them for UDP.
452 dns_len = ptr[0] * 256 + ptr[1];
461 hdr = (void *) (ptr + offset);
465 hdr->rcode = ns_r_noerror;
466 hdr->ancount = htons(answers);
470 /* if this is a negative reply, we are authorative */
474 update_cached_ttl((unsigned char *)hdr, adj_len, ttl);
476 debug("sk %d id 0x%04x answers %d ptr %p length %d dns %d",
477 sk, hdr->id, answers, ptr, len, dns_len);
479 err = sendto(sk, ptr, len, MSG_NOSIGNAL, to, tolen);
481 connman_error("Cannot send cached DNS response: %s",
486 if (err != len || (dns_len != (len - 2) && protocol == IPPROTO_TCP) ||
487 (dns_len != len && protocol == IPPROTO_UDP))
488 debug("Packet length mismatch, sent %d wanted %d dns %d",
492 static void send_response(int sk, unsigned char *buf, int len,
493 const struct sockaddr *to, socklen_t tolen,
496 struct domain_hdr *hdr;
497 int err, offset = protocol_offset(protocol);
507 hdr = (void *) (buf + offset);
509 debug("id 0x%04x qr %d opcode %d", hdr->id, hdr->qr, hdr->opcode);
512 hdr->rcode = ns_r_servfail;
518 err = sendto(sk, buf, len, MSG_NOSIGNAL, to, tolen);
520 connman_error("Failed to send DNS response to %d: %s",
521 sk, strerror(errno));
526 static int get_req_udp_socket(struct request_data *req)
530 if (req->family == AF_INET)
531 channel = req->ifdata->udp4_listener_channel;
533 channel = req->ifdata->udp6_listener_channel;
538 return g_io_channel_unix_get_fd(channel);
541 static void destroy_request_data(struct request_data *req)
543 if (req->timeout > 0)
544 g_source_remove(req->timeout);
547 g_free(req->request);
552 static gboolean request_timeout(gpointer user_data)
554 struct request_data *req = user_data;
561 debug("id 0x%04x", req->srcid);
563 request_list = g_slist_remove(request_list, req);
565 if (req->protocol == IPPROTO_UDP) {
566 sk = get_req_udp_socket(req);
568 } else if (req->protocol == IPPROTO_TCP) {
574 if (req->resplen > 0 && req->resp) {
576 * Here we have received at least one reply (probably telling
577 * "not found" result), so send that back to client instead
578 * of more fatal server failed error.
581 sendto(sk, req->resp, req->resplen, MSG_NOSIGNAL,
584 } else if (req->request) {
586 * There was not reply from server at all.
588 struct domain_hdr *hdr;
590 hdr = (void *)(req->request + protocol_offset(req->protocol));
591 hdr->id = req->srcid;
594 send_response(sk, req->request, req->request_len,
595 sa, req->sa_len, req->protocol);
599 * We cannot leave TCP client hanging so just kick it out
600 * if we get a request timeout from server.
602 if (req->protocol == IPPROTO_TCP) {
603 debug("client %d removed", req->client_sk);
604 g_hash_table_remove(partial_tcp_req_table,
605 GINT_TO_POINTER(req->client_sk));
610 destroy_request_data(req);
615 static int append_query(unsigned char *buf, unsigned int size,
616 const char *query, const char *domain)
618 unsigned char *ptr = buf;
621 debug("query %s domain %s", query, domain);
626 tmp = strchr(query, '.');
632 memcpy(ptr + 1, query, len);
638 memcpy(ptr + 1, query, tmp - query);
639 ptr += tmp - query + 1;
647 tmp = strchr(domain, '.');
649 len = strlen(domain);
653 memcpy(ptr + 1, domain, len);
659 memcpy(ptr + 1, domain, tmp - domain);
660 ptr += tmp - domain + 1;
670 static bool cache_check_is_valid(struct cache_data *data,
676 if (data->cache_until < current_time)
683 * remove stale cached entries so that they can be refreshed
685 static void cache_enforce_validity(struct cache_entry *entry)
687 time_t current_time = time(NULL);
689 if (!cache_check_is_valid(entry->ipv4, current_time)
691 debug("cache timeout \"%s\" type A", entry->key);
692 g_free(entry->ipv4->data);
698 if (!cache_check_is_valid(entry->ipv6, current_time)
700 debug("cache timeout \"%s\" type AAAA", entry->key);
701 g_free(entry->ipv6->data);
707 static uint16_t cache_check_validity(char *question, uint16_t type,
708 struct cache_entry *entry)
710 time_t current_time = time(NULL);
711 bool want_refresh = false;
714 * if we have a popular entry, we want a refresh instead of
715 * total destruction of the entry.
720 cache_enforce_validity(entry);
724 if (!cache_check_is_valid(entry->ipv4, current_time)) {
725 debug("cache %s \"%s\" type A", entry->ipv4 ?
726 "timeout" : "entry missing", question);
729 entry->want_refresh = true;
732 * We do not remove cache entry if there is still
733 * valid IPv6 entry found in the cache.
735 if (!cache_check_is_valid(entry->ipv6, current_time) && !want_refresh) {
736 g_hash_table_remove(cache, question);
743 if (!cache_check_is_valid(entry->ipv6, current_time)) {
744 debug("cache %s \"%s\" type AAAA", entry->ipv6 ?
745 "timeout" : "entry missing", question);
748 entry->want_refresh = true;
750 if (!cache_check_is_valid(entry->ipv4, current_time) && !want_refresh) {
751 g_hash_table_remove(cache, question);
761 static void cache_element_destroy(gpointer value)
763 struct cache_entry *entry = value;
769 g_free(entry->ipv4->data);
774 g_free(entry->ipv6->data);
781 if (--cache_size < 0)
785 static gboolean try_remove_cache(gpointer user_data)
789 if (__sync_fetch_and_sub(&cache_refcount, 1) == 1) {
790 debug("No cache users, removing it.");
792 g_hash_table_destroy(cache);
799 static void create_cache(void)
801 if (__sync_fetch_and_add(&cache_refcount, 1) == 0)
802 cache = g_hash_table_new_full(g_str_hash,
805 cache_element_destroy);
808 static struct cache_entry *cache_check(gpointer request, int *qtype, int proto)
811 struct cache_entry *entry;
812 struct domain_question *q;
814 int offset, proto_offset;
819 proto_offset = protocol_offset(proto);
820 if (proto_offset < 0)
823 question = request + proto_offset + 12;
825 offset = strlen(question) + 1;
826 q = (void *) (question + offset);
827 type = ntohs(q->type);
829 /* We only cache either A (1) or AAAA (28) requests */
830 if (type != 1 && type != 28)
838 entry = g_hash_table_lookup(cache, question);
842 type = cache_check_validity(question, type, entry);
851 * Get a label/name from DNS resource record. The function decompresses the
852 * label if necessary. The function does not convert the name to presentation
853 * form. This means that the result string will contain label lengths instead
854 * of dots between labels. We intentionally do not want to convert to dotted
855 * format so that we can cache the wire format string directly.
857 static int get_name(int counter,
858 unsigned char *pkt, unsigned char *start, unsigned char *max,
859 unsigned char *output, int output_max, int *output_len,
860 unsigned char **end, char *name, size_t max_name, int *name_len)
864 /* Limit recursion to 10 (this means up to 10 labels in domain name) */
870 if ((*p & NS_CMPRSFLGS) == NS_CMPRSFLGS) {
871 uint16_t offset = (*p & 0x3F) * 256 + *(p + 1);
873 if (offset >= max - pkt)
879 return get_name(counter + 1, pkt, pkt + offset, max,
880 output, output_max, output_len, end,
881 name, max_name, name_len);
883 unsigned label_len = *p;
885 if (pkt + label_len > max)
888 if (*output_len > output_max)
891 if ((*name_len + 1 + label_len + 1) > max_name)
895 * We need the original name in order to check
896 * if this answer is the correct one.
898 name[(*name_len)++] = label_len;
899 memcpy(name + *name_len, p + 1, label_len + 1);
900 *name_len += label_len;
902 /* We compress the result */
903 output[0] = NS_CMPRSFLGS;
920 static int parse_rr(unsigned char *buf, unsigned char *start,
922 unsigned char *response, unsigned int *response_size,
923 uint16_t *type, uint16_t *class, int *ttl, int *rdlen,
925 char *name, size_t max_name)
927 struct domain_rr *rr;
929 int name_len = 0, output_len = 0, max_rsp = *response_size;
931 err = get_name(0, buf, start, max, response, max_rsp,
932 &output_len, end, name, max_name, &name_len);
938 if ((unsigned int) offset > *response_size)
941 rr = (void *) (*end);
946 *type = ntohs(rr->type);
947 *class = ntohs(rr->class);
948 *ttl = ntohl(rr->ttl);
949 *rdlen = ntohs(rr->rdlen);
954 memcpy(response + offset, *end, sizeof(struct domain_rr));
956 offset += sizeof(struct domain_rr);
957 *end += sizeof(struct domain_rr);
959 if ((unsigned int) (offset + *rdlen) > *response_size)
962 memcpy(response + offset, *end, *rdlen);
966 *response_size = offset + *rdlen;
971 static bool check_alias(GSList *aliases, char *name)
976 for (list = aliases; list; list = list->next) {
977 int len = strlen((char *)list->data);
978 if (strncmp((char *)list->data, name, len) == 0)
986 static int parse_response(unsigned char *buf, int buflen,
987 char *question, int qlen,
988 uint16_t *type, uint16_t *class, int *ttl,
989 unsigned char *response, unsigned int *response_len,
992 struct domain_hdr *hdr = (void *) buf;
993 struct domain_question *q;
995 uint16_t qdcount = ntohs(hdr->qdcount);
996 uint16_t ancount = ntohs(hdr->ancount);
998 uint16_t qtype, qclass;
999 unsigned char *next = NULL;
1000 unsigned int maxlen = *response_len;
1001 GSList *aliases = NULL, *list;
1002 char name[NS_MAXDNAME + 1];
1007 debug("qr %d qdcount %d", hdr->qr, qdcount);
1009 /* We currently only cache responses where question count is 1 */
1010 if (hdr->qr != 1 || qdcount != 1)
1013 ptr = buf + sizeof(struct domain_hdr);
1015 strncpy(question, (char *) ptr, qlen);
1016 qlen = strlen(question);
1017 ptr += qlen + 1; /* skip \0 */
1020 qtype = ntohs(q->type);
1022 /* We cache only A and AAAA records */
1023 if (qtype != 1 && qtype != 28)
1026 qclass = ntohs(q->class);
1028 ptr += 2 + 2; /* ptr points now to answers */
1034 memset(name, 0, sizeof(name));
1037 * We have a bunch of answers (like A, AAAA, CNAME etc) to
1038 * A or AAAA question. We traverse the answers and parse the
1039 * resource records. Only A and AAAA records are cached, all
1040 * the other records in answers are skipped.
1042 for (i = 0; i < ancount; i++) {
1044 * Get one address at a time to this buffer.
1045 * The max size of the answer is
1046 * 2 (pointer) + 2 (type) + 2 (class) +
1047 * 4 (ttl) + 2 (rdlen) + addr (16 or 4) = 28
1048 * for A or AAAA record.
1049 * For CNAME the size can be bigger.
1051 unsigned char rsp[NS_MAXCDNAME];
1052 unsigned int rsp_len = sizeof(rsp) - 1;
1055 memset(rsp, 0, sizeof(rsp));
1057 ret = parse_rr(buf, ptr, buf + buflen, rsp, &rsp_len,
1058 type, class, ttl, &rdlen, &next, name,
1066 * Now rsp contains compressed or uncompressed resource
1067 * record. Next we check if this record answers the question.
1068 * The name var contains the uncompressed label.
1069 * One tricky bit is the CNAME records as they alias
1070 * the name we might be interested in.
1074 * Go to next answer if the class is not the one we are
1077 if (*class != qclass) {
1084 * Try to resolve aliases also, type is CNAME(5).
1085 * This is important as otherwise the aliased names would not
1086 * be cached at all as the cache would not contain the aliased
1089 * If any CNAME is found in DNS packet, then we cache the alias
1090 * IP address instead of the question (as the server
1091 * said that question has only an alias).
1092 * This means in practice that if e.g., ipv6.google.com is
1093 * queried, DNS server returns CNAME of that name which is
1094 * ipv6.l.google.com. We then cache the address of the CNAME
1095 * but return the question name to client. So the alias
1096 * status of the name is not saved in cache and thus not
1097 * returned to the client. We do not return DNS packets from
1098 * cache to client saying that ipv6.google.com is an alias to
1099 * ipv6.l.google.com but we return instead a DNS packet that
1100 * says ipv6.google.com has address xxx which is in fact the
1101 * address of ipv6.l.google.com. For caching purposes this
1102 * should not cause any issues.
1104 if (*type == 5 && strncmp(question, name, qlen) == 0) {
1106 * So now the alias answered the question. This is
1107 * not very useful from caching point of view as
1108 * the following A or AAAA records will not match the
1109 * question. We need to find the real A/AAAA record
1110 * of the alias and cache that.
1112 unsigned char *end = NULL;
1113 int name_len = 0, output_len = 0;
1115 memset(rsp, 0, sizeof(rsp));
1116 rsp_len = sizeof(rsp) - 1;
1119 * Alias is in rdata part of the message,
1120 * and next-rdlen points to it. So we need to get
1121 * the real name of the alias.
1123 ret = get_name(0, buf, next - rdlen, buf + buflen,
1124 rsp, rsp_len, &output_len, &end,
1125 name, sizeof(name) - 1, &name_len);
1127 /* just ignore the error at this point */
1134 * We should now have the alias of the entry we might
1135 * want to cache. Just remember it for a while.
1136 * We check the alias list when we have parsed the
1139 aliases = g_slist_prepend(aliases, g_strdup(name));
1146 if (*type == qtype) {
1148 * We found correct type (A or AAAA)
1150 if (check_alias(aliases, name) ||
1151 (!aliases && strncmp(question, name,
1154 * We found an alias or the name of the rr
1155 * matches the question. If so, we append
1156 * the compressed label to the cache.
1157 * The end result is a response buffer that
1158 * will contain one or more cached and
1159 * compressed resource records.
1161 if (*response_len + rsp_len > maxlen) {
1165 memcpy(response + *response_len, rsp, rsp_len);
1166 *response_len += rsp_len;
1177 for (list = aliases; list; list = list->next)
1179 g_slist_free(aliases);
1184 struct cache_timeout {
1185 time_t current_time;
1190 static gboolean cache_check_entry(gpointer key, gpointer value,
1193 struct cache_timeout *data = user_data;
1194 struct cache_entry *entry = value;
1197 /* Scale the number of hits by half as part of cache aging */
1202 * If either IPv4 or IPv6 cached entry has expired, we
1203 * remove both from the cache.
1206 if (entry->ipv4 && entry->ipv4->timeout > 0) {
1207 max_timeout = entry->ipv4->cache_until;
1208 if (max_timeout > data->max_timeout)
1209 data->max_timeout = max_timeout;
1211 if (entry->ipv4->cache_until < data->current_time)
1215 if (entry->ipv6 && entry->ipv6->timeout > 0) {
1216 max_timeout = entry->ipv6->cache_until;
1217 if (max_timeout > data->max_timeout)
1218 data->max_timeout = max_timeout;
1220 if (entry->ipv6->cache_until < data->current_time)
1225 * if we're asked to try harder, also remove entries that have
1228 if (data->try_harder && entry->hits < 4)
1234 static void cache_cleanup(void)
1236 static int max_timeout;
1237 struct cache_timeout data;
1240 data.current_time = time(NULL);
1241 data.max_timeout = 0;
1242 data.try_harder = 0;
1245 * In the first pass, we only remove entries that have timed out.
1246 * We use a cache of the first time to expire to do this only
1247 * when it makes sense.
1249 if (max_timeout <= data.current_time) {
1250 count = g_hash_table_foreach_remove(cache, cache_check_entry,
1253 debug("removed %d in the first pass", count);
1256 * In the second pass, if the first pass turned up blank,
1257 * we also expire entries with a low hit count,
1258 * while aging the hit count at the same time.
1260 data.try_harder = 1;
1262 count = g_hash_table_foreach_remove(cache, cache_check_entry,
1267 * If we could not remove anything, then remember
1268 * what is the max timeout and do nothing if we
1269 * have not yet reached it. This will prevent
1270 * constant traversal of the cache if it is full.
1272 max_timeout = data.max_timeout;
1277 static gboolean cache_invalidate_entry(gpointer key, gpointer value,
1280 struct cache_entry *entry = value;
1282 /* first, delete any expired elements */
1283 cache_enforce_validity(entry);
1285 /* if anything is not expired, mark the entry for refresh */
1286 if (entry->hits > 0 && (entry->ipv4 || entry->ipv6))
1287 entry->want_refresh = true;
1289 /* delete the cached data */
1291 g_free(entry->ipv4->data);
1292 g_free(entry->ipv4);
1297 g_free(entry->ipv6->data);
1298 g_free(entry->ipv6);
1302 /* keep the entry if we want it refreshed, delete it otherwise */
1303 if (entry->want_refresh)
1310 * cache_invalidate is called from places where the DNS landscape
1311 * has changed, say because connections are added or we entered a VPN.
1312 * The logic is to wipe all cache data, but mark all non-expired
1313 * parts of the cache for refresh rather than deleting the whole cache.
1315 static void cache_invalidate(void)
1317 debug("Invalidating the DNS cache %p", cache);
1322 g_hash_table_foreach_remove(cache, cache_invalidate_entry, NULL);
1325 static void cache_refresh_entry(struct cache_entry *entry)
1328 cache_enforce_validity(entry);
1330 if (entry->hits > 2 && !entry->ipv4)
1331 entry->want_refresh = true;
1332 if (entry->hits > 2 && !entry->ipv6)
1333 entry->want_refresh = true;
1335 if (entry->want_refresh) {
1337 char dns_name[NS_MAXDNAME + 1];
1338 entry->want_refresh = false;
1340 /* turn a DNS name into a hostname with dots */
1341 strncpy(dns_name, entry->key, NS_MAXDNAME);
1349 debug("Refreshing %s\n", dns_name);
1350 /* then refresh the hostname */
1351 refresh_dns_entry(entry, &dns_name[1]);
1355 static void cache_refresh_iterator(gpointer key, gpointer value,
1358 struct cache_entry *entry = value;
1360 cache_refresh_entry(entry);
1363 static void cache_refresh(void)
1368 g_hash_table_foreach(cache, cache_refresh_iterator, NULL);
1371 static int reply_query_type(unsigned char *msg, int len)
1377 /* skip the header */
1378 c = msg + sizeof(struct domain_hdr);
1379 len -= sizeof(struct domain_hdr);
1384 /* now the query, which is a name and 2 16 bit words */
1385 l = dns_name_length(c);
1387 type = c[0] << 8 | c[1];
1392 static int cache_update(struct server_data *srv, unsigned char *msg,
1393 unsigned int msg_len)
1395 int offset = protocol_offset(srv->protocol);
1396 int err, qlen, ttl = 0;
1397 uint16_t answers = 0, type = 0, class = 0;
1398 struct domain_hdr *hdr = (void *)(msg + offset);
1399 struct domain_question *q;
1400 struct cache_entry *entry;
1401 struct cache_data *data;
1402 char question[NS_MAXDNAME + 1];
1403 unsigned char response[NS_MAXDNAME + 1];
1405 unsigned int rsplen;
1406 bool new_entry = true;
1407 time_t current_time;
1409 if (cache_size >= MAX_CACHE_SIZE) {
1411 if (cache_size >= MAX_CACHE_SIZE)
1415 current_time = time(NULL);
1417 /* don't do a cache refresh more than twice a minute */
1418 if (next_refresh < current_time) {
1420 next_refresh = current_time + 30;
1426 debug("offset %d hdr %p msg %p rcode %d", offset, hdr, msg, hdr->rcode);
1428 /* Continue only if response code is 0 (=ok) */
1429 if (hdr->rcode != ns_r_noerror)
1435 rsplen = sizeof(response) - 1;
1436 question[sizeof(question) - 1] = '\0';
1438 err = parse_response(msg + offset, msg_len - offset,
1439 question, sizeof(question) - 1,
1440 &type, &class, &ttl,
1441 response, &rsplen, &answers);
1444 * special case: if we do a ipv6 lookup and get no result
1445 * for a record that's already in our ipv4 cache.. we want
1446 * to cache the negative response.
1448 if ((err == -ENOMSG || err == -ENOBUFS) &&
1449 reply_query_type(msg + offset,
1450 msg_len - offset) == 28) {
1451 entry = g_hash_table_lookup(cache, question);
1452 if (entry && entry->ipv4 && !entry->ipv6) {
1453 int cache_offset = 0;
1455 data = g_try_new(struct cache_data, 1);
1458 data->inserted = entry->ipv4->inserted;
1460 data->answers = ntohs(hdr->ancount);
1461 data->timeout = entry->ipv4->timeout;
1462 if (srv->protocol == IPPROTO_UDP)
1464 data->data_len = msg_len + cache_offset;
1465 data->data = ptr = g_malloc(data->data_len);
1466 ptr[0] = (data->data_len - 2) / 256;
1467 ptr[1] = (data->data_len - 2) - ptr[0] * 256;
1468 if (srv->protocol == IPPROTO_UDP)
1470 data->valid_until = entry->ipv4->valid_until;
1471 data->cache_until = entry->ipv4->cache_until;
1472 memcpy(ptr, msg, msg_len);
1475 * we will get a "hit" when we serve the response
1479 if (entry->hits < 0)
1485 if (err < 0 || ttl == 0)
1488 qlen = strlen(question);
1491 * If the cache contains already data, check if the
1492 * type of the cached data is the same and do not add
1493 * to cache if data is already there.
1494 * This is needed so that we can cache both A and AAAA
1495 * records for the same name.
1497 entry = g_hash_table_lookup(cache, question);
1499 entry = g_try_new(struct cache_entry, 1);
1503 data = g_try_new(struct cache_data, 1);
1509 entry->key = g_strdup(question);
1510 entry->ipv4 = entry->ipv6 = NULL;
1511 entry->want_refresh = false;
1519 if (type == 1 && entry->ipv4)
1522 if (type == 28 && entry->ipv6)
1525 data = g_try_new(struct cache_data, 1);
1535 * compensate for the hit we'll get for serving
1536 * the response out of the cache
1539 if (entry->hits < 0)
1545 if (ttl < MIN_CACHE_TTL)
1546 ttl = MIN_CACHE_TTL;
1548 data->inserted = current_time;
1550 data->answers = answers;
1551 data->timeout = ttl;
1553 * The "2" in start of the length is the TCP offset. We allocate it
1554 * here even for UDP packet because it simplifies the sending
1557 data->data_len = 2 + 12 + qlen + 1 + 2 + 2 + rsplen;
1558 data->data = ptr = g_malloc(data->data_len);
1559 data->valid_until = current_time + ttl;
1562 * Restrict the cached DNS record TTL to some sane value
1563 * in order to prevent data staying in the cache too long.
1565 if (ttl > MAX_CACHE_TTL)
1566 ttl = MAX_CACHE_TTL;
1568 data->cache_until = round_down_ttl(current_time + ttl, ttl);
1578 * We cache the two extra bytes at the start of the message
1579 * in a TCP packet. When sending UDP packet, we skip the first
1580 * two bytes. This way we do not need to know the format
1581 * (UDP/TCP) of the cached message.
1583 if (srv->protocol == IPPROTO_UDP)
1584 memcpy(ptr + 2, msg, offset + 12);
1586 memcpy(ptr, msg, offset + 12);
1588 ptr[0] = (data->data_len - 2) / 256;
1589 ptr[1] = (data->data_len - 2) - ptr[0] * 256;
1590 if (srv->protocol == IPPROTO_UDP)
1593 memcpy(ptr + offset + 12, question, qlen + 1); /* copy also the \0 */
1595 q = (void *) (ptr + offset + 12 + qlen + 1);
1596 q->type = htons(type);
1597 q->class = htons(class);
1598 memcpy(ptr + offset + 12 + qlen + 1 + sizeof(struct domain_question),
1602 g_hash_table_replace(cache, entry->key, entry);
1606 debug("cache %d %squestion \"%s\" type %d ttl %d size %zd packet %u "
1608 cache_size, new_entry ? "new " : "old ",
1609 question, type, ttl,
1610 sizeof(*entry) + sizeof(*data) + data->data_len + qlen,
1612 srv->protocol == IPPROTO_TCP ?
1613 (unsigned int)(data->data[0] * 256 + data->data[1]) :
1619 static int ns_resolv(struct server_data *server, struct request_data *req,
1620 gpointer request, gpointer name)
1623 int sk, err, type = 0;
1624 char *dot, *lookup = (char *) name;
1625 struct cache_entry *entry;
1627 entry = cache_check(request, &type, req->protocol);
1630 struct cache_data *data;
1632 debug("cache hit %s type %s", lookup, type == 1 ? "A" : "AAAA");
1639 ttl_left = data->valid_until - time(NULL);
1643 if (data && req->protocol == IPPROTO_TCP) {
1644 send_cached_response(req->client_sk, data->data,
1645 data->data_len, NULL, 0, IPPROTO_TCP,
1646 req->srcid, data->answers, ttl_left);
1650 if (data && req->protocol == IPPROTO_UDP) {
1651 int udp_sk = get_req_udp_socket(req);
1656 send_cached_response(udp_sk, data->data,
1657 data->data_len, &req->sa, req->sa_len,
1658 IPPROTO_UDP, req->srcid, data->answers,
1664 #if defined TIZEN_EXT
1665 if (server->protocol == IPPROTO_UDP) {
1667 struct server_data *new_server = NULL;
1669 new_server = create_server_sec(server->index, NULL,
1670 server->server, IPPROTO_UDP);
1672 if (new_server != NULL) {
1673 for (domains = server->domains; domains;
1674 domains = domains->next) {
1675 char *dom = domains->data;
1677 DBG("Adding domain %s to %s",
1678 dom, new_server->server);
1680 new_server->domains = g_list_append(
1681 new_server->domains,
1685 server = new_server;
1689 sk = g_io_channel_unix_get_fd(server->channel);
1691 err = sendto(sk, request, req->request_len, MSG_NOSIGNAL,
1692 server->server_addr, server->server_addr_len);
1694 debug("Cannot send message to server %s sock %d "
1695 "protocol %d (%s/%d)",
1696 server->server, sk, server->protocol,
1697 strerror(errno), errno);
1703 /* If we have more than one dot, we don't add domains */
1704 dot = strchr(lookup, '.');
1705 if (dot && dot != lookup + strlen(lookup) - 1)
1708 if (server->domains && server->domains->data)
1709 req->append_domain = true;
1711 for (list = server->domains; list; list = list->next) {
1713 unsigned char alt[1024];
1714 struct domain_hdr *hdr = (void *) &alt;
1715 int altlen, domlen, offset;
1717 domain = list->data;
1722 offset = protocol_offset(server->protocol);
1726 domlen = strlen(domain) + 1;
1730 alt[offset] = req->altid & 0xff;
1731 alt[offset + 1] = req->altid >> 8;
1733 memcpy(alt + offset + 2, request + offset + 2, 10);
1734 hdr->qdcount = htons(1);
1736 altlen = append_query(alt + offset + 12, sizeof(alt) - 12,
1743 memcpy(alt + offset + altlen,
1744 request + offset + altlen - domlen,
1745 req->request_len - altlen - offset + domlen);
1747 if (server->protocol == IPPROTO_TCP) {
1748 int req_len = req->request_len + domlen - 2;
1750 alt[0] = (req_len >> 8) & 0xff;
1751 alt[1] = req_len & 0xff;
1754 debug("req %p dstid 0x%04x altid 0x%04x", req, req->dstid,
1757 err = send(sk, alt, req->request_len + domlen, MSG_NOSIGNAL);
1767 static char *convert_label(char *start, char *end, char *ptr, char *uptr,
1768 int remaining_len, int *used_comp, int *used_uncomp)
1771 char name[NS_MAXLABEL];
1773 pos = dn_expand((u_char *)start, (u_char *)end, (u_char *)ptr,
1776 debug("uncompress error [%d/%s]", errno, strerror(errno));
1781 * We need to compress back the name so that we get back to internal
1782 * label presentation.
1784 comp_pos = dn_comp(name, (u_char *)uptr, remaining_len, NULL, NULL);
1786 debug("compress error [%d/%s]", errno, strerror(errno));
1791 *used_uncomp = comp_pos;
1799 static char *uncompress(int16_t field_count, char *start, char *end,
1800 char *ptr, char *uncompressed, int uncomp_len,
1801 char **uncompressed_ptr)
1803 char *uptr = *uncompressed_ptr; /* position in result buffer */
1805 debug("count %d ptr %p end %p uptr %p", field_count, ptr, end, uptr);
1807 while (field_count-- > 0 && ptr < end) {
1808 int dlen; /* data field length */
1809 int ulen; /* uncompress length */
1810 int pos; /* position in compressed string */
1811 char name[NS_MAXLABEL]; /* tmp label */
1812 uint16_t dns_type, dns_class;
1815 if (!convert_label(start, end, ptr, name, NS_MAXLABEL,
1820 * Copy the uncompressed resource record, type, class and \0 to
1824 ulen = strlen(name);
1825 strncpy(uptr, name, uncomp_len - (uptr - uncompressed));
1827 debug("pos %d ulen %d left %d name %s", pos, ulen,
1828 (int)(uncomp_len - (uptr - uncompressed)), uptr);
1836 * We copy also the fixed portion of the result (type, class,
1837 * ttl, address length and the address)
1839 memcpy(uptr, ptr, NS_RRFIXEDSZ);
1841 dns_type = uptr[0] << 8 | uptr[1];
1842 dns_class = uptr[2] << 8 | uptr[3];
1844 if (dns_class != ns_c_in)
1847 ptr += NS_RRFIXEDSZ;
1848 uptr += NS_RRFIXEDSZ;
1851 * Then the variable portion of the result (data length).
1852 * Typically this portion is also compressed
1853 * so we need to uncompress it also when necessary.
1855 if (dns_type == ns_t_cname) {
1856 if (!convert_label(start, end, ptr, uptr,
1857 uncomp_len - (uptr - uncompressed),
1861 uptr[-2] = comp_pos << 8;
1862 uptr[-1] = comp_pos & 0xff;
1867 } else if (dns_type == ns_t_a || dns_type == ns_t_aaaa) {
1868 dlen = uptr[-2] << 8 | uptr[-1];
1870 if (ptr + dlen > end) {
1871 debug("data len %d too long", dlen);
1875 memcpy(uptr, ptr, dlen);
1879 } else if (dns_type == ns_t_soa) {
1883 /* Primary name server expansion */
1884 if (!convert_label(start, end, ptr, uptr,
1885 uncomp_len - (uptr - uncompressed),
1889 total_len += comp_pos;
1890 len_ptr = &uptr[-2];
1894 /* Responsible authority's mailbox */
1895 if (!convert_label(start, end, ptr, uptr,
1896 uncomp_len - (uptr - uncompressed),
1900 total_len += comp_pos;
1905 * Copy rest of the soa fields (serial number,
1906 * refresh interval, retry interval, expiration
1907 * limit and minimum ttl). They are 20 bytes long.
1909 memcpy(uptr, ptr, 20);
1915 * Finally fix the length of the data part
1917 len_ptr[0] = total_len << 8;
1918 len_ptr[1] = total_len & 0xff;
1921 *uncompressed_ptr = uptr;
1930 static int strip_domains(char *name, char *answers, int maxlen)
1933 int name_len = strlen(name);
1934 char *ptr, *start = answers, *end = answers + maxlen;
1936 while (maxlen > 0) {
1937 ptr = strstr(answers, name);
1939 char *domain = ptr + name_len;
1942 int domain_len = strlen(domain);
1944 memmove(answers + name_len,
1945 domain + domain_len,
1946 end - (domain + domain_len));
1949 maxlen -= domain_len;
1953 answers += strlen(answers) + 1;
1954 answers += 2 + 2 + 4; /* skip type, class and ttl fields */
1956 data_len = answers[0] << 8 | answers[1];
1957 answers += 2; /* skip the length field */
1959 if (answers + data_len > end)
1962 answers += data_len;
1963 maxlen -= answers - ptr;
1969 static int forward_dns_reply(unsigned char *reply, int reply_len, int protocol,
1970 struct server_data *data)
1972 struct domain_hdr *hdr;
1973 struct request_data *req;
1974 int dns_id, sk, err, offset = protocol_offset(protocol);
1979 hdr = (void *)(reply + offset);
1980 dns_id = reply[offset] | reply[offset + 1] << 8;
1982 debug("Received %d bytes (id 0x%04x)", reply_len, dns_id);
1984 req = find_request(dns_id);
1988 debug("req %p dstid 0x%04x altid 0x%04x rcode %d",
1989 req, req->dstid, req->altid, hdr->rcode);
1991 reply[offset] = req->srcid & 0xff;
1992 reply[offset + 1] = req->srcid >> 8;
1996 if (hdr->rcode == ns_r_noerror || !req->resp) {
1997 unsigned char *new_reply = NULL;
2000 * If the domain name was append
2001 * remove it before forwarding the reply.
2002 * If there were more than one question, then this
2003 * domain name ripping can be hairy so avoid that
2004 * and bail out in that that case.
2006 * The reason we are doing this magic is that if the
2007 * user's DNS client tries to resolv hostname without
2008 * domain part, it also expects to get the result without
2009 * a domain name part.
2011 if (req->append_domain && ntohs(hdr->qdcount) == 1) {
2012 uint16_t domain_len = 0;
2013 uint16_t header_len;
2014 uint16_t dns_type, dns_class;
2015 uint8_t host_len, dns_type_pos;
2016 char uncompressed[NS_MAXDNAME], *uptr;
2017 char *ptr, *eom = (char *)reply + reply_len;
2020 * ptr points to the first char of the hostname.
2021 * ->hostname.domain.net
2023 header_len = offset + sizeof(struct domain_hdr);
2024 ptr = (char *)reply + header_len;
2028 domain_len = strnlen(ptr + 1 + host_len,
2029 reply_len - header_len);
2032 * If the query type is anything other than A or AAAA,
2033 * then bail out and pass the message as is.
2034 * We only want to deal with IPv4 or IPv6 addresses.
2036 dns_type_pos = host_len + 1 + domain_len + 1;
2038 dns_type = ptr[dns_type_pos] << 8 |
2039 ptr[dns_type_pos + 1];
2040 dns_class = ptr[dns_type_pos + 2] << 8 |
2041 ptr[dns_type_pos + 3];
2042 if (dns_type != ns_t_a && dns_type != ns_t_aaaa &&
2043 dns_class != ns_c_in) {
2044 debug("Pass msg dns type %d class %d",
2045 dns_type, dns_class);
2050 * Remove the domain name and replace it by the end
2051 * of reply. Check if the domain is really there
2052 * before trying to copy the data. We also need to
2053 * uncompress the answers if necessary.
2054 * The domain_len can be 0 because if the original
2055 * query did not contain a domain name, then we are
2056 * sending two packets, first without the domain name
2057 * and the second packet with domain name.
2058 * The append_domain is set to true even if we sent
2059 * the first packet without domain name. In this
2060 * case we end up in this branch.
2062 if (domain_len > 0) {
2063 int len = host_len + 1;
2064 int new_len, fixed_len;
2068 * First copy host (without domain name) into
2071 uptr = &uncompressed[0];
2072 memcpy(uptr, ptr, len);
2074 uptr[len] = '\0'; /* host termination */
2078 * Copy type and class fields of the question.
2080 ptr += len + domain_len + 1;
2081 memcpy(uptr, ptr, NS_QFIXEDSZ);
2084 * ptr points to answers after this
2087 uptr += NS_QFIXEDSZ;
2089 fixed_len = answers - uncompressed;
2092 * We then uncompress the result to buffer
2093 * so that we can rip off the domain name
2094 * part from the question. First answers,
2095 * then name server (authority) information,
2096 * and finally additional record info.
2099 ptr = uncompress(ntohs(hdr->ancount),
2100 (char *)reply + offset, eom,
2101 ptr, uncompressed, NS_MAXDNAME,
2106 ptr = uncompress(ntohs(hdr->nscount),
2107 (char *)reply + offset, eom,
2108 ptr, uncompressed, NS_MAXDNAME,
2113 ptr = uncompress(ntohs(hdr->arcount),
2114 (char *)reply + offset, eom,
2115 ptr, uncompressed, NS_MAXDNAME,
2121 * The uncompressed buffer now contains almost
2122 * valid response. Final step is to get rid of
2123 * the domain name because at least glibc
2124 * gethostbyname() implementation does extra
2125 * checks and expects to find an answer without
2126 * domain name if we asked a query without
2127 * domain part. Note that glibc getaddrinfo()
2128 * works differently and accepts FQDN in answer
2130 new_len = strip_domains(uncompressed, answers,
2133 debug("Corrupted packet");
2138 * Because we have now uncompressed the answers
2139 * we might have to create a bigger buffer to
2140 * hold all that data.
2143 reply_len = header_len + new_len + fixed_len;
2145 new_reply = g_try_malloc(reply_len);
2149 memcpy(new_reply, reply, header_len);
2150 memcpy(new_reply + header_len, uncompressed,
2151 new_len + fixed_len);
2161 req->resp = g_try_malloc(reply_len);
2165 memcpy(req->resp, reply, reply_len);
2166 req->resplen = reply_len;
2168 cache_update(data, reply, reply_len);
2174 if (req->numresp < req->numserv) {
2175 if (hdr->rcode > ns_r_noerror) {
2177 } else if (hdr->ancount == 0 && req->append_domain) {
2182 request_list = g_slist_remove(request_list, req);
2184 if (protocol == IPPROTO_UDP) {
2185 sk = get_req_udp_socket(req);
2190 err = sendto(sk, req->resp, req->resplen, 0,
2191 &req->sa, req->sa_len);
2193 sk = req->client_sk;
2194 err = send(sk, req->resp, req->resplen, MSG_NOSIGNAL);
2198 debug("Cannot send msg, sk %d proto %d errno %d/%s", sk,
2199 protocol, errno, strerror(errno));
2201 debug("proto %d sent %d bytes to %d", protocol, err, sk);
2203 destroy_request_data(req);
2208 static void server_destroy_socket(struct server_data *data)
2210 debug("index %d server %s proto %d", data->index,
2211 data->server, data->protocol);
2213 if (data->watch > 0) {
2214 g_source_remove(data->watch);
2218 if (data->timeout > 0) {
2219 g_source_remove(data->timeout);
2223 if (data->channel) {
2224 g_io_channel_shutdown(data->channel, TRUE, NULL);
2225 g_io_channel_unref(data->channel);
2226 data->channel = NULL;
2229 g_free(data->incoming_reply);
2230 data->incoming_reply = NULL;
2233 static void destroy_server(struct server_data *server)
2235 debug("index %d server %s sock %d", server->index, server->server,
2237 g_io_channel_unix_get_fd(server->channel): -1);
2239 server_list = g_slist_remove(server_list, server);
2240 server_destroy_socket(server);
2242 if (server->protocol == IPPROTO_UDP && server->enabled)
2243 debug("Removing DNS server %s", server->server);
2245 g_free(server->server);
2246 g_list_free_full(server->domains, g_free);
2247 g_free(server->server_addr);
2250 * We do not remove cache right away but delay it few seconds.
2251 * The idea is that when IPv6 DNS server is added via RDNSS, it has a
2252 * lifetime. When the lifetime expires we decrease the refcount so it
2253 * is possible that the cache is then removed. Because a new DNS server
2254 * is usually created almost immediately we would then loose the cache
2255 * without any good reason. The small delay allows the new RDNSS to
2256 * create a new DNS server instance and the refcount does not go to 0.
2258 if (cache && !cache_timer)
2259 cache_timer = g_timeout_add_seconds(3, try_remove_cache, NULL);
2264 static gboolean udp_server_event(GIOChannel *channel, GIOCondition condition,
2267 unsigned char buf[4096];
2269 struct server_data *data = user_data;
2271 if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
2272 connman_error("Error with UDP server %s", data->server);
2273 server_destroy_socket(data);
2277 sk = g_io_channel_unix_get_fd(channel);
2279 len = recv(sk, buf, sizeof(buf), 0);
2283 err = forward_dns_reply(buf, len, IPPROTO_UDP, data);
2287 #if defined TIZEN_EXT
2290 for (list = server_list_sec; list; list = list->next) {
2291 struct server_data *new_data = list->data;
2293 if (new_data == data) {
2294 destroy_server_sec(data);
2303 static gboolean tcp_server_event(GIOChannel *channel, GIOCondition condition,
2307 struct server_data *server = user_data;
2309 sk = g_io_channel_unix_get_fd(channel);
2313 if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
2316 debug("TCP server channel closed, sk %d", sk);
2319 * Discard any partial response which is buffered; better
2320 * to get a proper response from a working server.
2322 g_free(server->incoming_reply);
2323 server->incoming_reply = NULL;
2325 list = request_list;
2327 struct request_data *req = list->data;
2328 struct domain_hdr *hdr;
2331 if (req->protocol == IPPROTO_UDP)
2338 * If we're not waiting for any further response
2339 * from another name server, then we send an error
2340 * response to the client.
2342 if (req->numserv && --(req->numserv))
2345 hdr = (void *) (req->request + 2);
2346 hdr->id = req->srcid;
2347 send_response(req->client_sk, req->request,
2348 req->request_len, NULL, 0, IPPROTO_TCP);
2350 request_list = g_slist_remove(request_list, req);
2353 destroy_server(server);
2358 if ((condition & G_IO_OUT) && !server->connected) {
2361 bool no_request_sent = true;
2362 struct server_data *udp_server;
2364 udp_server = find_server(server->index, server->server,
2367 for (domains = udp_server->domains; domains;
2368 domains = domains->next) {
2369 char *dom = domains->data;
2371 debug("Adding domain %s to %s",
2372 dom, server->server);
2374 server->domains = g_list_append(server->domains,
2379 server->connected = true;
2380 server_list = g_slist_append(server_list, server);
2382 if (server->timeout > 0) {
2383 g_source_remove(server->timeout);
2384 server->timeout = 0;
2387 for (list = request_list; list; ) {
2388 struct request_data *req = list->data;
2391 if (req->protocol == IPPROTO_UDP) {
2396 debug("Sending req %s over TCP", (char *)req->name);
2398 status = ns_resolv(server, req,
2399 req->request, req->name);
2402 * A cached result was sent,
2403 * so the request can be released
2406 request_list = g_slist_remove(request_list, req);
2407 destroy_request_data(req);
2416 no_request_sent = false;
2418 if (req->timeout > 0)
2419 g_source_remove(req->timeout);
2421 req->timeout = g_timeout_add_seconds(30,
2422 request_timeout, req);
2426 if (no_request_sent) {
2427 destroy_server(server);
2431 } else if (condition & G_IO_IN) {
2432 struct partial_reply *reply = server->incoming_reply;
2436 unsigned char reply_len_buf[2];
2439 bytes_recv = recv(sk, reply_len_buf, 2, MSG_PEEK);
2442 } else if (bytes_recv < 0) {
2443 if (errno == EAGAIN || errno == EWOULDBLOCK)
2446 connman_error("DNS proxy error %s",
2449 } else if (bytes_recv < 2)
2452 reply_len = reply_len_buf[1] | reply_len_buf[0] << 8;
2455 debug("TCP reply %d bytes from %d", reply_len, sk);
2457 reply = g_try_malloc(sizeof(*reply) + reply_len + 2);
2461 reply->len = reply_len;
2462 reply->received = 0;
2464 server->incoming_reply = reply;
2467 while (reply->received < reply->len) {
2468 bytes_recv = recv(sk, reply->buf + reply->received,
2469 reply->len - reply->received, 0);
2471 connman_error("DNS proxy TCP disconnect");
2473 } else if (bytes_recv < 0) {
2474 if (errno == EAGAIN || errno == EWOULDBLOCK)
2477 connman_error("DNS proxy error %s",
2481 reply->received += bytes_recv;
2484 forward_dns_reply(reply->buf, reply->received, IPPROTO_TCP,
2488 server->incoming_reply = NULL;
2490 destroy_server(server);
2498 static gboolean tcp_idle_timeout(gpointer user_data)
2500 struct server_data *server = user_data;
2507 destroy_server(server);
2512 static int server_create_socket(struct server_data *data)
2517 debug("index %d server %s proto %d", data->index,
2518 data->server, data->protocol);
2520 sk = socket(data->server_addr->sa_family,
2521 data->protocol == IPPROTO_TCP ? SOCK_STREAM : SOCK_DGRAM,
2525 connman_error("Failed to create server %s socket",
2527 server_destroy_socket(data);
2533 interface = connman_inet_ifname(data->index);
2535 if (setsockopt(sk, SOL_SOCKET, SO_BINDTODEVICE,
2537 strlen(interface) + 1) < 0) {
2539 connman_error("Failed to bind server %s "
2541 data->server, interface);
2543 server_destroy_socket(data);
2550 data->channel = g_io_channel_unix_new(sk);
2551 if (!data->channel) {
2552 connman_error("Failed to create server %s channel",
2555 server_destroy_socket(data);
2559 g_io_channel_set_close_on_unref(data->channel, TRUE);
2561 if (data->protocol == IPPROTO_TCP) {
2562 g_io_channel_set_flags(data->channel, G_IO_FLAG_NONBLOCK, NULL);
2563 data->watch = g_io_add_watch(data->channel,
2564 G_IO_OUT | G_IO_IN | G_IO_HUP | G_IO_NVAL | G_IO_ERR,
2565 tcp_server_event, data);
2566 data->timeout = g_timeout_add_seconds(30, tcp_idle_timeout,
2569 data->watch = g_io_add_watch(data->channel,
2570 G_IO_IN | G_IO_NVAL | G_IO_ERR | G_IO_HUP,
2571 udp_server_event, data);
2573 if (connect(sk, data->server_addr, data->server_addr_len) < 0) {
2576 if ((data->protocol == IPPROTO_TCP && errno != EINPROGRESS) ||
2577 data->protocol == IPPROTO_UDP) {
2579 connman_error("Failed to connect to server %s",
2581 server_destroy_socket(data);
2591 static void enable_fallback(bool enable)
2595 for (list = server_list; list; list = list->next) {
2596 struct server_data *data = list->data;
2598 if (data->index != -1)
2602 DBG("Enabling fallback DNS server %s", data->server);
2604 DBG("Disabling fallback DNS server %s", data->server);
2606 data->enabled = enable;
2610 #if defined TIZEN_EXT
2612 static void destroy_server_sec(struct server_data *server)
2617 if (server->channel)
2618 fd = g_io_channel_unix_get_fd(server->channel);
2622 DBG("index %d server %s sock %d", server->index, server->server, fd);
2624 server_list_sec = g_slist_remove(server_list_sec, server);
2629 server_destroy_socket(server);
2631 if (server->protocol == IPPROTO_UDP && server->enabled)
2632 DBG("Removing DNS server %s", server->server);
2634 g_free(server->server);
2635 for (list = server->domains; list; list = list->next) {
2636 char *domain = list->data;
2638 server->domains = g_list_remove(server->domains, domain);
2641 g_free(server->server_addr);
2644 * We do not remove cache right away but delay it few seconds.
2645 * The idea is that when IPv6 DNS server is added via RDNSS, it has a
2646 * lifetime. When the lifetime expires we decrease the refcount so it
2647 * is possible that the cache is then removed. Because a new DNS server
2648 * is usually created almost immediately we would then loose the cache
2649 * without any good reason. The small delay allows the new RDNSS to
2650 * create a new DNS server instance and the refcount does not go to 0.
2652 /* TODO: Need to check this */
2653 /* g_timeout_add_seconds(3, try_remove_cache, NULL); */
2658 static void destroy_all_server_sec()
2662 DBG("remove all dns server");
2664 for (list = server_list_sec; list; list = list->next) {
2665 struct server_data *server = list->data;
2666 destroy_server_sec(server);
2668 server_list_sec = NULL;
2671 static gboolean sec_udp_idle_timeout(gpointer user_data)
2673 struct server_data *server = user_data;
2680 destroy_server_sec(server);
2685 static struct server_data *create_server_sec(int index,
2686 const char *domain, const char *server,
2689 struct server_data *data;
2690 struct addrinfo hints, *rp;
2693 DBG("index %d server %s", index, server);
2695 data = g_try_new0(struct server_data, 1);
2697 connman_error("Failed to allocate server %s data", server);
2701 data->index = index;
2703 data->domains = g_list_append(data->domains, g_strdup(domain));
2704 data->server = g_strdup(server);
2705 data->protocol = protocol;
2707 memset(&hints, 0, sizeof(hints));
2711 hints.ai_socktype = SOCK_DGRAM;
2715 hints.ai_socktype = SOCK_STREAM;
2719 destroy_server_sec(data);
2722 hints.ai_family = AF_UNSPEC;
2723 hints.ai_flags = AI_NUMERICSERV | AI_NUMERICHOST;
2725 ret = getaddrinfo(data->server, "53", &hints, &rp);
2727 connman_error("Failed to parse server %s address: %s\n",
2728 data->server, gai_strerror(ret));
2730 destroy_server_sec(data);
2734 /* Do not blindly copy this code elsewhere; it doesn't loop over the
2735 results using ->ai_next as it should. That's OK in *this* case
2736 because it was a numeric lookup; we *know* there's only one. */
2738 data->server_addr_len = rp->ai_addrlen;
2740 switch (rp->ai_family) {
2742 data->server_addr = (struct sockaddr *)
2743 g_try_new0(struct sockaddr_in, 1);
2746 data->server_addr = (struct sockaddr *)
2747 g_try_new0(struct sockaddr_in6, 1);
2750 connman_error("Wrong address family %d", rp->ai_family);
2753 if (data->server_addr == NULL) {
2755 destroy_server_sec(data);
2758 memcpy(data->server_addr, rp->ai_addr, rp->ai_addrlen);
2761 if (server_create_socket(data) != 0) {
2762 destroy_server_sec(data);
2766 if (protocol == IPPROTO_UDP) {
2767 /* Enable new servers by default */
2768 data->enabled = TRUE;
2769 DBG("Adding DNS server %s", data->server);
2771 data->timeout = g_timeout_add_seconds(30, sec_udp_idle_timeout,
2774 server_list_sec = g_slist_append(server_list_sec, data);
2781 static struct server_data *create_server(int index,
2782 const char *domain, const char *server,
2785 struct server_data *data;
2786 struct addrinfo hints, *rp;
2789 DBG("index %d server %s", index, server);
2791 data = g_try_new0(struct server_data, 1);
2793 connman_error("Failed to allocate server %s data", server);
2797 data->index = index;
2799 data->domains = g_list_append(data->domains, g_strdup(domain));
2800 data->server = g_strdup(server);
2801 data->protocol = protocol;
2803 memset(&hints, 0, sizeof(hints));
2807 hints.ai_socktype = SOCK_DGRAM;
2811 hints.ai_socktype = SOCK_STREAM;
2815 destroy_server(data);
2818 hints.ai_family = AF_UNSPEC;
2819 hints.ai_flags = AI_NUMERICSERV | AI_NUMERICHOST;
2821 ret = getaddrinfo(data->server, "53", &hints, &rp);
2823 connman_error("Failed to parse server %s address: %s\n",
2824 data->server, gai_strerror(ret));
2825 destroy_server(data);
2829 /* Do not blindly copy this code elsewhere; it doesn't loop over the
2830 results using ->ai_next as it should. That's OK in *this* case
2831 because it was a numeric lookup; we *know* there's only one. */
2833 data->server_addr_len = rp->ai_addrlen;
2835 switch (rp->ai_family) {
2837 data->server_addr = (struct sockaddr *)
2838 g_try_new0(struct sockaddr_in, 1);
2841 data->server_addr = (struct sockaddr *)
2842 g_try_new0(struct sockaddr_in6, 1);
2845 connman_error("Wrong address family %d", rp->ai_family);
2848 if (!data->server_addr) {
2850 destroy_server(data);
2853 memcpy(data->server_addr, rp->ai_addr, rp->ai_addrlen);
2856 if (server_create_socket(data) != 0) {
2857 destroy_server(data);
2861 if (protocol == IPPROTO_UDP) {
2862 if (__connman_service_index_is_default(data->index) ||
2863 __connman_service_index_is_split_routing(
2865 data->enabled = true;
2866 DBG("Adding DNS server %s", data->server);
2868 enable_fallback(false);
2871 server_list = g_slist_append(server_list, data);
2877 static bool resolv(struct request_data *req,
2878 gpointer request, gpointer name)
2882 for (list = server_list; list; list = list->next) {
2883 struct server_data *data = list->data;
2885 if (data->protocol == IPPROTO_TCP) {
2886 DBG("server %s ignored proto TCP", data->server);
2890 debug("server %s enabled %d", data->server, data->enabled);
2895 if (!data->channel && data->protocol == IPPROTO_UDP) {
2896 if (server_create_socket(data) < 0) {
2897 DBG("socket creation failed while resolving");
2902 if (ns_resolv(data, req, request, name) > 0)
2909 static void update_domain(int index, const char *domain, bool append)
2913 DBG("index %d domain %s", index, domain);
2918 for (list = server_list; list; list = list->next) {
2919 struct server_data *data = list->data;
2922 bool dom_found = false;
2924 if (data->index < 0)
2927 if (data->index != index)
2930 for (dom_list = data->domains; dom_list;
2931 dom_list = dom_list->next) {
2932 dom = dom_list->data;
2934 if (g_str_equal(dom, domain)) {
2940 if (!dom_found && append) {
2942 g_list_append(data->domains, g_strdup(domain));
2943 } else if (dom_found && !append) {
2945 g_list_remove(data->domains, dom);
2951 static void append_domain(int index, const char *domain)
2953 update_domain(index, domain, true);
2956 static void remove_domain(int index, const char *domain)
2958 update_domain(index, domain, false);
2961 static void flush_requests(struct server_data *server)
2965 list = request_list;
2967 struct request_data *req = list->data;
2971 if (ns_resolv(server, req, req->request, req->name)) {
2973 * A cached result was sent,
2974 * so the request can be released
2977 g_slist_remove(request_list, req);
2978 destroy_request_data(req);
2982 if (req->timeout > 0)
2983 g_source_remove(req->timeout);
2985 req->timeout = g_timeout_add_seconds(5, request_timeout, req);
2989 int __connman_dnsproxy_append(int index, const char *domain,
2992 struct server_data *data;
2994 DBG("index %d server %s", index, server);
2996 if (!server && !domain)
3000 append_domain(index, domain);
3005 if (g_str_equal(server, "127.0.0.1"))
3008 if (g_str_equal(server, "::1"))
3011 data = find_server(index, server, IPPROTO_UDP);
3013 append_domain(index, domain);
3017 data = create_server(index, domain, server, IPPROTO_UDP);
3021 flush_requests(data);
3026 static void remove_server(int index, const char *domain,
3027 const char *server, int protocol)
3029 struct server_data *data;
3032 data = find_server(index, server, protocol);
3036 destroy_server(data);
3038 for (list = server_list; list; list = list->next) {
3039 struct server_data *data = list->data;
3041 if (data->index != -1 && data->enabled == true)
3045 enable_fallback(true);
3048 int __connman_dnsproxy_remove(int index, const char *domain,
3051 DBG("index %d server %s", index, server);
3053 if (!server && !domain)
3057 remove_domain(index, domain);
3062 if (g_str_equal(server, "127.0.0.1"))
3065 if (g_str_equal(server, "::1"))
3068 remove_server(index, domain, server, IPPROTO_UDP);
3069 remove_server(index, domain, server, IPPROTO_TCP);
3071 #if defined TIZEN_EXT
3072 destroy_all_server_sec();
3078 static void dnsproxy_offline_mode(bool enabled)
3082 DBG("enabled %d", enabled);
3084 for (list = server_list; list; list = list->next) {
3085 struct server_data *data = list->data;
3088 DBG("Enabling DNS server %s", data->server);
3089 data->enabled = true;
3093 DBG("Disabling DNS server %s", data->server);
3094 data->enabled = false;
3100 static void dnsproxy_default_changed(struct connman_service *service)
3102 bool server_enabled = false;
3106 DBG("service %p", service);
3108 /* DNS has changed, invalidate the cache */
3112 /* When no services are active, then disable DNS proxying */
3113 dnsproxy_offline_mode(true);
3117 index = __connman_service_get_index(service);
3121 for (list = server_list; list; list = list->next) {
3122 struct server_data *data = list->data;
3124 if (data->index == index) {
3125 DBG("Enabling DNS server %s", data->server);
3126 data->enabled = true;
3127 server_enabled = true;
3129 DBG("Disabling DNS server %s", data->server);
3130 data->enabled = false;
3134 if (!server_enabled)
3135 enable_fallback(true);
3140 static struct connman_notifier dnsproxy_notifier = {
3142 .default_changed = dnsproxy_default_changed,
3143 .offline_mode = dnsproxy_offline_mode,
3146 static unsigned char opt_edns0_type[2] = { 0x00, 0x29 };
3148 static int parse_request(unsigned char *buf, int len,
3149 char *name, unsigned int size)
3151 struct domain_hdr *hdr = (void *) buf;
3152 uint16_t qdcount = ntohs(hdr->qdcount);
3153 uint16_t arcount = ntohs(hdr->arcount);
3155 char *last_label = NULL;
3156 unsigned int remain, used = 0;
3161 debug("id 0x%04x qr %d opcode %d qdcount %d arcount %d",
3162 hdr->id, hdr->qr, hdr->opcode,
3165 if (hdr->qr != 0 || qdcount != 1)
3170 ptr = buf + sizeof(struct domain_hdr);
3171 remain = len - sizeof(struct domain_hdr);
3173 while (remain > 0) {
3174 uint8_t label_len = *ptr;
3176 if (label_len == 0x00) {
3177 last_label = (char *) (ptr + 1);
3181 if (used + label_len + 1 > size)
3184 strncat(name, (char *) (ptr + 1), label_len);
3187 used += label_len + 1;
3189 ptr += label_len + 1;
3190 remain -= label_len + 1;
3193 if (last_label && arcount && remain >= 9 && last_label[4] == 0 &&
3194 !memcmp(last_label + 5, opt_edns0_type, 2)) {
3195 uint16_t edns0_bufsize;
3197 edns0_bufsize = last_label[7] << 8 | last_label[8];
3199 debug("EDNS0 buffer size %u", edns0_bufsize);
3201 /* This is an evil hack until full TCP support has been
3204 * Somtimes the EDNS0 request gets send with a too-small
3205 * buffer size. Since glibc doesn't seem to crash when it
3206 * gets a response biffer then it requested, just bump
3207 * the buffer size up to 4KiB.
3209 if (edns0_bufsize < 0x1000) {
3210 last_label[7] = 0x10;
3211 last_label[8] = 0x00;
3215 debug("query %s", name);
3220 static void client_reset(struct tcp_partial_client_data *client)
3225 if (client->channel) {
3226 debug("client %d closing",
3227 g_io_channel_unix_get_fd(client->channel));
3229 g_io_channel_unref(client->channel);
3230 client->channel = NULL;
3233 if (client->watch > 0) {
3234 g_source_remove(client->watch);
3238 if (client->timeout > 0) {
3239 g_source_remove(client->timeout);
3240 client->timeout = 0;
3243 g_free(client->buf);
3246 client->buf_end = 0;
3249 static unsigned int get_msg_len(unsigned char *buf)
3251 return buf[0]<<8 | buf[1];
3254 static bool read_tcp_data(struct tcp_partial_client_data *client,
3255 void *client_addr, socklen_t client_addr_len,
3258 char query[TCP_MAX_BUF_LEN];
3259 struct request_data *req;
3261 unsigned int msg_len;
3263 bool waiting_for_connect = false;
3265 struct cache_entry *entry;
3267 client_sk = g_io_channel_unix_get_fd(client->channel);
3269 if (read_len == 0) {
3270 debug("client %d closed, pending %d bytes",
3271 client_sk, client->buf_end);
3272 g_hash_table_remove(partial_tcp_req_table,
3273 GINT_TO_POINTER(client_sk));
3277 debug("client %d received %d bytes", client_sk, read_len);
3279 client->buf_end += read_len;
3281 if (client->buf_end < 2)
3284 msg_len = get_msg_len(client->buf);
3285 if (msg_len > TCP_MAX_BUF_LEN) {
3286 debug("client %d sent too much data %d", client_sk, msg_len);
3287 g_hash_table_remove(partial_tcp_req_table,
3288 GINT_TO_POINTER(client_sk));
3293 debug("client %d msg len %d end %d past end %d", client_sk, msg_len,
3294 client->buf_end, client->buf_end - (msg_len + 2));
3296 if (client->buf_end < (msg_len + 2)) {
3297 debug("client %d still missing %d bytes",
3299 msg_len + 2 - client->buf_end);
3303 debug("client %d all data %d received", client_sk, msg_len);
3305 err = parse_request(client->buf + 2, msg_len,
3306 query, sizeof(query));
3307 if (err < 0 || (g_slist_length(server_list) == 0)) {
3308 send_response(client_sk, client->buf, msg_len + 2,
3309 NULL, 0, IPPROTO_TCP);
3313 req = g_try_new0(struct request_data, 1);
3317 memcpy(&req->sa, client_addr, client_addr_len);
3318 req->sa_len = client_addr_len;
3319 req->client_sk = client_sk;
3320 req->protocol = IPPROTO_TCP;
3321 req->family = client->family;
3323 req->srcid = client->buf[2] | (client->buf[3] << 8);
3324 req->dstid = get_id();
3325 req->altid = get_id();
3326 req->request_len = msg_len + 2;
3328 client->buf[2] = req->dstid & 0xff;
3329 client->buf[3] = req->dstid >> 8;
3332 req->ifdata = client->ifdata;
3333 req->append_domain = false;
3336 * Check if the answer is found in the cache before
3337 * creating sockets to the server.
3339 entry = cache_check(client->buf, &qtype, IPPROTO_TCP);
3342 struct cache_data *data;
3344 debug("cache hit %s type %s", query, qtype == 1 ? "A" : "AAAA");
3351 ttl_left = data->valid_until - time(NULL);
3354 send_cached_response(client_sk, data->data,
3355 data->data_len, NULL, 0, IPPROTO_TCP,
3356 req->srcid, data->answers, ttl_left);
3361 debug("data missing, ignoring cache for this query");
3364 for (list = server_list; list; list = list->next) {
3365 struct server_data *data = list->data;
3367 if (data->protocol != IPPROTO_UDP || !data->enabled)
3370 if (!create_server(data->index, NULL, data->server,
3374 waiting_for_connect = true;
3377 if (!waiting_for_connect) {
3378 /* No server is waiting for connect */
3379 send_response(client_sk, client->buf,
3380 req->request_len, NULL, 0, IPPROTO_TCP);
3386 * The server is not connected yet.
3387 * Copy the relevant buffers.
3388 * The request will actually be sent once we're
3389 * properly connected over TCP to the nameserver.
3391 req->request = g_try_malloc0(req->request_len);
3392 if (!req->request) {
3393 send_response(client_sk, client->buf,
3394 req->request_len, NULL, 0, IPPROTO_TCP);
3398 memcpy(req->request, client->buf, req->request_len);
3400 req->name = g_try_malloc0(sizeof(query));
3402 send_response(client_sk, client->buf,
3403 req->request_len, NULL, 0, IPPROTO_TCP);
3404 g_free(req->request);
3408 memcpy(req->name, query, sizeof(query));
3410 req->timeout = g_timeout_add_seconds(30, request_timeout, req);
3412 request_list = g_slist_append(request_list, req);
3415 if (client->buf_end > (msg_len + 2)) {
3416 debug("client %d buf %p -> %p end %d len %d new %d",
3418 client->buf + msg_len + 2,
3419 client->buf, client->buf_end,
3420 TCP_MAX_BUF_LEN - client->buf_end,
3421 client->buf_end - (msg_len + 2));
3422 memmove(client->buf, client->buf + msg_len + 2,
3423 TCP_MAX_BUF_LEN - client->buf_end);
3424 client->buf_end = client->buf_end - (msg_len + 2);
3427 * If we have a full message waiting, just read it
3430 msg_len = get_msg_len(client->buf);
3431 if ((msg_len + 2) == client->buf_end) {
3432 debug("client %d reading another %d bytes", client_sk,
3437 debug("client %d clearing reading buffer", client_sk);
3439 client->buf_end = 0;
3440 memset(client->buf, 0, TCP_MAX_BUF_LEN);
3443 * We received all the packets from client so we must also
3444 * remove the timeout handler here otherwise we might get
3445 * timeout while waiting the results from server.
3447 g_source_remove(client->timeout);
3448 client->timeout = 0;
3454 static gboolean tcp_client_event(GIOChannel *channel, GIOCondition condition,
3457 struct tcp_partial_client_data *client = user_data;
3458 struct sockaddr_in6 client_addr6;
3459 socklen_t client_addr6_len = sizeof(client_addr6);
3460 struct sockaddr_in client_addr4;
3461 socklen_t client_addr4_len = sizeof(client_addr4);
3463 socklen_t *client_addr_len;
3466 client_sk = g_io_channel_unix_get_fd(channel);
3468 if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
3469 g_hash_table_remove(partial_tcp_req_table,
3470 GINT_TO_POINTER(client_sk));
3472 connman_error("Error with TCP client %d channel", client_sk);
3476 switch (client->family) {
3478 client_addr = &client_addr4;
3479 client_addr_len = &client_addr4_len;
3482 client_addr = &client_addr6;
3483 client_addr_len = &client_addr6_len;
3486 g_hash_table_remove(partial_tcp_req_table,
3487 GINT_TO_POINTER(client_sk));
3488 connman_error("client %p corrupted", client);
3492 len = recvfrom(client_sk, client->buf + client->buf_end,
3493 TCP_MAX_BUF_LEN - client->buf_end, 0,
3494 client_addr, client_addr_len);
3496 if (errno == EAGAIN || errno == EWOULDBLOCK)
3499 debug("client %d cannot read errno %d/%s", client_sk, -errno,
3501 g_hash_table_remove(partial_tcp_req_table,
3502 GINT_TO_POINTER(client_sk));
3506 return read_tcp_data(client, client_addr, *client_addr_len, len);
3509 static gboolean client_timeout(gpointer user_data)
3511 struct tcp_partial_client_data *client = user_data;
3514 sock = g_io_channel_unix_get_fd(client->channel);
3516 debug("client %d timeout pending %d bytes", sock, client->buf_end);
3518 g_hash_table_remove(partial_tcp_req_table, GINT_TO_POINTER(sock));
3523 #if defined TIZEN_EXT
3524 static void recover_listener(GIOChannel *channel, struct listener_data *ifdata)
3528 index = ifdata->index;
3530 sk = g_io_channel_unix_get_fd(channel);
3533 __connman_dnsproxy_remove_listener(index);
3535 if (__connman_dnsproxy_add_listener(index) == 0)
3536 DBG("listener %d successfully recovered", index);
3540 static bool tcp_listener_event(GIOChannel *channel, GIOCondition condition,
3541 struct listener_data *ifdata, int family,
3542 guint *listener_watch)
3544 int sk, client_sk, len;
3545 unsigned int msg_len;
3546 struct tcp_partial_client_data *client;
3547 struct sockaddr_in6 client_addr6;
3548 socklen_t client_addr6_len = sizeof(client_addr6);
3549 struct sockaddr_in client_addr4;
3550 socklen_t client_addr4_len = sizeof(client_addr4);
3552 socklen_t *client_addr_len;
3556 debug("condition 0x%02x channel %p ifdata %p family %d",
3557 condition, channel, ifdata, family);
3559 if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
3560 #if defined TIZEN_EXT
3561 connman_error("Error %d with TCP listener channel", condition);
3563 recover_listener(channel, ifdata);
3565 if (*listener_watch > 0)
3566 g_source_remove(*listener_watch);
3567 *listener_watch = 0;
3569 connman_error("Error with TCP listener channel");
3575 sk = g_io_channel_unix_get_fd(channel);
3577 if (family == AF_INET) {
3578 client_addr = &client_addr4;
3579 client_addr_len = &client_addr4_len;
3581 client_addr = &client_addr6;
3582 client_addr_len = &client_addr6_len;
3585 tv.tv_sec = tv.tv_usec = 0;
3587 FD_SET(sk, &readfds);
3589 select(sk + 1, &readfds, NULL, NULL, &tv);
3590 if (FD_ISSET(sk, &readfds)) {
3591 client_sk = accept(sk, client_addr, client_addr_len);
3592 debug("client %d accepted", client_sk);
3594 debug("No data to read from master %d, waiting.", sk);
3598 if (client_sk < 0) {
3599 connman_error("Accept failure on TCP listener");
3600 *listener_watch = 0;
3604 fcntl(client_sk, F_SETFL, O_NONBLOCK);
3606 client = g_hash_table_lookup(partial_tcp_req_table,
3607 GINT_TO_POINTER(client_sk));
3609 client = g_try_new0(struct tcp_partial_client_data, 1);
3615 g_hash_table_insert(partial_tcp_req_table,
3616 GINT_TO_POINTER(client_sk),
3619 client->channel = g_io_channel_unix_new(client_sk);
3620 g_io_channel_set_close_on_unref(client->channel, TRUE);
3622 client->watch = g_io_add_watch(client->channel,
3623 G_IO_IN, tcp_client_event,
3626 client->ifdata = ifdata;
3628 debug("client %d created %p", client_sk, client);
3630 debug("client %d already exists %p", client_sk, client);
3634 client->buf = g_try_malloc(TCP_MAX_BUF_LEN);
3638 memset(client->buf, 0, TCP_MAX_BUF_LEN);
3639 client->buf_end = 0;
3640 client->family = family;
3642 if (client->timeout == 0)
3643 client->timeout = g_timeout_add_seconds(2, client_timeout,
3647 * Check how much data there is. If all is there, then we can
3648 * proceed normally, otherwise read the bits until everything
3649 * is received or timeout occurs.
3651 len = recv(client_sk, client->buf, TCP_MAX_BUF_LEN, 0);
3653 if (errno == EAGAIN || errno == EWOULDBLOCK) {
3654 debug("client %d no data to read, waiting", client_sk);
3658 debug("client %d cannot read errno %d/%s", client_sk, -errno,
3660 g_hash_table_remove(partial_tcp_req_table,
3661 GINT_TO_POINTER(client_sk));
3666 debug("client %d not enough data to read, waiting", client_sk);
3667 client->buf_end += len;
3671 msg_len = get_msg_len(client->buf);
3672 if (msg_len > TCP_MAX_BUF_LEN) {
3673 debug("client %d invalid message length %u ignoring packet",
3674 client_sk, msg_len);
3675 g_hash_table_remove(partial_tcp_req_table,
3676 GINT_TO_POINTER(client_sk));
3681 * The packet length bytes do not contain the total message length,
3682 * that is the reason to -2 below.
3684 #if defined TIZEN_EXT
3685 if (msg_len > (unsigned int)(len - 2)) {
3687 if (msg_len != (unsigned int)(len - 2)) {
3689 debug("client %d sent %d bytes but expecting %u pending %d",
3690 client_sk, len, msg_len + 2, msg_len + 2 - len);
3692 client->buf_end += len;
3696 return read_tcp_data(client, client_addr, *client_addr_len, len);
3699 static gboolean tcp4_listener_event(GIOChannel *channel, GIOCondition condition,
3702 struct listener_data *ifdata = user_data;
3704 return tcp_listener_event(channel, condition, ifdata, AF_INET,
3705 &ifdata->tcp4_listener_watch);
3708 static gboolean tcp6_listener_event(GIOChannel *channel, GIOCondition condition,
3711 struct listener_data *ifdata = user_data;
3713 return tcp_listener_event(channel, condition, user_data, AF_INET6,
3714 &ifdata->tcp6_listener_watch);
3717 static bool udp_listener_event(GIOChannel *channel, GIOCondition condition,
3718 struct listener_data *ifdata, int family,
3719 guint *listener_watch)
3721 unsigned char buf[768];
3723 struct request_data *req;
3724 struct sockaddr_in6 client_addr6;
3725 socklen_t client_addr6_len = sizeof(client_addr6);
3726 struct sockaddr_in client_addr4;
3727 socklen_t client_addr4_len = sizeof(client_addr4);
3729 socklen_t *client_addr_len;
3732 if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
3733 #if defined TIZEN_EXT
3734 connman_error("Error %d with UDP listener channel", condition);
3736 recover_listener(channel, ifdata);
3738 connman_error("Error with UDP listener channel");
3739 *listener_watch = 0;
3744 sk = g_io_channel_unix_get_fd(channel);
3746 if (family == AF_INET) {
3747 client_addr = &client_addr4;
3748 client_addr_len = &client_addr4_len;
3750 client_addr = &client_addr6;
3751 client_addr_len = &client_addr6_len;
3754 memset(client_addr, 0, *client_addr_len);
3755 len = recvfrom(sk, buf, sizeof(buf), 0, client_addr, client_addr_len);
3759 debug("Received %d bytes (id 0x%04x)", len, buf[0] | buf[1] << 8);
3761 err = parse_request(buf, len, query, sizeof(query));
3762 if (err < 0 || (g_slist_length(server_list) == 0)) {
3763 send_response(sk, buf, len, client_addr,
3764 *client_addr_len, IPPROTO_UDP);
3768 req = g_try_new0(struct request_data, 1);
3772 memcpy(&req->sa, client_addr, *client_addr_len);
3773 req->sa_len = *client_addr_len;
3775 req->protocol = IPPROTO_UDP;
3776 req->family = family;
3778 req->srcid = buf[0] | (buf[1] << 8);
3779 req->dstid = get_id();
3780 req->altid = get_id();
3781 req->request_len = len;
3783 buf[0] = req->dstid & 0xff;
3784 buf[1] = req->dstid >> 8;
3787 req->ifdata = ifdata;
3788 req->append_domain = false;
3790 if (resolv(req, buf, query)) {
3791 /* a cached result was sent, so the request can be released */
3796 req->name = g_strdup(query);
3797 req->request = g_malloc(len);
3798 memcpy(req->request, buf, len);
3799 #if defined TIZEN_EXT
3800 DBG("req %p dstid 0x%04x altid 0x%04x", req, req->dstid, req->altid);
3801 req->timeout = g_timeout_add_seconds(30, request_timeout, req);
3803 req->timeout = g_timeout_add_seconds(5, request_timeout, req);
3805 request_list = g_slist_append(request_list, req);
3810 static gboolean udp4_listener_event(GIOChannel *channel, GIOCondition condition,
3813 struct listener_data *ifdata = user_data;
3815 return udp_listener_event(channel, condition, ifdata, AF_INET,
3816 &ifdata->udp4_listener_watch);
3819 static gboolean udp6_listener_event(GIOChannel *channel, GIOCondition condition,
3822 struct listener_data *ifdata = user_data;
3824 return udp_listener_event(channel, condition, user_data, AF_INET6,
3825 &ifdata->udp6_listener_watch);
3828 static GIOChannel *get_listener(int family, int protocol, int index)
3830 GIOChannel *channel;
3832 #if !defined TIZEN_EXT
3835 struct sockaddr_in6 sin6;
3836 struct sockaddr_in sin;
3841 #if !defined TIZEN_EXT
3844 #if defined TIZEN_EXT
3848 int is_socket_inet = 0;
3851 debug("family %d protocol %d index %d", family, protocol, index);
3856 type = SOCK_DGRAM | SOCK_CLOEXEC;
3861 type = SOCK_STREAM | SOCK_CLOEXEC;
3867 #if defined TIZEN_EXT
3868 sd_num = sd_listen_fds(0);
3869 DBG("socket type(%s) systemd number of fds(%d)", proto, sd_num);
3871 DBG("fail to get the fd from systemd");
3875 if(protocol == IPPROTO_TCP)
3880 for(sk = SD_LISTEN_FDS_START; sk < SD_LISTEN_FDS_START+sd_num; ++sk){
3881 rv = sd_is_socket_inet(sk, family, type, -1, 53);
3883 DBG("socket fd (%d) is passed by systemd", sk);
3889 if (!is_socket_inet) {
3890 DBG("socket fd is not matched what connman requests");
3894 sk = socket(family, type, protocol);
3895 if (sk < 0 && family == AF_INET6 && errno == EAFNOSUPPORT) {
3896 connman_error("No IPv6 support");
3901 connman_error("Failed to create %s listener socket", proto);
3905 /* ConnMan listens DNS from multiple interfaces
3906 * E.g. various technology based and tethering interfaces
3908 interface = connman_inet_ifname(index);
3909 if (!interface || setsockopt(sk, SOL_SOCKET, SO_BINDTODEVICE,
3911 strlen(interface) + 1) < 0) {
3912 connman_error("Failed to bind %s listener interface "
3914 proto, family == AF_INET ? "IPv4" : "IPv6",
3915 -errno, strerror(errno));
3922 if (family == AF_INET6) {
3923 memset(&s.sin6, 0, sizeof(s.sin6));
3924 s.sin6.sin6_family = AF_INET6;
3925 s.sin6.sin6_port = htons(53);
3926 slen = sizeof(s.sin6);
3928 if (__connman_inet_get_interface_address(index,
3930 &s.sin6.sin6_addr) < 0) {
3931 /* So we could not find suitable IPv6 address for
3932 * the interface. This could happen if we have
3933 * disabled IPv6 for the interface.
3939 } else if (family == AF_INET) {
3940 memset(&s.sin, 0, sizeof(s.sin));
3941 s.sin.sin_family = AF_INET;
3942 s.sin.sin_port = htons(53);
3943 slen = sizeof(s.sin);
3944 if (__connman_inet_get_interface_address(index,
3946 &s.sin.sin_addr) < 0) {
3955 #if defined TIZEN_EXT
3956 /* When ConnMan crashed,
3957 * probably DNS listener cannot bind existing address */
3959 if (setsockopt(sk, SOL_SOCKET, SO_REUSEADDR, &option, sizeof(option)) < 0) {
3960 connman_error("Failed to set socket option SO_REUSEADDR");
3965 #if !defined TIZEN_EXT
3966 if (bind(sk, &s.sa, slen) < 0) {
3967 connman_error("Failed to bind %s listener socket", proto);
3973 if (protocol == IPPROTO_TCP) {
3974 #if !defined TIZEN_EXT
3975 if (listen(sk, 10) < 0) {
3976 connman_error("Failed to listen on TCP socket %d/%s",
3977 -errno, strerror(errno));
3982 fcntl(sk, F_SETFL, O_NONBLOCK);
3985 channel = g_io_channel_unix_new(sk);
3987 connman_error("Failed to create %s listener channel", proto);
3992 g_io_channel_set_close_on_unref(channel, TRUE);
3997 #define UDP_IPv4_FAILED 0x01
3998 #define TCP_IPv4_FAILED 0x02
3999 #define UDP_IPv6_FAILED 0x04
4000 #define TCP_IPv6_FAILED 0x08
4001 #define UDP_FAILED (UDP_IPv4_FAILED | UDP_IPv6_FAILED)
4002 #define TCP_FAILED (TCP_IPv4_FAILED | TCP_IPv6_FAILED)
4003 #define IPv6_FAILED (UDP_IPv6_FAILED | TCP_IPv6_FAILED)
4004 #define IPv4_FAILED (UDP_IPv4_FAILED | TCP_IPv4_FAILED)
4006 static int create_dns_listener(int protocol, struct listener_data *ifdata)
4010 if (protocol == IPPROTO_TCP) {
4011 ifdata->tcp4_listener_channel = get_listener(AF_INET, protocol,
4013 if (ifdata->tcp4_listener_channel)
4014 #if defined TIZEN_EXT
4015 ifdata->tcp4_listener_watch =
4016 g_io_add_watch(ifdata->tcp4_listener_channel,
4017 G_IO_IN | G_IO_ERR | G_IO_HUP | G_IO_NVAL,
4018 tcp4_listener_event, (gpointer)ifdata);
4020 ifdata->tcp4_listener_watch =
4021 g_io_add_watch(ifdata->tcp4_listener_channel,
4022 G_IO_IN, tcp4_listener_event,
4026 ret |= TCP_IPv4_FAILED;
4028 ifdata->tcp6_listener_channel = get_listener(AF_INET6, protocol,
4030 if (ifdata->tcp6_listener_channel)
4031 #if defined TIZEN_EXT
4032 ifdata->tcp6_listener_watch =
4033 g_io_add_watch(ifdata->tcp6_listener_channel,
4034 G_IO_IN | G_IO_ERR | G_IO_HUP | G_IO_NVAL,
4035 tcp6_listener_event, (gpointer)ifdata);
4037 ifdata->tcp6_listener_watch =
4038 g_io_add_watch(ifdata->tcp6_listener_channel,
4039 G_IO_IN, tcp6_listener_event,
4043 ret |= TCP_IPv6_FAILED;
4045 ifdata->udp4_listener_channel = get_listener(AF_INET, protocol,
4047 if (ifdata->udp4_listener_channel)
4048 #if defined TIZEN_EXT
4049 ifdata->udp4_listener_watch =
4050 g_io_add_watch(ifdata->udp4_listener_channel,
4051 G_IO_IN | G_IO_ERR | G_IO_HUP | G_IO_NVAL,
4052 udp4_listener_event, (gpointer)ifdata);
4054 ifdata->udp4_listener_watch =
4055 g_io_add_watch(ifdata->udp4_listener_channel,
4056 G_IO_IN, udp4_listener_event,
4060 ret |= UDP_IPv4_FAILED;
4062 ifdata->udp6_listener_channel = get_listener(AF_INET6, protocol,
4064 if (ifdata->udp6_listener_channel)
4065 #if defined TIZEN_EXT
4066 ifdata->udp6_listener_watch =
4067 g_io_add_watch(ifdata->udp6_listener_channel,
4068 G_IO_IN | G_IO_ERR | G_IO_HUP | G_IO_NVAL,
4069 udp6_listener_event, (gpointer)ifdata);
4071 ifdata->udp6_listener_watch =
4072 g_io_add_watch(ifdata->udp6_listener_channel,
4073 G_IO_IN, udp6_listener_event,
4077 ret |= UDP_IPv6_FAILED;
4083 static void destroy_udp_listener(struct listener_data *ifdata)
4085 DBG("index %d", ifdata->index);
4087 if (ifdata->udp4_listener_watch > 0)
4088 g_source_remove(ifdata->udp4_listener_watch);
4090 if (ifdata->udp6_listener_watch > 0)
4091 g_source_remove(ifdata->udp6_listener_watch);
4093 if (ifdata->udp4_listener_channel)
4094 g_io_channel_unref(ifdata->udp4_listener_channel);
4095 if (ifdata->udp6_listener_channel)
4096 g_io_channel_unref(ifdata->udp6_listener_channel);
4099 static void destroy_tcp_listener(struct listener_data *ifdata)
4101 DBG("index %d", ifdata->index);
4103 if (ifdata->tcp4_listener_watch > 0)
4104 g_source_remove(ifdata->tcp4_listener_watch);
4105 if (ifdata->tcp6_listener_watch > 0)
4106 g_source_remove(ifdata->tcp6_listener_watch);
4108 if (ifdata->tcp4_listener_channel)
4109 g_io_channel_unref(ifdata->tcp4_listener_channel);
4110 if (ifdata->tcp6_listener_channel)
4111 g_io_channel_unref(ifdata->tcp6_listener_channel);
4114 static int create_listener(struct listener_data *ifdata)
4118 err = create_dns_listener(IPPROTO_UDP, ifdata);
4119 if ((err & UDP_FAILED) == UDP_FAILED)
4122 err |= create_dns_listener(IPPROTO_TCP, ifdata);
4123 if ((err & TCP_FAILED) == TCP_FAILED) {
4124 destroy_udp_listener(ifdata);
4128 index = connman_inet_ifindex("lo");
4129 if (ifdata->index == index) {
4130 if ((err & IPv6_FAILED) != IPv6_FAILED)
4131 __connman_resolvfile_append(index, NULL, "::1");
4133 if ((err & IPv4_FAILED) != IPv4_FAILED)
4134 __connman_resolvfile_append(index, NULL, "127.0.0.1");
4140 static void destroy_listener(struct listener_data *ifdata)
4145 index = connman_inet_ifindex("lo");
4146 if (ifdata->index == index) {
4147 __connman_resolvfile_remove(index, NULL, "127.0.0.1");
4148 __connman_resolvfile_remove(index, NULL, "::1");
4151 for (list = request_list; list; list = list->next) {
4152 struct request_data *req = list->data;
4154 debug("Dropping request (id 0x%04x -> 0x%04x)",
4155 req->srcid, req->dstid);
4156 destroy_request_data(req);
4160 g_slist_free(request_list);
4161 request_list = NULL;
4163 destroy_tcp_listener(ifdata);
4164 destroy_udp_listener(ifdata);
4167 int __connman_dnsproxy_add_listener(int index)
4169 struct listener_data *ifdata;
4172 DBG("index %d", index);
4177 if (!listener_table)
4180 if (g_hash_table_lookup(listener_table, GINT_TO_POINTER(index)))
4183 ifdata = g_try_new0(struct listener_data, 1);
4187 ifdata->index = index;
4188 ifdata->udp4_listener_channel = NULL;
4189 ifdata->udp4_listener_watch = 0;
4190 ifdata->tcp4_listener_channel = NULL;
4191 ifdata->tcp4_listener_watch = 0;
4192 ifdata->udp6_listener_channel = NULL;
4193 ifdata->udp6_listener_watch = 0;
4194 ifdata->tcp6_listener_channel = NULL;
4195 ifdata->tcp6_listener_watch = 0;
4197 err = create_listener(ifdata);
4199 connman_error("Couldn't create listener for index %d err %d",
4204 g_hash_table_insert(listener_table, GINT_TO_POINTER(ifdata->index),
4209 void __connman_dnsproxy_remove_listener(int index)
4211 struct listener_data *ifdata;
4213 DBG("index %d", index);
4215 if (!listener_table)
4218 ifdata = g_hash_table_lookup(listener_table, GINT_TO_POINTER(index));
4222 destroy_listener(ifdata);
4224 g_hash_table_remove(listener_table, GINT_TO_POINTER(index));
4227 static void remove_listener(gpointer key, gpointer value, gpointer user_data)
4229 int index = GPOINTER_TO_INT(key);
4230 struct listener_data *ifdata = value;
4232 DBG("index %d", index);
4234 destroy_listener(ifdata);
4237 static void free_partial_reqs(gpointer value)
4239 struct tcp_partial_client_data *data = value;
4245 int __connman_dnsproxy_init(void)
4251 listener_table = g_hash_table_new_full(g_direct_hash, g_direct_equal,
4254 partial_tcp_req_table = g_hash_table_new_full(g_direct_hash,
4259 index = connman_inet_ifindex("lo");
4260 err = __connman_dnsproxy_add_listener(index);
4264 err = connman_notifier_register(&dnsproxy_notifier);
4271 __connman_dnsproxy_remove_listener(index);
4272 g_hash_table_destroy(listener_table);
4273 g_hash_table_destroy(partial_tcp_req_table);
4278 void __connman_dnsproxy_cleanup(void)
4283 g_source_remove(cache_timer);
4288 g_hash_table_destroy(cache);
4292 connman_notifier_unregister(&dnsproxy_notifier);
4294 g_hash_table_foreach(listener_table, remove_listener, NULL);
4296 g_hash_table_destroy(listener_table);
4298 g_hash_table_destroy(partial_tcp_req_table);