2 This file is part of GNUnet.
3 (C) 2012 Christian Grothoff (and other contributing authors)
5 GNUnet is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published
7 by the Free Software Foundation; either version 3, or (at your
8 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 General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with GNUnet; see the file COPYING. If not, write to the
17 Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18 Boston, MA 02111-1307, USA.
22 * @file dns/gnunet-service-dns.c
23 * @brief service to intercept and modify DNS queries (and replies) of this system
24 * @author Christian Grothoff
26 * For "secure" interaction with the legacy DNS system, we permit
27 * replies only to arrive within a 5s window (and they must match
28 * ports, IPs and request IDs). Furthermore, we let the OS pick a
29 * source port, opening up to 128 sockets per address family (IPv4 or
30 * IPv6). Those sockets are closed if they are not in use for 5s
31 * (which means they will be freshly randomized afterwards). For new
32 * requests, we pick a random slot in the array with 128 socket slots
33 * (and re-use an existing socket if the slot is still in use). Thus
34 * each request will be given one of 128 random source ports, and the
35 * 128 random source ports will also change "often" (less often if the
36 * system is very busy, each time if we are mostly idle). At the same
37 * time, the system will never use more than 256 UDP sockets.
40 #include "gnunet_util_lib.h"
41 #include "gnunet_applications.h"
42 #include "gnunet_constants.h"
43 #include "gnunet_protocols.h"
44 #include "gnunet_signatures.h"
46 #include "gnunet_dns_service.h"
47 #include "gnunet_dnsparser_lib.h"
48 #include "gnunet_mesh_service.h"
49 #include "gnunet_statistics_service.h"
50 #include "gnunet_tun_lib.h"
54 * Timeout for an external (Internet-DNS) DNS resolution
56 #define REQUEST_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 5)
59 * How many DNS sockets do we open at most at the same time?
60 * (technical socket maximum is this number x2 for IPv4+IPv6)
62 #define DNS_SOCKET_MAX 128
65 * Phases each request goes through.
70 * Request has just been received.
75 * Showing the request to all monitor clients. If
76 * client list is empty, will enter QUERY phase.
81 * Showing the request to PRE-RESOLUTION clients to find an answer.
82 * If client list is empty, will trigger global DNS request.
87 * Global Internet query is now pending.
92 * Client (or global DNS request) has resulted in a response.
93 * Forward to all POST-RESOLUTION clients. If client list is empty,
94 * will enter RESPONSE_MONITOR phase.
99 * Showing the request to all monitor clients. If
100 * client list is empty, give the result to the hijacker (and be done).
105 * Some client has told us to drop the request.
112 * Entry we keep for each client.
117 * Kept in doubly-linked list.
119 struct ClientRecord *next;
122 * Kept in doubly-linked list.
124 struct ClientRecord *prev;
127 * Handle to the client.
129 struct GNUNET_SERVER_Client *client;
132 * Flags for the client.
134 enum GNUNET_DNS_Flags flags;
140 * UDP socket we are using for sending DNS requests to the Internet.
146 * UDP socket we use for this request for IPv4
148 struct GNUNET_NETWORK_Handle *dnsout4;
151 * UDP socket we use for this request for IPv6
153 struct GNUNET_NETWORK_Handle *dnsout6;
156 * Task for reading from dnsout4 and dnsout6.
158 GNUNET_SCHEDULER_TaskIdentifier read_task;
161 * When should this socket be closed?
163 struct GNUNET_TIME_Absolute timeout;
168 * Entry we keep for each active request.
174 * List of clients that still need to see this request (each entry
175 * is set to NULL when the client is done).
177 struct ClientRecord **client_wait_list;
180 * Payload of the UDP packet (the UDP payload), can be either query
181 * or already the response.
186 * Socket we are using to transmit this request (must match if we receive
187 * a response). Must NOT be freed as part of this request record (as it
188 * might be shared with other requests).
190 struct GNUNET_NETWORK_Handle *dnsout;
193 * Source address of the original request (for sending response).
195 struct sockaddr_storage src_addr;
198 * Destination address of the original request (for potential use as exit).
200 struct sockaddr_storage dst_addr;
203 * When should this request time out?
205 struct GNUNET_TIME_Absolute timeout;
208 * ID of this request, also basis for hashing. Lowest 16 bit will
209 * be our message ID when doing a global DNS request and our index
210 * into the 'requests' array.
215 * Number of bytes in payload.
217 size_t payload_length;
220 * Length of the client wait list.
222 unsigned int client_wait_list_length;
225 * In which phase this this request?
227 enum RequestPhase phase;
233 * State we keep for each DNS tunnel that terminates at this node.
239 * Associated MESH tunnel.
241 struct GNUNET_MESH_Tunnel *tunnel;
244 * Active request for sending a reply.
246 struct GNUNET_MESH_TransmitHandle *th;
249 * DNS reply ready for transmission.
254 * Socket we are using to transmit this request (must match if we receive
255 * a response). Must NOT be freed as part of this request record (as it
256 * might be shared with other requests).
258 struct GNUNET_NETWORK_Handle *dnsout;
261 * Address we sent the DNS request to.
263 struct sockaddr_storage addr;
266 * When should this request time out?
268 struct GNUNET_TIME_Absolute timeout;
271 * Number of bytes in 'addr'.
276 * Number of bytes in 'reply'.
281 * Original DNS request ID as used by the client.
283 uint16_t original_id;
286 * DNS request ID that we used for forwarding.
293 * The configuration to use
295 static const struct GNUNET_CONFIGURATION_Handle *cfg;
300 static struct GNUNET_STATISTICS_Handle *stats;
303 * Handle to DNS hijacker helper process ("gnunet-helper-dns").
305 static struct GNUNET_HELPER_Handle *hijacker;
308 * Command-line arguments we are giving to the hijacker process.
310 static char *helper_argv[7];
313 * Head of DLL of clients we consult.
315 static struct ClientRecord *clients_head;
318 * Tail of DLL of clients we consult.
320 static struct ClientRecord *clients_tail;
323 * Our notification context.
325 static struct GNUNET_SERVER_NotificationContext *nc;
328 * Array of all open requests.
330 static struct RequestRecord requests[UINT16_MAX + 1];
333 * Array of all open requests from tunnels.
335 static struct TunnelState *tunnels[UINT16_MAX + 1];
338 * Array of all open sockets for DNS requests.
340 static struct RequestSocket sockets[DNS_SOCKET_MAX];
343 * Generator for unique request IDs.
345 static uint64_t request_id_gen;
348 * IP address to use for the DNS server if we are a DNS exit service
349 * (for VPN via mesh); otherwise NULL.
351 static char *dns_exit;
354 * Handle to the MESH service (for receiving DNS queries), or NULL
355 * if we are not a DNS exit.
357 static struct GNUNET_MESH_Handle *mesh;
361 * We're done with a RequestSocket, close it for now.
363 * @param rs request socket to clean up
366 cleanup_rs (struct RequestSocket *rs)
368 if (NULL != rs->dnsout4)
370 GNUNET_NETWORK_socket_close (rs->dnsout4);
373 if (NULL != rs->dnsout6)
375 GNUNET_NETWORK_socket_close (rs->dnsout6);
378 if (GNUNET_SCHEDULER_NO_TASK != rs->read_task)
380 GNUNET_SCHEDULER_cancel (rs->read_task);
381 rs->read_task = GNUNET_SCHEDULER_NO_TASK;
387 * We're done processing a DNS request, free associated memory.
389 * @param rr request to clean up
392 cleanup_rr (struct RequestRecord *rr)
394 GNUNET_free_non_null (rr->payload);
396 rr->payload_length = 0;
397 GNUNET_array_grow (rr->client_wait_list,
398 rr->client_wait_list_length,
404 * Task run during shutdown.
410 cleanup_task (void *cls GNUNET_UNUSED,
411 const struct GNUNET_SCHEDULER_TaskContext *tc)
415 GNUNET_HELPER_stop (hijacker);
418 GNUNET_free_non_null (helper_argv[i]);
419 for (i=0;i<=UINT16_MAX;i++)
420 cleanup_rr (&requests[i]);
421 GNUNET_SERVER_notification_context_destroy (nc);
425 GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
428 if (NULL != dns_exit)
430 GNUNET_free (dns_exit);
435 GNUNET_MESH_disconnect(mesh);
442 * Open source port for sending DNS requests
444 * @param af AF_INET or AF_INET6
445 * @return GNUNET_OK on success
447 static struct GNUNET_NETWORK_Handle *
450 struct sockaddr_in a4;
451 struct sockaddr_in6 a6;
454 struct GNUNET_NETWORK_Handle *ret;
456 ret = GNUNET_NETWORK_socket_create (af, SOCK_DGRAM, 0);
462 memset (&a4, 0, alen = sizeof (struct sockaddr_in));
463 sa = (struct sockaddr *) &a4;
466 memset (&a6, 0, alen = sizeof (struct sockaddr_in6));
467 sa = (struct sockaddr *) &a6;
471 GNUNET_NETWORK_socket_close (ret);
475 if (GNUNET_OK != GNUNET_NETWORK_socket_bind (ret,
479 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
480 _("Could not bind to any port: %s\n"),
482 GNUNET_NETWORK_socket_close (ret);
490 * We're done with some request, finish processing.
492 * @param rr request send to the network or just clean up.
495 request_done (struct RequestRecord *rr)
497 struct GNUNET_MessageHeader *hdr;
499 uint16_t source_port;
500 uint16_t destination_port;
502 GNUNET_array_grow (rr->client_wait_list,
503 rr->client_wait_list_length,
505 if (RP_RESPONSE_MONITOR != rr->phase)
507 /* no response, drop */
512 /* send response via hijacker */
513 reply_len = sizeof (struct GNUNET_MessageHeader);
514 reply_len += sizeof (struct GNUNET_TUN_Layer2PacketHeader);
515 switch (rr->src_addr.ss_family)
518 reply_len += sizeof (struct GNUNET_TUN_IPv4Header);
521 reply_len += sizeof (struct GNUNET_TUN_IPv6Header);
528 reply_len += sizeof (struct GNUNET_TUN_UdpHeader);
529 reply_len += rr->payload_length;
530 if (reply_len >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
532 /* response too big, drop */
533 GNUNET_break (0); /* how can this be? */
540 struct GNUNET_TUN_IPv4Header ip4;
541 struct GNUNET_TUN_IPv6Header ip6;
543 /* first, GNUnet message header */
544 hdr = (struct GNUNET_MessageHeader*) buf;
545 hdr->type = htons (GNUNET_MESSAGE_TYPE_DNS_HELPER);
546 hdr->size = htons ((uint16_t) reply_len);
547 off = sizeof (struct GNUNET_MessageHeader);
549 /* first, TUN header */
551 struct GNUNET_TUN_Layer2PacketHeader tun;
553 tun.flags = htons (0);
554 if (rr->src_addr.ss_family == AF_INET)
555 tun.proto = htons (ETH_P_IPV4);
557 tun.proto = htons (ETH_P_IPV6);
558 memcpy (&buf[off], &tun, sizeof (struct GNUNET_TUN_Layer2PacketHeader));
559 off += sizeof (struct GNUNET_TUN_Layer2PacketHeader);
563 switch (rr->src_addr.ss_family)
567 struct sockaddr_in *src = (struct sockaddr_in *) &rr->src_addr;
568 struct sockaddr_in *dst = (struct sockaddr_in *) &rr->dst_addr;
570 source_port = dst->sin_port;
571 destination_port = src->sin_port;
572 GNUNET_TUN_initialize_ipv4_header (&ip4,
574 reply_len - off - sizeof (struct GNUNET_TUN_IPv4Header),
577 memcpy (&buf[off], &ip4, sizeof (ip4));
583 struct sockaddr_in6 *src = (struct sockaddr_in6 *) &rr->src_addr;
584 struct sockaddr_in6 *dst = (struct sockaddr_in6 *) &rr->dst_addr;
586 source_port = dst->sin6_port;
587 destination_port = src->sin6_port;
588 GNUNET_TUN_initialize_ipv6_header (&ip6,
590 reply_len - sizeof (struct GNUNET_TUN_IPv6Header),
593 memcpy (&buf[off], &ip6, sizeof (ip6));
603 struct GNUNET_TUN_UdpHeader udp;
605 udp.source_port = source_port;
606 udp.destination_port = destination_port;
607 udp.len = htons (reply_len - off);
608 if (AF_INET == rr->src_addr.ss_family)
609 GNUNET_TUN_calculate_udp4_checksum (&ip4,
614 GNUNET_TUN_calculate_udp6_checksum (&ip6,
618 memcpy (&buf[off], &udp, sizeof (udp));
622 /* now DNS payload */
624 memcpy (&buf[off], rr->payload, rr->payload_length);
625 off += rr->payload_length;
627 /* final checks & sending */
628 GNUNET_assert (off == reply_len);
629 GNUNET_HELPER_send (hijacker,
633 GNUNET_STATISTICS_update (stats,
634 gettext_noop ("# DNS requests answered via TUN interface"),
637 /* clean up, we're done */
643 * Show the payload of the given request record to the client
644 * (and wait for a response).
646 * @param rr request to send to client
647 * @param client client to send the response to
650 send_request_to_client (struct RequestRecord *rr,
651 struct GNUNET_SERVER_Client *client)
653 char buf[sizeof (struct GNUNET_DNS_Request) + rr->payload_length];
654 struct GNUNET_DNS_Request *req;
656 if (sizeof (buf) >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
662 req = (struct GNUNET_DNS_Request*) buf;
663 req->header.type = htons (GNUNET_MESSAGE_TYPE_DNS_CLIENT_REQUEST);
664 req->header.size = htons (sizeof (buf));
665 req->reserved = htonl (0);
666 req->request_id = rr->request_id;
667 memcpy (&req[1], rr->payload, rr->payload_length);
668 GNUNET_SERVER_notification_context_unicast (nc,
676 * Read a DNS response from the (unhindered) UDP-Socket
678 * @param cls socket to read from
679 * @param tc scheduler context (must be shutdown or read ready)
682 read_response (void *cls,
683 const struct GNUNET_SCHEDULER_TaskContext *tc);
687 * Get a socket of the specified address family to send out a
688 * UDP DNS request to the Internet.
690 * @param af desired address family
691 * @return NULL on error (given AF not "supported")
693 static struct GNUNET_NETWORK_Handle *
694 get_request_socket (int af)
696 struct RequestSocket *rs;
697 struct GNUNET_NETWORK_FDSet *rset;
698 static struct GNUNET_NETWORK_Handle *ret;
700 rs = &sockets[GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE,
702 rs->timeout = GNUNET_TIME_relative_to_absolute (REQUEST_TIMEOUT);
706 if (NULL == rs->dnsout4)
707 rs->dnsout4 = open_socket (AF_INET);
711 if (NULL == rs->dnsout6)
712 rs->dnsout6 = open_socket (AF_INET6);
718 if (GNUNET_SCHEDULER_NO_TASK != rs->read_task)
720 GNUNET_SCHEDULER_cancel (rs->read_task);
721 rs->read_task = GNUNET_SCHEDULER_NO_TASK;
723 if ( (NULL == rs->dnsout4) &&
724 (NULL == rs->dnsout6) )
726 rset = GNUNET_NETWORK_fdset_create ();
727 if (NULL != rs->dnsout4)
728 GNUNET_NETWORK_fdset_set (rset, rs->dnsout4);
729 if (NULL != rs->dnsout6)
730 GNUNET_NETWORK_fdset_set (rset, rs->dnsout6);
731 rs->read_task = GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
732 GNUNET_SCHEDULER_NO_TASK,
737 GNUNET_NETWORK_fdset_destroy (rset);
743 * A client has completed its processing for this
746 * @param rr request to process further
749 next_phase (struct RequestRecord *rr)
751 struct ClientRecord *cr;
756 if (rr->phase == RP_DROP)
762 for (j=0;j<rr->client_wait_list_length;j++)
764 if (NULL != rr->client_wait_list[j])
772 send_request_to_client (rr, rr->client_wait_list[nz]->client);
775 /* done with current phase, advance! */
779 rr->phase = RP_REQUEST_MONITOR;
780 for (cr = clients_head; NULL != cr; cr = cr->next)
782 if (0 != (cr->flags & GNUNET_DNS_FLAG_REQUEST_MONITOR))
783 GNUNET_array_append (rr->client_wait_list,
784 rr->client_wait_list_length,
789 case RP_REQUEST_MONITOR:
790 rr->phase = RP_QUERY;
791 for (cr = clients_head; NULL != cr; cr = cr->next)
793 if (0 != (cr->flags & GNUNET_DNS_FLAG_PRE_RESOLUTION))
794 GNUNET_array_append (rr->client_wait_list,
795 rr->client_wait_list_length,
801 switch (rr->dst_addr.ss_family)
804 salen = sizeof (struct sockaddr_in);
807 salen = sizeof (struct sockaddr_in6);
813 rr->phase = RP_INTERNET_DNS;
814 rr->dnsout = get_request_socket (rr->dst_addr.ss_family);
815 if (NULL == rr->dnsout)
817 GNUNET_STATISTICS_update (stats,
818 gettext_noop ("# DNS exit failed (failed to open socket)"),
823 GNUNET_NETWORK_socket_sendto (rr->dnsout,
826 (struct sockaddr*) &rr->dst_addr,
828 rr->timeout = GNUNET_TIME_relative_to_absolute (REQUEST_TIMEOUT);
830 case RP_INTERNET_DNS:
831 rr->phase = RP_MODIFY;
832 for (cr = clients_head; NULL != cr; cr = cr->next)
834 if (0 != (cr->flags & GNUNET_DNS_FLAG_POST_RESOLUTION))
835 GNUNET_array_append (rr->client_wait_list,
836 rr->client_wait_list_length,
842 rr->phase = RP_RESPONSE_MONITOR;
843 for (cr = clients_head; NULL != cr; cr = cr->next)
845 if (0 != (cr->flags & GNUNET_DNS_FLAG_RESPONSE_MONITOR))
846 GNUNET_array_append (rr->client_wait_list,
847 rr->client_wait_list_length,
852 case RP_RESPONSE_MONITOR:
867 * A client disconnected, clean up after it.
870 * @param client handle of client that disconnected
873 client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
875 struct ClientRecord *cr;
876 struct RequestRecord *rr;
880 for (cr = clients_head; NULL != cr; cr = cr->next)
882 if (cr->client == client)
884 GNUNET_SERVER_client_drop (client);
885 GNUNET_CONTAINER_DLL_remove (clients_head,
888 for (i=0;i<UINT16_MAX;i++)
891 if (0 == rr->client_wait_list_length)
892 continue; /* not in use */
893 for (j=0;j<rr->client_wait_list_length;j++)
895 if (rr->client_wait_list[j] == cr)
897 rr->client_wait_list[j] = NULL;
910 * We got a reply from DNS for a request of a MESH tunnel. Send it
911 * via the tunnel (after changing the request ID back).
913 * @param cls the 'struct TunnelState'
914 * @param size number of bytes available in buf
915 * @param buf where to copy the reply
916 * @return number of bytes written to buf
919 transmit_reply_to_mesh (void *cls,
923 struct TunnelState *ts = cls;
927 struct GNUNET_MessageHeader hdr;
928 struct GNUNET_TUN_DnsHeader dns;
931 GNUNET_assert (ts->reply != NULL);
934 ret = sizeof (struct GNUNET_MessageHeader) + ts->reply_length;
935 GNUNET_assert (ret <= size);
936 hdr.size = htons (ret);
937 hdr.type = htons (GNUNET_MESSAGE_TYPE_VPN_DNS_FROM_INTERNET);
938 memcpy (&dns, ts->reply, sizeof (dns));
939 dns.id = ts->original_id;
941 memcpy (&cbuf[off], &hdr, sizeof (hdr));
943 memcpy (&cbuf[off], &dns, sizeof (dns));
945 memcpy (&cbuf[off], &ts->reply[sizeof (dns)], ts->reply_length - sizeof (dns));
946 off += ts->reply_length - sizeof (dns);
947 GNUNET_free (ts->reply);
949 ts->reply_length = 0;
950 GNUNET_assert (ret == off);
956 * Actually do the reading of a DNS packet from our UDP socket and see
957 * if we have a valid, matching, pending request.
959 * @param dnsout socket to read from
960 * @return GNUNET_OK on success, GNUNET_NO on drop, GNUNET_SYSERR on IO-errors (closed socket)
963 do_dns_read (struct GNUNET_NETWORK_Handle *dnsout)
965 struct sockaddr_storage addr;
967 struct GNUNET_TUN_DnsHeader *dns;
968 struct RequestRecord *rr;
969 struct TunnelState *ts;
974 if (0 != ioctl (GNUNET_NETWORK_get_fd (dnsout), FIONREAD, &len))
976 /* conservative choice: */
980 /* port the code above? */
985 unsigned char buf[len];
987 addrlen = sizeof (addr);
988 memset (&addr, 0, sizeof (addr));
989 r = GNUNET_NETWORK_socket_recvfrom (dnsout,
991 (struct sockaddr*) &addr, &addrlen);
994 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "recvfrom");
995 GNUNET_NETWORK_socket_close (dnsout);
996 return GNUNET_SYSERR;
998 if (sizeof (struct GNUNET_TUN_DnsHeader) > r)
1000 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1001 _("Received DNS response that is too small (%u bytes)"),
1005 dns = (struct GNUNET_TUN_DnsHeader *) buf;
1006 /* Handle case that this is a reply to a request from a MESH DNS tunnel */
1007 ts = tunnels[dns->id];
1008 if ( (NULL == ts) ||
1009 (ts->dnsout != dnsout) ||
1010 (addrlen != ts->addrlen) ||
1011 (0 != memcmp (&ts->addr,
1014 (0 == GNUNET_TIME_absolute_get_remaining (ts->timeout).rel_value) )
1015 ts = NULL; /* DNS responder address missmatch */
1018 tunnels[dns->id] = NULL;
1019 GNUNET_free_non_null (ts->reply);
1020 ts->reply = GNUNET_malloc (r);
1021 ts->reply_length = r;
1022 memcpy (ts->reply, dns, r);
1024 GNUNET_MESH_notify_transmit_ready_cancel (ts->th);
1025 ts->th = GNUNET_MESH_notify_transmit_ready (ts->tunnel,
1027 GNUNET_TIME_UNIT_FOREVER_REL,
1029 sizeof (struct GNUNET_MessageHeader) + r,
1030 &transmit_reply_to_mesh,
1033 /* Handle case that this is a reply to a local request (intercepted from TUN interface) */
1034 rr = &requests[dns->id];
1035 if ( (rr->phase != RP_INTERNET_DNS) ||
1036 (rr->dnsout != dnsout) ||
1037 (0 != memcmp (&rr->dst_addr,
1040 (0 == GNUNET_TIME_absolute_get_remaining (rr->timeout).rel_value) )
1044 /* unexpected / bogus reply */
1045 GNUNET_STATISTICS_update (stats,
1046 gettext_noop ("# External DNS response discarded (no matching request)"),
1051 GNUNET_free_non_null (rr->payload);
1052 rr->payload = GNUNET_malloc (r);
1053 memcpy (rr->payload, buf, r);
1054 rr->payload_length = r;
1062 * Read a DNS response from the (unhindered) UDP-Socket
1064 * @param cls socket to read from
1065 * @param tc scheduler context (must be shutdown or read ready)
1068 read_response (void *cls,
1069 const struct GNUNET_SCHEDULER_TaskContext *tc)
1071 struct RequestSocket *rs = cls;
1072 struct GNUNET_NETWORK_FDSet *rset;
1074 rs->read_task = GNUNET_SCHEDULER_NO_TASK;
1075 if (0 == (tc->reason & GNUNET_SCHEDULER_REASON_READ_READY))
1077 /* timeout or shutdown */
1081 /* read and process ready sockets */
1082 if ((NULL != rs->dnsout4) &&
1083 (GNUNET_NETWORK_fdset_isset (tc->read_ready, rs->dnsout4)) &&
1084 (GNUNET_SYSERR == do_dns_read (rs->dnsout4)))
1086 if ((NULL != rs->dnsout6) &&
1087 (GNUNET_NETWORK_fdset_isset (tc->read_ready, rs->dnsout6)) &&
1088 (GNUNET_SYSERR == do_dns_read (rs->dnsout6)))
1091 /* re-schedule read task */
1092 rset = GNUNET_NETWORK_fdset_create ();
1093 if (NULL != rs->dnsout4)
1094 GNUNET_NETWORK_fdset_set (rset, rs->dnsout4);
1095 if (NULL != rs->dnsout6)
1096 GNUNET_NETWORK_fdset_set (rset, rs->dnsout6);
1097 rs->read_task = GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1098 GNUNET_SCHEDULER_NO_TASK,
1099 GNUNET_TIME_absolute_get_remaining (rs->timeout),
1102 &read_response, rs);
1103 GNUNET_NETWORK_fdset_destroy (rset);
1108 * We got a new client. Make sure all new DNS requests pass by its desk.
1111 * @param client the new client
1112 * @param message the init message (unused)
1115 handle_client_init (void *cls GNUNET_UNUSED,
1116 struct GNUNET_SERVER_Client *client,
1117 const struct GNUNET_MessageHeader *message)
1119 struct ClientRecord *cr;
1120 const struct GNUNET_DNS_Register *reg = (const struct GNUNET_DNS_Register*) message;
1122 cr = GNUNET_malloc (sizeof (struct ClientRecord));
1123 cr->client = client;
1124 cr->flags = (enum GNUNET_DNS_Flags) ntohl (reg->flags);
1125 GNUNET_SERVER_client_keep (client);
1126 GNUNET_CONTAINER_DLL_insert (clients_head,
1129 GNUNET_SERVER_notification_context_add (nc, client);
1130 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1135 * We got a response from a client.
1138 * @param client the client
1139 * @param message the response
1142 handle_client_response (void *cls GNUNET_UNUSED,
1143 struct GNUNET_SERVER_Client *client,
1144 const struct GNUNET_MessageHeader *message)
1146 const struct GNUNET_DNS_Response *resp;
1147 struct RequestRecord *rr;
1152 msize = ntohs (message->size);
1153 if (msize < sizeof (struct GNUNET_DNS_Response))
1156 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1159 resp = (const struct GNUNET_DNS_Response*) message;
1160 off = (uint16_t) resp->request_id;
1161 rr = &requests[off];
1162 if (rr->request_id != resp->request_id)
1164 GNUNET_STATISTICS_update (stats,
1165 gettext_noop ("# Client response discarded (no matching request)"),
1167 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1170 for (i=0;i<rr->client_wait_list_length;i++)
1172 if (NULL == rr->client_wait_list[i])
1174 if (rr->client_wait_list[i]->client != client)
1176 rr->client_wait_list[i] = NULL;
1177 switch (ntohl (resp->drop_flag))
1180 rr->phase = RP_DROP;
1182 case 1: /* no change */
1184 case 2: /* update */
1185 msize -= sizeof (struct GNUNET_DNS_Response);
1186 if ( (sizeof (struct GNUNET_TUN_DnsHeader) > msize) ||
1187 (RP_REQUEST_MONITOR == rr->phase) ||
1188 (RP_RESPONSE_MONITOR == rr->phase) )
1191 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1195 GNUNET_free_non_null (rr->payload);
1197 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1198 _("Changing DNS reply according to client specifications\n"));
1200 rr->payload = GNUNET_malloc (msize);
1201 rr->payload_length = msize;
1202 memcpy (rr->payload, &resp[1], msize);
1203 if (rr->phase == RP_QUERY)
1205 /* clear wait list, we're moving to MODIFY phase next */
1206 GNUNET_array_grow (rr->client_wait_list,
1207 rr->client_wait_list_length,
1210 /* if query changed to answer, move past DNS resolution phase... */
1211 if ( (RP_QUERY == rr->phase) &&
1212 (rr->payload_length > sizeof (struct GNUNET_TUN_DnsHeader)) &&
1213 ((struct GNUNET_DNSPARSER_Flags*)&(((struct GNUNET_TUN_DnsHeader*) rr->payload)->flags))->query_or_response == 1)
1215 rr->phase = RP_INTERNET_DNS;
1216 GNUNET_array_grow (rr->client_wait_list,
1217 rr->client_wait_list_length,
1223 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1226 /* odd, client was not on our list for the request, that ought
1229 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1234 * Functions with this signature are called whenever a complete
1235 * message is received by the tokenizer from the DNS hijack process.
1237 * @param cls closure
1238 * @param client identification of the client
1239 * @param message the actual message, a DNS request we should handle
1242 process_helper_messages (void *cls GNUNET_UNUSED, void *client,
1243 const struct GNUNET_MessageHeader *message)
1246 const struct GNUNET_TUN_Layer2PacketHeader *tun;
1247 const struct GNUNET_TUN_IPv4Header *ip4;
1248 const struct GNUNET_TUN_IPv6Header *ip6;
1249 const struct GNUNET_TUN_UdpHeader *udp;
1250 const struct GNUNET_TUN_DnsHeader *dns;
1251 struct RequestRecord *rr;
1252 struct sockaddr_in *srca4;
1253 struct sockaddr_in6 *srca6;
1254 struct sockaddr_in *dsta4;
1255 struct sockaddr_in6 *dsta6;
1257 msize = ntohs (message->size);
1258 if (msize < sizeof (struct GNUNET_MessageHeader) + sizeof (struct GNUNET_TUN_Layer2PacketHeader) + sizeof (struct GNUNET_TUN_IPv4Header))
1260 /* non-IP packet received on TUN!? */
1264 msize -= sizeof (struct GNUNET_MessageHeader);
1265 tun = (const struct GNUNET_TUN_Layer2PacketHeader *) &message[1];
1266 msize -= sizeof (struct GNUNET_TUN_Layer2PacketHeader);
1267 switch (ntohs (tun->proto))
1270 ip4 = (const struct GNUNET_TUN_IPv4Header *) &tun[1];
1271 ip6 = NULL; /* make compiler happy */
1272 if ( (msize < sizeof (struct GNUNET_TUN_IPv4Header)) ||
1273 (ip4->version != 4) ||
1274 (ip4->header_length != sizeof (struct GNUNET_TUN_IPv4Header) / 4) ||
1275 (ntohs(ip4->total_length) != msize) ||
1276 (ip4->protocol != IPPROTO_UDP) )
1278 /* non-IP/UDP packet received on TUN (or with options) */
1279 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1280 _("Received malformed IPv4-UDP packet on TUN interface.\n"));
1283 udp = (const struct GNUNET_TUN_UdpHeader*) &ip4[1];
1284 msize -= sizeof (struct GNUNET_TUN_IPv4Header);
1287 ip4 = NULL; /* make compiler happy */
1288 ip6 = (const struct GNUNET_TUN_IPv6Header *) &tun[1];
1289 if ( (msize < sizeof (struct GNUNET_TUN_IPv6Header)) ||
1290 (ip6->version != 6) ||
1291 (ntohs (ip6->payload_length) != msize) ||
1292 (ip6->next_header != IPPROTO_UDP) )
1294 /* non-IP/UDP packet received on TUN (or with extensions) */
1295 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1296 _("Received malformed IPv6-UDP packet on TUN interface.\n"));
1299 udp = (const struct GNUNET_TUN_UdpHeader*) &ip6[1];
1300 msize -= sizeof (struct GNUNET_TUN_IPv6Header);
1303 /* non-IP packet received on TUN!? */
1304 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1305 _("Got non-IP packet with %u bytes and protocol %u from TUN\n"),
1306 (unsigned int) msize,
1307 ntohs (tun->proto));
1310 if (msize <= sizeof (struct GNUNET_TUN_UdpHeader) + sizeof (struct GNUNET_TUN_DnsHeader))
1312 /* non-DNS packet received on TUN, ignore */
1313 GNUNET_STATISTICS_update (stats,
1314 gettext_noop ("# Non-DNS UDP packet received via TUN interface"),
1318 msize -= sizeof (struct GNUNET_TUN_UdpHeader);
1319 dns = (const struct GNUNET_TUN_DnsHeader*) &udp[1];
1320 rr = &requests[dns->id];
1322 /* clean up from previous request */
1323 GNUNET_free_non_null (rr->payload);
1325 GNUNET_array_grow (rr->client_wait_list,
1326 rr->client_wait_list_length,
1329 /* setup new request */
1330 rr->phase = RP_INIT;
1331 switch (ntohs (tun->proto))
1335 srca4 = (struct sockaddr_in*) &rr->src_addr;
1336 dsta4 = (struct sockaddr_in*) &rr->dst_addr;
1337 memset (srca4, 0, sizeof (struct sockaddr_in));
1338 memset (dsta4, 0, sizeof (struct sockaddr_in));
1339 srca4->sin_family = AF_INET;
1340 dsta4->sin_family = AF_INET;
1341 srca4->sin_addr = ip4->source_address;
1342 dsta4->sin_addr = ip4->destination_address;
1343 srca4->sin_port = udp->source_port;
1344 dsta4->sin_port = udp->destination_port;
1345 #if HAVE_SOCKADDR_IN_SIN_LEN
1346 srca4->sin_len = sizeof (struct sockaddr_in);
1347 dsta4->sin_len = sizeof (struct sockaddr_in);
1353 srca6 = (struct sockaddr_in6*) &rr->src_addr;
1354 dsta6 = (struct sockaddr_in6*) &rr->dst_addr;
1355 memset (srca6, 0, sizeof (struct sockaddr_in6));
1356 memset (dsta6, 0, sizeof (struct sockaddr_in6));
1357 srca6->sin6_family = AF_INET6;
1358 dsta6->sin6_family = AF_INET6;
1359 srca6->sin6_addr = ip6->source_address;
1360 dsta6->sin6_addr = ip6->destination_address;
1361 srca6->sin6_port = udp->source_port;
1362 dsta6->sin6_port = udp->destination_port;
1363 #if HAVE_SOCKADDR_IN_SIN_LEN
1364 srca6->sin6_len = sizeof (struct sockaddr_in6);
1365 dsta6->sin6_len = sizeof (struct sockaddr_in6);
1372 rr->payload = GNUNET_malloc (msize);
1373 rr->payload_length = msize;
1374 memcpy (rr->payload, dns, msize);
1375 rr->request_id = dns->id | (request_id_gen << 16);
1378 GNUNET_STATISTICS_update (stats,
1379 gettext_noop ("# DNS requests received via TUN interface"),
1381 /* start request processing state machine */
1387 * Process a request via mesh to perform a DNS query.
1389 * @param cls closure, NULL
1390 * @param tunnel connection to the other end
1391 * @param tunnel_ctx pointer to our 'struct TunnelState *'
1392 * @param sender who sent the message
1393 * @param message the actual message
1394 * @param atsi performance data for the connection
1395 * @return GNUNET_OK to keep the connection open,
1396 * GNUNET_SYSERR to close it (signal serious error)
1399 receive_dns_request (void *cls GNUNET_UNUSED, struct GNUNET_MESH_Tunnel *tunnel,
1401 const struct GNUNET_PeerIdentity *sender GNUNET_UNUSED,
1402 const struct GNUNET_MessageHeader *message,
1403 const struct GNUNET_ATS_Information *atsi GNUNET_UNUSED)
1405 struct TunnelState *ts = *tunnel_ctx;
1406 const struct GNUNET_TUN_DnsHeader *dns;
1407 size_t mlen = ntohs (message->size);
1408 size_t dlen = mlen - sizeof (struct GNUNET_MessageHeader);
1410 struct GNUNET_TUN_DnsHeader *dout;
1411 struct sockaddr_in v4;
1412 struct sockaddr_in6 v6;
1413 struct sockaddr *so;
1416 if (dlen < sizeof (struct GNUNET_TUN_DnsHeader))
1418 GNUNET_break_op (0);
1419 return GNUNET_SYSERR;
1421 dns = (const struct GNUNET_TUN_DnsHeader *) &message[1];
1422 ts->original_id = dns->id;
1423 if (tunnels[ts->my_id] == ts)
1424 tunnels[ts->my_id] = NULL;
1425 ts->my_id = (uint16_t) GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
1427 tunnels[ts->my_id] = ts;
1428 memcpy (buf, dns, dlen);
1429 dout = (struct GNUNET_TUN_DnsHeader*) buf;
1430 dout->id = ts->my_id;
1431 memset (&v4, 0, sizeof (v4));
1432 memset (&v6, 0, sizeof (v6));
1433 if (1 == inet_pton (AF_INET, dns_exit, &v4.sin_addr))
1435 salen = sizeof (v4);
1436 v4.sin_family = AF_INET;
1437 v4.sin_port = htons (53);
1438 #if HAVE_SOCKADDR_IN_SIN_LEN
1439 v4.sin_len = (u_char) salen;
1441 so = (struct sockaddr *) &v4;
1442 ts->dnsout = get_request_socket (AF_INET);
1444 else if (1 == inet_pton (AF_INET6, dns_exit, &v6.sin6_addr))
1446 salen = sizeof (v6);
1447 v6.sin6_family = AF_INET6;
1448 v6.sin6_port = htons (53);
1449 #if HAVE_SOCKADDR_IN_SIN_LEN
1450 v6.sin6_len = (u_char) salen;
1452 so = (struct sockaddr *) &v6;
1453 ts->dnsout = get_request_socket (AF_INET6);
1458 return GNUNET_SYSERR;
1460 if (NULL == ts->dnsout)
1462 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1463 _("Configured DNS exit `%s' is not working / valid.\n"),
1465 return GNUNET_SYSERR;
1470 ts->addrlen = salen;
1471 GNUNET_NETWORK_socket_sendto (ts->dnsout,
1472 buf, dlen, so, salen);
1473 ts->timeout = GNUNET_TIME_relative_to_absolute (REQUEST_TIMEOUT);
1479 * Callback from GNUNET_MESH for new tunnels.
1481 * @param cls closure
1482 * @param tunnel new handle to the tunnel
1483 * @param initiator peer that started the tunnel
1484 * @param ats performance information for the tunnel
1485 * @return initial tunnel context for the tunnel
1488 accept_dns_tunnel (void *cls GNUNET_UNUSED, struct GNUNET_MESH_Tunnel *tunnel,
1489 const struct GNUNET_PeerIdentity *initiator GNUNET_UNUSED,
1490 const struct GNUNET_ATS_Information *ats GNUNET_UNUSED)
1492 struct TunnelState *ts = GNUNET_malloc (sizeof (struct TunnelState));
1494 GNUNET_STATISTICS_update (stats,
1495 gettext_noop ("# Inbound MESH tunnels created"),
1497 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1498 "Received inbound tunnel from `%s'\n",
1499 GNUNET_i2s (initiator));
1500 ts->tunnel = tunnel;
1506 * Function called by mesh whenever an inbound tunnel is destroyed.
1507 * Should clean up any associated state.
1509 * @param cls closure (set from GNUNET_MESH_connect)
1510 * @param tunnel connection to the other end (henceforth invalid)
1511 * @param tunnel_ctx place where local state associated
1512 * with the tunnel is stored
1515 destroy_dns_tunnel (void *cls GNUNET_UNUSED,
1516 const struct GNUNET_MESH_Tunnel *tunnel,
1519 struct TunnelState *ts = tunnel_ctx;
1521 if (tunnels[ts->my_id] == ts)
1522 tunnels[ts->my_id] = NULL;
1524 GNUNET_MESH_notify_transmit_ready_cancel (ts->th);
1525 GNUNET_free_non_null (ts->reply);
1531 * @param cls closure
1532 * @param server the initialized server
1533 * @param cfg_ configuration to use
1536 run (void *cls, struct GNUNET_SERVER_Handle *server,
1537 const struct GNUNET_CONFIGURATION_Handle *cfg_)
1539 static const struct GNUNET_SERVER_MessageHandler handlers[] = {
1540 /* callback, cls, type, size */
1541 {&handle_client_init, NULL, GNUNET_MESSAGE_TYPE_DNS_CLIENT_INIT,
1542 sizeof (struct GNUNET_DNS_Register)},
1543 {&handle_client_response, NULL, GNUNET_MESSAGE_TYPE_DNS_CLIENT_RESPONSE, 0},
1551 struct in_addr dns_exit4;
1552 struct in6_addr dns_exit6;
1555 stats = GNUNET_STATISTICS_create ("dns", cfg);
1556 nc = GNUNET_SERVER_notification_context_create (server, 1);
1557 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &cleanup_task,
1560 GNUNET_CONFIGURATION_get_value_yesno (cfg_, "dns", "PROVIDE_EXIT")) &&
1562 GNUNET_CONFIGURATION_get_value_string (cfg, "dns",
1565 ( (1 != inet_pton (AF_INET, dns_exit, &dns_exit4)) &&
1566 (1 != inet_pton (AF_INET6, dns_exit, &dns_exit6)) ) ) )
1568 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1569 _("Configured to provide DNS exit, but no valid DNS server configured!\n"));
1570 GNUNET_free_non_null (dns_exit);
1574 helper_argv[0] = GNUNET_strdup ("gnunet-dns");
1575 if (GNUNET_SYSERR ==
1576 GNUNET_CONFIGURATION_get_value_string (cfg, "dns", "IFNAME", &ifc_name))
1578 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1579 "No entry 'IFNAME' in configuration!\n");
1580 GNUNET_SCHEDULER_shutdown ();
1583 helper_argv[1] = ifc_name;
1584 if ( (GNUNET_SYSERR ==
1585 GNUNET_CONFIGURATION_get_value_string (cfg, "dns", "IPV6ADDR",
1588 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1589 "No entry 'IPV6ADDR' in configuration!\n");
1590 GNUNET_SCHEDULER_shutdown ();
1593 helper_argv[2] = ipv6addr;
1594 if (GNUNET_SYSERR ==
1595 GNUNET_CONFIGURATION_get_value_string (cfg, "dns", "IPV6PREFIX",
1598 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1599 "No entry 'IPV6PREFIX' in configuration!\n");
1600 GNUNET_SCHEDULER_shutdown ();
1603 helper_argv[3] = ipv6prefix;
1605 if (GNUNET_SYSERR ==
1606 GNUNET_CONFIGURATION_get_value_string (cfg, "dns", "IPV4ADDR",
1609 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1610 "No entry 'IPV4ADDR' in configuration!\n");
1611 GNUNET_SCHEDULER_shutdown ();
1614 helper_argv[4] = ipv4addr;
1615 if (GNUNET_SYSERR ==
1616 GNUNET_CONFIGURATION_get_value_string (cfg, "dns", "IPV4MASK",
1619 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1620 "No entry 'IPV4MASK' in configuration!\n");
1621 GNUNET_SCHEDULER_shutdown ();
1624 helper_argv[5] = ipv4mask;
1625 helper_argv[6] = NULL;
1627 if (NULL != dns_exit)
1629 static struct GNUNET_MESH_MessageHandler mesh_handlers[] = {
1630 {&receive_dns_request, GNUNET_MESSAGE_TYPE_VPN_DNS_TO_INTERNET, 0},
1633 static GNUNET_MESH_ApplicationType mesh_types[] = {
1634 GNUNET_APPLICATION_TYPE_INTERNET_RESOLVER,
1635 GNUNET_APPLICATION_TYPE_END
1637 mesh = GNUNET_MESH_connect (cfg,
1640 &destroy_dns_tunnel,
1644 hijacker = GNUNET_HELPER_start ("gnunet-helper-dns",
1646 &process_helper_messages,
1648 GNUNET_SERVER_add_handlers (server, handlers);
1649 GNUNET_SERVER_disconnect_notify (server, &client_disconnect, NULL);
1654 * The main function for the dns service.
1656 * @param argc number of arguments from the command line
1657 * @param argv command line arguments
1658 * @return 0 ok, 1 on error
1661 main (int argc, char *const *argv)
1663 return (GNUNET_OK ==
1664 GNUNET_SERVICE_run (argc, argv, "dns", GNUNET_SERVICE_OPTION_NONE,
1665 &run, NULL)) ? 0 : 1;
1669 /* end of gnunet-service-dns.c */