2 This file is part of GNUnet
3 (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 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.
21 * @file transport/plugin_transport_tcp.c
22 * @brief Implementation of the TCP transport service
23 * @author Christian Grothoff
26 #include "gnunet_hello_lib.h"
27 #include "gnunet_constants.h"
28 #include "gnunet_connection_lib.h"
29 #include "gnunet_container_lib.h"
30 #include "gnunet_nat_lib.h"
31 #include "gnunet_os_lib.h"
32 #include "gnunet_protocols.h"
33 #include "gnunet_resolver_service.h"
34 #include "gnunet_server_lib.h"
35 #include "gnunet_service_lib.h"
36 #include "gnunet_signatures.h"
37 #include "gnunet_statistics_service.h"
38 #include "gnunet_transport_service.h"
39 #include "gnunet_transport_plugin.h"
40 #include "transport.h"
42 #define DEBUG_TCP GNUNET_EXTRA_LOGGING
44 #define DEBUG_TCP_NAT GNUNET_EXTRA_LOGGING
48 * How long until we give up on establishing an NAT connection?
51 #define NAT_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 10)
54 GNUNET_NETWORK_STRUCT_BEGIN
57 * Initial handshake message for a session.
62 * Type is GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME.
64 struct GNUNET_MessageHeader header;
67 * Identity of the node connecting (TCP client)
69 struct GNUNET_PeerIdentity clientIdentity;
75 * Basically a WELCOME message, but with the purpose
76 * of giving the waiting peer a client handle to use
78 struct TCP_NAT_ProbeMessage
81 * Type is GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE.
83 struct GNUNET_MessageHeader header;
86 * Identity of the sender of the message.
88 struct GNUNET_PeerIdentity clientIdentity;
91 GNUNET_NETWORK_STRUCT_END
94 * Context for sending a NAT probe via TCP.
96 struct TCPProbeContext
100 * Active probes are kept in a DLL.
102 struct TCPProbeContext *next;
105 * Active probes are kept in a DLL.
107 struct TCPProbeContext *prev;
112 struct GNUNET_CONNECTION_Handle *sock;
115 * Message to be sent.
117 struct TCP_NAT_ProbeMessage message;
120 * Handle to the transmission.
122 struct GNUNET_CONNECTION_TransmitHandle *transmit_handle;
125 * Transport plugin handle.
127 struct Plugin *plugin;
131 GNUNET_NETWORK_STRUCT_BEGIN
134 * Network format for IPv4 addresses.
136 struct IPv4TcpAddress
139 * IPv4 address, in network byte order.
141 uint32_t ipv4_addr GNUNET_PACKED;
144 * Port number, in network byte order.
146 uint16_t t4_port GNUNET_PACKED;
152 * Network format for IPv6 addresses.
154 struct IPv6TcpAddress
159 struct in6_addr ipv6_addr GNUNET_PACKED;
162 * Port number, in network byte order.
164 uint16_t t6_port GNUNET_PACKED;
167 GNUNET_NETWORK_STRUCT_END
170 * Encapsulation of all of the state of the plugin.
176 * Information kept for each message that is yet to
179 struct PendingMessage
183 * This is a doubly-linked list.
185 struct PendingMessage *next;
188 * This is a doubly-linked list.
190 struct PendingMessage *prev;
193 * The pending message
198 * Continuation function to call once the message
199 * has been sent. Can be NULL if there is no
200 * continuation to call.
202 GNUNET_TRANSPORT_TransmitContinuation transmit_cont;
205 * Closure for transmit_cont.
207 void *transmit_cont_cls;
210 * Timeout value for the pending message.
212 struct GNUNET_TIME_Absolute timeout;
215 * So that the gnunet-service-transport can group messages together,
216 * these pending messages need to accept a message buffer and size
217 * instead of just a GNUNET_MessageHeader.
225 * Session handle for TCP connections.
233 struct SessionHeader header;
236 * Stored in a linked list.
238 struct Session *next;
241 * Pointer to the global plugin struct.
243 struct Plugin *plugin;
246 * The client (used to identify this connection)
248 struct GNUNET_SERVER_Client *client;
251 * Task cleaning up a NAT client connection establishment attempt;
253 GNUNET_SCHEDULER_TaskIdentifier nat_connection_timeout;
256 * Messages currently pending for transmission
257 * to this peer, if any.
259 struct PendingMessage *pending_messages_head;
262 * Messages currently pending for transmission
263 * to this peer, if any.
265 struct PendingMessage *pending_messages_tail;
268 * Handle for pending transmission request.
270 struct GNUNET_SERVER_TransmitHandle *transmit_handle;
273 * To whom are we talking to (set to our identity
274 * if we are still waiting for the welcome message)
276 struct GNUNET_PeerIdentity target;
279 * ID of task used to delay receiving more to throttle sender.
281 GNUNET_SCHEDULER_TaskIdentifier receive_delay_task;
284 * Address of the other peer (either based on our 'connect'
285 * call or on our 'accept' call).
287 * struct IPv4TcpAddress or struct IPv6TcpAddress
293 * Length of connect_addr.
298 * Last activity on this connection. Used to select preferred
301 struct GNUNET_TIME_Absolute last_activity;
304 * Are we still expecting the welcome message? (GNUNET_YES/GNUNET_NO)
306 int expecting_welcome;
309 * Was this a connection that was inbound (we accepted)? (GNUNET_YES/GNUNET_NO)
314 * Was this session created using NAT traversal?
319 * ATS network type in NBO
321 uint32_t ats_address_network_type;
326 * Encapsulation of all of the state of the plugin.
333 struct GNUNET_TRANSPORT_PluginEnvironment *env;
338 struct GNUNET_CONNECTION_Handle *lsock;
341 * Our handle to the NAT module.
343 struct GNUNET_NAT_Handle *nat;
345 struct GNUNET_CONTAINER_MultiHashMap * sessionmap;
348 * Handle to the network service.
350 struct GNUNET_SERVICE_Context *service;
353 * Handle to the server for this service.
355 struct GNUNET_SERVER_Handle *server;
358 * Copy of the handler array where the closures are
359 * set to this struct's instance.
361 struct GNUNET_SERVER_MessageHandler *handlers;
364 * Map of peers we have tried to contact behind a NAT
366 struct GNUNET_CONTAINER_MultiHashMap *nat_wait_conns;
369 * List of active TCP probes.
371 struct TCPProbeContext *probe_head;
374 * List of active TCP probes.
376 struct TCPProbeContext *probe_tail;
379 * Handle for (DYN)DNS lookup of our external IP.
381 struct GNUNET_RESOLVER_RequestHandle *ext_dns;
384 * How many more TCP sessions are we allowed to open right now?
386 unsigned long long max_connections;
389 * ID of task used to update our addresses when one expires.
391 GNUNET_SCHEDULER_TaskIdentifier address_update_task;
394 * Port that we are actually listening on.
399 * Port that the user said we would have visible to the
408 tcp_address_to_string (void *cls, const void *addr, size_t addrlen);
410 static unsigned int sessions;
412 static void inc_sessions (struct Plugin *plugin, struct Session *session, int line)
415 unsigned int size = GNUNET_CONTAINER_multihashmap_size(plugin->sessionmap);
416 if (sessions != size)
417 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp", "Inconsistent sessions %u <-> session map size: %u\n",
419 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp", "%4i Session increased to %u (session map size: %u): `%s' `%s'\n",
423 GNUNET_i2s (&session->target),
424 tcp_address_to_string (NULL, session->addr, session->addrlen));
427 static void dec_sessions (struct Plugin *plugin, struct Session *session, int line)
429 GNUNET_assert (sessions > 0);
430 unsigned int size = GNUNET_CONTAINER_multihashmap_size(plugin->sessionmap);
432 if (sessions != size)
433 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp", "Inconsistent sessions %u <-> session map size: %u\n",
435 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp", "%4i Session decreased to %u (session map size: %u): `%s' `%s'\n",
439 GNUNET_i2s (&session->target),
440 tcp_address_to_string (NULL, session->addr, session->addrlen));
446 * Function to check if an inbound connection is acceptable.
447 * Mostly used to limit the total number of open connections
450 * @param cls the 'struct Plugin'
451 * @param ucred credentials, if available, otherwise NULL
452 * @param addr address
453 * @param addrlen length of address
454 * @return GNUNET_YES to allow, GNUNET_NO to deny, GNUNET_SYSERR
455 * for unknown address family (will be denied).
458 plugin_tcp_access_check (void *cls,
459 const struct GNUNET_CONNECTION_Credentials *ucred,
460 const struct sockaddr *addr, socklen_t addrlen)
462 struct Plugin *plugin = cls;
464 if (0 == plugin->max_connections)
466 plugin->max_connections--;
472 * Our external IP address/port mapping has changed.
474 * @param cls closure, the 'struct LocalAddrList'
475 * @param add_remove GNUNET_YES to mean the new public IP address, GNUNET_NO to mean
476 * the previous (now invalid) one
477 * @param addr either the previous or the new public IP address
478 * @param addrlen actual lenght of the address
481 tcp_nat_port_map_callback (void *cls, int add_remove,
482 const struct sockaddr *addr, socklen_t addrlen)
484 struct Plugin *plugin = cls;
485 struct IPv4TcpAddress t4;
486 struct IPv6TcpAddress t6;
490 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
491 "NPMC called with %d for address `%s'\n", add_remove,
492 GNUNET_a2s (addr, addrlen));
493 /* convert 'addr' to our internal format */
494 switch (addr->sa_family)
497 GNUNET_assert (addrlen == sizeof (struct sockaddr_in));
498 t4.ipv4_addr = ((struct sockaddr_in *) addr)->sin_addr.s_addr;
499 t4.t4_port = ((struct sockaddr_in *) addr)->sin_port;
504 GNUNET_assert (addrlen == sizeof (struct sockaddr_in6));
505 memcpy (&t6.ipv6_addr, &((struct sockaddr_in6 *) addr)->sin6_addr,
506 sizeof (struct in6_addr));
507 t6.t6_port = ((struct sockaddr_in6 *) addr)->sin6_port;
515 /* modify our published address list */
516 plugin->env->notify_address (plugin->env->cls, add_remove, arg, args);
521 * Function called for a quick conversion of the binary address to
522 * a numeric address. Note that the caller must not free the
523 * address and that the next call to this function is allowed
524 * to override the address again.
526 * @param cls closure ('struct Plugin*')
527 * @param addr binary address
528 * @param addrlen length of the address
529 * @return string representing the same address
532 tcp_address_to_string (void *cls, const void *addr, size_t addrlen)
534 static char rbuf[INET6_ADDRSTRLEN + 12];
535 char buf[INET6_ADDRSTRLEN];
539 const struct IPv4TcpAddress *t4;
540 const struct IPv6TcpAddress *t6;
544 if (addrlen == sizeof (struct IPv6TcpAddress))
548 port = ntohs (t6->t6_port);
549 memcpy (&a6, &t6->ipv6_addr, sizeof (a6));
552 else if (addrlen == sizeof (struct IPv4TcpAddress))
556 port = ntohs (t4->t4_port);
557 memcpy (&a4, &t4->ipv4_addr, sizeof (a4));
562 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, "tcp",
563 _("Unexpected address length: %u bytes\n"),
564 (unsigned int) addrlen);
568 if (NULL == inet_ntop (af, sb, buf, INET6_ADDRSTRLEN))
570 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "inet_ntop");
573 GNUNET_snprintf (rbuf, sizeof (rbuf), (af == AF_INET6) ? "[%s]:%u" : "%s:%u",
580 * Function called to convert a string address to
583 * @param cls closure ('struct Plugin*')
584 * @param addr string address
585 * @param addrlen length of the address
586 * @param buf location to store the buffer
587 * @param added location to store the number of bytes in the buffer.
588 * If the function returns GNUNET_SYSERR, its contents are undefined.
589 * @return GNUNET_OK on success, GNUNET_SYSERR on failure
592 tcp_string_to_address (void *cls, const char *addr, uint16_t addrlen,
593 void **buf, size_t *added)
595 struct sockaddr_storage socket_address;
596 int ret = GNUNET_STRINGS_to_address_ip (addr, addrlen,
599 if (ret != GNUNET_OK)
600 return GNUNET_SYSERR;
602 if (socket_address.ss_family == AF_INET)
604 struct IPv4TcpAddress *t4;
605 struct sockaddr_in *in4 = (struct sockaddr_in *) &socket_address;
606 t4 = GNUNET_malloc (sizeof (struct IPv4TcpAddress));
607 t4->ipv4_addr = in4->sin_addr.s_addr;
608 t4->t4_port = in4->sin_port;
610 *added = sizeof (struct IPv4TcpAddress);
612 else if (socket_address.ss_family == AF_INET6)
614 struct IPv6TcpAddress *t6;
615 struct sockaddr_in6 *in6 = (struct sockaddr_in6 *) &socket_address;
616 t6 = GNUNET_malloc (sizeof (struct IPv6TcpAddress));
617 t6->ipv6_addr = in6->sin6_addr;
618 t6->t6_port = in6->sin6_port;
620 *added = sizeof (struct IPv6TcpAddress);
622 return GNUNET_SYSERR;
626 struct SessionClientCtx
628 const struct GNUNET_SERVER_Client *client;
632 int session_lookup_by_client_it (void *cls,
633 const GNUNET_HashCode * key,
636 struct SessionClientCtx *sc_ctx = cls;
637 struct Session *s = value;
639 if (s->client == sc_ctx->client)
648 * Find the session handle for the given client.
650 * @param plugin the plugin
651 * @param client which client to find the session handle for
652 * @return NULL if no matching session exists
654 static struct Session *
655 lookup_session_by_client (struct Plugin *plugin,
656 const struct GNUNET_SERVER_Client *client)
658 struct SessionClientCtx sc_ctx;
659 sc_ctx.client = client;
662 GNUNET_CONTAINER_multihashmap_iterate (plugin->sessionmap, &session_lookup_by_client_it, &sc_ctx);
669 * Create a new session. Also queues a welcome message.
671 * @param plugin the plugin
672 * @param target peer to connect to
673 * @param client client to use
674 * @param is_nat this a NAT session, we should wait for a client to
675 * connect to us from an address, then assign that to
677 * @return new session object
679 static struct Session *
680 create_session (struct Plugin *plugin, const struct GNUNET_PeerIdentity *target,
681 struct GNUNET_SERVER_Client *client, int is_nat)
684 struct PendingMessage *pm;
685 struct WelcomeMessage welcome;
687 if (is_nat != GNUNET_YES)
688 GNUNET_assert (client != NULL);
690 GNUNET_assert (client == NULL);
692 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
693 "Creating new session for peer `%4s'\n",
694 GNUNET_i2s (target));
696 ret = GNUNET_malloc (sizeof (struct Session));
697 ret->last_activity = GNUNET_TIME_absolute_get ();
698 ret->plugin = plugin;
699 ret->is_nat = is_nat;
700 ret->client = client;
701 ret->target = *target;
702 ret->expecting_welcome = GNUNET_YES;
703 ret->ats_address_network_type = htonl (GNUNET_ATS_NET_UNSPECIFIED);
704 pm = GNUNET_malloc (sizeof (struct PendingMessage) +
705 sizeof (struct WelcomeMessage));
706 pm->msg = (const char *) &pm[1];
707 pm->message_size = sizeof (struct WelcomeMessage);
708 welcome.header.size = htons (sizeof (struct WelcomeMessage));
709 welcome.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME);
710 welcome.clientIdentity = *plugin->env->my_identity;
711 memcpy (&pm[1], &welcome, sizeof (welcome));
712 pm->timeout = GNUNET_TIME_UNIT_FOREVER_ABS;
713 GNUNET_STATISTICS_update (plugin->env->stats,
714 gettext_noop ("# bytes currently in TCP buffers"),
715 pm->message_size, GNUNET_NO);
716 GNUNET_CONTAINER_DLL_insert (ret->pending_messages_head,
717 ret->pending_messages_tail, pm);
718 if (is_nat != GNUNET_YES)
720 GNUNET_STATISTICS_update (plugin->env->stats,
721 gettext_noop ("# TCP sessions active"), 1,
729 * If we have pending messages, ask the server to
730 * transmit them (schedule the respective tasks, etc.)
732 * @param session for which session should we do this
735 process_pending_messages (struct Session *session);
739 * Function called to notify a client about the socket
740 * being ready to queue more data. "buf" will be
741 * NULL and "size" zero if the socket was closed for
742 * writing in the meantime.
745 * @param size number of bytes available in buf
746 * @param buf where the callee should write the message
747 * @return number of bytes written to buf
750 do_transmit (void *cls, size_t size, void *buf)
752 struct Session *session = cls;
753 struct GNUNET_PeerIdentity pid;
754 struct Plugin *plugin;
755 struct PendingMessage *pos;
756 struct PendingMessage *hd;
757 struct PendingMessage *tl;
758 struct GNUNET_TIME_Absolute now;
762 GNUNET_assert (session != NULL);
763 session->transmit_handle = NULL;
764 plugin = session->plugin;
768 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
769 "Timeout trying to transmit to peer `%4s', discarding message queue.\n",
770 GNUNET_i2s (&session->target));
772 /* timeout; cancel all messages that have already expired */
776 now = GNUNET_TIME_absolute_get ();
777 while ((NULL != (pos = session->pending_messages_head)) &&
778 (pos->timeout.abs_value <= now.abs_value))
780 GNUNET_CONTAINER_DLL_remove (session->pending_messages_head,
781 session->pending_messages_tail, pos);
783 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
784 "Failed to transmit %u byte message to `%4s'.\n",
785 pos->message_size, GNUNET_i2s (&session->target));
787 ret += pos->message_size;
788 GNUNET_CONTAINER_DLL_insert_after (hd, tl, tl, pos);
790 /* do this call before callbacks (so that if callbacks destroy
791 * session, they have a chance to cancel actions done by this
793 process_pending_messages (session);
794 pid = session->target;
795 /* no do callbacks and do not use session again since
796 * the callbacks may abort the session */
797 while (NULL != (pos = hd))
799 GNUNET_CONTAINER_DLL_remove (hd, tl, pos);
800 if (pos->transmit_cont != NULL)
801 pos->transmit_cont (pos->transmit_cont_cls, &pid, GNUNET_SYSERR);
804 GNUNET_STATISTICS_update (plugin->env->stats,
805 gettext_noop ("# bytes currently in TCP buffers"),
806 -(int64_t) ret, GNUNET_NO);
807 GNUNET_STATISTICS_update (plugin->env->stats,
809 ("# bytes discarded by TCP (timeout)"), ret,
813 /* copy all pending messages that would fit */
818 while (NULL != (pos = session->pending_messages_head))
820 if (ret + pos->message_size > size)
822 GNUNET_CONTAINER_DLL_remove (session->pending_messages_head,
823 session->pending_messages_tail, pos);
824 GNUNET_assert (size >= pos->message_size);
825 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
826 "Transmitting message of type %u\n",
827 ntohs (((struct GNUNET_MessageHeader *) pos->msg)->type));
828 /* FIXME: this memcpy can be up to 7% of our total runtime */
829 memcpy (cbuf, pos->msg, pos->message_size);
830 cbuf += pos->message_size;
831 ret += pos->message_size;
832 size -= pos->message_size;
833 GNUNET_CONTAINER_DLL_insert_tail (hd, tl, pos);
835 /* schedule 'continuation' before callbacks so that callbacks that
836 * cancel everything don't cause us to use a session that no longer
838 process_pending_messages (session);
839 session->last_activity = GNUNET_TIME_absolute_get ();
840 pid = session->target;
841 /* we'll now call callbacks that may cancel the session; hence
842 * we should not use 'session' after this point */
843 while (NULL != (pos = hd))
845 GNUNET_CONTAINER_DLL_remove (hd, tl, pos);
846 if (pos->transmit_cont != NULL)
847 pos->transmit_cont (pos->transmit_cont_cls, &pid, GNUNET_OK);
850 GNUNET_assert (hd == NULL);
851 GNUNET_assert (tl == NULL);
853 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp", "Transmitting %u bytes\n",
856 GNUNET_STATISTICS_update (plugin->env->stats,
857 gettext_noop ("# bytes currently in TCP buffers"),
858 -(int64_t) ret, GNUNET_NO);
859 GNUNET_STATISTICS_update (plugin->env->stats,
860 gettext_noop ("# bytes transmitted via TCP"), ret,
867 * If we have pending messages, ask the server to
868 * transmit them (schedule the respective tasks, etc.)
870 * @param session for which session should we do this
873 process_pending_messages (struct Session *session)
875 struct PendingMessage *pm;
877 GNUNET_assert (session->client != NULL);
878 if (session->transmit_handle != NULL)
880 if (NULL == (pm = session->pending_messages_head))
883 session->transmit_handle =
884 GNUNET_SERVER_notify_transmit_ready (session->client, pm->message_size,
885 GNUNET_TIME_absolute_get_remaining
886 (pm->timeout), &do_transmit,
892 * Functions with this signature are called whenever we need
893 * to close a session due to a disconnect or failure to
894 * establish a connection.
896 * @param session session to close down
899 disconnect_session (struct Session *session)
901 struct PendingMessage *pm;
902 struct Plugin * plugin = session->plugin;
904 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
905 "Disconnecting session %p for peer `%s' address `%s'\n",
907 GNUNET_i2s (&session->target),
908 tcp_address_to_string(NULL, session->addr, session->addrlen));
910 if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(plugin->sessionmap, &session->target.hashPubKey, session))
912 GNUNET_STATISTICS_update (session->plugin->env->stats,
913 gettext_noop ("# TCP sessions active"), -1,
915 dec_sessions (plugin, session, __LINE__);
917 else GNUNET_assert (GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(plugin->nat_wait_conns, &session->target.hashPubKey, session));
920 if (session->transmit_handle != NULL)
922 GNUNET_SERVER_notify_transmit_ready_cancel (session->transmit_handle);
923 session->transmit_handle = NULL;
925 session->plugin->env->session_end (session->plugin->env->cls,
926 &session->target, session);
928 if (session->nat_connection_timeout != GNUNET_SCHEDULER_NO_TASK)
930 GNUNET_SCHEDULER_cancel (session->nat_connection_timeout);
931 session->nat_connection_timeout = GNUNET_SCHEDULER_NO_TASK;
934 while (NULL != (pm = session->pending_messages_head))
937 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
939 NULL ? "Could not deliver message to `%4s'.\n" :
940 "Could not deliver message to `%4s', notifying.\n",
941 GNUNET_i2s (&session->target));
943 GNUNET_STATISTICS_update (session->plugin->env->stats,
944 gettext_noop ("# bytes currently in TCP buffers"),
945 -(int64_t) pm->message_size, GNUNET_NO);
946 GNUNET_STATISTICS_update (session->plugin->env->stats,
948 ("# bytes discarded by TCP (disconnect)"),
949 pm->message_size, GNUNET_NO);
950 GNUNET_CONTAINER_DLL_remove (session->pending_messages_head,
951 session->pending_messages_tail, pm);
952 if (NULL != pm->transmit_cont)
953 pm->transmit_cont (pm->transmit_cont_cls, &session->target,
957 if (session->receive_delay_task != GNUNET_SCHEDULER_NO_TASK)
959 GNUNET_SCHEDULER_cancel (session->receive_delay_task);
960 if (session->client != NULL)
961 GNUNET_SERVER_receive_done (session->client, GNUNET_SYSERR);
963 if (session->client != NULL)
965 GNUNET_SERVER_client_drop (session->client);
966 session->client = NULL;
970 GNUNET_free_non_null (session->addr);
971 GNUNET_assert (NULL == session->transmit_handle);
972 GNUNET_free (session);
977 * Function that can be used by the transport service to transmit
978 * a message using the plugin. Note that in the case of a
979 * peer disconnecting, the continuation MUST be called
980 * prior to the disconnect notification itself. This function
981 * will be called with this peer's HELLO message to initiate
982 * a fresh connection to another peer.
985 * @param session which session must be used
986 * @param msgbuf the message to transmit
987 * @param msgbuf_size number of bytes in 'msgbuf'
988 * @param priority how important is the message (most plugins will
989 * ignore message priority and just FIFO)
990 * @param to how long to wait at most for the transmission (does not
991 * require plugins to discard the message after the timeout,
992 * just advisory for the desired delay; most plugins will ignore
994 * @param cont continuation to call once the message has
995 * been transmitted (or if the transport is ready
996 * for the next transmission call; or if the
997 * peer disconnected...); can be NULL
998 * @param cont_cls closure for cont
999 * @return number of bytes used (on the physical network, with overheads);
1000 * -1 on hard errors (i.e. address invalid); 0 is a legal value
1001 * and does NOT mean that the message was not transmitted (DV)
1004 tcp_plugin_send (void *cls,
1005 struct Session *session,
1006 const char *msgbuf, size_t msgbuf_size,
1007 unsigned int priority,
1008 struct GNUNET_TIME_Relative to,
1009 GNUNET_TRANSPORT_TransmitContinuation cont, void *cont_cls)
1011 struct Plugin * plugin = cls;
1012 struct PendingMessage *pm;
1014 GNUNET_assert (plugin != NULL);
1015 GNUNET_assert (session != NULL);
1017 /* create new message entry */
1018 pm = GNUNET_malloc (sizeof (struct PendingMessage) + msgbuf_size);
1019 pm->msg = (const char *) &pm[1];
1020 memcpy (&pm[1], msgbuf, msgbuf_size);
1021 pm->message_size = msgbuf_size;
1022 pm->timeout = GNUNET_TIME_relative_to_absolute (to);
1023 pm->transmit_cont = cont;
1024 pm->transmit_cont_cls = cont_cls;
1027 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1028 "Asked to transmit %u bytes to `%s', added message to list.\n",
1029 msgbuf_size, GNUNET_i2s (&session->target));
1031 if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains_value(plugin->sessionmap, &session->target.hashPubKey, session))
1033 GNUNET_assert (session->client != NULL);
1035 GNUNET_SERVER_client_set_timeout (session->client,
1036 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1037 GNUNET_STATISTICS_update (plugin->env->stats,
1038 gettext_noop ("# bytes currently in TCP buffers"),
1039 msgbuf_size, GNUNET_NO);
1041 /* append pm to pending_messages list */
1042 GNUNET_CONTAINER_DLL_insert_tail (session->pending_messages_head,
1043 session->pending_messages_tail, pm);
1045 process_pending_messages (session);
1048 else if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains_value(plugin->nat_wait_conns, &session->target.hashPubKey, session))
1050 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1051 "This NAT WAIT session for peer `%s' is not yet ready!\n",
1052 GNUNET_i2s (&session->target));
1054 GNUNET_STATISTICS_update (plugin->env->stats,
1055 gettext_noop ("# bytes currently in TCP buffers"),
1056 msgbuf_size, GNUNET_NO);
1058 /* append pm to pending_messages list */
1059 GNUNET_CONTAINER_DLL_insert_tail (session->pending_messages_head,
1060 session->pending_messages_tail, pm);
1066 cont (cont_cls, &session->target, GNUNET_SYSERR);
1069 return GNUNET_SYSERR; /* session does not exist here */
1077 struct Session * result;
1080 int session_lookup_it (void *cls,
1081 const GNUNET_HashCode * key,
1084 struct SessionItCtx * si_ctx = cls;
1085 struct Session * session = value;
1087 char * a1 = strdup (tcp_address_to_string(NULL, session->addr, session->addrlen));
1088 char * a2 = strdup (tcp_address_to_string(NULL, si_ctx->addr, si_ctx->addrlen));
1089 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, "tcp",
1090 "Comparing: %s %u <-> %s %u\n",
1098 if (session->addrlen != si_ctx->addrlen)
1102 if (0 != memcmp (session->addr, si_ctx->addr, si_ctx->addrlen))
1107 a1 = strdup (tcp_address_to_string(NULL, session->addr, session->addrlen));
1108 a2 = strdup (tcp_address_to_string(NULL, si_ctx->addr, si_ctx->addrlen));
1109 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, "tcp",
1110 "Comparing: %s %u <-> %s %u , OK!\n",
1118 /* Found existing session */
1119 si_ctx->result = session;
1124 * Task cleaning up a NAT connection attempt after timeout
1128 nat_connect_timeout (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1130 struct Session *session = cls;
1132 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1133 "NAT WAIT connection to `%4s' at `%s' could not be established, removing session\n",
1134 GNUNET_i2s (&session->target), tcp_address_to_string(NULL, session->addr, session->addrlen));
1136 disconnect_session (session);
1141 * Create a new session to transmit data to the target
1142 * This session will used to send data to this peer and the plugin will
1143 * notify us by calling the env->session_end function
1145 * @param cls closure
1146 * @param address pointer to the GNUNET_HELLO_Address
1147 * @return the session if the address is valid, NULL otherwise
1149 static struct Session *
1150 tcp_plugin_get_session (void *cls,
1151 const struct GNUNET_HELLO_Address *address)
1153 struct Plugin * plugin = cls;
1154 struct Session * session = NULL;
1159 struct GNUNET_CONNECTION_Handle *sa;
1160 struct sockaddr_in a4;
1161 struct sockaddr_in6 a6;
1162 const struct IPv4TcpAddress *t4;
1163 const struct IPv6TcpAddress *t6;
1164 struct GNUNET_ATS_Information ats;
1165 unsigned int is_natd = GNUNET_NO;
1168 GNUNET_assert (plugin != NULL);
1169 GNUNET_assert (address != NULL);
1171 addrlen = address->address_length;
1173 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1174 "Trying to get session for `%s' address length %i\n",
1175 tcp_address_to_string(NULL, address->address, address->address_length),
1178 /* look for existing session */
1179 if (GNUNET_CONTAINER_multihashmap_contains(plugin->sessionmap, &address->peer.hashPubKey))
1181 struct SessionItCtx si_ctx;
1183 si_ctx.addr = (void *) address->address;
1184 si_ctx.addrlen = address->address_length;
1186 si_ctx.result = NULL;
1188 GNUNET_CONTAINER_multihashmap_get_multiple(plugin->sessionmap, &address->peer.hashPubKey, &session_lookup_it, &si_ctx);
1189 if (si_ctx.result != NULL)
1191 session = si_ctx.result;
1192 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1193 "Found exisiting session for `%s' address `%s' session %p\n",
1194 GNUNET_i2s (&address->peer),
1195 tcp_address_to_string(NULL, address->address, address->address_length),
1201 if (addrlen == sizeof (struct IPv6TcpAddress))
1203 GNUNET_assert (NULL != address->address); /* make static analysis happy */
1204 t6 = address->address;
1206 memset (&a6, 0, sizeof (a6));
1207 #if HAVE_SOCKADDR_IN_SIN_LEN
1208 a6.sin6_len = sizeof (a6);
1210 a6.sin6_family = AF_INET6;
1211 a6.sin6_port = t6->t6_port;
1212 if (t6->t6_port == 0)
1213 is_natd = GNUNET_YES;
1214 memcpy (&a6.sin6_addr, &t6->ipv6_addr, sizeof (struct in6_addr));
1218 else if (addrlen == sizeof (struct IPv4TcpAddress))
1220 GNUNET_assert (NULL != address->address); /* make static analysis happy */
1221 t4 = address->address;
1223 memset (&a4, 0, sizeof (a4));
1224 #if HAVE_SOCKADDR_IN_SIN_LEN
1225 a4.sin_len = sizeof (a4);
1227 a4.sin_family = AF_INET;
1228 a4.sin_port = t4->t4_port;
1229 if (t4->t4_port == 0)
1230 is_natd = GNUNET_YES;
1231 a4.sin_addr.s_addr = t4->ipv4_addr;
1237 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, "tcp",
1238 _("Address of unexpected length: %u\n"), addrlen);
1243 ats = plugin->env->get_address_type (plugin->env->cls, sb ,sbs);
1245 if ((is_natd == GNUNET_YES) && (addrlen == sizeof (struct IPv6TcpAddress)))
1247 /* NAT client only works with IPv4 addresses */
1251 if (0 == plugin->max_connections)
1257 if ((is_natd == GNUNET_YES) &&
1259 GNUNET_CONTAINER_multihashmap_contains (plugin->nat_wait_conns,
1260 &address->peer.hashPubKey)))
1262 /* Only do one NAT punch attempt per peer identity */
1266 if ((is_natd == GNUNET_YES) && (NULL != plugin->nat) &&
1268 GNUNET_CONTAINER_multihashmap_contains (plugin->nat_wait_conns,
1269 &address->peer.hashPubKey)))
1272 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1273 _("Found valid IPv4 NAT address (creating session)!\n"));
1275 session = create_session (plugin, &address->peer, NULL, GNUNET_YES);
1276 session->addrlen = 0;
1277 session->addr = NULL;
1278 session->ats_address_network_type = ats.value;
1279 session->nat_connection_timeout = GNUNET_SCHEDULER_add_delayed(NAT_TIMEOUT,
1280 &nat_connect_timeout,
1282 GNUNET_assert (session != NULL);
1284 GNUNET_assert (GNUNET_CONTAINER_multihashmap_put
1285 (plugin->nat_wait_conns, &address->peer.hashPubKey, session,
1286 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY) == GNUNET_OK);
1288 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1289 "Created NAT WAIT connection to `%4s' at `%s'\n",
1290 GNUNET_i2s (&session->target), GNUNET_a2s (sb, sbs));
1292 if (GNUNET_OK == GNUNET_NAT_run_client (plugin->nat, &a4))
1296 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1297 "Running NAT client for `%4s' at `%s' failed\n",
1298 GNUNET_i2s (&session->target), GNUNET_a2s (sb, sbs));
1300 disconnect_session (session);
1305 /* create new outbound session */
1306 GNUNET_assert (0 != plugin->max_connections);
1307 sa = GNUNET_CONNECTION_create_from_sockaddr (af, sb, sbs);
1311 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1312 "Failed to create connection to `%4s' at `%s'\n",
1313 GNUNET_i2s (&session->target), GNUNET_a2s (sb, sbs));
1317 plugin->max_connections--;
1319 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1320 "Asked to transmit to `%4s', creating fresh session using address `%s'.\n",
1321 GNUNET_i2s (&address->peer), GNUNET_a2s (sb, sbs));
1323 session = create_session (plugin,
1325 GNUNET_SERVER_connect_socket (plugin->server, sa),
1327 session->addr = GNUNET_malloc (addrlen);
1328 memcpy (session->addr, address->address, addrlen);
1329 session->addrlen = addrlen;
1330 session->ats_address_network_type = ats.value;
1332 GNUNET_CONTAINER_multihashmap_put(plugin->sessionmap, &address->peer.hashPubKey, session, GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
1333 inc_sessions (plugin, session, __LINE__);
1334 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1335 "Creating new session for `%s' address `%s' session %p\n",
1336 GNUNET_i2s (&address->peer),
1337 tcp_address_to_string(NULL, address->address, address->address_length),
1340 /* Send TCP Welcome */
1341 process_pending_messages (session);
1347 int session_disconnect_it (void *cls,
1348 const GNUNET_HashCode * key,
1351 struct Session *session = value;
1353 GNUNET_STATISTICS_update (session->plugin->env->stats,
1355 ("# transport-service disconnect requests for TCP"),
1357 disconnect_session (session);
1362 * Function that can be called to force a disconnect from the
1363 * specified neighbour. This should also cancel all previously
1364 * scheduled transmissions. Obviously the transmission may have been
1365 * partially completed already, which is OK. The plugin is supposed
1366 * to close the connection (if applicable) and no longer call the
1367 * transmit continuation(s).
1369 * Finally, plugin MUST NOT call the services's receive function to
1370 * notify the service that the connection to the specified target was
1371 * closed after a getting this call.
1373 * @param cls closure
1374 * @param target peer for which the last transmission is
1378 tcp_plugin_disconnect (void *cls, const struct GNUNET_PeerIdentity *target)
1380 struct Plugin *plugin = cls;
1381 struct Session *nat_session = NULL;
1383 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1384 "Disconnecting peer `%4s'\n", GNUNET_i2s (target));
1386 GNUNET_CONTAINER_multihashmap_get_multiple (plugin->sessionmap, &target->hashPubKey, session_disconnect_it, plugin);
1388 nat_session = GNUNET_CONTAINER_multihashmap_get(plugin->nat_wait_conns, &target->hashPubKey);
1389 if (nat_session != NULL)
1391 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1392 "Cleaning up pending NAT session for peer `%4s'\n", GNUNET_i2s (target));
1393 disconnect_session (nat_session);
1399 * Context for address to string conversion.
1401 struct PrettyPrinterContext
1404 * Function to call with the result.
1406 GNUNET_TRANSPORT_AddressStringCallback asc;
1409 * Clsoure for 'asc'.
1414 * Port to add after the IP address.
1423 * Append our port and forward the result.
1425 * @param cls the 'struct PrettyPrinterContext*'
1426 * @param hostname hostname part of the address
1429 append_port (void *cls, const char *hostname)
1431 struct PrettyPrinterContext *ppc = cls;
1434 if (hostname == NULL)
1436 ppc->asc (ppc->asc_cls, NULL);
1440 if (GNUNET_YES == ppc->ipv6)
1441 GNUNET_asprintf (&ret, "[%s]:%d", hostname, ppc->port);
1443 GNUNET_asprintf (&ret, "%s:%d", hostname, ppc->port);
1444 ppc->asc (ppc->asc_cls, ret);
1450 * Convert the transports address to a nice, human-readable
1453 * @param cls closure
1454 * @param type name of the transport that generated the address
1455 * @param addr one of the addresses of the host, NULL for the last address
1456 * the specific address format depends on the transport
1457 * @param addrlen length of the address
1458 * @param numeric should (IP) addresses be displayed in numeric form?
1459 * @param timeout after how long should we give up?
1460 * @param asc function to call on each string
1461 * @param asc_cls closure for asc
1464 tcp_plugin_address_pretty_printer (void *cls, const char *type,
1465 const void *addr, size_t addrlen,
1467 struct GNUNET_TIME_Relative timeout,
1468 GNUNET_TRANSPORT_AddressStringCallback asc,
1471 struct PrettyPrinterContext *ppc;
1474 struct sockaddr_in a4;
1475 struct sockaddr_in6 a6;
1476 const struct IPv4TcpAddress *t4;
1477 const struct IPv6TcpAddress *t6;
1480 if (addrlen == sizeof (struct IPv6TcpAddress))
1483 memset (&a6, 0, sizeof (a6));
1484 a6.sin6_family = AF_INET6;
1485 a6.sin6_port = t6->t6_port;
1486 memcpy (&a6.sin6_addr, &t6->ipv6_addr, sizeof (struct in6_addr));
1487 port = ntohs (t6->t6_port);
1491 else if (addrlen == sizeof (struct IPv4TcpAddress))
1494 memset (&a4, 0, sizeof (a4));
1495 a4.sin_family = AF_INET;
1496 a4.sin_port = t4->t4_port;
1497 a4.sin_addr.s_addr = t4->ipv4_addr;
1498 port = ntohs (t4->t4_port);
1504 /* invalid address */
1505 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, "tcp",
1506 "Invalid address to string request: plugin `%s', address length: %u bytes\n");
1507 GNUNET_break_op (0);
1508 asc (asc_cls, NULL);
1511 ppc = GNUNET_malloc (sizeof (struct PrettyPrinterContext));
1512 if (addrlen == sizeof (struct IPv6TcpAddress))
1513 ppc->ipv6 = GNUNET_YES;
1515 ppc->ipv6 = GNUNET_NO;
1517 ppc->asc_cls = asc_cls;
1519 GNUNET_RESOLVER_hostname_get (sb, sbs, !numeric, timeout, &append_port, ppc);
1524 * Check if the given port is plausible (must be either our listen
1525 * port or our advertised port), or any port if we are behind NAT
1526 * and do not have a port open. If it is neither, we return
1529 * @param plugin global variables
1530 * @param in_port port number to check
1531 * @return GNUNET_OK if port is either open_port or adv_port
1534 check_port (struct Plugin *plugin, uint16_t in_port)
1536 if ((in_port == plugin->adv_port) || (in_port == plugin->open_port))
1538 return GNUNET_SYSERR;
1543 * Function that will be called to check if a binary address for this
1544 * plugin is well-formed and corresponds to an address for THIS peer
1545 * (as per our configuration). Naturally, if absolutely necessary,
1546 * plugins can be a bit conservative in their answer, but in general
1547 * plugins should make sure that the address does not redirect
1548 * traffic to a 3rd party that might try to man-in-the-middle our
1551 * @param cls closure, our 'struct Plugin*'
1552 * @param addr pointer to the address
1553 * @param addrlen length of addr
1554 * @return GNUNET_OK if this is a plausible address for this peer
1555 * and transport, GNUNET_SYSERR if not
1558 tcp_plugin_check_address (void *cls, const void *addr, size_t addrlen)
1560 struct Plugin *plugin = cls;
1561 struct IPv4TcpAddress *v4;
1562 struct IPv6TcpAddress *v6;
1564 if ((addrlen != sizeof (struct IPv4TcpAddress)) &&
1565 (addrlen != sizeof (struct IPv6TcpAddress)))
1567 GNUNET_break_op (0);
1568 return GNUNET_SYSERR;
1570 if (addrlen == sizeof (struct IPv4TcpAddress))
1572 v4 = (struct IPv4TcpAddress *) addr;
1573 if (GNUNET_OK != check_port (plugin, ntohs (v4->t4_port)))
1574 return GNUNET_SYSERR;
1576 GNUNET_NAT_test_address (plugin->nat, &v4->ipv4_addr,
1577 sizeof (struct in_addr)))
1578 return GNUNET_SYSERR;
1582 v6 = (struct IPv6TcpAddress *) addr;
1583 if (IN6_IS_ADDR_LINKLOCAL (&v6->ipv6_addr))
1585 GNUNET_break_op (0);
1586 return GNUNET_SYSERR;
1588 if (GNUNET_OK != check_port (plugin, ntohs (v6->t6_port)))
1589 return GNUNET_SYSERR;
1591 GNUNET_NAT_test_address (plugin->nat, &v6->ipv6_addr,
1592 sizeof (struct in6_addr)))
1593 return GNUNET_SYSERR;
1600 * We've received a nat probe from this peer via TCP. Finish
1601 * creating the client session and resume sending of queued
1604 * @param cls closure
1605 * @param client identification of the client
1606 * @param message the actual message
1609 handle_tcp_nat_probe (void *cls, struct GNUNET_SERVER_Client *client,
1610 const struct GNUNET_MessageHeader *message)
1612 struct Plugin *plugin = cls;
1613 struct Session *session;
1614 const struct TCP_NAT_ProbeMessage *tcp_nat_probe;
1617 struct IPv4TcpAddress *t4;
1618 struct IPv6TcpAddress *t6;
1619 const struct sockaddr_in *s4;
1620 const struct sockaddr_in6 *s6;
1622 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp", "received NAT probe\n");
1624 /* We have received a TCP NAT probe, meaning we (hopefully) initiated
1625 * a connection to this peer by running gnunet-nat-client. This peer
1626 * received the punch message and now wants us to use the new connection
1627 * as the default for that peer. Do so and then send a WELCOME message
1628 * so we can really be connected!
1630 if (ntohs (message->size) != sizeof (struct TCP_NAT_ProbeMessage))
1632 GNUNET_break_op (0);
1633 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1637 tcp_nat_probe = (const struct TCP_NAT_ProbeMessage *) message;
1639 memcmp (&tcp_nat_probe->clientIdentity, plugin->env->my_identity,
1640 sizeof (struct GNUNET_PeerIdentity)))
1642 /* refuse connections from ourselves */
1643 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1648 GNUNET_CONTAINER_multihashmap_get (plugin->nat_wait_conns,
1650 clientIdentity.hashPubKey);
1651 if (session == NULL)
1653 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1654 "Did NOT find session for NAT probe!\n");
1655 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1658 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1659 "Found session for NAT probe!\n");
1661 if (session->nat_connection_timeout != GNUNET_SCHEDULER_NO_TASK)
1663 GNUNET_SCHEDULER_cancel (session->nat_connection_timeout);
1664 session->nat_connection_timeout = GNUNET_SCHEDULER_NO_TASK;
1667 GNUNET_assert (GNUNET_CONTAINER_multihashmap_remove
1668 (plugin->nat_wait_conns,
1669 &tcp_nat_probe->clientIdentity.hashPubKey,
1670 session) == GNUNET_YES);
1671 if (GNUNET_OK != GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
1674 GNUNET_free (session);
1675 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1679 GNUNET_SERVER_client_keep (client);
1680 session->client = client;
1681 session->last_activity = GNUNET_TIME_absolute_get ();
1682 session->inbound = GNUNET_NO;
1685 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1686 "Found address `%s' for incoming connection\n",
1687 GNUNET_a2s (vaddr, alen));
1689 switch (((const struct sockaddr *) vaddr)->sa_family)
1693 t4 = GNUNET_malloc (sizeof (struct IPv4TcpAddress));
1694 t4->t4_port = s4->sin_port;
1695 t4->ipv4_addr = s4->sin_addr.s_addr;
1697 session->addrlen = sizeof (struct IPv4TcpAddress);
1701 t6 = GNUNET_malloc (sizeof (struct IPv6TcpAddress));
1702 t6->t6_port = s6->sin6_port;
1703 memcpy (&t6->ipv6_addr, &s6->sin6_addr, sizeof (struct in6_addr));
1705 session->addrlen = sizeof (struct IPv6TcpAddress);
1708 GNUNET_break_op (0);
1710 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1711 "Bad address for incoming connection!\n");
1712 GNUNET_free (vaddr);
1714 GNUNET_SERVER_client_drop (client);
1715 GNUNET_free (session);
1716 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1719 GNUNET_free (vaddr);
1721 GNUNET_CONTAINER_multihashmap_put(plugin->sessionmap, &session->target.hashPubKey, session, GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
1722 inc_sessions (plugin, session, __LINE__);
1723 GNUNET_STATISTICS_update (plugin->env->stats,
1724 gettext_noop ("# TCP sessions active"), 1,
1726 process_pending_messages (session);
1727 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1732 * We've received a welcome from this peer via TCP. Possibly create a
1733 * fresh client record and send back our welcome.
1735 * @param cls closure
1736 * @param client identification of the client
1737 * @param message the actual message
1740 handle_tcp_welcome (void *cls, struct GNUNET_SERVER_Client *client,
1741 const struct GNUNET_MessageHeader *message)
1743 struct Plugin *plugin = cls;
1744 const struct WelcomeMessage *wm = (const struct WelcomeMessage *) message;
1745 struct Session *session;
1748 struct IPv4TcpAddress *t4;
1749 struct IPv6TcpAddress *t6;
1750 const struct sockaddr_in *s4;
1751 const struct sockaddr_in6 *s6;
1754 memcmp (&wm->clientIdentity, plugin->env->my_identity,
1755 sizeof (struct GNUNET_PeerIdentity)))
1757 /* refuse connections from ourselves */
1758 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1762 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1763 "Received %s message from `%4s'\n", "WELCOME",
1764 GNUNET_i2s (&wm->clientIdentity));
1765 GNUNET_STATISTICS_update (plugin->env->stats,
1766 gettext_noop ("# TCP WELCOME messages received"), 1,
1769 session = lookup_session_by_client (plugin, client);
1770 if (session != NULL)
1772 if (GNUNET_OK == GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
1774 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1775 "Found existing session %p for peer `%s'\n",
1777 GNUNET_a2s (vaddr, alen));
1778 GNUNET_free (vaddr);
1783 GNUNET_SERVER_client_keep (client);
1784 session = create_session (plugin, &wm->clientIdentity, client, GNUNET_NO);
1785 session->inbound = GNUNET_YES;
1787 if (GNUNET_OK == GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
1789 if (alen == sizeof (struct sockaddr_in))
1792 t4 = GNUNET_malloc (sizeof (struct IPv4TcpAddress));
1793 t4->t4_port = s4->sin_port;
1794 t4->ipv4_addr = s4->sin_addr.s_addr;
1796 session->addrlen = sizeof (struct IPv4TcpAddress);
1798 else if (alen == sizeof (struct sockaddr_in6))
1801 t6 = GNUNET_malloc (sizeof (struct IPv6TcpAddress));
1802 t6->t6_port = s6->sin6_port;
1803 memcpy (&t6->ipv6_addr, &s6->sin6_addr, sizeof (struct in6_addr));
1805 session->addrlen = sizeof (struct IPv6TcpAddress);
1808 struct GNUNET_ATS_Information ats;
1809 ats = plugin->env->get_address_type (plugin->env->cls, vaddr ,alen);
1810 session->ats_address_network_type = ats.value;
1812 GNUNET_free (vaddr);
1817 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1818 "Did not obtain TCP socket address for incoming connection\n");
1821 GNUNET_CONTAINER_multihashmap_put(plugin->sessionmap, &wm->clientIdentity.hashPubKey, session, GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
1822 inc_sessions (plugin, session, __LINE__);
1825 if (session->expecting_welcome != GNUNET_YES)
1827 GNUNET_break_op (0);
1828 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1831 session->last_activity = GNUNET_TIME_absolute_get ();
1832 session->expecting_welcome = GNUNET_NO;
1835 process_pending_messages (session);
1837 GNUNET_SERVER_client_set_timeout (client,
1838 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1839 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1844 * Task to signal the server that we can continue
1845 * receiving from the TCP client now.
1847 * @param cls the 'struct Session*'
1848 * @param tc task context (unused)
1851 delayed_done (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1853 struct Session *session = cls;
1854 struct GNUNET_TIME_Relative delay;
1855 struct GNUNET_ATS_Information ats;
1857 session->receive_delay_task = GNUNET_SCHEDULER_NO_TASK;
1859 session->plugin->env->receive (session->plugin->env->cls,
1860 &session->target, NULL, &ats, 0, session,
1862 if (delay.rel_value == 0)
1863 GNUNET_SERVER_receive_done (session->client, GNUNET_OK);
1865 session->receive_delay_task =
1866 GNUNET_SCHEDULER_add_delayed (delay, &delayed_done, session);
1871 * We've received data for this peer via TCP. Unbox,
1872 * compute latency and forward.
1874 * @param cls closure
1875 * @param client identification of the client
1876 * @param message the actual message
1879 handle_tcp_data (void *cls, struct GNUNET_SERVER_Client *client,
1880 const struct GNUNET_MessageHeader *message)
1882 struct Plugin *plugin = cls;
1883 struct Session *session;
1884 struct GNUNET_TIME_Relative delay;
1887 type = ntohs (message->type);
1888 if ((GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME == type) ||
1889 (GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE == type))
1891 /* We don't want to propagate WELCOME and NAT Probe messages up! */
1892 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1895 session = lookup_session_by_client (plugin, client);
1896 if (NULL == session)
1898 /* No inbound session found */
1901 GNUNET_SERVER_client_get_address (client, &vaddr, &alen);
1902 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, "tcp",
1903 "Received unexpected %u bytes of type %u from `%s'\n",
1904 (unsigned int) ntohs (message->size),
1905 (unsigned int) ntohs (message->type),
1906 GNUNET_a2s(vaddr, alen));
1907 GNUNET_break_op (0);
1908 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1911 else if (GNUNET_YES == session->expecting_welcome)
1913 /* Session is expecting WELCOME message */
1916 GNUNET_SERVER_client_get_address (client, &vaddr, &alen);
1917 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, "tcp",
1918 "Received unexpected %u bytes of type %u from `%s'\n",
1919 (unsigned int) ntohs (message->size),
1920 (unsigned int) ntohs (message->type),
1921 GNUNET_a2s(vaddr, alen));
1922 GNUNET_break_op (0);
1923 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1927 session->last_activity = GNUNET_TIME_absolute_get ();
1929 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1930 "Passing %u bytes of type %u from `%4s' to transport service.\n",
1931 (unsigned int) ntohs (message->size),
1932 (unsigned int) ntohs (message->type),
1933 GNUNET_i2s (&session->target));
1935 GNUNET_STATISTICS_update (plugin->env->stats,
1936 gettext_noop ("# bytes received via TCP"),
1937 ntohs (message->size), GNUNET_NO);
1938 struct GNUNET_ATS_Information distance[2];
1940 distance[0].type = htonl (GNUNET_ATS_QUALITY_NET_DISTANCE);
1941 distance[0].value = htonl (1);
1942 distance[1].type = htonl (GNUNET_ATS_NETWORK_TYPE);
1943 distance[1].value = session->ats_address_network_type;
1944 GNUNET_break (ntohl(session->ats_address_network_type) != GNUNET_ATS_NET_UNSPECIFIED);
1946 delay = plugin->env->receive (plugin->env->cls,
1949 (const struct GNUNET_ATS_Information *) &distance,
1951 (GNUNET_YES == session->inbound) ? NULL : session->addr,
1952 (GNUNET_YES == session->inbound) ? 0 : session->addrlen);
1953 if (delay.rel_value == 0)
1955 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1960 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1961 "Throttling receiving from `%s' for %llu ms\n",
1962 GNUNET_i2s (&session->target),
1963 (unsigned long long) delay.rel_value);
1965 GNUNET_SERVER_disable_receive_done_warning (client);
1966 session->receive_delay_task =
1967 GNUNET_SCHEDULER_add_delayed (delay, &delayed_done, session);
1973 * Functions with this signature are called whenever a peer
1974 * is disconnected on the network level.
1976 * @param cls closure
1977 * @param client identification of the client
1980 disconnect_notify (void *cls, struct GNUNET_SERVER_Client *client)
1982 struct Plugin *plugin = cls;
1983 struct Session *session;
1987 plugin->max_connections++;
1988 session = lookup_session_by_client (plugin, client);
1989 if (session == NULL)
1990 return; /* unknown, nothing to do */
1992 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1993 "Destroying session of `%4s' with %s due to network-level disconnect.\n",
1994 GNUNET_i2s (&session->target),
1996 NULL) ? tcp_address_to_string (session->plugin,
2001 GNUNET_STATISTICS_update (session->plugin->env->stats,
2003 ("# network-level TCP disconnect events"), 1,
2005 disconnect_session (session);
2010 * We can now send a probe message, copy into buffer to really send.
2012 * @param cls closure, a struct TCPProbeContext
2013 * @param size max size to copy
2014 * @param buf buffer to copy message to
2015 * @return number of bytes copied into buf
2018 notify_send_probe (void *cls, size_t size, void *buf)
2020 struct TCPProbeContext *tcp_probe_ctx = cls;
2021 struct Plugin *plugin = tcp_probe_ctx->plugin;
2024 tcp_probe_ctx->transmit_handle = NULL;
2025 GNUNET_CONTAINER_DLL_remove (plugin->probe_head, plugin->probe_tail,
2029 GNUNET_CONNECTION_destroy (tcp_probe_ctx->sock);
2030 GNUNET_free (tcp_probe_ctx);
2033 GNUNET_assert (size >= sizeof (tcp_probe_ctx->message));
2034 memcpy (buf, &tcp_probe_ctx->message, sizeof (tcp_probe_ctx->message));
2035 GNUNET_SERVER_connect_socket (tcp_probe_ctx->plugin->server,
2036 tcp_probe_ctx->sock);
2037 ret = sizeof (tcp_probe_ctx->message);
2038 GNUNET_free (tcp_probe_ctx);
2044 * Function called by the NAT subsystem suggesting another peer wants
2045 * to connect to us via connection reversal. Try to connect back to the
2048 * @param cls closure
2049 * @param addr address to try
2050 * @param addrlen number of bytes in addr
2053 try_connection_reversal (void *cls, const struct sockaddr *addr,
2056 struct Plugin *plugin = cls;
2057 struct GNUNET_CONNECTION_Handle *sock;
2058 struct TCPProbeContext *tcp_probe_ctx;
2061 * We have received an ICMP response, ostensibly from a peer
2062 * that wants to connect to us! Send a message to establish a connection.
2064 sock = GNUNET_CONNECTION_create_from_sockaddr (AF_INET, addr, addrlen);
2067 /* failed for some odd reason (out of sockets?); ignore attempt */
2071 /* FIXME: do we need to track these probe context objects so that
2072 * we can clean them up on plugin unload? */
2073 tcp_probe_ctx = GNUNET_malloc (sizeof (struct TCPProbeContext));
2074 tcp_probe_ctx->message.header.size =
2075 htons (sizeof (struct TCP_NAT_ProbeMessage));
2076 tcp_probe_ctx->message.header.type =
2077 htons (GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE);
2078 memcpy (&tcp_probe_ctx->message.clientIdentity, plugin->env->my_identity,
2079 sizeof (struct GNUNET_PeerIdentity));
2080 tcp_probe_ctx->plugin = plugin;
2081 tcp_probe_ctx->sock = sock;
2082 GNUNET_CONTAINER_DLL_insert (plugin->probe_head, plugin->probe_tail,
2084 tcp_probe_ctx->transmit_handle =
2085 GNUNET_CONNECTION_notify_transmit_ready (sock,
2086 ntohs (tcp_probe_ctx->
2087 message.header.size),
2088 GNUNET_TIME_UNIT_FOREVER_REL,
2096 * Entry point for the plugin.
2098 * @param cls closure, the 'struct GNUNET_TRANSPORT_PluginEnvironment*'
2099 * @return the 'struct GNUNET_TRANSPORT_PluginFunctions*' or NULL on error
2102 libgnunet_plugin_transport_tcp_init (void *cls)
2104 static const struct GNUNET_SERVER_MessageHandler my_handlers[] = {
2105 {&handle_tcp_welcome, NULL, GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME,
2106 sizeof (struct WelcomeMessage)},
2107 {&handle_tcp_nat_probe, NULL, GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE,
2108 sizeof (struct TCP_NAT_ProbeMessage)},
2109 {&handle_tcp_data, NULL, GNUNET_MESSAGE_TYPE_ALL, 0},
2112 struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
2113 struct GNUNET_TRANSPORT_PluginFunctions *api;
2114 struct Plugin *plugin;
2115 struct GNUNET_SERVICE_Context *service;
2116 unsigned long long aport;
2117 unsigned long long bport;
2118 unsigned long long max_connections;
2120 struct GNUNET_TIME_Relative idle_timeout;
2122 struct sockaddr **addrs;
2123 socklen_t *addrlens;
2125 if (NULL == env->receive)
2127 /* run in 'stub' mode (i.e. as part of gnunet-peerinfo), don't fully
2128 initialze the plugin or the API */
2129 api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
2131 api->address_pretty_printer = &tcp_plugin_address_pretty_printer;
2132 api->address_to_string = &tcp_address_to_string;
2133 api->string_to_address = &tcp_string_to_address;
2138 GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-tcp",
2141 max_connections = 128;
2145 GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-tcp", "PORT",
2146 &bport)) || (bport > 65535) ||
2148 GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-tcp",
2149 "ADVERTISED-PORT", &aport)) &&
2152 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, "tcp",
2154 ("Require valid port number for service `%s' in configuration!\n"),
2164 service = GNUNET_SERVICE_start ("transport-tcp", env->cfg, GNUNET_SERVICE_OPTION_NONE);
2165 if (service == NULL)
2167 GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, "tcp",
2168 _("Failed to start service.\n"));
2175 plugin = GNUNET_malloc (sizeof (struct Plugin));
2176 plugin->sessionmap = GNUNET_CONTAINER_multihashmap_create(max_connections);
2177 plugin->max_connections = max_connections;
2178 plugin->open_port = bport;
2179 plugin->adv_port = aport;
2181 plugin->lsock = NULL;
2182 if ((service != NULL) &&
2185 GNUNET_SERVICE_get_server_addresses ("transport-tcp", env->cfg, &addrs,
2189 GNUNET_NAT_register (env->cfg, GNUNET_YES, aport, (unsigned int) ret,
2190 (const struct sockaddr **) addrs, addrlens,
2191 &tcp_nat_port_map_callback,
2192 &try_connection_reversal, plugin);
2196 GNUNET_assert (addrs[ret] != NULL);
2197 GNUNET_free (addrs[ret]);
2199 GNUNET_free_non_null (addrs);
2200 GNUNET_free_non_null (addrlens);
2205 GNUNET_NAT_register (env->cfg, GNUNET_YES, 0, 0, NULL, NULL, NULL,
2206 &try_connection_reversal, plugin);
2208 api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
2210 api->send = &tcp_plugin_send;
2211 api->get_session = &tcp_plugin_get_session;
2213 api->disconnect = &tcp_plugin_disconnect;
2214 api->address_pretty_printer = &tcp_plugin_address_pretty_printer;
2215 api->check_address = &tcp_plugin_check_address;
2216 api->address_to_string = &tcp_address_to_string;
2217 api->string_to_address = &tcp_string_to_address;
2218 plugin->service = service;
2219 if (service != NULL)
2221 plugin->server = GNUNET_SERVICE_get_server (service);
2226 GNUNET_CONFIGURATION_get_value_time (env->cfg, "transport-tcp",
2227 "TIMEOUT", &idle_timeout))
2229 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, "tcp",
2230 _("Failed to find option %s in section %s!\n"),
2231 "TIMEOUT", "transport-tcp");
2232 if (plugin->nat != NULL)
2233 GNUNET_NAT_unregister (plugin->nat);
2234 GNUNET_free (plugin);
2239 GNUNET_SERVER_create_with_sockets (&plugin_tcp_access_check, plugin,
2240 NULL, idle_timeout, GNUNET_YES);
2242 plugin->handlers = GNUNET_malloc (sizeof (my_handlers));
2243 memcpy (plugin->handlers, my_handlers, sizeof (my_handlers));
2245 i < sizeof (my_handlers) / sizeof (struct GNUNET_SERVER_MessageHandler);
2247 plugin->handlers[i].callback_cls = plugin;
2248 GNUNET_SERVER_add_handlers (plugin->server, plugin->handlers);
2249 GNUNET_SERVER_disconnect_notify (plugin->server, &disconnect_notify, plugin);
2250 plugin->nat_wait_conns = GNUNET_CONTAINER_multihashmap_create (16);
2252 GNUNET_log_from (GNUNET_ERROR_TYPE_INFO, "tcp",
2253 _("TCP transport listening on port %llu\n"), bport);
2255 GNUNET_log_from (GNUNET_ERROR_TYPE_INFO, "tcp",
2257 ("TCP transport not listening on any port (client only)\n"));
2259 GNUNET_log_from (GNUNET_ERROR_TYPE_INFO, "tcp",
2261 ("TCP transport advertises itself as being on port %llu\n"),
2263 /* Initially set connections to 0 */
2264 GNUNET_STATISTICS_set(plugin->env->stats,
2265 gettext_noop ("# TCP sessions active"), 0,
2272 * Exit point from the plugin.
2275 libgnunet_plugin_transport_tcp_done (void *cls)
2277 struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
2278 struct Plugin *plugin = api->cls;
2279 struct TCPProbeContext *tcp_probe;
2286 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp", "Shutting down TCP plugin\n");
2288 /* Removing leftover sessions */
2289 GNUNET_CONTAINER_multihashmap_iterate(plugin->sessionmap, &session_disconnect_it, NULL);
2290 /* Removing leftover NAT sessions */
2291 GNUNET_CONTAINER_multihashmap_iterate(plugin->nat_wait_conns, &session_disconnect_it, NULL);
2293 if (plugin->service != NULL)
2294 GNUNET_SERVICE_stop (plugin->service);
2296 GNUNET_SERVER_destroy (plugin->server);
2297 GNUNET_free (plugin->handlers);
2298 if (plugin->nat != NULL)
2299 GNUNET_NAT_unregister (plugin->nat);
2300 while (NULL != (tcp_probe = plugin->probe_head))
2302 GNUNET_CONTAINER_DLL_remove (plugin->probe_head, plugin->probe_tail,
2304 GNUNET_CONNECTION_destroy (tcp_probe->sock);
2305 GNUNET_free (tcp_probe);
2307 GNUNET_CONTAINER_multihashmap_destroy (plugin->nat_wait_conns);
2308 GNUNET_CONTAINER_multihashmap_destroy (plugin->sessionmap);
2309 GNUNET_free (plugin);
2314 /* end of plugin_transport_tcp.c */