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_CONNECTION_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 * Function to check if an inbound connection is acceptable.
409 * Mostly used to limit the total number of open connections
412 * @param cls the 'struct Plugin'
413 * @param ucred credentials, if available, otherwise NULL
414 * @param addr address
415 * @param addrlen length of address
416 * @return GNUNET_YES to allow, GNUNET_NO to deny, GNUNET_SYSERR
417 * for unknown address family (will be denied).
420 plugin_tcp_access_check (void *cls,
421 const struct GNUNET_CONNECTION_Credentials *ucred,
422 const struct sockaddr *addr, socklen_t addrlen)
424 struct Plugin *plugin = cls;
426 if (0 == plugin->max_connections)
428 plugin->max_connections--;
434 * Our external IP address/port mapping has changed.
436 * @param cls closure, the 'struct LocalAddrList'
437 * @param add_remove GNUNET_YES to mean the new public IP address, GNUNET_NO to mean
438 * the previous (now invalid) one
439 * @param addr either the previous or the new public IP address
440 * @param addrlen actual lenght of the address
443 tcp_nat_port_map_callback (void *cls, int add_remove,
444 const struct sockaddr *addr, socklen_t addrlen)
446 struct Plugin *plugin = cls;
447 struct IPv4TcpAddress t4;
448 struct IPv6TcpAddress t6;
452 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
453 "NPMC called with %d for address `%s'\n", add_remove,
454 GNUNET_a2s (addr, addrlen));
455 /* convert 'addr' to our internal format */
456 switch (addr->sa_family)
459 GNUNET_assert (addrlen == sizeof (struct sockaddr_in));
460 t4.ipv4_addr = ((struct sockaddr_in *) addr)->sin_addr.s_addr;
461 t4.t4_port = ((struct sockaddr_in *) addr)->sin_port;
466 GNUNET_assert (addrlen == sizeof (struct sockaddr_in6));
467 memcpy (&t6.ipv6_addr, &((struct sockaddr_in6 *) addr)->sin6_addr,
468 sizeof (struct in6_addr));
469 t6.t6_port = ((struct sockaddr_in6 *) addr)->sin6_port;
477 /* modify our published address list */
478 plugin->env->notify_address (plugin->env->cls, add_remove, arg, args);
483 * Function called for a quick conversion of the binary address to
484 * a numeric address. Note that the caller must not free the
485 * address and that the next call to this function is allowed
486 * to override the address again.
488 * @param cls closure ('struct Plugin*')
489 * @param addr binary address
490 * @param addrlen length of the address
491 * @return string representing the same address
494 tcp_address_to_string (void *cls, const void *addr, size_t addrlen)
496 static char rbuf[INET6_ADDRSTRLEN + 12];
497 char buf[INET6_ADDRSTRLEN];
501 const struct IPv4TcpAddress *t4;
502 const struct IPv6TcpAddress *t6;
506 if (addrlen == sizeof (struct IPv6TcpAddress))
510 port = ntohs (t6->t6_port);
511 memcpy (&a6, &t6->ipv6_addr, sizeof (a6));
514 else if (addrlen == sizeof (struct IPv4TcpAddress))
518 port = ntohs (t4->t4_port);
519 memcpy (&a4, &t4->ipv4_addr, sizeof (a4));
524 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, "tcp",
525 _("Unexpected address length: %u bytes\n"),
526 (unsigned int) addrlen);
530 if (NULL == inet_ntop (af, sb, buf, INET6_ADDRSTRLEN))
532 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "inet_ntop");
535 GNUNET_snprintf (rbuf, sizeof (rbuf), (af == AF_INET6) ? "[%s]:%u" : "%s:%u",
540 #define MAX_IPV6_ADDRLEN 47
543 tcp_string_to_address_ipv6 (void *cls, const char *addr, uint16_t addrlen,
544 void **buf, size_t *added)
546 char zt_addr[MAX_IPV6_ADDRLEN + 1];
550 struct IPv6TcpAddress *ipv6addr;
553 return GNUNET_SYSERR;
555 memset (zt_addr, 0, MAX_IPV6_ADDRLEN + 1);
556 strncpy (zt_addr, addr, addrlen <= MAX_IPV6_ADDRLEN ? addrlen : MAX_IPV6_ADDRLEN);
558 port_colon = strrchr (zt_addr, ':');
559 if (port_colon == NULL)
560 return GNUNET_SYSERR;
561 ret = sscanf (port_colon, ":%u", &port);
562 if (ret != 1 || port > 65535)
563 return GNUNET_SYSERR;
564 port_colon[0] = '\0';
566 ipv6addr = GNUNET_malloc (sizeof (struct IPv6TcpAddress));
567 ret = inet_pton (AF_INET6, zt_addr, &ipv6addr->ipv6_addr);
570 GNUNET_free (ipv6addr);
571 return GNUNET_SYSERR;
573 ipv6addr->t6_port = port;
575 *added = sizeof (struct IPv6TcpAddress);
579 #define MAX_IPV4_ADDRLEN 21
582 tcp_string_to_address_ipv4 (void *cls, const char *addr, uint16_t addrlen,
583 void **buf, size_t *added)
585 unsigned int temps[5];
588 char zt_addr[MAX_IPV4_ADDRLEN + 1];
589 struct IPv4TcpAddress *ipv4addr;
592 return GNUNET_SYSERR;
594 memset (zt_addr, 0, MAX_IPV4_ADDRLEN + 1);
595 strncpy (zt_addr, addr, addrlen <= MAX_IPV4_ADDRLEN ? addrlen : MAX_IPV4_ADDRLEN);
597 cnt = sscanf (zt_addr, "%u.%u.%u.%u:%u", &temps[0], &temps[1], &temps[2], &temps[3], &port);
599 return GNUNET_SYSERR;
601 for (cnt = 0; cnt < 4; cnt++)
602 if (temps[cnt] > 0xFF)
603 return GNUNET_SYSERR;
605 return GNUNET_SYSERR;
607 ipv4addr = GNUNET_malloc (sizeof (struct IPv4TcpAddress));
608 ipv4addr->ipv4_addr =
609 htonl ((temps[0] << 24) + (temps[1] << 16) + (temps[2] << 8) +
611 ipv4addr->t4_port = htonl (port);
613 *added = sizeof (struct IPv4TcpAddress);
618 * Function called to convert a string address to
621 * @param cls closure ('struct Plugin*')
622 * @param addr string address
623 * @param addrlen length of the address
624 * @param buf location to store the buffer
625 * @param max size of the buffer
626 * @param added location to store the number of bytes in the buffer.
627 * If the function returns GNUNET_SYSERR, its contents are undefined.
628 * @return GNUNET_OK on success, GNUNET_SYSERR on failure
631 tcp_string_to_address (void *cls, const char *addr, uint16_t addrlen,
632 void **buf, size_t *added)
635 return GNUNET_SYSERR;
638 return tcp_string_to_address_ipv6 (cls, addr, addrlen, buf, added);
640 return tcp_string_to_address_ipv4 (cls, addr, addrlen, buf, added);
644 struct SessionClientCtx
646 const struct GNUNET_SERVER_Client *client;
650 int session_lookup_by_client_it (void *cls,
651 const GNUNET_HashCode * key,
654 struct SessionClientCtx *sc_ctx = cls;
655 struct Session *s = value;
657 if (s->client == sc_ctx->client)
666 * Find the session handle for the given client.
668 * @param plugin the plugin
669 * @param client which client to find the session handle for
670 * @return NULL if no matching session exists
672 static struct Session *
673 lookup_session_by_client (struct Plugin *plugin,
674 const struct GNUNET_SERVER_Client *client)
676 struct SessionClientCtx sc_ctx;
677 sc_ctx.client = client;
680 GNUNET_CONTAINER_multihashmap_iterate (plugin->sessionmap, &session_lookup_by_client_it, &sc_ctx);
687 * Create a new session. Also queues a welcome message.
689 * @param plugin the plugin
690 * @param target peer to connect to
691 * @param client client to use
692 * @param is_nat this a NAT session, we should wait for a client to
693 * connect to us from an address, then assign that to
695 * @return new session object
697 static struct Session *
698 create_session (struct Plugin *plugin, const struct GNUNET_PeerIdentity *target,
699 struct GNUNET_SERVER_Client *client, int is_nat)
702 struct PendingMessage *pm;
703 struct WelcomeMessage welcome;
705 if (is_nat != GNUNET_YES)
706 GNUNET_assert (client != NULL);
708 GNUNET_assert (client == NULL);
710 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
711 "Creating new session for peer `%4s'\n",
712 GNUNET_i2s (target));
714 ret = GNUNET_malloc (sizeof (struct Session));
715 ret->last_activity = GNUNET_TIME_absolute_get ();
716 ret->plugin = plugin;
717 ret->is_nat = is_nat;
718 ret->client = client;
719 ret->target = *target;
720 ret->expecting_welcome = GNUNET_YES;
721 ret->ats_address_network_type = htonl (GNUNET_ATS_NET_UNSPECIFIED);
722 pm = GNUNET_malloc (sizeof (struct PendingMessage) +
723 sizeof (struct WelcomeMessage));
724 pm->msg = (const char *) &pm[1];
725 pm->message_size = sizeof (struct WelcomeMessage);
726 welcome.header.size = htons (sizeof (struct WelcomeMessage));
727 welcome.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME);
728 welcome.clientIdentity = *plugin->env->my_identity;
729 memcpy (&pm[1], &welcome, sizeof (welcome));
730 pm->timeout = GNUNET_TIME_UNIT_FOREVER_ABS;
731 GNUNET_STATISTICS_update (plugin->env->stats,
732 gettext_noop ("# bytes currently in TCP buffers"),
733 pm->message_size, GNUNET_NO);
734 GNUNET_CONTAINER_DLL_insert (ret->pending_messages_head,
735 ret->pending_messages_tail, pm);
736 if (is_nat != GNUNET_YES)
737 GNUNET_STATISTICS_update (plugin->env->stats,
738 gettext_noop ("# TCP sessions active"), 1,
745 * If we have pending messages, ask the server to
746 * transmit them (schedule the respective tasks, etc.)
748 * @param session for which session should we do this
751 process_pending_messages (struct Session *session);
755 * Function called to notify a client about the socket
756 * being ready to queue more data. "buf" will be
757 * NULL and "size" zero if the socket was closed for
758 * writing in the meantime.
761 * @param size number of bytes available in buf
762 * @param buf where the callee should write the message
763 * @return number of bytes written to buf
766 do_transmit (void *cls, size_t size, void *buf)
768 struct Session *session = cls;
769 struct GNUNET_PeerIdentity pid;
770 struct Plugin *plugin;
771 struct PendingMessage *pos;
772 struct PendingMessage *hd;
773 struct PendingMessage *tl;
774 struct GNUNET_TIME_Absolute now;
778 GNUNET_assert (session != NULL);
779 session->transmit_handle = NULL;
780 plugin = session->plugin;
784 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
785 "Timeout trying to transmit to peer `%4s', discarding message queue.\n",
786 GNUNET_i2s (&session->target));
788 /* timeout; cancel all messages that have already expired */
792 now = GNUNET_TIME_absolute_get ();
793 while ((NULL != (pos = session->pending_messages_head)) &&
794 (pos->timeout.abs_value <= now.abs_value))
796 GNUNET_CONTAINER_DLL_remove (session->pending_messages_head,
797 session->pending_messages_tail, pos);
799 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
800 "Failed to transmit %u byte message to `%4s'.\n",
801 pos->message_size, GNUNET_i2s (&session->target));
803 ret += pos->message_size;
804 GNUNET_CONTAINER_DLL_insert_after (hd, tl, tl, pos);
806 /* do this call before callbacks (so that if callbacks destroy
807 * session, they have a chance to cancel actions done by this
809 process_pending_messages (session);
810 pid = session->target;
811 /* no do callbacks and do not use session again since
812 * the callbacks may abort the session */
813 while (NULL != (pos = hd))
815 GNUNET_CONTAINER_DLL_remove (hd, tl, pos);
816 if (pos->transmit_cont != NULL)
817 pos->transmit_cont (pos->transmit_cont_cls, &pid, GNUNET_SYSERR);
820 GNUNET_STATISTICS_update (plugin->env->stats,
821 gettext_noop ("# bytes currently in TCP buffers"),
822 -(int64_t) ret, GNUNET_NO);
823 GNUNET_STATISTICS_update (plugin->env->stats,
825 ("# bytes discarded by TCP (timeout)"), ret,
829 /* copy all pending messages that would fit */
834 while (NULL != (pos = session->pending_messages_head))
836 if (ret + pos->message_size > size)
838 GNUNET_CONTAINER_DLL_remove (session->pending_messages_head,
839 session->pending_messages_tail, pos);
840 GNUNET_assert (size >= pos->message_size);
841 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
842 "Transmitting message of type %u\n",
843 ntohs (((struct GNUNET_MessageHeader *) pos->msg)->type));
844 /* FIXME: this memcpy can be up to 7% of our total runtime */
845 memcpy (cbuf, pos->msg, pos->message_size);
846 cbuf += pos->message_size;
847 ret += pos->message_size;
848 size -= pos->message_size;
849 GNUNET_CONTAINER_DLL_insert_tail (hd, tl, pos);
851 /* schedule 'continuation' before callbacks so that callbacks that
852 * cancel everything don't cause us to use a session that no longer
854 process_pending_messages (session);
855 session->last_activity = GNUNET_TIME_absolute_get ();
856 pid = session->target;
857 /* we'll now call callbacks that may cancel the session; hence
858 * we should not use 'session' after this point */
859 while (NULL != (pos = hd))
861 GNUNET_CONTAINER_DLL_remove (hd, tl, pos);
862 if (pos->transmit_cont != NULL)
863 pos->transmit_cont (pos->transmit_cont_cls, &pid, GNUNET_OK);
866 GNUNET_assert (hd == NULL);
867 GNUNET_assert (tl == NULL);
869 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp", "Transmitting %u bytes\n",
872 GNUNET_STATISTICS_update (plugin->env->stats,
873 gettext_noop ("# bytes currently in TCP buffers"),
874 -(int64_t) ret, GNUNET_NO);
875 GNUNET_STATISTICS_update (plugin->env->stats,
876 gettext_noop ("# bytes transmitted via TCP"), ret,
883 * If we have pending messages, ask the server to
884 * transmit them (schedule the respective tasks, etc.)
886 * @param session for which session should we do this
889 process_pending_messages (struct Session *session)
891 struct PendingMessage *pm;
893 GNUNET_assert (session->client != NULL);
894 if (session->transmit_handle != NULL)
896 if (NULL == (pm = session->pending_messages_head))
899 session->transmit_handle =
900 GNUNET_SERVER_notify_transmit_ready (session->client, pm->message_size,
901 GNUNET_TIME_absolute_get_remaining
902 (pm->timeout), &do_transmit,
908 * Functions with this signature are called whenever we need
909 * to close a session due to a disconnect or failure to
910 * establish a connection.
912 * @param session session to close down
915 disconnect_session (struct Session *session)
917 struct PendingMessage *pm;
918 struct Plugin * plugin = session->plugin;
920 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
921 "Disconnecting session %p for peer `%s' address `%s'\n",
923 GNUNET_i2s (&session->target),
924 tcp_address_to_string(NULL, session->addr, session->addrlen));
926 GNUNET_assert (GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(plugin->sessionmap, &session->target.hashPubKey, session) ||
927 GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(plugin->nat_wait_conns, &session->target.hashPubKey, session));
930 if (session->transmit_handle != NULL)
932 GNUNET_CONNECTION_notify_transmit_ready_cancel (session->transmit_handle);
933 session->transmit_handle = NULL;
935 session->plugin->env->session_end (session->plugin->env->cls,
936 &session->target, session);
938 if (session->nat_connection_timeout != GNUNET_SCHEDULER_NO_TASK)
940 GNUNET_SCHEDULER_cancel (session->nat_connection_timeout);
941 session->nat_connection_timeout = GNUNET_SCHEDULER_NO_TASK;
944 while (NULL != (pm = session->pending_messages_head))
947 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
949 NULL ? "Could not deliver message to `%4s'.\n" :
950 "Could not deliver message to `%4s', notifying.\n",
951 GNUNET_i2s (&session->target));
953 GNUNET_STATISTICS_update (session->plugin->env->stats,
954 gettext_noop ("# bytes currently in TCP buffers"),
955 -(int64_t) pm->message_size, GNUNET_NO);
956 GNUNET_STATISTICS_update (session->plugin->env->stats,
958 ("# bytes discarded by TCP (disconnect)"),
959 pm->message_size, GNUNET_NO);
960 GNUNET_CONTAINER_DLL_remove (session->pending_messages_head,
961 session->pending_messages_tail, pm);
962 if (NULL != pm->transmit_cont)
963 pm->transmit_cont (pm->transmit_cont_cls, &session->target,
967 if (session->receive_delay_task != GNUNET_SCHEDULER_NO_TASK)
969 GNUNET_SCHEDULER_cancel (session->receive_delay_task);
970 if (session->client != NULL)
971 GNUNET_SERVER_receive_done (session->client, GNUNET_SYSERR);
973 if (session->client != NULL)
975 GNUNET_SERVER_client_drop (session->client);
976 session->client = NULL;
978 GNUNET_STATISTICS_update (session->plugin->env->stats,
979 gettext_noop ("# TCP sessions active"), -1,
981 GNUNET_free_non_null (session->addr);
982 GNUNET_assert (NULL == session->transmit_handle);
983 GNUNET_free (session);
988 * Function that can be used by the transport service to transmit
989 * a message using the plugin. Note that in the case of a
990 * peer disconnecting, the continuation MUST be called
991 * prior to the disconnect notification itself. This function
992 * will be called with this peer's HELLO message to initiate
993 * a fresh connection to another peer.
996 * @param session which session must be used
997 * @param msgbuf the message to transmit
998 * @param msgbuf_size number of bytes in 'msgbuf'
999 * @param priority how important is the message (most plugins will
1000 * ignore message priority and just FIFO)
1001 * @param to how long to wait at most for the transmission (does not
1002 * require plugins to discard the message after the timeout,
1003 * just advisory for the desired delay; most plugins will ignore
1005 * @param cont continuation to call once the message has
1006 * been transmitted (or if the transport is ready
1007 * for the next transmission call; or if the
1008 * peer disconnected...); can be NULL
1009 * @param cont_cls closure for cont
1010 * @return number of bytes used (on the physical network, with overheads);
1011 * -1 on hard errors (i.e. address invalid); 0 is a legal value
1012 * and does NOT mean that the message was not transmitted (DV)
1015 tcp_plugin_send (void *cls,
1016 struct Session *session,
1017 const char *msgbuf, size_t msgbuf_size,
1018 unsigned int priority,
1019 struct GNUNET_TIME_Relative to,
1020 GNUNET_TRANSPORT_TransmitContinuation cont, void *cont_cls)
1022 struct Plugin * plugin = cls;
1023 struct PendingMessage *pm;
1025 GNUNET_assert (plugin != NULL);
1026 GNUNET_assert (session != NULL);
1028 /* create new message entry */
1029 pm = GNUNET_malloc (sizeof (struct PendingMessage) + msgbuf_size);
1030 pm->msg = (const char *) &pm[1];
1031 memcpy (&pm[1], msgbuf, msgbuf_size);
1032 pm->message_size = msgbuf_size;
1033 pm->timeout = GNUNET_TIME_relative_to_absolute (to);
1034 pm->transmit_cont = cont;
1035 pm->transmit_cont_cls = cont_cls;
1038 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1039 "Asked to transmit %u bytes to `%s', added message to list.\n",
1040 msgbuf_size, GNUNET_i2s (&session->target));
1042 if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains_value(plugin->sessionmap, &session->target.hashPubKey, session))
1044 GNUNET_assert (session->client != NULL);
1046 GNUNET_SERVER_client_set_timeout (session->client,
1047 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1048 GNUNET_STATISTICS_update (plugin->env->stats,
1049 gettext_noop ("# bytes currently in TCP buffers"),
1050 msgbuf_size, GNUNET_NO);
1052 /* append pm to pending_messages list */
1053 GNUNET_CONTAINER_DLL_insert_tail (session->pending_messages_head,
1054 session->pending_messages_tail, pm);
1056 process_pending_messages (session);
1059 else if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains_value(plugin->nat_wait_conns, &session->target.hashPubKey, session))
1061 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1062 "This NAT WAIT session for peer `%s' is not yet ready!\n",
1063 GNUNET_i2s (&session->target));
1065 GNUNET_STATISTICS_update (plugin->env->stats,
1066 gettext_noop ("# bytes currently in TCP buffers"),
1067 msgbuf_size, GNUNET_NO);
1069 /* append pm to pending_messages list */
1070 GNUNET_CONTAINER_DLL_insert_tail (session->pending_messages_head,
1071 session->pending_messages_tail, pm);
1077 cont (cont_cls, &session->target, GNUNET_SYSERR);
1080 return GNUNET_SYSERR; /* session does not exist here */
1088 struct Session * result;
1091 int session_lookup_it (void *cls,
1092 const GNUNET_HashCode * key,
1095 struct SessionItCtx * si_ctx = cls;
1096 struct Session * session = value;
1098 char * a1 = strdup (tcp_address_to_string(NULL, session->addr, session->addrlen));
1099 char * a2 = strdup (tcp_address_to_string(NULL, si_ctx->addr, si_ctx->addrlen));
1100 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, "tcp",
1101 "Comparing: %s %u <-> %s %u\n",
1109 if (session->addrlen != si_ctx->addrlen)
1113 if (0 != memcmp (session->addr, si_ctx->addr, si_ctx->addrlen))
1118 a1 = strdup (tcp_address_to_string(NULL, session->addr, session->addrlen));
1119 a2 = strdup (tcp_address_to_string(NULL, si_ctx->addr, si_ctx->addrlen));
1120 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, "tcp",
1121 "Comparing: %s %u <-> %s %u , OK!\n",
1129 /* Found existing session */
1130 si_ctx->result = session;
1135 * Task cleaning up a NAT connection attempt after timeout
1139 nat_connect_timeout (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1141 struct Session *session = cls;
1143 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1144 "NAT WAIT connection to `%4s' at `%s' could not be established, removing session\n",
1145 GNUNET_i2s (&session->target), tcp_address_to_string(NULL, session->addr, session->addrlen));
1147 disconnect_session (session);
1152 * Create a new session to transmit data to the target
1153 * This session will used to send data to this peer and the plugin will
1154 * notify us by calling the env->session_end function
1156 * @param cls closure
1157 * @param address pointer to the GNUNET_HELLO_Address
1158 * @return the session if the address is valid, NULL otherwise
1160 static struct Session *
1161 tcp_plugin_get_session (void *cls,
1162 const struct GNUNET_HELLO_Address *address)
1164 struct Plugin * plugin = cls;
1165 struct Session * session = NULL;
1170 struct GNUNET_CONNECTION_Handle *sa;
1171 struct sockaddr_in a4;
1172 struct sockaddr_in6 a6;
1173 const struct IPv4TcpAddress *t4;
1174 const struct IPv6TcpAddress *t6;
1175 struct GNUNET_ATS_Information ats;
1176 unsigned int is_natd = GNUNET_NO;
1179 GNUNET_assert (plugin != NULL);
1180 GNUNET_assert (address != NULL);
1182 addrlen = address->address_length;
1184 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1185 "Trying to get session for `%s' address length %i\n",
1186 tcp_address_to_string(NULL, address->address, address->address_length),
1189 /* look for existing session */
1190 if (GNUNET_CONTAINER_multihashmap_contains(plugin->sessionmap, &address->peer.hashPubKey))
1192 struct SessionItCtx si_ctx;
1194 si_ctx.addr = (void *) address->address;
1195 si_ctx.addrlen = address->address_length;
1197 si_ctx.result = NULL;
1199 GNUNET_CONTAINER_multihashmap_get_multiple(plugin->sessionmap, &address->peer.hashPubKey, &session_lookup_it, &si_ctx);
1200 if (si_ctx.result != NULL)
1202 session = si_ctx.result;
1203 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1204 "Found exisiting session for `%s' address `%s' session %p\n",
1205 GNUNET_i2s (&address->peer),
1206 tcp_address_to_string(NULL, address->address, address->address_length),
1212 if (addrlen == sizeof (struct IPv6TcpAddress))
1214 GNUNET_assert (NULL != address->address); /* make static analysis happy */
1215 t6 = address->address;
1217 memset (&a6, 0, sizeof (a6));
1218 #if HAVE_SOCKADDR_IN_SIN_LEN
1219 a6.sin6_len = sizeof (a6);
1221 a6.sin6_family = AF_INET6;
1222 a6.sin6_port = t6->t6_port;
1223 if (t6->t6_port == 0)
1224 is_natd = GNUNET_YES;
1225 memcpy (&a6.sin6_addr, &t6->ipv6_addr, sizeof (struct in6_addr));
1229 else if (addrlen == sizeof (struct IPv4TcpAddress))
1231 GNUNET_assert (NULL != address->address); /* make static analysis happy */
1232 t4 = address->address;
1234 memset (&a4, 0, sizeof (a4));
1235 #if HAVE_SOCKADDR_IN_SIN_LEN
1236 a4.sin_len = sizeof (a4);
1238 a4.sin_family = AF_INET;
1239 a4.sin_port = t4->t4_port;
1240 if (t4->t4_port == 0)
1241 is_natd = GNUNET_YES;
1242 a4.sin_addr.s_addr = t4->ipv4_addr;
1248 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, "tcp",
1249 _("Address of unexpected length: %u\n"), addrlen);
1254 ats = plugin->env->get_address_type (plugin->env->cls, sb ,sbs);
1256 if ((is_natd == GNUNET_YES) && (addrlen == sizeof (struct IPv6TcpAddress)))
1258 /* NAT client only works with IPv4 addresses */
1262 if (0 == plugin->max_connections)
1268 if ((is_natd == GNUNET_YES) &&
1270 GNUNET_CONTAINER_multihashmap_contains (plugin->nat_wait_conns,
1271 &address->peer.hashPubKey)))
1273 /* Only do one NAT punch attempt per peer identity */
1277 if ((is_natd == GNUNET_YES) && (NULL != plugin->nat) &&
1279 GNUNET_CONTAINER_multihashmap_contains (plugin->nat_wait_conns,
1280 &address->peer.hashPubKey)))
1283 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1284 _("Found valid IPv4 NAT address (creating session)!\n"));
1286 session = create_session (plugin, &address->peer, NULL, GNUNET_YES);
1287 session->addrlen = 0;
1288 session->addr = NULL;
1289 session->ats_address_network_type = ats.value;
1290 session->nat_connection_timeout = GNUNET_SCHEDULER_add_delayed(NAT_TIMEOUT,
1291 &nat_connect_timeout,
1293 GNUNET_assert (session != NULL);
1295 GNUNET_assert (GNUNET_CONTAINER_multihashmap_put
1296 (plugin->nat_wait_conns, &address->peer.hashPubKey, session,
1297 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY) == GNUNET_OK);
1299 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1300 "Created NAT WAIT connection to `%4s' at `%s'\n",
1301 GNUNET_i2s (&session->target), GNUNET_a2s (sb, sbs));
1303 if (GNUNET_OK == GNUNET_NAT_run_client (plugin->nat, &a4))
1307 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1308 "Running NAT client for `%4s' at `%s' failed\n",
1309 GNUNET_i2s (&session->target), GNUNET_a2s (sb, sbs));
1311 disconnect_session (session);
1316 /* create new outbound session */
1317 GNUNET_assert (0 != plugin->max_connections);
1318 sa = GNUNET_CONNECTION_create_from_sockaddr (af, sb, sbs);
1322 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1323 "Failed to create connection to `%4s' at `%s'\n",
1324 GNUNET_i2s (&session->target), GNUNET_a2s (sb, sbs));
1328 plugin->max_connections--;
1330 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1331 "Asked to transmit to `%4s', creating fresh session using address `%s'.\n",
1332 GNUNET_i2s (&address->peer), GNUNET_a2s (sb, sbs));
1334 session = create_session (plugin,
1336 GNUNET_SERVER_connect_socket (plugin->server, sa),
1338 session->addr = GNUNET_malloc (addrlen);
1339 memcpy (session->addr, address->address, addrlen);
1340 session->addrlen = addrlen;
1341 session->ats_address_network_type = ats.value;
1343 GNUNET_CONTAINER_multihashmap_put(plugin->sessionmap, &address->peer.hashPubKey, session, GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
1345 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1346 "Creating new session for `%s' address `%s' session %p\n",
1347 GNUNET_i2s (&address->peer),
1348 tcp_address_to_string(NULL, address->address, address->address_length),
1351 /* Send TCP Welcome */
1352 process_pending_messages (session);
1358 int session_disconnect_it (void *cls,
1359 const GNUNET_HashCode * key,
1362 struct Session *session = value;
1364 GNUNET_STATISTICS_update (session->plugin->env->stats,
1366 ("# transport-service disconnect requests for TCP"),
1368 disconnect_session (session);
1373 * Function that can be called to force a disconnect from the
1374 * specified neighbour. This should also cancel all previously
1375 * scheduled transmissions. Obviously the transmission may have been
1376 * partially completed already, which is OK. The plugin is supposed
1377 * to close the connection (if applicable) and no longer call the
1378 * transmit continuation(s).
1380 * Finally, plugin MUST NOT call the services's receive function to
1381 * notify the service that the connection to the specified target was
1382 * closed after a getting this call.
1384 * @param cls closure
1385 * @param target peer for which the last transmission is
1389 tcp_plugin_disconnect (void *cls, const struct GNUNET_PeerIdentity *target)
1391 struct Plugin *plugin = cls;
1392 struct Session *nat_session = NULL;
1394 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1395 "Disconnecting peer `%4s'\n", GNUNET_i2s (target));
1397 GNUNET_CONTAINER_multihashmap_get_multiple (plugin->sessionmap, &target->hashPubKey, session_disconnect_it, plugin);
1399 nat_session = GNUNET_CONTAINER_multihashmap_get(plugin->nat_wait_conns, &target->hashPubKey);
1400 if (nat_session != NULL)
1402 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1403 "Cleaning up pending NAT session for peer `%4s'\n", GNUNET_i2s (target));
1404 disconnect_session (nat_session);
1410 * Context for address to string conversion.
1412 struct PrettyPrinterContext
1415 * Function to call with the result.
1417 GNUNET_TRANSPORT_AddressStringCallback asc;
1420 * Clsoure for 'asc'.
1425 * Port to add after the IP address.
1432 * Append our port and forward the result.
1434 * @param cls the 'struct PrettyPrinterContext*'
1435 * @param hostname hostname part of the address
1438 append_port (void *cls, const char *hostname)
1440 struct PrettyPrinterContext *ppc = cls;
1443 if (hostname == NULL)
1445 ppc->asc (ppc->asc_cls, NULL);
1449 GNUNET_asprintf (&ret, "%s:%d", hostname, ppc->port);
1450 ppc->asc (ppc->asc_cls, ret);
1456 * Convert the transports address to a nice, human-readable
1459 * @param cls closure
1460 * @param type name of the transport that generated the address
1461 * @param addr one of the addresses of the host, NULL for the last address
1462 * the specific address format depends on the transport
1463 * @param addrlen length of the address
1464 * @param numeric should (IP) addresses be displayed in numeric form?
1465 * @param timeout after how long should we give up?
1466 * @param asc function to call on each string
1467 * @param asc_cls closure for asc
1470 tcp_plugin_address_pretty_printer (void *cls, const char *type,
1471 const void *addr, size_t addrlen,
1473 struct GNUNET_TIME_Relative timeout,
1474 GNUNET_TRANSPORT_AddressStringCallback asc,
1477 struct PrettyPrinterContext *ppc;
1480 struct sockaddr_in a4;
1481 struct sockaddr_in6 a6;
1482 const struct IPv4TcpAddress *t4;
1483 const struct IPv6TcpAddress *t6;
1486 if (addrlen == sizeof (struct IPv6TcpAddress))
1489 memset (&a6, 0, sizeof (a6));
1490 a6.sin6_family = AF_INET6;
1491 a6.sin6_port = t6->t6_port;
1492 memcpy (&a6.sin6_addr, &t6->ipv6_addr, sizeof (struct in6_addr));
1493 port = ntohs (t6->t6_port);
1497 else if (addrlen == sizeof (struct IPv4TcpAddress))
1500 memset (&a4, 0, sizeof (a4));
1501 a4.sin_family = AF_INET;
1502 a4.sin_port = t4->t4_port;
1503 a4.sin_addr.s_addr = t4->ipv4_addr;
1504 port = ntohs (t4->t4_port);
1510 /* invalid address */
1511 GNUNET_break_op (0);
1512 asc (asc_cls, NULL);
1515 ppc = GNUNET_malloc (sizeof (struct PrettyPrinterContext));
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);
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);
1824 if (session->expecting_welcome != GNUNET_YES)
1826 GNUNET_break_op (0);
1827 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1830 session->last_activity = GNUNET_TIME_absolute_get ();
1831 session->expecting_welcome = GNUNET_NO;
1834 process_pending_messages (session);
1836 GNUNET_SERVER_client_set_timeout (client,
1837 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1838 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1843 * Task to signal the server that we can continue
1844 * receiving from the TCP client now.
1846 * @param cls the 'struct Session*'
1847 * @param tc task context (unused)
1850 delayed_done (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1852 struct Session *session = cls;
1853 struct GNUNET_TIME_Relative delay;
1854 struct GNUNET_ATS_Information ats;
1856 session->receive_delay_task = GNUNET_SCHEDULER_NO_TASK;
1858 session->plugin->env->receive (session->plugin->env->cls,
1859 &session->target, NULL, &ats, 0, session,
1861 if (delay.rel_value == 0)
1862 GNUNET_SERVER_receive_done (session->client, GNUNET_OK);
1864 session->receive_delay_task =
1865 GNUNET_SCHEDULER_add_delayed (delay, &delayed_done, session);
1870 * We've received data for this peer via TCP. Unbox,
1871 * compute latency and forward.
1873 * @param cls closure
1874 * @param client identification of the client
1875 * @param message the actual message
1878 handle_tcp_data (void *cls, struct GNUNET_SERVER_Client *client,
1879 const struct GNUNET_MessageHeader *message)
1881 struct Plugin *plugin = cls;
1882 struct Session *session;
1883 struct GNUNET_TIME_Relative delay;
1886 type = ntohs (message->type);
1887 if ((GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME == type) ||
1888 (GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE == type))
1890 /* We don't want to propagate WELCOME and NAT Probe messages up! */
1891 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1894 session = lookup_session_by_client (plugin, client);
1895 if (NULL == session)
1897 /* No inbound session found */
1898 GNUNET_break_op (0);
1899 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1902 else if (GNUNET_YES == session->expecting_welcome)
1904 /* Session is expecting WELCOME message */
1905 GNUNET_break_op (0);
1906 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1910 session->last_activity = GNUNET_TIME_absolute_get ();
1912 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1913 "Passing %u bytes of type %u from `%4s' to transport service.\n",
1914 (unsigned int) ntohs (message->size),
1915 (unsigned int) ntohs (message->type),
1916 GNUNET_i2s (&session->target));
1918 GNUNET_STATISTICS_update (plugin->env->stats,
1919 gettext_noop ("# bytes received via TCP"),
1920 ntohs (message->size), GNUNET_NO);
1921 struct GNUNET_ATS_Information distance[2];
1923 distance[0].type = htonl (GNUNET_ATS_QUALITY_NET_DISTANCE);
1924 distance[0].value = htonl (1);
1925 distance[1].type = htonl (GNUNET_ATS_NETWORK_TYPE);
1926 distance[1].value = session->ats_address_network_type;
1927 GNUNET_break (ntohl(session->ats_address_network_type) != GNUNET_ATS_NET_UNSPECIFIED);
1929 delay = plugin->env->receive (plugin->env->cls,
1932 (const struct GNUNET_ATS_Information *) &distance,
1934 (GNUNET_YES == session->inbound) ? NULL : session->addr,
1935 (GNUNET_YES == session->inbound) ? 0 : session->addrlen);
1936 if (delay.rel_value == 0)
1938 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1943 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1944 "Throttling receiving from `%s' for %llu ms\n",
1945 GNUNET_i2s (&session->target),
1946 (unsigned long long) delay.rel_value);
1948 GNUNET_SERVER_disable_receive_done_warning (client);
1949 session->receive_delay_task =
1950 GNUNET_SCHEDULER_add_delayed (delay, &delayed_done, session);
1956 * Functions with this signature are called whenever a peer
1957 * is disconnected on the network level.
1959 * @param cls closure
1960 * @param client identification of the client
1963 disconnect_notify (void *cls, struct GNUNET_SERVER_Client *client)
1965 struct Plugin *plugin = cls;
1966 struct Session *session;
1970 plugin->max_connections++;
1971 session = lookup_session_by_client (plugin, client);
1972 if (session == NULL)
1973 return; /* unknown, nothing to do */
1975 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1976 "Destroying session of `%4s' with %s due to network-level disconnect.\n",
1977 GNUNET_i2s (&session->target),
1979 NULL) ? tcp_address_to_string (session->plugin,
1984 GNUNET_STATISTICS_update (session->plugin->env->stats,
1986 ("# network-level TCP disconnect events"), 1,
1988 disconnect_session (session);
1993 * We can now send a probe message, copy into buffer to really send.
1995 * @param cls closure, a struct TCPProbeContext
1996 * @param size max size to copy
1997 * @param buf buffer to copy message to
1998 * @return number of bytes copied into buf
2001 notify_send_probe (void *cls, size_t size, void *buf)
2003 struct TCPProbeContext *tcp_probe_ctx = cls;
2004 struct Plugin *plugin = tcp_probe_ctx->plugin;
2007 tcp_probe_ctx->transmit_handle = NULL;
2008 GNUNET_CONTAINER_DLL_remove (plugin->probe_head, plugin->probe_tail,
2012 GNUNET_CONNECTION_destroy (tcp_probe_ctx->sock, GNUNET_NO);
2013 GNUNET_free (tcp_probe_ctx);
2016 GNUNET_assert (size >= sizeof (tcp_probe_ctx->message));
2017 memcpy (buf, &tcp_probe_ctx->message, sizeof (tcp_probe_ctx->message));
2018 GNUNET_SERVER_connect_socket (tcp_probe_ctx->plugin->server,
2019 tcp_probe_ctx->sock);
2020 ret = sizeof (tcp_probe_ctx->message);
2021 GNUNET_free (tcp_probe_ctx);
2027 * Function called by the NAT subsystem suggesting another peer wants
2028 * to connect to us via connection reversal. Try to connect back to the
2031 * @param cls closure
2032 * @param addr address to try
2033 * @param addrlen number of bytes in addr
2036 try_connection_reversal (void *cls, const struct sockaddr *addr,
2039 struct Plugin *plugin = cls;
2040 struct GNUNET_CONNECTION_Handle *sock;
2041 struct TCPProbeContext *tcp_probe_ctx;
2044 * We have received an ICMP response, ostensibly from a peer
2045 * that wants to connect to us! Send a message to establish a connection.
2047 sock = GNUNET_CONNECTION_create_from_sockaddr (AF_INET, addr, addrlen);
2050 /* failed for some odd reason (out of sockets?); ignore attempt */
2054 /* FIXME: do we need to track these probe context objects so that
2055 * we can clean them up on plugin unload? */
2056 tcp_probe_ctx = GNUNET_malloc (sizeof (struct TCPProbeContext));
2057 tcp_probe_ctx->message.header.size =
2058 htons (sizeof (struct TCP_NAT_ProbeMessage));
2059 tcp_probe_ctx->message.header.type =
2060 htons (GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE);
2061 memcpy (&tcp_probe_ctx->message.clientIdentity, plugin->env->my_identity,
2062 sizeof (struct GNUNET_PeerIdentity));
2063 tcp_probe_ctx->plugin = plugin;
2064 tcp_probe_ctx->sock = sock;
2065 GNUNET_CONTAINER_DLL_insert (plugin->probe_head, plugin->probe_tail,
2067 tcp_probe_ctx->transmit_handle =
2068 GNUNET_CONNECTION_notify_transmit_ready (sock,
2069 ntohs (tcp_probe_ctx->
2070 message.header.size),
2071 GNUNET_TIME_UNIT_FOREVER_REL,
2079 * Entry point for the plugin.
2081 * @param cls closure, the 'struct GNUNET_TRANSPORT_PluginEnvironment*'
2082 * @return the 'struct GNUNET_TRANSPORT_PluginFunctions*' or NULL on error
2085 libgnunet_plugin_transport_tcp_init (void *cls)
2087 static const struct GNUNET_SERVER_MessageHandler my_handlers[] = {
2088 {&handle_tcp_welcome, NULL, GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME,
2089 sizeof (struct WelcomeMessage)},
2090 {&handle_tcp_nat_probe, NULL, GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE,
2091 sizeof (struct TCP_NAT_ProbeMessage)},
2092 {&handle_tcp_data, NULL, GNUNET_MESSAGE_TYPE_ALL, 0},
2095 struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
2096 struct GNUNET_TRANSPORT_PluginFunctions *api;
2097 struct Plugin *plugin;
2098 struct GNUNET_SERVICE_Context *service;
2099 unsigned long long aport;
2100 unsigned long long bport;
2101 unsigned long long max_connections;
2103 struct GNUNET_TIME_Relative idle_timeout;
2105 struct sockaddr **addrs;
2106 socklen_t *addrlens;
2108 if (NULL == env->receive)
2110 /* run in 'stub' mode (i.e. as part of gnunet-peerinfo), don't fully
2111 initialze the plugin or the API */
2112 api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
2114 api->address_pretty_printer = &tcp_plugin_address_pretty_printer;
2115 api->address_to_string = &tcp_address_to_string;
2116 api->string_to_address = &tcp_string_to_address;
2121 GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-tcp",
2124 max_connections = 128;
2128 GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-tcp", "PORT",
2129 &bport)) || (bport > 65535) ||
2131 GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-tcp",
2132 "ADVERTISED-PORT", &aport)) &&
2135 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, "tcp",
2137 ("Require valid port number for service `%s' in configuration!\n"),
2147 service = GNUNET_SERVICE_start ("transport-tcp", env->cfg);
2148 if (service == NULL)
2150 GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, "tcp",
2151 _("Failed to start service.\n"));
2158 plugin = GNUNET_malloc (sizeof (struct Plugin));
2159 plugin->sessionmap = GNUNET_CONTAINER_multihashmap_create(max_connections);
2160 plugin->max_connections = max_connections;
2161 plugin->open_port = bport;
2162 plugin->adv_port = aport;
2164 plugin->lsock = NULL;
2165 if ((service != NULL) &&
2168 GNUNET_SERVICE_get_server_addresses ("transport-tcp", env->cfg, &addrs,
2172 GNUNET_NAT_register (env->cfg, GNUNET_YES, aport, (unsigned int) ret,
2173 (const struct sockaddr **) addrs, addrlens,
2174 &tcp_nat_port_map_callback,
2175 &try_connection_reversal, plugin);
2179 GNUNET_assert (addrs[ret] != NULL);
2180 GNUNET_free (addrs[ret]);
2182 GNUNET_free_non_null (addrs);
2183 GNUNET_free_non_null (addrlens);
2188 GNUNET_NAT_register (env->cfg, GNUNET_YES, 0, 0, NULL, NULL, NULL,
2189 &try_connection_reversal, plugin);
2191 api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
2193 api->send = &tcp_plugin_send;
2194 api->get_session = &tcp_plugin_get_session;
2196 api->disconnect = &tcp_plugin_disconnect;
2197 api->address_pretty_printer = &tcp_plugin_address_pretty_printer;
2198 api->check_address = &tcp_plugin_check_address;
2199 api->address_to_string = &tcp_address_to_string;
2200 api->string_to_address = &tcp_string_to_address;
2201 plugin->service = service;
2202 if (service != NULL)
2204 plugin->server = GNUNET_SERVICE_get_server (service);
2209 GNUNET_CONFIGURATION_get_value_time (env->cfg, "transport-tcp",
2210 "TIMEOUT", &idle_timeout))
2212 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, "tcp",
2213 _("Failed to find option %s in section %s!\n"),
2214 "TIMEOUT", "transport-tcp");
2215 if (plugin->nat != NULL)
2216 GNUNET_NAT_unregister (plugin->nat);
2217 GNUNET_free (plugin);
2222 GNUNET_SERVER_create_with_sockets (&plugin_tcp_access_check, plugin,
2223 NULL, idle_timeout, GNUNET_YES);
2225 plugin->handlers = GNUNET_malloc (sizeof (my_handlers));
2226 memcpy (plugin->handlers, my_handlers, sizeof (my_handlers));
2228 i < sizeof (my_handlers) / sizeof (struct GNUNET_SERVER_MessageHandler);
2230 plugin->handlers[i].callback_cls = plugin;
2231 GNUNET_SERVER_add_handlers (plugin->server, plugin->handlers);
2232 GNUNET_SERVER_disconnect_notify (plugin->server, &disconnect_notify, plugin);
2233 plugin->nat_wait_conns = GNUNET_CONTAINER_multihashmap_create (16);
2235 GNUNET_log_from (GNUNET_ERROR_TYPE_INFO, "tcp",
2236 _("TCP transport listening on port %llu\n"), bport);
2238 GNUNET_log_from (GNUNET_ERROR_TYPE_INFO, "tcp",
2240 ("TCP transport not listening on any port (client only)\n"));
2242 GNUNET_log_from (GNUNET_ERROR_TYPE_INFO, "tcp",
2244 ("TCP transport advertises itself as being on port %llu\n"),
2251 * Exit point from the plugin.
2254 libgnunet_plugin_transport_tcp_done (void *cls)
2256 struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
2257 struct Plugin *plugin = api->cls;
2258 struct TCPProbeContext *tcp_probe;
2265 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp", "Shutting down TCP plugin\n");
2267 /* Removing leftover sessions */
2268 GNUNET_CONTAINER_multihashmap_iterate(plugin->sessionmap, &session_disconnect_it, NULL);
2269 /* Removing leftover NAT sessions */
2270 GNUNET_CONTAINER_multihashmap_iterate(plugin->nat_wait_conns, &session_disconnect_it, NULL);
2272 if (plugin->service != NULL)
2273 GNUNET_SERVICE_stop (plugin->service);
2275 GNUNET_SERVER_destroy (plugin->server);
2276 GNUNET_free (plugin->handlers);
2277 if (plugin->nat != NULL)
2278 GNUNET_NAT_unregister (plugin->nat);
2279 while (NULL != (tcp_probe = plugin->probe_head))
2281 GNUNET_CONTAINER_DLL_remove (plugin->probe_head, plugin->probe_tail,
2283 GNUNET_CONNECTION_destroy (tcp_probe->sock, GNUNET_NO);
2284 GNUNET_free (tcp_probe);
2286 GNUNET_CONTAINER_multihashmap_destroy (plugin->nat_wait_conns);
2287 GNUNET_CONTAINER_multihashmap_destroy (plugin->sessionmap);
2288 GNUNET_free (plugin);
2293 /* end of plugin_transport_tcp.c */