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"
44 * How long until we give up on establishing an NAT connection?
47 #define NAT_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 10)
50 GNUNET_NETWORK_STRUCT_BEGIN
53 * Initial handshake message for a session.
58 * Type is GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME.
60 struct GNUNET_MessageHeader header;
63 * Identity of the node connecting (TCP client)
65 struct GNUNET_PeerIdentity clientIdentity;
71 * Basically a WELCOME message, but with the purpose
72 * of giving the waiting peer a client handle to use
74 struct TCP_NAT_ProbeMessage
77 * Type is GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE.
79 struct GNUNET_MessageHeader header;
82 * Identity of the sender of the message.
84 struct GNUNET_PeerIdentity clientIdentity;
87 GNUNET_NETWORK_STRUCT_END
90 * Context for sending a NAT probe via TCP.
92 struct TCPProbeContext
96 * Active probes are kept in a DLL.
98 struct TCPProbeContext *next;
101 * Active probes are kept in a DLL.
103 struct TCPProbeContext *prev;
108 struct GNUNET_CONNECTION_Handle *sock;
111 * Message to be sent.
113 struct TCP_NAT_ProbeMessage message;
116 * Handle to the transmission.
118 struct GNUNET_CONNECTION_TransmitHandle *transmit_handle;
121 * Transport plugin handle.
123 struct Plugin *plugin;
127 GNUNET_NETWORK_STRUCT_BEGIN
130 * Network format for IPv4 addresses.
132 struct IPv4TcpAddress
135 * IPv4 address, in network byte order.
137 uint32_t ipv4_addr GNUNET_PACKED;
140 * Port number, in network byte order.
142 uint16_t t4_port GNUNET_PACKED;
148 * Network format for IPv6 addresses.
150 struct IPv6TcpAddress
155 struct in6_addr ipv6_addr GNUNET_PACKED;
158 * Port number, in network byte order.
160 uint16_t t6_port GNUNET_PACKED;
163 GNUNET_NETWORK_STRUCT_END
166 * Encapsulation of all of the state of the plugin.
172 * Information kept for each message that is yet to
175 struct PendingMessage
179 * This is a doubly-linked list.
181 struct PendingMessage *next;
184 * This is a doubly-linked list.
186 struct PendingMessage *prev;
189 * The pending message
194 * Continuation function to call once the message
195 * has been sent. Can be NULL if there is no
196 * continuation to call.
198 GNUNET_TRANSPORT_TransmitContinuation transmit_cont;
201 * Closure for transmit_cont.
203 void *transmit_cont_cls;
206 * Timeout value for the pending message.
208 struct GNUNET_TIME_Absolute timeout;
211 * So that the gnunet-service-transport can group messages together,
212 * these pending messages need to accept a message buffer and size
213 * instead of just a GNUNET_MessageHeader.
221 * Session handle for TCP connections.
229 struct SessionHeader header;
232 * Stored in a linked list.
234 struct Session *next;
237 * Pointer to the global plugin struct.
239 struct Plugin *plugin;
242 * The client (used to identify this connection)
244 struct GNUNET_SERVER_Client *client;
247 * Task cleaning up a NAT client connection establishment attempt;
249 GNUNET_SCHEDULER_TaskIdentifier nat_connection_timeout;
252 * Messages currently pending for transmission
253 * to this peer, if any.
255 struct PendingMessage *pending_messages_head;
258 * Messages currently pending for transmission
259 * to this peer, if any.
261 struct PendingMessage *pending_messages_tail;
264 * Handle for pending transmission request.
266 struct GNUNET_SERVER_TransmitHandle *transmit_handle;
269 * To whom are we talking to (set to our identity
270 * if we are still waiting for the welcome message)
272 struct GNUNET_PeerIdentity target;
275 * ID of task used to delay receiving more to throttle sender.
277 GNUNET_SCHEDULER_TaskIdentifier receive_delay_task;
280 * Address of the other peer (either based on our 'connect'
281 * call or on our 'accept' call).
283 * struct IPv4TcpAddress or struct IPv6TcpAddress
289 * Length of connect_addr.
294 * Last activity on this connection. Used to select preferred
297 struct GNUNET_TIME_Absolute last_activity;
300 * Are we still expecting the welcome message? (GNUNET_YES/GNUNET_NO)
302 int expecting_welcome;
305 * Was this a connection that was inbound (we accepted)? (GNUNET_YES/GNUNET_NO)
310 * Was this session created using NAT traversal?
315 * ATS network type in NBO
317 uint32_t ats_address_network_type;
322 * Encapsulation of all of the state of the plugin.
329 struct GNUNET_TRANSPORT_PluginEnvironment *env;
334 struct GNUNET_CONNECTION_Handle *lsock;
337 * Our handle to the NAT module.
339 struct GNUNET_NAT_Handle *nat;
341 struct GNUNET_CONTAINER_MultiHashMap * sessionmap;
344 * Handle to the network service.
346 struct GNUNET_SERVICE_Context *service;
349 * Handle to the server for this service.
351 struct GNUNET_SERVER_Handle *server;
354 * Copy of the handler array where the closures are
355 * set to this struct's instance.
357 struct GNUNET_SERVER_MessageHandler *handlers;
360 * Map of peers we have tried to contact behind a NAT
362 struct GNUNET_CONTAINER_MultiHashMap *nat_wait_conns;
365 * List of active TCP probes.
367 struct TCPProbeContext *probe_head;
370 * List of active TCP probes.
372 struct TCPProbeContext *probe_tail;
375 * Handle for (DYN)DNS lookup of our external IP.
377 struct GNUNET_RESOLVER_RequestHandle *ext_dns;
380 * How many more TCP sessions are we allowed to open right now?
382 unsigned long long max_connections;
385 * ID of task used to update our addresses when one expires.
387 GNUNET_SCHEDULER_TaskIdentifier address_update_task;
390 * Port that we are actually listening on.
395 * Port that the user said we would have visible to the
404 tcp_address_to_string (void *cls, const void *addr, size_t addrlen);
406 static unsigned int sessions;
408 static void inc_sessions (struct Plugin *plugin, struct Session *session, int line)
411 unsigned int size = GNUNET_CONTAINER_multihashmap_size(plugin->sessionmap);
412 if (sessions != size)
413 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp", "Inconsistent sessions %u <-> session map size: %u\n",
415 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp", "%4i Session increased to %u (session map size: %u): `%s' `%s'\n",
419 GNUNET_i2s (&session->target),
420 tcp_address_to_string (NULL, session->addr, session->addrlen));
423 static void dec_sessions (struct Plugin *plugin, struct Session *session, int line)
425 GNUNET_assert (sessions > 0);
426 unsigned int size = GNUNET_CONTAINER_multihashmap_size(plugin->sessionmap);
428 if (sessions != size)
429 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp", "Inconsistent sessions %u <-> session map size: %u\n",
431 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp", "%4i Session decreased to %u (session map size: %u): `%s' `%s'\n",
435 GNUNET_i2s (&session->target),
436 tcp_address_to_string (NULL, session->addr, session->addrlen));
442 * Function to check if an inbound connection is acceptable.
443 * Mostly used to limit the total number of open connections
446 * @param cls the 'struct Plugin'
447 * @param ucred credentials, if available, otherwise NULL
448 * @param addr address
449 * @param addrlen length of address
450 * @return GNUNET_YES to allow, GNUNET_NO to deny, GNUNET_SYSERR
451 * for unknown address family (will be denied).
454 plugin_tcp_access_check (void *cls,
455 const struct GNUNET_CONNECTION_Credentials *ucred,
456 const struct sockaddr *addr, socklen_t addrlen)
458 struct Plugin *plugin = cls;
460 if (0 == plugin->max_connections)
462 plugin->max_connections--;
468 * Our external IP address/port mapping has changed.
470 * @param cls closure, the 'struct LocalAddrList'
471 * @param add_remove GNUNET_YES to mean the new public IP address, GNUNET_NO to mean
472 * the previous (now invalid) one
473 * @param addr either the previous or the new public IP address
474 * @param addrlen actual lenght of the address
477 tcp_nat_port_map_callback (void *cls, int add_remove,
478 const struct sockaddr *addr, socklen_t addrlen)
480 struct Plugin *plugin = cls;
481 struct IPv4TcpAddress t4;
482 struct IPv6TcpAddress t6;
486 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
487 "NPMC called with %d for address `%s'\n", add_remove,
488 GNUNET_a2s (addr, addrlen));
489 /* convert 'addr' to our internal format */
490 switch (addr->sa_family)
493 GNUNET_assert (addrlen == sizeof (struct sockaddr_in));
494 t4.ipv4_addr = ((struct sockaddr_in *) addr)->sin_addr.s_addr;
495 t4.t4_port = ((struct sockaddr_in *) addr)->sin_port;
500 GNUNET_assert (addrlen == sizeof (struct sockaddr_in6));
501 memcpy (&t6.ipv6_addr, &((struct sockaddr_in6 *) addr)->sin6_addr,
502 sizeof (struct in6_addr));
503 t6.t6_port = ((struct sockaddr_in6 *) addr)->sin6_port;
511 /* modify our published address list */
512 plugin->env->notify_address (plugin->env->cls, add_remove, arg, args);
517 * Function called for a quick conversion of the binary address to
518 * a numeric address. Note that the caller must not free the
519 * address and that the next call to this function is allowed
520 * to override the address again.
522 * @param cls closure ('struct Plugin*')
523 * @param addr binary address
524 * @param addrlen length of the address
525 * @return string representing the same address
528 tcp_address_to_string (void *cls, const void *addr, size_t addrlen)
530 static char rbuf[INET6_ADDRSTRLEN + 12];
531 char buf[INET6_ADDRSTRLEN];
535 const struct IPv4TcpAddress *t4;
536 const struct IPv6TcpAddress *t6;
540 if (addrlen == sizeof (struct IPv6TcpAddress))
544 port = ntohs (t6->t6_port);
545 memcpy (&a6, &t6->ipv6_addr, sizeof (a6));
548 else if (addrlen == sizeof (struct IPv4TcpAddress))
552 port = ntohs (t4->t4_port);
553 memcpy (&a4, &t4->ipv4_addr, sizeof (a4));
558 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, "tcp",
559 _("Unexpected address length: %u bytes\n"),
560 (unsigned int) addrlen);
564 if (NULL == inet_ntop (af, sb, buf, INET6_ADDRSTRLEN))
566 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "inet_ntop");
569 GNUNET_snprintf (rbuf, sizeof (rbuf), (af == AF_INET6) ? "[%s]:%u" : "%s:%u",
576 * Function called to convert a string address to
579 * @param cls closure ('struct Plugin*')
580 * @param addr string address
581 * @param addrlen length of the address
582 * @param buf location to store the buffer
583 * @param added location to store the number of bytes in the buffer.
584 * If the function returns GNUNET_SYSERR, its contents are undefined.
585 * @return GNUNET_OK on success, GNUNET_SYSERR on failure
588 tcp_string_to_address (void *cls, const char *addr, uint16_t addrlen,
589 void **buf, size_t *added)
591 struct sockaddr_storage socket_address;
593 if ((NULL == addr) || (addrlen == 0))
596 return GNUNET_SYSERR;
599 if ('\0' != addr[addrlen - 1])
602 return GNUNET_SYSERR;
605 if (strlen (addr) != addrlen - 1)
608 return GNUNET_SYSERR;
611 int ret = GNUNET_STRINGS_to_address_ip (addr, strlen (addr),
614 if (ret != GNUNET_OK)
617 return GNUNET_SYSERR;
620 if (socket_address.ss_family == AF_INET)
622 struct IPv4TcpAddress *t4;
623 struct sockaddr_in *in4 = (struct sockaddr_in *) &socket_address;
624 t4 = GNUNET_malloc (sizeof (struct IPv4TcpAddress));
625 t4->ipv4_addr = in4->sin_addr.s_addr;
626 t4->t4_port = in4->sin_port;
628 *added = sizeof (struct IPv4TcpAddress);
631 else if (socket_address.ss_family == AF_INET6)
633 struct IPv6TcpAddress *t6;
634 struct sockaddr_in6 *in6 = (struct sockaddr_in6 *) &socket_address;
635 t6 = GNUNET_malloc (sizeof (struct IPv6TcpAddress));
636 t6->ipv6_addr = in6->sin6_addr;
637 t6->t6_port = in6->sin6_port;
639 *added = sizeof (struct IPv6TcpAddress);
642 return GNUNET_SYSERR;
646 struct SessionClientCtx
648 const struct GNUNET_SERVER_Client *client;
652 int session_lookup_by_client_it (void *cls,
653 const GNUNET_HashCode * key,
656 struct SessionClientCtx *sc_ctx = cls;
657 struct Session *s = value;
659 if (s->client == sc_ctx->client)
668 * Find the session handle for the given client.
670 * @param plugin the plugin
671 * @param client which client to find the session handle for
672 * @return NULL if no matching session exists
674 static struct Session *
675 lookup_session_by_client (struct Plugin *plugin,
676 const struct GNUNET_SERVER_Client *client)
678 struct SessionClientCtx sc_ctx;
679 sc_ctx.client = client;
682 GNUNET_CONTAINER_multihashmap_iterate (plugin->sessionmap, &session_lookup_by_client_it, &sc_ctx);
689 * Create a new session. Also queues a welcome message.
691 * @param plugin the plugin
692 * @param target peer to connect to
693 * @param client client to use
694 * @param is_nat this a NAT session, we should wait for a client to
695 * connect to us from an address, then assign that to
697 * @return new session object
699 static struct Session *
700 create_session (struct Plugin *plugin, const struct GNUNET_PeerIdentity *target,
701 struct GNUNET_SERVER_Client *client, int is_nat)
704 struct PendingMessage *pm;
705 struct WelcomeMessage welcome;
707 if (is_nat != GNUNET_YES)
708 GNUNET_assert (client != NULL);
710 GNUNET_assert (client == NULL);
712 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
713 "Creating new session for peer `%4s'\n",
714 GNUNET_i2s (target));
716 ret = GNUNET_malloc (sizeof (struct Session));
717 ret->last_activity = GNUNET_TIME_absolute_get ();
718 ret->plugin = plugin;
719 ret->is_nat = is_nat;
720 ret->client = client;
721 ret->target = *target;
722 ret->expecting_welcome = GNUNET_YES;
723 ret->ats_address_network_type = htonl (GNUNET_ATS_NET_UNSPECIFIED);
724 pm = GNUNET_malloc (sizeof (struct PendingMessage) +
725 sizeof (struct WelcomeMessage));
726 pm->msg = (const char *) &pm[1];
727 pm->message_size = sizeof (struct WelcomeMessage);
728 welcome.header.size = htons (sizeof (struct WelcomeMessage));
729 welcome.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME);
730 welcome.clientIdentity = *plugin->env->my_identity;
731 memcpy (&pm[1], &welcome, sizeof (welcome));
732 pm->timeout = GNUNET_TIME_UNIT_FOREVER_ABS;
733 GNUNET_STATISTICS_update (plugin->env->stats,
734 gettext_noop ("# bytes currently in TCP buffers"),
735 pm->message_size, GNUNET_NO);
736 GNUNET_CONTAINER_DLL_insert (ret->pending_messages_head,
737 ret->pending_messages_tail, pm);
738 if (is_nat != GNUNET_YES)
740 GNUNET_STATISTICS_update (plugin->env->stats,
741 gettext_noop ("# TCP sessions active"), 1,
749 * If we have pending messages, ask the server to
750 * transmit them (schedule the respective tasks, etc.)
752 * @param session for which session should we do this
755 process_pending_messages (struct Session *session);
759 * Function called to notify a client about the socket
760 * being ready to queue more data. "buf" will be
761 * NULL and "size" zero if the socket was closed for
762 * writing in the meantime.
765 * @param size number of bytes available in buf
766 * @param buf where the callee should write the message
767 * @return number of bytes written to buf
770 do_transmit (void *cls, size_t size, void *buf)
772 struct Session *session = cls;
773 struct GNUNET_PeerIdentity pid;
774 struct Plugin *plugin;
775 struct PendingMessage *pos;
776 struct PendingMessage *hd;
777 struct PendingMessage *tl;
778 struct GNUNET_TIME_Absolute now;
782 GNUNET_assert (session != NULL);
783 session->transmit_handle = NULL;
784 plugin = session->plugin;
787 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
788 "Timeout trying to transmit to peer `%4s', discarding message queue.\n",
789 GNUNET_i2s (&session->target));
790 /* timeout; cancel all messages that have already expired */
794 now = GNUNET_TIME_absolute_get ();
795 while ((NULL != (pos = session->pending_messages_head)) &&
796 (pos->timeout.abs_value <= now.abs_value))
798 GNUNET_CONTAINER_DLL_remove (session->pending_messages_head,
799 session->pending_messages_tail, pos);
800 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
801 "Failed to transmit %u byte message to `%4s'.\n",
802 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);
868 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp", "Transmitting %u bytes\n",
870 GNUNET_STATISTICS_update (plugin->env->stats,
871 gettext_noop ("# bytes currently in TCP buffers"),
872 -(int64_t) ret, GNUNET_NO);
873 GNUNET_STATISTICS_update (plugin->env->stats,
874 gettext_noop ("# bytes transmitted via TCP"), ret,
881 * If we have pending messages, ask the server to
882 * transmit them (schedule the respective tasks, etc.)
884 * @param session for which session should we do this
887 process_pending_messages (struct Session *session)
889 struct PendingMessage *pm;
891 GNUNET_assert (session->client != NULL);
892 if (session->transmit_handle != NULL)
894 if (NULL == (pm = session->pending_messages_head))
897 session->transmit_handle =
898 GNUNET_SERVER_notify_transmit_ready (session->client, pm->message_size,
899 GNUNET_TIME_absolute_get_remaining
900 (pm->timeout), &do_transmit,
906 * Functions with this signature are called whenever we need
907 * to close a session due to a disconnect or failure to
908 * establish a connection.
910 * @param session session to close down
913 disconnect_session (struct Session *session)
915 struct PendingMessage *pm;
916 struct Plugin * plugin = session->plugin;
918 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
919 "Disconnecting session %p for peer `%s' address `%s'\n",
921 GNUNET_i2s (&session->target),
922 tcp_address_to_string(NULL, session->addr, session->addrlen));
924 if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(plugin->sessionmap, &session->target.hashPubKey, session))
926 GNUNET_STATISTICS_update (session->plugin->env->stats,
927 gettext_noop ("# TCP sessions active"), -1,
929 dec_sessions (plugin, session, __LINE__);
931 else GNUNET_assert (GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(plugin->nat_wait_conns, &session->target.hashPubKey, session));
934 if (session->transmit_handle != NULL)
936 GNUNET_SERVER_notify_transmit_ready_cancel (session->transmit_handle);
937 session->transmit_handle = NULL;
939 session->plugin->env->session_end (session->plugin->env->cls,
940 &session->target, session);
942 if (session->nat_connection_timeout != GNUNET_SCHEDULER_NO_TASK)
944 GNUNET_SCHEDULER_cancel (session->nat_connection_timeout);
945 session->nat_connection_timeout = GNUNET_SCHEDULER_NO_TASK;
948 while (NULL != (pm = session->pending_messages_head))
950 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
952 NULL ? "Could not deliver message to `%4s'.\n" :
953 "Could not deliver message to `%4s', notifying.\n",
954 GNUNET_i2s (&session->target));
955 GNUNET_STATISTICS_update (session->plugin->env->stats,
956 gettext_noop ("# bytes currently in TCP buffers"),
957 -(int64_t) pm->message_size, GNUNET_NO);
958 GNUNET_STATISTICS_update (session->plugin->env->stats,
960 ("# bytes discarded by TCP (disconnect)"),
961 pm->message_size, GNUNET_NO);
962 GNUNET_CONTAINER_DLL_remove (session->pending_messages_head,
963 session->pending_messages_tail, pm);
964 if (NULL != pm->transmit_cont)
965 pm->transmit_cont (pm->transmit_cont_cls, &session->target,
969 if (session->receive_delay_task != GNUNET_SCHEDULER_NO_TASK)
971 GNUNET_SCHEDULER_cancel (session->receive_delay_task);
972 if (session->client != NULL)
973 GNUNET_SERVER_receive_done (session->client, GNUNET_SYSERR);
975 if (session->client != NULL)
977 GNUNET_SERVER_client_drop (session->client);
978 session->client = NULL;
982 GNUNET_free_non_null (session->addr);
983 GNUNET_assert (NULL == session->transmit_handle);
984 GNUNET_free (session);
989 * Function that can be used by the transport service to transmit
990 * a message using the plugin. Note that in the case of a
991 * peer disconnecting, the continuation MUST be called
992 * prior to the disconnect notification itself. This function
993 * will be called with this peer's HELLO message to initiate
994 * a fresh connection to another peer.
997 * @param session which session must be used
998 * @param msgbuf the message to transmit
999 * @param msgbuf_size number of bytes in 'msgbuf'
1000 * @param priority how important is the message (most plugins will
1001 * ignore message priority and just FIFO)
1002 * @param to how long to wait at most for the transmission (does not
1003 * require plugins to discard the message after the timeout,
1004 * just advisory for the desired delay; most plugins will ignore
1006 * @param cont continuation to call once the message has
1007 * been transmitted (or if the transport is ready
1008 * for the next transmission call; or if the
1009 * peer disconnected...); can be NULL
1010 * @param cont_cls closure for cont
1011 * @return number of bytes used (on the physical network, with overheads);
1012 * -1 on hard errors (i.e. address invalid); 0 is a legal value
1013 * and does NOT mean that the message was not transmitted (DV)
1016 tcp_plugin_send (void *cls,
1017 struct Session *session,
1018 const char *msgbuf, size_t msgbuf_size,
1019 unsigned int priority,
1020 struct GNUNET_TIME_Relative to,
1021 GNUNET_TRANSPORT_TransmitContinuation cont, void *cont_cls)
1023 struct Plugin * plugin = cls;
1024 struct PendingMessage *pm;
1026 GNUNET_assert (plugin != NULL);
1027 GNUNET_assert (session != NULL);
1029 /* create new message entry */
1030 pm = GNUNET_malloc (sizeof (struct PendingMessage) + msgbuf_size);
1031 pm->msg = (const char *) &pm[1];
1032 memcpy (&pm[1], msgbuf, msgbuf_size);
1033 pm->message_size = msgbuf_size;
1034 pm->timeout = GNUNET_TIME_relative_to_absolute (to);
1035 pm->transmit_cont = cont;
1036 pm->transmit_cont_cls = cont_cls;
1039 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1040 "Asked to transmit %u bytes to `%s', added message to list.\n",
1041 msgbuf_size, GNUNET_i2s (&session->target));
1043 if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains_value(plugin->sessionmap, &session->target.hashPubKey, session))
1045 GNUNET_assert (session->client != NULL);
1047 GNUNET_SERVER_client_set_timeout (session->client,
1048 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1049 GNUNET_STATISTICS_update (plugin->env->stats,
1050 gettext_noop ("# bytes currently in TCP buffers"),
1051 msgbuf_size, GNUNET_NO);
1053 /* append pm to pending_messages list */
1054 GNUNET_CONTAINER_DLL_insert_tail (session->pending_messages_head,
1055 session->pending_messages_tail, pm);
1057 process_pending_messages (session);
1060 else if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains_value(plugin->nat_wait_conns, &session->target.hashPubKey, session))
1062 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1063 "This NAT WAIT session for peer `%s' is not yet ready!\n",
1064 GNUNET_i2s (&session->target));
1066 GNUNET_STATISTICS_update (plugin->env->stats,
1067 gettext_noop ("# bytes currently in TCP buffers"),
1068 msgbuf_size, GNUNET_NO);
1070 /* append pm to pending_messages list */
1071 GNUNET_CONTAINER_DLL_insert_tail (session->pending_messages_head,
1072 session->pending_messages_tail, pm);
1078 cont (cont_cls, &session->target, GNUNET_SYSERR);
1081 return GNUNET_SYSERR; /* session does not exist here */
1089 struct Session * result;
1092 int session_lookup_it (void *cls,
1093 const GNUNET_HashCode * key,
1096 struct SessionItCtx * si_ctx = cls;
1097 struct Session * session = value;
1099 char * a1 = strdup (tcp_address_to_string(NULL, session->addr, session->addrlen));
1100 char * a2 = strdup (tcp_address_to_string(NULL, si_ctx->addr, si_ctx->addrlen));
1101 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, "tcp",
1102 "Comparing: %s %u <-> %s %u\n",
1110 if (session->addrlen != si_ctx->addrlen)
1114 if (0 != memcmp (session->addr, si_ctx->addr, si_ctx->addrlen))
1119 a1 = strdup (tcp_address_to_string(NULL, session->addr, session->addrlen));
1120 a2 = strdup (tcp_address_to_string(NULL, si_ctx->addr, si_ctx->addrlen));
1121 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, "tcp",
1122 "Comparing: %s %u <-> %s %u , OK!\n",
1130 /* Found existing session */
1131 si_ctx->result = session;
1136 * Task cleaning up a NAT connection attempt after timeout
1140 nat_connect_timeout (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1142 struct Session *session = cls;
1144 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1145 "NAT WAIT connection to `%4s' at `%s' could not be established, removing session\n",
1146 GNUNET_i2s (&session->target), tcp_address_to_string(NULL, session->addr, session->addrlen));
1148 disconnect_session (session);
1153 * Create a new session to transmit data to the target
1154 * This session will used to send data to this peer and the plugin will
1155 * notify us by calling the env->session_end function
1157 * @param cls closure
1158 * @param address pointer to the GNUNET_HELLO_Address
1159 * @return the session if the address is valid, NULL otherwise
1161 static struct Session *
1162 tcp_plugin_get_session (void *cls,
1163 const struct GNUNET_HELLO_Address *address)
1165 struct Plugin * plugin = cls;
1166 struct Session * session = NULL;
1171 struct GNUNET_CONNECTION_Handle *sa;
1172 struct sockaddr_in a4;
1173 struct sockaddr_in6 a6;
1174 const struct IPv4TcpAddress *t4;
1175 const struct IPv6TcpAddress *t6;
1176 struct GNUNET_ATS_Information ats;
1177 unsigned int is_natd = GNUNET_NO;
1180 GNUNET_assert (plugin != NULL);
1181 GNUNET_assert (address != NULL);
1183 addrlen = address->address_length;
1185 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1186 "Trying to get session for `%s' address length %i\n",
1187 tcp_address_to_string(NULL, address->address, address->address_length),
1190 /* look for existing session */
1191 if (GNUNET_CONTAINER_multihashmap_contains(plugin->sessionmap, &address->peer.hashPubKey))
1193 struct SessionItCtx si_ctx;
1195 si_ctx.addr = (void *) address->address;
1196 si_ctx.addrlen = address->address_length;
1198 si_ctx.result = NULL;
1200 GNUNET_CONTAINER_multihashmap_get_multiple(plugin->sessionmap, &address->peer.hashPubKey, &session_lookup_it, &si_ctx);
1201 if (si_ctx.result != NULL)
1203 session = si_ctx.result;
1204 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1205 "Found exisiting session for `%s' address `%s' session %p\n",
1206 GNUNET_i2s (&address->peer),
1207 tcp_address_to_string(NULL, address->address, address->address_length),
1213 if (addrlen == sizeof (struct IPv6TcpAddress))
1215 GNUNET_assert (NULL != address->address); /* make static analysis happy */
1216 t6 = address->address;
1218 memset (&a6, 0, sizeof (a6));
1219 #if HAVE_SOCKADDR_IN_SIN_LEN
1220 a6.sin6_len = sizeof (a6);
1222 a6.sin6_family = AF_INET6;
1223 a6.sin6_port = t6->t6_port;
1224 if (t6->t6_port == 0)
1225 is_natd = GNUNET_YES;
1226 memcpy (&a6.sin6_addr, &t6->ipv6_addr, sizeof (struct in6_addr));
1230 else if (addrlen == sizeof (struct IPv4TcpAddress))
1232 GNUNET_assert (NULL != address->address); /* make static analysis happy */
1233 t4 = address->address;
1235 memset (&a4, 0, sizeof (a4));
1236 #if HAVE_SOCKADDR_IN_SIN_LEN
1237 a4.sin_len = sizeof (a4);
1239 a4.sin_family = AF_INET;
1240 a4.sin_port = t4->t4_port;
1241 if (t4->t4_port == 0)
1242 is_natd = GNUNET_YES;
1243 a4.sin_addr.s_addr = t4->ipv4_addr;
1249 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, "tcp",
1250 _("Address of unexpected length: %u\n"), addrlen);
1255 ats = plugin->env->get_address_type (plugin->env->cls, sb ,sbs);
1257 if ((is_natd == GNUNET_YES) && (addrlen == sizeof (struct IPv6TcpAddress)))
1259 /* NAT client only works with IPv4 addresses */
1263 if (0 == plugin->max_connections)
1269 if ((is_natd == GNUNET_YES) &&
1271 GNUNET_CONTAINER_multihashmap_contains (plugin->nat_wait_conns,
1272 &address->peer.hashPubKey)))
1274 /* Only do one NAT punch attempt per peer identity */
1278 if ((is_natd == GNUNET_YES) && (NULL != plugin->nat) &&
1280 GNUNET_CONTAINER_multihashmap_contains (plugin->nat_wait_conns,
1281 &address->peer.hashPubKey)))
1283 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1284 _("Found valid IPv4 NAT address (creating session)!\n"));
1285 session = create_session (plugin, &address->peer, NULL, GNUNET_YES);
1286 session->addrlen = 0;
1287 session->addr = NULL;
1288 session->ats_address_network_type = ats.value;
1289 session->nat_connection_timeout = GNUNET_SCHEDULER_add_delayed(NAT_TIMEOUT,
1290 &nat_connect_timeout,
1292 GNUNET_assert (session != NULL);
1294 GNUNET_assert (GNUNET_CONTAINER_multihashmap_put
1295 (plugin->nat_wait_conns, &address->peer.hashPubKey, session,
1296 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY) == GNUNET_OK);
1298 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1299 "Created NAT WAIT connection to `%4s' at `%s'\n",
1300 GNUNET_i2s (&session->target), GNUNET_a2s (sb, sbs));
1302 if (GNUNET_OK == GNUNET_NAT_run_client (plugin->nat, &a4))
1306 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1307 "Running NAT client for `%4s' at `%s' failed\n",
1308 GNUNET_i2s (&session->target), GNUNET_a2s (sb, sbs));
1310 disconnect_session (session);
1315 /* create new outbound session */
1316 GNUNET_assert (0 != plugin->max_connections);
1317 sa = GNUNET_CONNECTION_create_from_sockaddr (af, sb, sbs);
1320 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1321 "Failed to create connection to `%4s' at `%s'\n",
1322 GNUNET_i2s (&session->target), GNUNET_a2s (sb, sbs));
1325 plugin->max_connections--;
1327 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1328 "Asked to transmit to `%4s', creating fresh session using address `%s'.\n",
1329 GNUNET_i2s (&address->peer), GNUNET_a2s (sb, sbs));
1331 session = create_session (plugin,
1333 GNUNET_SERVER_connect_socket (plugin->server, sa),
1335 session->addr = GNUNET_malloc (addrlen);
1336 memcpy (session->addr, address->address, addrlen);
1337 session->addrlen = addrlen;
1338 session->ats_address_network_type = ats.value;
1340 GNUNET_CONTAINER_multihashmap_put(plugin->sessionmap, &address->peer.hashPubKey, session, GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
1341 inc_sessions (plugin, session, __LINE__);
1342 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1343 "Creating new session for `%s' address `%s' session %p\n",
1344 GNUNET_i2s (&address->peer),
1345 tcp_address_to_string(NULL, address->address, address->address_length),
1348 /* Send TCP Welcome */
1349 process_pending_messages (session);
1355 int session_disconnect_it (void *cls,
1356 const GNUNET_HashCode * key,
1359 struct Session *session = value;
1361 GNUNET_STATISTICS_update (session->plugin->env->stats,
1363 ("# transport-service disconnect requests for TCP"),
1365 disconnect_session (session);
1370 * Function that can be called to force a disconnect from the
1371 * specified neighbour. This should also cancel all previously
1372 * scheduled transmissions. Obviously the transmission may have been
1373 * partially completed already, which is OK. The plugin is supposed
1374 * to close the connection (if applicable) and no longer call the
1375 * transmit continuation(s).
1377 * Finally, plugin MUST NOT call the services's receive function to
1378 * notify the service that the connection to the specified target was
1379 * closed after a getting this call.
1381 * @param cls closure
1382 * @param target peer for which the last transmission is
1386 tcp_plugin_disconnect (void *cls, const struct GNUNET_PeerIdentity *target)
1388 struct Plugin *plugin = cls;
1389 struct Session *nat_session = NULL;
1391 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1392 "Disconnecting peer `%4s'\n", GNUNET_i2s (target));
1394 GNUNET_CONTAINER_multihashmap_get_multiple (plugin->sessionmap, &target->hashPubKey, session_disconnect_it, plugin);
1396 nat_session = GNUNET_CONTAINER_multihashmap_get(plugin->nat_wait_conns, &target->hashPubKey);
1397 if (nat_session != NULL)
1399 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1400 "Cleaning up pending NAT session for peer `%4s'\n", GNUNET_i2s (target));
1401 disconnect_session (nat_session);
1407 * Context for address to string conversion.
1409 struct PrettyPrinterContext
1412 * Function to call with the result.
1414 GNUNET_TRANSPORT_AddressStringCallback asc;
1417 * Clsoure for 'asc'.
1422 * Port to add after the IP address.
1431 * Append our port and forward the result.
1433 * @param cls the 'struct PrettyPrinterContext*'
1434 * @param hostname hostname part of the address
1437 append_port (void *cls, const char *hostname)
1439 struct PrettyPrinterContext *ppc = cls;
1442 if (hostname == NULL)
1444 ppc->asc (ppc->asc_cls, NULL);
1448 if (GNUNET_YES == ppc->ipv6)
1449 GNUNET_asprintf (&ret, "[%s]:%d", hostname, ppc->port);
1451 GNUNET_asprintf (&ret, "%s:%d", hostname, ppc->port);
1452 ppc->asc (ppc->asc_cls, ret);
1458 * Convert the transports address to a nice, human-readable
1461 * @param cls closure
1462 * @param type name of the transport that generated the address
1463 * @param addr one of the addresses of the host, NULL for the last address
1464 * the specific address format depends on the transport
1465 * @param addrlen length of the address
1466 * @param numeric should (IP) addresses be displayed in numeric form?
1467 * @param timeout after how long should we give up?
1468 * @param asc function to call on each string
1469 * @param asc_cls closure for asc
1472 tcp_plugin_address_pretty_printer (void *cls, const char *type,
1473 const void *addr, size_t addrlen,
1475 struct GNUNET_TIME_Relative timeout,
1476 GNUNET_TRANSPORT_AddressStringCallback asc,
1479 struct PrettyPrinterContext *ppc;
1482 struct sockaddr_in a4;
1483 struct sockaddr_in6 a6;
1484 const struct IPv4TcpAddress *t4;
1485 const struct IPv6TcpAddress *t6;
1488 if (addrlen == sizeof (struct IPv6TcpAddress))
1491 memset (&a6, 0, sizeof (a6));
1492 a6.sin6_family = AF_INET6;
1493 a6.sin6_port = t6->t6_port;
1494 memcpy (&a6.sin6_addr, &t6->ipv6_addr, sizeof (struct in6_addr));
1495 port = ntohs (t6->t6_port);
1499 else if (addrlen == sizeof (struct IPv4TcpAddress))
1502 memset (&a4, 0, sizeof (a4));
1503 a4.sin_family = AF_INET;
1504 a4.sin_port = t4->t4_port;
1505 a4.sin_addr.s_addr = t4->ipv4_addr;
1506 port = ntohs (t4->t4_port);
1510 else if (0 == addrlen)
1512 asc (asc_cls, "<inbound connection>");
1513 asc (asc_cls, NULL);
1518 /* invalid address */
1519 GNUNET_break_op (0);
1520 asc (asc_cls, NULL);
1523 ppc = GNUNET_malloc (sizeof (struct PrettyPrinterContext));
1524 if (addrlen == sizeof (struct IPv6TcpAddress))
1525 ppc->ipv6 = GNUNET_YES;
1527 ppc->ipv6 = GNUNET_NO;
1529 ppc->asc_cls = asc_cls;
1531 GNUNET_RESOLVER_hostname_get (sb, sbs, !numeric, timeout, &append_port, ppc);
1536 * Check if the given port is plausible (must be either our listen
1537 * port or our advertised port), or any port if we are behind NAT
1538 * and do not have a port open. If it is neither, we return
1541 * @param plugin global variables
1542 * @param in_port port number to check
1543 * @return GNUNET_OK if port is either open_port or adv_port
1546 check_port (struct Plugin *plugin, uint16_t in_port)
1548 if ((in_port == plugin->adv_port) || (in_port == plugin->open_port))
1550 return GNUNET_SYSERR;
1555 * Function that will be called to check if a binary address for this
1556 * plugin is well-formed and corresponds to an address for THIS peer
1557 * (as per our configuration). Naturally, if absolutely necessary,
1558 * plugins can be a bit conservative in their answer, but in general
1559 * plugins should make sure that the address does not redirect
1560 * traffic to a 3rd party that might try to man-in-the-middle our
1563 * @param cls closure, our 'struct Plugin*'
1564 * @param addr pointer to the address
1565 * @param addrlen length of addr
1566 * @return GNUNET_OK if this is a plausible address for this peer
1567 * and transport, GNUNET_SYSERR if not
1570 tcp_plugin_check_address (void *cls, const void *addr, size_t addrlen)
1572 struct Plugin *plugin = cls;
1573 struct IPv4TcpAddress *v4;
1574 struct IPv6TcpAddress *v6;
1576 if ((addrlen != sizeof (struct IPv4TcpAddress)) &&
1577 (addrlen != sizeof (struct IPv6TcpAddress)))
1579 GNUNET_break_op (0);
1580 return GNUNET_SYSERR;
1582 if (addrlen == sizeof (struct IPv4TcpAddress))
1584 v4 = (struct IPv4TcpAddress *) addr;
1585 if (GNUNET_OK != check_port (plugin, ntohs (v4->t4_port)))
1586 return GNUNET_SYSERR;
1588 GNUNET_NAT_test_address (plugin->nat, &v4->ipv4_addr,
1589 sizeof (struct in_addr)))
1590 return GNUNET_SYSERR;
1594 v6 = (struct IPv6TcpAddress *) addr;
1595 if (IN6_IS_ADDR_LINKLOCAL (&v6->ipv6_addr))
1597 GNUNET_break_op (0);
1598 return GNUNET_SYSERR;
1600 if (GNUNET_OK != check_port (plugin, ntohs (v6->t6_port)))
1601 return GNUNET_SYSERR;
1603 GNUNET_NAT_test_address (plugin->nat, &v6->ipv6_addr,
1604 sizeof (struct in6_addr)))
1605 return GNUNET_SYSERR;
1612 * We've received a nat probe from this peer via TCP. Finish
1613 * creating the client session and resume sending of queued
1616 * @param cls closure
1617 * @param client identification of the client
1618 * @param message the actual message
1621 handle_tcp_nat_probe (void *cls, struct GNUNET_SERVER_Client *client,
1622 const struct GNUNET_MessageHeader *message)
1624 struct Plugin *plugin = cls;
1625 struct Session *session;
1626 const struct TCP_NAT_ProbeMessage *tcp_nat_probe;
1629 struct IPv4TcpAddress *t4;
1630 struct IPv6TcpAddress *t6;
1631 const struct sockaddr_in *s4;
1632 const struct sockaddr_in6 *s6;
1634 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp", "received NAT probe\n");
1636 /* We have received a TCP NAT probe, meaning we (hopefully) initiated
1637 * a connection to this peer by running gnunet-nat-client. This peer
1638 * received the punch message and now wants us to use the new connection
1639 * as the default for that peer. Do so and then send a WELCOME message
1640 * so we can really be connected!
1642 if (ntohs (message->size) != sizeof (struct TCP_NAT_ProbeMessage))
1644 GNUNET_break_op (0);
1645 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1649 tcp_nat_probe = (const struct TCP_NAT_ProbeMessage *) message;
1651 memcmp (&tcp_nat_probe->clientIdentity, plugin->env->my_identity,
1652 sizeof (struct GNUNET_PeerIdentity)))
1654 /* refuse connections from ourselves */
1655 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1660 GNUNET_CONTAINER_multihashmap_get (plugin->nat_wait_conns,
1662 clientIdentity.hashPubKey);
1663 if (session == NULL)
1665 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1666 "Did NOT find session for NAT probe!\n");
1667 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1670 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1671 "Found session for NAT probe!\n");
1673 if (session->nat_connection_timeout != GNUNET_SCHEDULER_NO_TASK)
1675 GNUNET_SCHEDULER_cancel (session->nat_connection_timeout);
1676 session->nat_connection_timeout = GNUNET_SCHEDULER_NO_TASK;
1679 GNUNET_assert (GNUNET_CONTAINER_multihashmap_remove
1680 (plugin->nat_wait_conns,
1681 &tcp_nat_probe->clientIdentity.hashPubKey,
1682 session) == GNUNET_YES);
1683 if (GNUNET_OK != GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
1686 GNUNET_free (session);
1687 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1691 GNUNET_SERVER_client_keep (client);
1692 session->client = client;
1693 session->last_activity = GNUNET_TIME_absolute_get ();
1694 session->inbound = GNUNET_NO;
1695 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1696 "Found address `%s' for incoming connection\n",
1697 GNUNET_a2s (vaddr, alen));
1698 switch (((const struct sockaddr *) vaddr)->sa_family)
1702 t4 = GNUNET_malloc (sizeof (struct IPv4TcpAddress));
1703 t4->t4_port = s4->sin_port;
1704 t4->ipv4_addr = s4->sin_addr.s_addr;
1706 session->addrlen = sizeof (struct IPv4TcpAddress);
1710 t6 = GNUNET_malloc (sizeof (struct IPv6TcpAddress));
1711 t6->t6_port = s6->sin6_port;
1712 memcpy (&t6->ipv6_addr, &s6->sin6_addr, sizeof (struct in6_addr));
1714 session->addrlen = sizeof (struct IPv6TcpAddress);
1717 GNUNET_break_op (0);
1719 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1720 "Bad address for incoming connection!\n");
1721 GNUNET_free (vaddr);
1723 GNUNET_SERVER_client_drop (client);
1724 GNUNET_free (session);
1725 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1728 GNUNET_free (vaddr);
1730 GNUNET_CONTAINER_multihashmap_put(plugin->sessionmap, &session->target.hashPubKey, session, GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
1731 inc_sessions (plugin, session, __LINE__);
1732 GNUNET_STATISTICS_update (plugin->env->stats,
1733 gettext_noop ("# TCP sessions active"), 1,
1735 process_pending_messages (session);
1736 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1741 * We've received a welcome from this peer via TCP. Possibly create a
1742 * fresh client record and send back our welcome.
1744 * @param cls closure
1745 * @param client identification of the client
1746 * @param message the actual message
1749 handle_tcp_welcome (void *cls, struct GNUNET_SERVER_Client *client,
1750 const struct GNUNET_MessageHeader *message)
1752 struct Plugin *plugin = cls;
1753 const struct WelcomeMessage *wm = (const struct WelcomeMessage *) message;
1754 struct Session *session;
1757 struct IPv4TcpAddress *t4;
1758 struct IPv6TcpAddress *t6;
1759 const struct sockaddr_in *s4;
1760 const struct sockaddr_in6 *s6;
1763 memcmp (&wm->clientIdentity, plugin->env->my_identity,
1764 sizeof (struct GNUNET_PeerIdentity)))
1766 /* refuse connections from ourselves */
1767 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1771 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1772 "Received %s message from `%4s'\n", "WELCOME",
1773 GNUNET_i2s (&wm->clientIdentity));
1774 GNUNET_STATISTICS_update (plugin->env->stats,
1775 gettext_noop ("# TCP WELCOME messages received"), 1,
1778 session = lookup_session_by_client (plugin, client);
1779 if (session != NULL)
1781 if (GNUNET_OK == GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
1783 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1784 "Found existing session %p for peer `%s'\n",
1786 GNUNET_a2s (vaddr, alen));
1787 GNUNET_free (vaddr);
1792 GNUNET_SERVER_client_keep (client);
1793 session = create_session (plugin, &wm->clientIdentity, client, GNUNET_NO);
1794 session->inbound = GNUNET_YES;
1796 if (GNUNET_OK == GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
1798 if (alen == sizeof (struct sockaddr_in))
1801 t4 = GNUNET_malloc (sizeof (struct IPv4TcpAddress));
1802 t4->t4_port = s4->sin_port;
1803 t4->ipv4_addr = s4->sin_addr.s_addr;
1805 session->addrlen = sizeof (struct IPv4TcpAddress);
1807 else if (alen == sizeof (struct sockaddr_in6))
1810 t6 = GNUNET_malloc (sizeof (struct IPv6TcpAddress));
1811 t6->t6_port = s6->sin6_port;
1812 memcpy (&t6->ipv6_addr, &s6->sin6_addr, sizeof (struct in6_addr));
1814 session->addrlen = sizeof (struct IPv6TcpAddress);
1817 struct GNUNET_ATS_Information ats;
1818 ats = plugin->env->get_address_type (plugin->env->cls, vaddr ,alen);
1819 session->ats_address_network_type = ats.value;
1821 GNUNET_free (vaddr);
1825 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1826 "Did not obtain TCP socket address for incoming connection\n");
1828 GNUNET_CONTAINER_multihashmap_put(plugin->sessionmap, &wm->clientIdentity.hashPubKey, session, GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
1829 inc_sessions (plugin, session, __LINE__);
1832 if (session->expecting_welcome != GNUNET_YES)
1834 GNUNET_break_op (0);
1835 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1838 session->last_activity = GNUNET_TIME_absolute_get ();
1839 session->expecting_welcome = GNUNET_NO;
1842 process_pending_messages (session);
1844 GNUNET_SERVER_client_set_timeout (client,
1845 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1846 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1851 * Task to signal the server that we can continue
1852 * receiving from the TCP client now.
1854 * @param cls the 'struct Session*'
1855 * @param tc task context (unused)
1858 delayed_done (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1860 struct Session *session = cls;
1861 struct GNUNET_TIME_Relative delay;
1862 struct GNUNET_ATS_Information ats;
1864 session->receive_delay_task = GNUNET_SCHEDULER_NO_TASK;
1866 session->plugin->env->receive (session->plugin->env->cls,
1867 &session->target, NULL, &ats, 0, session,
1869 if (delay.rel_value == 0)
1870 GNUNET_SERVER_receive_done (session->client, GNUNET_OK);
1872 session->receive_delay_task =
1873 GNUNET_SCHEDULER_add_delayed (delay, &delayed_done, session);
1878 * We've received data for this peer via TCP. Unbox,
1879 * compute latency and forward.
1881 * @param cls closure
1882 * @param client identification of the client
1883 * @param message the actual message
1886 handle_tcp_data (void *cls, struct GNUNET_SERVER_Client *client,
1887 const struct GNUNET_MessageHeader *message)
1889 struct Plugin *plugin = cls;
1890 struct Session *session;
1891 struct GNUNET_TIME_Relative delay;
1894 type = ntohs (message->type);
1895 if ((GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME == type) ||
1896 (GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE == type))
1898 /* We don't want to propagate WELCOME and NAT Probe messages up! */
1899 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1902 session = lookup_session_by_client (plugin, client);
1903 if (NULL == session)
1905 /* No inbound session found */
1908 GNUNET_SERVER_client_get_address (client, &vaddr, &alen);
1909 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, "tcp",
1910 "Received unexpected %u bytes of type %u from `%s'\n",
1911 (unsigned int) ntohs (message->size),
1912 (unsigned int) ntohs (message->type),
1913 GNUNET_a2s(vaddr, alen));
1914 GNUNET_break_op (0);
1915 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1916 GNUNET_free_non_null(vaddr);
1919 else if (GNUNET_YES == session->expecting_welcome)
1921 /* Session is expecting WELCOME message */
1924 GNUNET_SERVER_client_get_address (client, &vaddr, &alen);
1925 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, "tcp",
1926 "Received unexpected %u bytes of type %u from `%s'\n",
1927 (unsigned int) ntohs (message->size),
1928 (unsigned int) ntohs (message->type),
1929 GNUNET_a2s(vaddr, alen));
1930 GNUNET_break_op (0);
1931 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1932 GNUNET_free_non_null(vaddr);
1936 session->last_activity = GNUNET_TIME_absolute_get ();
1938 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1939 "Passing %u bytes of type %u from `%4s' to transport service.\n",
1940 (unsigned int) ntohs (message->size),
1941 (unsigned int) ntohs (message->type),
1942 GNUNET_i2s (&session->target));
1944 GNUNET_STATISTICS_update (plugin->env->stats,
1945 gettext_noop ("# bytes received via TCP"),
1946 ntohs (message->size), GNUNET_NO);
1947 struct GNUNET_ATS_Information distance[2];
1949 distance[0].type = htonl (GNUNET_ATS_QUALITY_NET_DISTANCE);
1950 distance[0].value = htonl (1);
1951 distance[1].type = htonl (GNUNET_ATS_NETWORK_TYPE);
1952 distance[1].value = session->ats_address_network_type;
1953 GNUNET_break (ntohl(session->ats_address_network_type) != GNUNET_ATS_NET_UNSPECIFIED);
1955 delay = plugin->env->receive (plugin->env->cls,
1958 (const struct GNUNET_ATS_Information *) &distance,
1960 (GNUNET_YES == session->inbound) ? NULL : session->addr,
1961 (GNUNET_YES == session->inbound) ? 0 : session->addrlen);
1962 if (delay.rel_value == 0)
1964 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1968 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1969 "Throttling receiving from `%s' for %llu ms\n",
1970 GNUNET_i2s (&session->target),
1971 (unsigned long long) delay.rel_value);
1972 GNUNET_SERVER_disable_receive_done_warning (client);
1973 session->receive_delay_task =
1974 GNUNET_SCHEDULER_add_delayed (delay, &delayed_done, session);
1980 * Functions with this signature are called whenever a peer
1981 * is disconnected on the network level.
1983 * @param cls closure
1984 * @param client identification of the client
1987 disconnect_notify (void *cls, struct GNUNET_SERVER_Client *client)
1989 struct Plugin *plugin = cls;
1990 struct Session *session;
1994 plugin->max_connections++;
1995 session = lookup_session_by_client (plugin, client);
1996 if (session == NULL)
1997 return; /* unknown, nothing to do */
1998 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1999 "Destroying session of `%4s' with %s due to network-level disconnect.\n",
2000 GNUNET_i2s (&session->target),
2002 NULL) ? tcp_address_to_string (session->plugin,
2006 GNUNET_STATISTICS_update (session->plugin->env->stats,
2008 ("# network-level TCP disconnect events"), 1,
2010 disconnect_session (session);
2015 * We can now send a probe message, copy into buffer to really send.
2017 * @param cls closure, a struct TCPProbeContext
2018 * @param size max size to copy
2019 * @param buf buffer to copy message to
2020 * @return number of bytes copied into buf
2023 notify_send_probe (void *cls, size_t size, void *buf)
2025 struct TCPProbeContext *tcp_probe_ctx = cls;
2026 struct Plugin *plugin = tcp_probe_ctx->plugin;
2029 tcp_probe_ctx->transmit_handle = NULL;
2030 GNUNET_CONTAINER_DLL_remove (plugin->probe_head, plugin->probe_tail,
2034 GNUNET_CONNECTION_destroy (tcp_probe_ctx->sock);
2035 GNUNET_free (tcp_probe_ctx);
2038 GNUNET_assert (size >= sizeof (tcp_probe_ctx->message));
2039 memcpy (buf, &tcp_probe_ctx->message, sizeof (tcp_probe_ctx->message));
2040 GNUNET_SERVER_connect_socket (tcp_probe_ctx->plugin->server,
2041 tcp_probe_ctx->sock);
2042 ret = sizeof (tcp_probe_ctx->message);
2043 GNUNET_free (tcp_probe_ctx);
2049 * Function called by the NAT subsystem suggesting another peer wants
2050 * to connect to us via connection reversal. Try to connect back to the
2053 * @param cls closure
2054 * @param addr address to try
2055 * @param addrlen number of bytes in addr
2058 try_connection_reversal (void *cls, const struct sockaddr *addr,
2061 struct Plugin *plugin = cls;
2062 struct GNUNET_CONNECTION_Handle *sock;
2063 struct TCPProbeContext *tcp_probe_ctx;
2066 * We have received an ICMP response, ostensibly from a peer
2067 * that wants to connect to us! Send a message to establish a connection.
2069 sock = GNUNET_CONNECTION_create_from_sockaddr (AF_INET, addr, addrlen);
2072 /* failed for some odd reason (out of sockets?); ignore attempt */
2076 /* FIXME: do we need to track these probe context objects so that
2077 * we can clean them up on plugin unload? */
2078 tcp_probe_ctx = GNUNET_malloc (sizeof (struct TCPProbeContext));
2079 tcp_probe_ctx->message.header.size =
2080 htons (sizeof (struct TCP_NAT_ProbeMessage));
2081 tcp_probe_ctx->message.header.type =
2082 htons (GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE);
2083 memcpy (&tcp_probe_ctx->message.clientIdentity, plugin->env->my_identity,
2084 sizeof (struct GNUNET_PeerIdentity));
2085 tcp_probe_ctx->plugin = plugin;
2086 tcp_probe_ctx->sock = sock;
2087 GNUNET_CONTAINER_DLL_insert (plugin->probe_head, plugin->probe_tail,
2089 tcp_probe_ctx->transmit_handle =
2090 GNUNET_CONNECTION_notify_transmit_ready (sock,
2091 ntohs (tcp_probe_ctx->
2092 message.header.size),
2093 GNUNET_TIME_UNIT_FOREVER_REL,
2101 * Entry point for the plugin.
2103 * @param cls closure, the 'struct GNUNET_TRANSPORT_PluginEnvironment*'
2104 * @return the 'struct GNUNET_TRANSPORT_PluginFunctions*' or NULL on error
2107 libgnunet_plugin_transport_tcp_init (void *cls)
2109 static const struct GNUNET_SERVER_MessageHandler my_handlers[] = {
2110 {&handle_tcp_welcome, NULL, GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME,
2111 sizeof (struct WelcomeMessage)},
2112 {&handle_tcp_nat_probe, NULL, GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE,
2113 sizeof (struct TCP_NAT_ProbeMessage)},
2114 {&handle_tcp_data, NULL, GNUNET_MESSAGE_TYPE_ALL, 0},
2117 struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
2118 struct GNUNET_TRANSPORT_PluginFunctions *api;
2119 struct Plugin *plugin;
2120 struct GNUNET_SERVICE_Context *service;
2121 unsigned long long aport;
2122 unsigned long long bport;
2123 unsigned long long max_connections;
2125 struct GNUNET_TIME_Relative idle_timeout;
2127 struct sockaddr **addrs;
2128 socklen_t *addrlens;
2130 if (NULL == env->receive)
2132 /* run in 'stub' mode (i.e. as part of gnunet-peerinfo), don't fully
2133 initialze the plugin or the API */
2134 api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
2136 api->address_pretty_printer = &tcp_plugin_address_pretty_printer;
2137 api->address_to_string = &tcp_address_to_string;
2138 api->string_to_address = &tcp_string_to_address;
2143 GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-tcp",
2146 max_connections = 128;
2150 GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-tcp", "PORT",
2151 &bport)) || (bport > 65535) ||
2153 GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-tcp",
2154 "ADVERTISED-PORT", &aport)) &&
2157 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, "tcp",
2159 ("Require valid port number for service `%s' in configuration!\n"),
2169 service = GNUNET_SERVICE_start ("transport-tcp", env->cfg, GNUNET_SERVICE_OPTION_NONE);
2170 if (service == NULL)
2172 GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, "tcp",
2173 _("Failed to start service.\n"));
2180 plugin = GNUNET_malloc (sizeof (struct Plugin));
2181 plugin->sessionmap = GNUNET_CONTAINER_multihashmap_create(max_connections);
2182 plugin->max_connections = max_connections;
2183 plugin->open_port = bport;
2184 plugin->adv_port = aport;
2186 plugin->lsock = NULL;
2187 if ((service != NULL) &&
2190 GNUNET_SERVICE_get_server_addresses ("transport-tcp", env->cfg, &addrs,
2194 GNUNET_NAT_register (env->cfg, GNUNET_YES, aport, (unsigned int) ret,
2195 (const struct sockaddr **) addrs, addrlens,
2196 &tcp_nat_port_map_callback,
2197 &try_connection_reversal, plugin);
2201 GNUNET_assert (addrs[ret] != NULL);
2202 GNUNET_free (addrs[ret]);
2204 GNUNET_free_non_null (addrs);
2205 GNUNET_free_non_null (addrlens);
2210 GNUNET_NAT_register (env->cfg, GNUNET_YES, 0, 0, NULL, NULL, NULL,
2211 &try_connection_reversal, plugin);
2213 api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
2215 api->send = &tcp_plugin_send;
2216 api->get_session = &tcp_plugin_get_session;
2218 api->disconnect = &tcp_plugin_disconnect;
2219 api->address_pretty_printer = &tcp_plugin_address_pretty_printer;
2220 api->check_address = &tcp_plugin_check_address;
2221 api->address_to_string = &tcp_address_to_string;
2222 api->string_to_address = &tcp_string_to_address;
2223 plugin->service = service;
2224 if (service != NULL)
2226 plugin->server = GNUNET_SERVICE_get_server (service);
2231 GNUNET_CONFIGURATION_get_value_time (env->cfg, "transport-tcp",
2232 "TIMEOUT", &idle_timeout))
2234 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, "tcp",
2235 _("Failed to find option %s in section %s!\n"),
2236 "TIMEOUT", "transport-tcp");
2237 if (plugin->nat != NULL)
2238 GNUNET_NAT_unregister (plugin->nat);
2239 GNUNET_free (plugin);
2244 GNUNET_SERVER_create_with_sockets (&plugin_tcp_access_check, plugin,
2245 NULL, idle_timeout, GNUNET_YES);
2247 plugin->handlers = GNUNET_malloc (sizeof (my_handlers));
2248 memcpy (plugin->handlers, my_handlers, sizeof (my_handlers));
2250 i < sizeof (my_handlers) / sizeof (struct GNUNET_SERVER_MessageHandler);
2252 plugin->handlers[i].callback_cls = plugin;
2253 GNUNET_SERVER_add_handlers (plugin->server, plugin->handlers);
2254 GNUNET_SERVER_disconnect_notify (plugin->server, &disconnect_notify, plugin);
2255 plugin->nat_wait_conns = GNUNET_CONTAINER_multihashmap_create (16);
2257 GNUNET_log_from (GNUNET_ERROR_TYPE_INFO, "tcp",
2258 _("TCP transport listening on port %llu\n"), bport);
2260 GNUNET_log_from (GNUNET_ERROR_TYPE_INFO, "tcp",
2262 ("TCP transport not listening on any port (client only)\n"));
2264 GNUNET_log_from (GNUNET_ERROR_TYPE_INFO, "tcp",
2266 ("TCP transport advertises itself as being on port %llu\n"),
2268 /* Initially set connections to 0 */
2269 GNUNET_STATISTICS_set(plugin->env->stats,
2270 gettext_noop ("# TCP sessions active"), 0,
2277 * Exit point from the plugin.
2280 libgnunet_plugin_transport_tcp_done (void *cls)
2282 struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
2283 struct Plugin *plugin = api->cls;
2284 struct TCPProbeContext *tcp_probe;
2291 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp", "Shutting down TCP plugin\n");
2293 /* Removing leftover sessions */
2294 GNUNET_CONTAINER_multihashmap_iterate(plugin->sessionmap, &session_disconnect_it, NULL);
2295 /* Removing leftover NAT sessions */
2296 GNUNET_CONTAINER_multihashmap_iterate(plugin->nat_wait_conns, &session_disconnect_it, NULL);
2298 if (plugin->service != NULL)
2299 GNUNET_SERVICE_stop (plugin->service);
2301 GNUNET_SERVER_destroy (plugin->server);
2302 GNUNET_free (plugin->handlers);
2303 if (plugin->nat != NULL)
2304 GNUNET_NAT_unregister (plugin->nat);
2305 while (NULL != (tcp_probe = plugin->probe_head))
2307 GNUNET_CONTAINER_DLL_remove (plugin->probe_head, plugin->probe_tail,
2309 GNUNET_CONNECTION_destroy (tcp_probe->sock);
2310 GNUNET_free (tcp_probe);
2312 GNUNET_CONTAINER_multihashmap_destroy (plugin->nat_wait_conns);
2313 GNUNET_CONTAINER_multihashmap_destroy (plugin->sessionmap);
2314 GNUNET_free (plugin);
2319 /* end of plugin_transport_tcp.c */