2 This file is part of GNUnet.
3 Copyright (C) 2007-2016 GNUnet e.V.
5 GNUnet is free software: you can redistribute it and/or modify it
6 under the terms of the GNU Affero General Public License as published
7 by the Free Software Foundation, either version 3 of the License,
8 or (at your option) any later version.
10 GNUnet is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Affero General Public License for more details.
15 You should have received a copy of the GNU Affero General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>.
20 * @file util/gnunet-service-resolver.c
21 * @brief code to do DNS resolution
22 * @author Christian Grothoff
25 #include "gnunet_util_lib.h"
26 #include "gnunet_protocols.h"
27 #include "gnunet_statistics_service.h"
32 * How long do we wait for DNS answers?
34 #define DNS_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 30)
37 * Maximum number of hostnames we cache results for.
39 #define MAX_CACHE 1024
42 * Entry in list of cached DNS records for a hostname.
44 struct RecordListEntry
47 * This is a doubly linked list.
49 struct RecordListEntry *next;
52 * This is a doubly linked list.
54 struct RecordListEntry *prev;
59 struct GNUNET_DNSPARSER_Record *record;
64 * A cached DNS lookup result.
69 * This is a doubly linked list.
71 struct ResolveCache *next;
74 * This is a doubly linked list.
76 struct ResolveCache *prev;
79 * Which hostname is this cache for?
84 * head of a double linked list containing the lookup results
86 struct RecordListEntry *records_head;
89 * tail of a double linked list containing the lookup results
91 struct RecordListEntry *records_tail;
97 * Information about pending lookups.
104 struct ActiveLookup *next;
109 struct ActiveLookup *prev;
112 * The client that queried the records contained in this cache entry.
114 struct GNUNET_SERVICE_Client *client;
117 * handle for cancelling a request
119 struct GNUNET_DNSSTUB_RequestSocket *resolve_handle;
122 * handle for the resolution timeout task
124 struct GNUNET_SCHEDULER_Task *timeout_task;
127 * Which hostname are we resolving?
132 * If @a record_type is #GNUNET_DNSPARSER_TYPE_ALL, did we go again
133 * for the AAAA records yet?
138 * type of queried DNS record
140 uint16_t record_type;
143 * Unique request ID of a client if a query for this hostname/record_type
144 * is currently pending, undefined otherwise.
149 * Unique DNS request ID of a client if a query for this hostname/record_type
150 * is currently pending, undefined otherwise.
158 * Start of the linked list of cached DNS lookup results.
160 static struct ResolveCache *cache_head;
163 * Tail of the linked list of cached DNS lookup results.
165 static struct ResolveCache *cache_tail;
168 * Start of the linked list of active DNS lookups.
170 static struct ActiveLookup *lookup_head;
173 * Tail of the linked list of active DNS lookups.
175 static struct ActiveLookup *lookup_tail;
178 * context of dnsstub library
180 static struct GNUNET_DNSSTUB_Context *dnsstub_ctx;
183 * How many entries do we have in #cache_head DLL?
185 static unsigned int cache_size;
188 * Remove @a entry from cache.
190 * @param rc entry to free
193 free_cache_entry (struct ResolveCache *rc)
195 struct RecordListEntry *pos;
197 while (NULL != (pos = rc->records_head))
199 GNUNET_CONTAINER_DLL_remove (rc->records_head,
202 GNUNET_DNSPARSER_free_record (pos->record);
203 GNUNET_free (pos->record);
206 GNUNET_free_non_null (rc->hostname);
207 GNUNET_CONTAINER_DLL_remove (cache_head,
216 * Release resources associated with @a al
218 * @param al an active lookup
221 free_active_lookup (struct ActiveLookup *al)
223 GNUNET_CONTAINER_DLL_remove (lookup_head,
226 if (NULL != al->resolve_handle)
228 GNUNET_DNSSTUB_resolve_cancel (al->resolve_handle);
229 al->resolve_handle = NULL;
231 if (NULL != al->timeout_task)
233 GNUNET_SCHEDULER_cancel (al->timeout_task);
234 al->timeout_task = NULL;
236 GNUNET_free_non_null (al->hostname);
243 * Find out if the configuration file line contains a string
244 * starting with "nameserver ", and if so, return a copy of
245 * the nameserver's IP.
247 * @param line line to parse
248 * @param line_len number of characters in @a line
249 * @return NULL if no nameserver is configured in this @a line
252 extract_dns_server (const char* line,
255 if (0 == strncmp (line,
257 strlen ("nameserver ")))
258 return GNUNET_strndup (line + strlen ("nameserver "),
259 line_len - strlen ("nameserver "));
265 * Reads the list of nameservers from /etc/resolve.conf
267 * @param server_addrs[out] a list of null-terminated server address strings
268 * @return the number of server addresses in @server_addrs, -1 on error
271 lookup_dns_servers (char ***server_addrs)
273 struct GNUNET_DISK_FileHandle *fh;
277 unsigned int num_dns_servers;
279 fh = GNUNET_DISK_file_open ("/etc/resolv.conf",
280 GNUNET_DISK_OPEN_READ,
281 GNUNET_DISK_PERM_NONE);
284 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
285 "Could not open /etc/resolv.conf. "
286 "DNS resolution will not be possible.\n");
289 bytes_read = GNUNET_DISK_file_read (fh,
292 *server_addrs = NULL;
295 while (read_offset < bytes_read)
301 newline = strchr (buf + read_offset,
305 line_len = newline - buf - read_offset;
306 dns_server = extract_dns_server (buf + read_offset,
308 if (NULL != dns_server)
309 GNUNET_array_append (*server_addrs,
312 read_offset += line_len + 1;
314 GNUNET_DISK_file_close (fh);
315 return (int) num_dns_servers;
320 * Compute name to use for DNS reverse lookups from @a ip.
322 * @param ip IP address to resolve, in binary format, network byte order
323 * @param af address family of @a ip, AF_INET or AF_INET6
326 make_reverse_hostname (const void *ip,
329 char *buf = GNUNET_new_array (80,
335 struct in_addr *addr = (struct in_addr *)ip;
336 uint32_t ip_int = addr->s_addr;
338 for (int i = 3; i >= 0; i--)
340 int n = GNUNET_snprintf (buf + pos,
343 ((uint8_t *)&ip_int)[i]);
351 pos += GNUNET_snprintf (buf + pos,
355 else if (AF_INET6 == af)
357 struct in6_addr *addr = (struct in6_addr *)ip;
358 for (int i = 15; i >= 0; i--)
360 int n = GNUNET_snprintf (buf + pos,
363 addr->s6_addr[i] & 0xf);
370 n = GNUNET_snprintf (buf + pos,
373 addr->s6_addr[i] >> 4);
381 pos += GNUNET_snprintf (buf + pos,
391 * Send DNS @a record back to our @a client.
393 * @param record information to transmit
394 * @param record_type requested record type from client
395 * @param request_id to which request are we responding
396 * @param client where to send @a record
397 * @return #GNUNET_YES if we sent a reply,
398 * #GNUNET_NO if the record type is not understood or
399 * does not match @a record_type
402 send_reply (struct GNUNET_DNSPARSER_Record *record,
403 uint16_t record_type,
405 struct GNUNET_SERVICE_Client *client)
407 struct GNUNET_RESOLVER_ResponseMessage *msg;
408 struct GNUNET_MQ_Envelope *env;
412 switch (record->type)
414 case GNUNET_DNSPARSER_TYPE_CNAME:
415 if (GNUNET_DNSPARSER_TYPE_CNAME != record_type)
417 payload = record->data.hostname;
418 payload_len = strlen (record->data.hostname) + 1;
420 case GNUNET_DNSPARSER_TYPE_PTR:
421 if (GNUNET_DNSPARSER_TYPE_PTR != record_type)
423 payload = record->data.hostname;
424 payload_len = strlen (record->data.hostname) + 1;
426 case GNUNET_DNSPARSER_TYPE_A:
427 if ( (GNUNET_DNSPARSER_TYPE_A != record_type) &&
428 (GNUNET_DNSPARSER_TYPE_ALL != record_type) )
430 payload = record->data.raw.data;
431 payload_len = record->data.raw.data_len;
433 case GNUNET_DNSPARSER_TYPE_AAAA:
434 if ( (GNUNET_DNSPARSER_TYPE_AAAA != record_type) &&
435 (GNUNET_DNSPARSER_TYPE_ALL != record_type) )
437 payload = record->data.raw.data;
438 payload_len = record->data.raw.data_len;
441 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
442 "Cannot handle DNS response type %u: not supported here\n",
446 env = GNUNET_MQ_msg_extra (msg,
448 GNUNET_MESSAGE_TYPE_RESOLVER_RESPONSE);
449 msg->id = request_id;
450 GNUNET_memcpy (&msg[1],
453 GNUNET_MQ_send (GNUNET_SERVICE_client_get_mq (client),
460 * Send message to @a client that we transmitted all
461 * responses for @a request_id
463 * @param request_id to which request are we responding
464 * @param client where to send @a record
467 send_end_msg (uint16_t request_id,
468 struct GNUNET_SERVICE_Client *client)
470 struct GNUNET_RESOLVER_ResponseMessage *msg;
471 struct GNUNET_MQ_Envelope *env;
473 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
474 "Sending END message\n");
475 env = GNUNET_MQ_msg (msg,
476 GNUNET_MESSAGE_TYPE_RESOLVER_RESPONSE);
477 msg->id = request_id;
478 GNUNET_MQ_send (GNUNET_SERVICE_client_get_mq (client),
484 * Remove expired entries from @a rc
486 * @param rc entry in resolver cache
487 * @return #GNUNET_YES if @a rc was completely expired
488 * #GNUNET_NO if some entries are left
491 remove_expired (struct ResolveCache *rc)
493 struct GNUNET_TIME_Absolute now = GNUNET_TIME_absolute_get ();
494 struct RecordListEntry *n;
496 for (struct RecordListEntry *pos = rc->records_head;
501 if (now.abs_value_us > pos->record->expiration_time.abs_value_us)
502 GNUNET_CONTAINER_DLL_remove (rc->records_head,
506 if (NULL == rc->records_head)
508 free_cache_entry (rc);
516 * Process DNS request for @a hostname with request ID @a request_id
517 * from @a client demanding records of type @a record_type.
519 * @param hostname DNS name to resolve
520 * @param record_type desired record type
521 * @param request_id client's request ID
522 * @param client who should get the result?
525 process_get (const char *hostname,
526 uint16_t record_type,
528 struct GNUNET_SERVICE_Client *client);
532 * Get an IP address as a string (works for both IPv4 and IPv6). Note
533 * that the resolution happens asynchronously and that the first call
534 * may not immediately result in the FQN (but instead in a
535 * human-readable IP address).
537 * @param hostname what hostname was to be resolved
538 * @param record_type what type of record was requested
539 * @param request_id unique identification of the client's request
540 * @param client handle to the client making the request (for sending the reply)
543 try_cache (const char *hostname,
544 uint16_t record_type,
546 struct GNUNET_SERVICE_Client *client)
548 struct ResolveCache *pos;
549 struct ResolveCache *next;
553 for (pos = next; NULL != pos; pos = next)
556 if (GNUNET_YES == remove_expired (pos))
558 if (0 == strcmp (pos->hostname,
564 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
565 "No cache entry for '%s'\n",
569 if (cache_head != pos)
571 /* move result to head to achieve LRU for cache eviction */
572 GNUNET_CONTAINER_DLL_remove (cache_head,
575 GNUNET_CONTAINER_DLL_insert (cache_head,
580 for (struct RecordListEntry *rle = pos->records_head;
584 const struct GNUNET_DNSPARSER_Record *record = rle->record;
586 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
587 "Found cache entry for '%s', record type '%u'\n",
590 if ( (GNUNET_DNSPARSER_TYPE_CNAME == record->type) &&
591 (GNUNET_DNSPARSER_TYPE_CNAME != record_type) &&
592 (GNUNET_NO == found) )
594 const char *hostname = record->data.hostname;
596 process_get (hostname,
600 return GNUNET_YES; /* counts as a cache "hit" */
602 found |= send_reply (rle->record,
607 if (GNUNET_NO == found)
608 return GNUNET_NO; /* had records, but none matched! */
609 send_end_msg (request_id,
616 * Create DNS query for @a hostname of type @a type
617 * with DNS request ID @a dns_id.
619 * @param hostname DNS name to query
620 * @param type requested DNS record type
621 * @param dns_id what should be the DNS request ID
622 * @param packet_buf[out] where to write the request packet
623 * @param packet_size[out] set to size of @a packet_buf on success
624 * @return #GNUNET_OK on success
627 pack (const char *hostname,
633 struct GNUNET_DNSPARSER_Query query;
634 struct GNUNET_DNSPARSER_Packet packet;
636 query.name = (char *)hostname;
638 query.dns_traffic_class = GNUNET_TUN_DNS_CLASS_INTERNET;
642 packet.num_queries = 1;
643 packet.queries = &query;
644 packet.id = htons (dns_id);
645 packet.flags.recursion_desired = 1;
647 GNUNET_DNSPARSER_pack (&packet,
652 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
653 "Failed to pack query for hostname `%s'\n",
656 return GNUNET_SYSERR;
663 * We got a result from DNS. Add it to the cache and
664 * see if we can make our client happy...
666 * @param cls the `struct ActiveLookup`
667 * @param dns the DNS response
668 * @param dns_len number of bytes in @a dns
671 handle_resolve_result (void *cls,
672 const struct GNUNET_TUN_DnsHeader *dns,
675 struct ActiveLookup *al = cls;
676 struct GNUNET_DNSPARSER_Packet *parsed;
677 struct ResolveCache *rc;
679 parsed = GNUNET_DNSPARSER_parse ((const char *)dns,
683 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
684 "Failed to parse DNS reply (hostname %s, request ID %u)\n",
689 if (al->dns_id != ntohs (parsed->id))
691 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
692 "Request ID in DNS reply does not match\n");
693 GNUNET_DNSPARSER_free_packet (parsed);
696 if (0 == parsed->num_answers)
698 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
699 "DNS reply (hostname %s, request ID %u) contains no answers\n",
702 GNUNET_DNSPARSER_free_packet (parsed);
703 send_end_msg (al->request_id,
705 free_active_lookup (al);
708 /* LRU-based cache eviction: we remove from tail */
709 while (cache_size > MAX_CACHE)
710 free_cache_entry (cache_tail);
712 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
713 "Got reply for hostname %s and request ID %u\n",
717 for (unsigned int i = 0; i != parsed->num_answers; i++)
719 struct GNUNET_DNSPARSER_Record *record = &parsed->answers[i];
720 struct RecordListEntry *rle;
722 for (rc = cache_head; NULL != rc; rc = rc->next)
723 if (0 == strcasecmp (rc->hostname,
728 rc = GNUNET_new (struct ResolveCache);
729 rc->hostname = GNUNET_strdup (record->name);
730 GNUNET_CONTAINER_DLL_insert (cache_head,
735 /* TODO: ought to check first if we have this exact record
736 already in the cache! */
737 rle = GNUNET_new (struct RecordListEntry);
738 rle->record = GNUNET_DNSPARSER_duplicate_record (record);
739 GNUNET_CONTAINER_DLL_insert (rc->records_head,
743 /* see if we need to do the 2nd request for AAAA records */
744 if ( (GNUNET_DNSPARSER_TYPE_ALL == al->record_type) &&
745 (GNUNET_NO == al->did_aaaa) )
751 dns_id = (uint16_t) GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE,
755 GNUNET_DNSPARSER_TYPE_AAAA,
760 al->did_aaaa = GNUNET_YES;
762 GNUNET_DNSSTUB_resolve_cancel (al->resolve_handle);
764 GNUNET_DNSSTUB_resolve (dnsstub_ctx,
767 &handle_resolve_result,
773 /* resume by trying again from cache */
775 try_cache (al->hostname,
779 /* cache failed, tell client we could not get an answer */
780 send_end_msg (al->request_id,
782 free_active_lookup (al);
783 GNUNET_DNSPARSER_free_packet (parsed);
788 * We encountered a timeout trying to perform a
791 * @param cls a `struct ActiveLookup`
794 handle_resolve_timeout (void *cls)
796 struct ActiveLookup *al = cls;
798 al->timeout_task = NULL;
799 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
800 "DNS lookup timeout!\n");
801 send_end_msg (al->request_id,
803 free_active_lookup (al);
808 * Initiate an active lookup, then cache the result and
809 * try to then complete the resolution.
811 * @param hostname DNS name to resolve
812 * @param record_type record type to locate
813 * @param request_id client request ID
814 * @param client handle to the client
815 * @return #GNUNET_OK if the DNS query is now pending
818 resolve_and_cache (const char* hostname,
819 uint16_t record_type,
821 struct GNUNET_SERVICE_Client *client)
825 struct ActiveLookup *al;
829 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
830 "resolve_and_cache\n");
831 dns_id = (uint16_t) GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE,
834 if (GNUNET_DNSPARSER_TYPE_ALL == record_type)
835 type = GNUNET_DNSPARSER_TYPE_A;
845 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
846 "Failed to pack query for hostname `%s'\n",
848 return GNUNET_SYSERR;
851 al = GNUNET_new (struct ActiveLookup);
852 al->hostname = GNUNET_strdup (hostname);
853 al->record_type = record_type;
854 al->request_id = request_id;
857 al->timeout_task = GNUNET_SCHEDULER_add_delayed (DNS_TIMEOUT,
858 &handle_resolve_timeout,
861 GNUNET_DNSSTUB_resolve (dnsstub_ctx,
864 &handle_resolve_result,
866 GNUNET_free (packet_buf);
867 GNUNET_CONTAINER_DLL_insert (lookup_head,
870 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
871 "Resolving %s, request_id = %u, dns_id = %u\n",
873 (unsigned int) request_id,
874 (unsigned int) dns_id);
880 * Process DNS request for @a hostname with request ID @a request_id
881 * from @a client demanding records of type @a record_type.
883 * @param hostname DNS name to resolve
884 * @param record_type desired record type
885 * @param request_id client's request ID
886 * @param client who should get the result?
889 process_get (const char *hostname,
890 uint16_t record_type,
892 struct GNUNET_SERVICE_Client *client)
901 resolve_and_cache (hostname,
906 send_end_msg (request_id,
914 * Verify well-formedness of GET-message.
916 * @param cls closure, unused
917 * @param get the actual message
918 * @return #GNUNET_OK if @a get is well-formed
921 check_get (void *cls,
922 const struct GNUNET_RESOLVER_GetMessage *get)
929 size = ntohs (get->header.size) - sizeof (*get);
930 direction = ntohl (get->direction);
931 if (GNUNET_NO == direction)
933 /* IP from hostname */
934 const char *hostname;
936 hostname = (const char *) &get[1];
937 if (hostname[size - 1] != '\0')
940 return GNUNET_SYSERR;
944 af = ntohl (get->af);
948 if (size != sizeof (struct in_addr))
951 return GNUNET_SYSERR;
955 if (size != sizeof (struct in6_addr))
958 return GNUNET_SYSERR;
963 return GNUNET_SYSERR;
970 * Handle GET-message.
972 * @param cls identification of the client
973 * @param msg the actual message
976 handle_get (void *cls,
977 const struct GNUNET_RESOLVER_GetMessage *msg)
979 struct GNUNET_SERVICE_Client *client = cls;
985 direction = ntohl (msg->direction);
986 af = ntohl (msg->af);
987 request_id = ntohs (msg->id);
988 if (GNUNET_NO == direction)
990 /* IP from hostname */
991 hostname = GNUNET_strdup ((const char *) &msg[1]);
996 process_get (hostname,
997 GNUNET_DNSPARSER_TYPE_ALL,
1004 process_get (hostname,
1005 GNUNET_DNSPARSER_TYPE_A,
1012 process_get (hostname,
1013 GNUNET_DNSPARSER_TYPE_AAAA,
1020 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1021 "got invalid af: %d\n",
1029 /* hostname from IP */
1030 hostname = make_reverse_hostname (&msg[1],
1032 process_get (hostname,
1033 GNUNET_DNSPARSER_TYPE_PTR,
1037 GNUNET_free_non_null (hostname);
1038 GNUNET_SERVICE_client_continue (client);
1043 * Service is shutting down, clean up.
1045 * @param cls NULL, unused
1048 shutdown_task (void *cls)
1052 while (NULL != lookup_head)
1053 free_active_lookup (lookup_head);
1054 while (NULL != cache_head)
1055 free_cache_entry (cache_head);
1056 GNUNET_DNSSTUB_stop (dnsstub_ctx);
1061 * Service is starting, initialize everything.
1063 * @param cls NULL, unused
1064 * @param cfg our configuration
1065 * @param sh service handle
1069 const struct GNUNET_CONFIGURATION_Handle *cfg,
1070 struct GNUNET_SERVICE_Handle *sh)
1073 int num_dns_servers;
1077 GNUNET_SCHEDULER_add_shutdown (&shutdown_task,
1079 dnsstub_ctx = GNUNET_DNSSTUB_start (128);
1081 num_dns_servers = lookup_dns_servers (&dns_servers);
1082 if (0 >= num_dns_servers)
1084 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1085 _("No DNS server available. DNS resolution will not be possible.\n"));
1088 for (int i = 0; i < num_dns_servers; i++)
1090 int result = GNUNET_DNSSTUB_add_dns_ip (dnsstub_ctx, dns_servers[i]);
1091 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1092 "Adding DNS server '%s': %s\n",
1094 GNUNET_OK == result ? "success" : "failure");
1095 GNUNET_free (dns_servers[i]);
1097 GNUNET_free_non_null (dns_servers);
1102 * Callback called when a client connects to the service.
1104 * @param cls closure for the service, unused
1105 * @param c the new client that connected to the service
1106 * @param mq the message queue used to send messages to the client
1110 connect_cb (void *cls,
1111 struct GNUNET_SERVICE_Client *c,
1112 struct GNUNET_MQ_Handle *mq)
1122 * Callback called when a client disconnected from the service
1124 * @param cls closure for the service
1125 * @param c the client that disconnected
1126 * @param internal_cls should be equal to @a c
1129 disconnect_cb (void *cls,
1130 struct GNUNET_SERVICE_Client *c,
1133 struct ActiveLookup *n;
1136 GNUNET_assert (c == internal_cls);
1138 for (struct ActiveLookup *al = n;
1143 if (al->client == c)
1144 free_active_lookup (al);
1150 * Define "main" method using service macro.
1154 GNUNET_SERVICE_OPTION_NONE,
1159 GNUNET_MQ_hd_var_size (get,
1160 GNUNET_MESSAGE_TYPE_RESOLVER_REQUEST,
1161 struct GNUNET_RESOLVER_GetMessage,
1163 GNUNET_MQ_handler_end ());
1166 #if defined(LINUX) && defined(__GLIBC__)
1170 * MINIMIZE heap size (way below 128k) since this process doesn't need much.
1172 void __attribute__ ((constructor))
1173 GNUNET_RESOLVER_memory_init ()
1175 mallopt (M_TRIM_THRESHOLD, 4 * 1024);
1176 mallopt (M_TOP_PAD, 1 * 1024);
1182 /* end of gnunet-service-resolver.c */