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 LOG(kind,...) GNUNET_log_from (kind, "transport-tcp",__VA_ARGS__)
45 * How long until we give up on establishing an NAT connection?
48 #define NAT_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 10)
51 GNUNET_NETWORK_STRUCT_BEGIN
54 * Initial handshake message for a session.
59 * Type is GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME.
61 struct GNUNET_MessageHeader header;
64 * Identity of the node connecting (TCP client)
66 struct GNUNET_PeerIdentity clientIdentity;
72 * Basically a WELCOME message, but with the purpose
73 * of giving the waiting peer a client handle to use
75 struct TCP_NAT_ProbeMessage
78 * Type is GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE.
80 struct GNUNET_MessageHeader header;
83 * Identity of the sender of the message.
85 struct GNUNET_PeerIdentity clientIdentity;
88 GNUNET_NETWORK_STRUCT_END
91 * Context for sending a NAT probe via TCP.
93 struct TCPProbeContext
97 * Active probes are kept in a DLL.
99 struct TCPProbeContext *next;
102 * Active probes are kept in a DLL.
104 struct TCPProbeContext *prev;
109 struct GNUNET_CONNECTION_Handle *sock;
112 * Message to be sent.
114 struct TCP_NAT_ProbeMessage message;
117 * Handle to the transmission.
119 struct GNUNET_CONNECTION_TransmitHandle *transmit_handle;
122 * Transport plugin handle.
124 struct Plugin *plugin;
128 GNUNET_NETWORK_STRUCT_BEGIN
131 * Network format for IPv4 addresses.
133 struct IPv4TcpAddress
136 * IPv4 address, in network byte order.
138 uint32_t ipv4_addr GNUNET_PACKED;
141 * Port number, in network byte order.
143 uint16_t t4_port GNUNET_PACKED;
149 * Network format for IPv6 addresses.
151 struct IPv6TcpAddress
156 struct in6_addr ipv6_addr GNUNET_PACKED;
159 * Port number, in network byte order.
161 uint16_t t6_port GNUNET_PACKED;
164 GNUNET_NETWORK_STRUCT_END
167 * Encapsulation of all of the state of the plugin.
173 * Information kept for each message that is yet to
176 struct PendingMessage
180 * This is a doubly-linked list.
182 struct PendingMessage *next;
185 * This is a doubly-linked list.
187 struct PendingMessage *prev;
190 * The pending message
195 * Continuation function to call once the message
196 * has been sent. Can be NULL if there is no
197 * continuation to call.
199 GNUNET_TRANSPORT_TransmitContinuation transmit_cont;
202 * Closure for transmit_cont.
204 void *transmit_cont_cls;
207 * Timeout value for the pending message.
209 struct GNUNET_TIME_Absolute timeout;
212 * So that the gnunet-service-transport can group messages together,
213 * these pending messages need to accept a message buffer and size
214 * instead of just a GNUNET_MessageHeader.
222 * Session handle for TCP connections.
230 struct SessionHeader header;
233 * Pointer to the global plugin struct.
235 struct Plugin *plugin;
238 * The client (used to identify this connection)
240 struct GNUNET_SERVER_Client *client;
243 * Task cleaning up a NAT client connection establishment attempt;
245 GNUNET_SCHEDULER_TaskIdentifier nat_connection_timeout;
248 * Messages currently pending for transmission
249 * to this peer, if any.
251 struct PendingMessage *pending_messages_head;
254 * Messages currently pending for transmission
255 * to this peer, if any.
257 struct PendingMessage *pending_messages_tail;
260 * Handle for pending transmission request.
262 struct GNUNET_SERVER_TransmitHandle *transmit_handle;
265 * To whom are we talking to (set to our identity
266 * if we are still waiting for the welcome message)
268 struct GNUNET_PeerIdentity target;
271 * ID of task used to delay receiving more to throttle sender.
273 GNUNET_SCHEDULER_TaskIdentifier receive_delay_task;
276 * Address of the other peer (either based on our 'connect'
277 * call or on our 'accept' call).
279 * struct IPv4TcpAddress or struct IPv6TcpAddress
285 * Length of connect_addr.
290 * Last activity on this connection. Used to select preferred
293 struct GNUNET_TIME_Absolute last_activity;
296 * Are we still expecting the welcome message? (GNUNET_YES/GNUNET_NO)
298 int expecting_welcome;
301 * Was this a connection that was inbound (we accepted)? (GNUNET_YES/GNUNET_NO)
306 * Was this session created using NAT traversal?
311 * ATS network type in NBO
313 uint32_t ats_address_network_type;
318 * Encapsulation of all of the state of the plugin.
325 struct GNUNET_TRANSPORT_PluginEnvironment *env;
330 struct GNUNET_CONNECTION_Handle *lsock;
333 * Our handle to the NAT module.
335 struct GNUNET_NAT_Handle *nat;
337 struct GNUNET_CONTAINER_MultiHashMap * sessionmap;
340 * Handle to the network service.
342 struct GNUNET_SERVICE_Context *service;
345 * Handle to the server for this service.
347 struct GNUNET_SERVER_Handle *server;
350 * Copy of the handler array where the closures are
351 * set to this struct's instance.
353 struct GNUNET_SERVER_MessageHandler *handlers;
356 * Map of peers we have tried to contact behind a NAT
358 struct GNUNET_CONTAINER_MultiHashMap *nat_wait_conns;
361 * List of active TCP probes.
363 struct TCPProbeContext *probe_head;
366 * List of active TCP probes.
368 struct TCPProbeContext *probe_tail;
371 * Handle for (DYN)DNS lookup of our external IP.
373 struct GNUNET_RESOLVER_RequestHandle *ext_dns;
376 * How many more TCP sessions are we allowed to open right now?
378 unsigned long long max_connections;
381 * ID of task used to update our addresses when one expires.
383 GNUNET_SCHEDULER_TaskIdentifier address_update_task;
386 * Port that we are actually listening on.
391 * Port that the user said we would have visible to the
400 tcp_address_to_string (void *cls, const void *addr, size_t addrlen);
402 static unsigned int sessions;
404 static void inc_sessions (struct Plugin *plugin, struct Session *session, int line)
407 unsigned int size = GNUNET_CONTAINER_multihashmap_size(plugin->sessionmap);
408 if (sessions != size)
409 LOG (GNUNET_ERROR_TYPE_DEBUG, "Inconsistent sessions %u <-> session map size: %u\n",
411 LOG (GNUNET_ERROR_TYPE_DEBUG, "%4i Session increased to %u (session map size: %u): `%s' `%s'\n",
415 GNUNET_i2s (&session->target),
416 tcp_address_to_string (NULL, session->addr, session->addrlen));
419 static void dec_sessions (struct Plugin *plugin, struct Session *session, int line)
421 GNUNET_assert (sessions > 0);
422 unsigned int size = GNUNET_CONTAINER_multihashmap_size(plugin->sessionmap);
424 if (sessions != size)
425 LOG (GNUNET_ERROR_TYPE_DEBUG, "Inconsistent sessions %u <-> session map size: %u\n",
427 LOG (GNUNET_ERROR_TYPE_DEBUG, "%4i Session decreased to %u (session map size: %u): `%s' `%s'\n",
431 GNUNET_i2s (&session->target),
432 tcp_address_to_string (NULL, session->addr, session->addrlen));
438 * Function to check if an inbound connection is acceptable.
439 * Mostly used to limit the total number of open connections
442 * @param cls the 'struct Plugin'
443 * @param ucred credentials, if available, otherwise NULL
444 * @param addr address
445 * @param addrlen length of address
446 * @return GNUNET_YES to allow, GNUNET_NO to deny, GNUNET_SYSERR
447 * for unknown address family (will be denied).
450 plugin_tcp_access_check (void *cls,
451 const struct GNUNET_CONNECTION_Credentials *ucred,
452 const struct sockaddr *addr, socklen_t addrlen)
454 struct Plugin *plugin = cls;
456 LOG (GNUNET_ERROR_TYPE_DEBUG,
457 "Accepting new incoming TCP connection\n");
458 if (0 == plugin->max_connections)
460 plugin->max_connections--;
466 * Our external IP address/port mapping has changed.
468 * @param cls closure, the 'struct LocalAddrList'
469 * @param add_remove GNUNET_YES to mean the new public IP address, GNUNET_NO to mean
470 * the previous (now invalid) one
471 * @param addr either the previous or the new public IP address
472 * @param addrlen actual lenght of the address
475 tcp_nat_port_map_callback (void *cls, int add_remove,
476 const struct sockaddr *addr, socklen_t addrlen)
478 struct Plugin *plugin = cls;
479 struct IPv4TcpAddress t4;
480 struct IPv6TcpAddress t6;
484 LOG (GNUNET_ERROR_TYPE_DEBUG,
485 "NPMC called with %d for address `%s'\n", add_remove,
486 GNUNET_a2s (addr, addrlen));
487 /* convert 'addr' to our internal format */
488 switch (addr->sa_family)
491 GNUNET_assert (addrlen == sizeof (struct sockaddr_in));
492 t4.ipv4_addr = ((struct sockaddr_in *) addr)->sin_addr.s_addr;
493 t4.t4_port = ((struct sockaddr_in *) addr)->sin_port;
498 GNUNET_assert (addrlen == sizeof (struct sockaddr_in6));
499 memcpy (&t6.ipv6_addr, &((struct sockaddr_in6 *) addr)->sin6_addr,
500 sizeof (struct in6_addr));
501 t6.t6_port = ((struct sockaddr_in6 *) addr)->sin6_port;
509 /* modify our published address list */
510 plugin->env->notify_address (plugin->env->cls, add_remove, arg, args);
515 * Function called for a quick conversion of the binary address to
516 * a numeric address. Note that the caller must not free the
517 * address and that the next call to this function is allowed
518 * to override the address again.
520 * @param cls closure ('struct Plugin*')
521 * @param addr binary address
522 * @param addrlen length of the address
523 * @return string representing the same address
526 tcp_address_to_string (void *cls, const void *addr, size_t addrlen)
528 static char rbuf[INET6_ADDRSTRLEN + 12];
529 char buf[INET6_ADDRSTRLEN];
533 const struct IPv4TcpAddress *t4;
534 const struct IPv6TcpAddress *t6;
538 if (addrlen == sizeof (struct IPv6TcpAddress))
542 port = ntohs (t6->t6_port);
543 memcpy (&a6, &t6->ipv6_addr, sizeof (a6));
546 else if (addrlen == sizeof (struct IPv4TcpAddress))
550 port = ntohs (t4->t4_port);
551 memcpy (&a4, &t4->ipv4_addr, sizeof (a4));
556 LOG (GNUNET_ERROR_TYPE_ERROR,
557 _("Unexpected address length: %u bytes\n"),
558 (unsigned int) addrlen);
562 if (NULL == inet_ntop (af, sb, buf, INET6_ADDRSTRLEN))
564 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "inet_ntop");
567 GNUNET_snprintf (rbuf, sizeof (rbuf), (af == AF_INET6) ? "[%s]:%u" : "%s:%u",
574 * Function called to convert a string address to
577 * @param cls closure ('struct Plugin*')
578 * @param addr string address
579 * @param addrlen length of the address
580 * @param buf location to store the buffer
581 * @param added location to store the number of bytes in the buffer.
582 * If the function returns GNUNET_SYSERR, its contents are undefined.
583 * @return GNUNET_OK on success, GNUNET_SYSERR on failure
586 tcp_string_to_address (void *cls, const char *addr, uint16_t addrlen,
587 void **buf, size_t *added)
589 struct sockaddr_storage socket_address;
591 if ((NULL == addr) || (addrlen == 0))
594 return GNUNET_SYSERR;
597 if ('\0' != addr[addrlen - 1])
600 return GNUNET_SYSERR;
603 if (strlen (addr) != addrlen - 1)
606 return GNUNET_SYSERR;
609 int ret = GNUNET_STRINGS_to_address_ip (addr, strlen (addr),
612 if (ret != GNUNET_OK)
615 return GNUNET_SYSERR;
618 if (socket_address.ss_family == AF_INET)
620 struct IPv4TcpAddress *t4;
621 struct sockaddr_in *in4 = (struct sockaddr_in *) &socket_address;
622 t4 = GNUNET_malloc (sizeof (struct IPv4TcpAddress));
623 t4->ipv4_addr = in4->sin_addr.s_addr;
624 t4->t4_port = in4->sin_port;
626 *added = sizeof (struct IPv4TcpAddress);
629 else if (socket_address.ss_family == AF_INET6)
631 struct IPv6TcpAddress *t6;
632 struct sockaddr_in6 *in6 = (struct sockaddr_in6 *) &socket_address;
633 t6 = GNUNET_malloc (sizeof (struct IPv6TcpAddress));
634 t6->ipv6_addr = in6->sin6_addr;
635 t6->t6_port = in6->sin6_port;
637 *added = sizeof (struct IPv6TcpAddress);
640 return GNUNET_SYSERR;
644 struct SessionClientCtx
646 const struct GNUNET_SERVER_Client *client;
652 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)
669 * Find the session handle for the given client.
671 * @param plugin the plugin
672 * @param client which client to find the session handle for
673 * @return NULL if no matching session exists
675 static struct Session *
676 lookup_session_by_client (struct Plugin *plugin,
677 const struct GNUNET_SERVER_Client *client)
679 struct SessionClientCtx sc_ctx;
681 sc_ctx.client = client;
683 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 LOG (GNUNET_ERROR_TYPE_DEBUG,
713 "Creating new session for peer `%4s'\n",
714 GNUNET_i2s (target));
715 ret = GNUNET_malloc (sizeof (struct Session));
716 ret->last_activity = GNUNET_TIME_absolute_get ();
717 ret->plugin = plugin;
718 ret->is_nat = is_nat;
719 ret->client = client;
720 ret->target = *target;
721 ret->expecting_welcome = GNUNET_YES;
722 ret->ats_address_network_type = htonl (GNUNET_ATS_NET_UNSPECIFIED);
723 pm = GNUNET_malloc (sizeof (struct PendingMessage) +
724 sizeof (struct WelcomeMessage));
725 pm->msg = (const char *) &pm[1];
726 pm->message_size = sizeof (struct WelcomeMessage);
727 welcome.header.size = htons (sizeof (struct WelcomeMessage));
728 welcome.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME);
729 welcome.clientIdentity = *plugin->env->my_identity;
730 memcpy (&pm[1], &welcome, sizeof (welcome));
731 pm->timeout = GNUNET_TIME_UNIT_FOREVER_ABS;
732 GNUNET_STATISTICS_update (plugin->env->stats,
733 gettext_noop ("# bytes currently in TCP buffers"),
734 pm->message_size, GNUNET_NO);
735 GNUNET_CONTAINER_DLL_insert (ret->pending_messages_head,
736 ret->pending_messages_tail, pm);
737 if (is_nat != GNUNET_YES)
739 GNUNET_STATISTICS_update (plugin->env->stats,
740 gettext_noop ("# TCP sessions active"), 1,
748 * If we have pending messages, ask the server to
749 * transmit them (schedule the respective tasks, etc.)
751 * @param session for which session should we do this
754 process_pending_messages (struct Session *session);
758 * Function called to notify a client about the socket
759 * being ready to queue more data. "buf" will be
760 * NULL and "size" zero if the socket was closed for
761 * writing in the meantime.
764 * @param size number of bytes available in buf
765 * @param buf where the callee should write the message
766 * @return number of bytes written to buf
769 do_transmit (void *cls, size_t size, void *buf)
771 struct Session *session = cls;
772 struct GNUNET_PeerIdentity pid;
773 struct Plugin *plugin;
774 struct PendingMessage *pos;
775 struct PendingMessage *hd;
776 struct PendingMessage *tl;
777 struct GNUNET_TIME_Absolute now;
781 GNUNET_assert (session != NULL);
782 session->transmit_handle = NULL;
783 plugin = session->plugin;
786 LOG (GNUNET_ERROR_TYPE_DEBUG,
787 "Timeout trying to transmit to peer `%4s', discarding message queue.\n",
788 GNUNET_i2s (&session->target));
789 /* timeout; cancel all messages that have already expired */
793 now = GNUNET_TIME_absolute_get ();
794 while ((NULL != (pos = session->pending_messages_head)) &&
795 (pos->timeout.abs_value <= now.abs_value))
797 GNUNET_CONTAINER_DLL_remove (session->pending_messages_head,
798 session->pending_messages_tail, pos);
799 LOG (GNUNET_ERROR_TYPE_DEBUG,
800 "Failed to transmit %u byte message to `%4s'.\n",
801 pos->message_size, GNUNET_i2s (&session->target));
802 ret += pos->message_size;
803 GNUNET_CONTAINER_DLL_insert_after (hd, tl, tl, pos);
805 /* do this call before callbacks (so that if callbacks destroy
806 * session, they have a chance to cancel actions done by this
808 process_pending_messages (session);
809 pid = session->target;
810 /* no do callbacks and do not use session again since
811 * the callbacks may abort the session */
812 while (NULL != (pos = hd))
814 GNUNET_CONTAINER_DLL_remove (hd, tl, pos);
815 if (pos->transmit_cont != NULL)
816 pos->transmit_cont (pos->transmit_cont_cls, &pid, GNUNET_SYSERR);
819 GNUNET_STATISTICS_update (plugin->env->stats,
820 gettext_noop ("# bytes currently in TCP buffers"),
821 -(int64_t) ret, GNUNET_NO);
822 GNUNET_STATISTICS_update (plugin->env->stats,
824 ("# bytes discarded by TCP (timeout)"), ret,
828 /* copy all pending messages that would fit */
833 while (NULL != (pos = session->pending_messages_head))
835 if (ret + pos->message_size > size)
837 GNUNET_CONTAINER_DLL_remove (session->pending_messages_head,
838 session->pending_messages_tail, pos);
839 GNUNET_assert (size >= pos->message_size);
840 LOG (GNUNET_ERROR_TYPE_DEBUG,
841 "Transmitting message of type %u\n",
842 ntohs (((struct GNUNET_MessageHeader *) pos->msg)->type));
843 /* FIXME: this memcpy can be up to 7% of our total runtime */
844 memcpy (cbuf, pos->msg, pos->message_size);
845 cbuf += pos->message_size;
846 ret += pos->message_size;
847 size -= pos->message_size;
848 GNUNET_CONTAINER_DLL_insert_tail (hd, tl, pos);
850 /* schedule 'continuation' before callbacks so that callbacks that
851 * cancel everything don't cause us to use a session that no longer
853 process_pending_messages (session);
854 session->last_activity = GNUNET_TIME_absolute_get ();
855 pid = session->target;
856 /* we'll now call callbacks that may cancel the session; hence
857 * we should not use 'session' after this point */
858 while (NULL != (pos = hd))
860 GNUNET_CONTAINER_DLL_remove (hd, tl, pos);
861 if (pos->transmit_cont != NULL)
862 pos->transmit_cont (pos->transmit_cont_cls, &pid, GNUNET_OK);
865 GNUNET_assert (hd == NULL);
866 GNUNET_assert (tl == NULL);
867 LOG (GNUNET_ERROR_TYPE_DEBUG, "Transmitting %u bytes\n",
869 GNUNET_STATISTICS_update (plugin->env->stats,
870 gettext_noop ("# bytes currently in TCP buffers"),
871 -(int64_t) ret, GNUNET_NO);
872 GNUNET_STATISTICS_update (plugin->env->stats,
873 gettext_noop ("# bytes transmitted via TCP"), ret,
880 * If we have pending messages, ask the server to
881 * transmit them (schedule the respective tasks, etc.)
883 * @param session for which session should we do this
886 process_pending_messages (struct Session *session)
888 struct PendingMessage *pm;
890 GNUNET_assert (session->client != NULL);
891 if (session->transmit_handle != NULL)
893 if (NULL == (pm = session->pending_messages_head))
896 session->transmit_handle =
897 GNUNET_SERVER_notify_transmit_ready (session->client, pm->message_size,
898 GNUNET_TIME_absolute_get_remaining
899 (pm->timeout), &do_transmit,
905 * Functions with this signature are called whenever we need
906 * to close a session due to a disconnect or failure to
907 * establish a connection.
909 * @param session session to close down
912 disconnect_session (struct Session *session)
914 struct PendingMessage *pm;
915 struct Plugin * plugin = session->plugin;
917 LOG (GNUNET_ERROR_TYPE_DEBUG,
918 "Disconnecting session of peer `%s' address `%s'\n",
919 GNUNET_i2s (&session->target),
920 tcp_address_to_string(NULL, session->addr, session->addrlen));
922 if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(plugin->sessionmap, &session->target.hashPubKey, session))
924 GNUNET_STATISTICS_update (session->plugin->env->stats,
925 gettext_noop ("# TCP sessions active"), -1,
927 dec_sessions (plugin, session, __LINE__);
929 else GNUNET_assert (GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(plugin->nat_wait_conns, &session->target.hashPubKey, session));
932 if (session->transmit_handle != NULL)
934 GNUNET_SERVER_notify_transmit_ready_cancel (session->transmit_handle);
935 session->transmit_handle = NULL;
937 session->plugin->env->session_end (session->plugin->env->cls,
938 &session->target, session);
940 if (session->nat_connection_timeout != GNUNET_SCHEDULER_NO_TASK)
942 GNUNET_SCHEDULER_cancel (session->nat_connection_timeout);
943 session->nat_connection_timeout = GNUNET_SCHEDULER_NO_TASK;
946 while (NULL != (pm = session->pending_messages_head))
948 LOG (GNUNET_ERROR_TYPE_DEBUG,
950 NULL ? "Could not deliver message to `%4s'.\n" :
951 "Could not deliver message to `%4s', notifying.\n",
952 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;
980 GNUNET_free_non_null (session->addr);
981 GNUNET_assert (NULL == session->transmit_handle);
982 GNUNET_free (session);
987 * Function that can be used by the transport service to transmit
988 * a message using the plugin. Note that in the case of a
989 * peer disconnecting, the continuation MUST be called
990 * prior to the disconnect notification itself. This function
991 * will be called with this peer's HELLO message to initiate
992 * a fresh connection to another peer.
995 * @param session which session must be used
996 * @param msgbuf the message to transmit
997 * @param msgbuf_size number of bytes in 'msgbuf'
998 * @param priority how important is the message (most plugins will
999 * ignore message priority and just FIFO)
1000 * @param to how long to wait at most for the transmission (does not
1001 * require plugins to discard the message after the timeout,
1002 * just advisory for the desired delay; most plugins will ignore
1004 * @param cont continuation to call once the message has
1005 * been transmitted (or if the transport is ready
1006 * for the next transmission call; or if the
1007 * peer disconnected...); can be NULL
1008 * @param cont_cls closure for cont
1009 * @return number of bytes used (on the physical network, with overheads);
1010 * -1 on hard errors (i.e. address invalid); 0 is a legal value
1011 * and does NOT mean that the message was not transmitted (DV)
1014 tcp_plugin_send (void *cls,
1015 struct Session *session,
1016 const char *msgbuf, size_t msgbuf_size,
1017 unsigned int priority,
1018 struct GNUNET_TIME_Relative to,
1019 GNUNET_TRANSPORT_TransmitContinuation cont, void *cont_cls)
1021 struct Plugin * plugin = cls;
1022 struct PendingMessage *pm;
1024 GNUNET_assert (plugin != NULL);
1025 GNUNET_assert (session != NULL);
1027 /* create new message entry */
1028 pm = GNUNET_malloc (sizeof (struct PendingMessage) + msgbuf_size);
1029 pm->msg = (const char *) &pm[1];
1030 memcpy (&pm[1], msgbuf, msgbuf_size);
1031 pm->message_size = msgbuf_size;
1032 pm->timeout = GNUNET_TIME_relative_to_absolute (to);
1033 pm->transmit_cont = cont;
1034 pm->transmit_cont_cls = cont_cls;
1036 LOG (GNUNET_ERROR_TYPE_DEBUG,
1037 "Asked to transmit %u bytes to `%s', added message to list.\n",
1038 msgbuf_size, GNUNET_i2s (&session->target));
1040 if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains_value(plugin->sessionmap, &session->target.hashPubKey, session))
1042 GNUNET_assert (session->client != NULL);
1044 GNUNET_SERVER_client_set_timeout (session->client,
1045 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1046 GNUNET_STATISTICS_update (plugin->env->stats,
1047 gettext_noop ("# bytes currently in TCP buffers"),
1048 msgbuf_size, GNUNET_NO);
1050 /* append pm to pending_messages list */
1051 GNUNET_CONTAINER_DLL_insert_tail (session->pending_messages_head,
1052 session->pending_messages_tail, pm);
1054 process_pending_messages (session);
1057 else if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains_value(plugin->nat_wait_conns, &session->target.hashPubKey, session))
1059 LOG (GNUNET_ERROR_TYPE_DEBUG,
1060 "This NAT WAIT session for peer `%s' is not yet ready!\n",
1061 GNUNET_i2s (&session->target));
1063 GNUNET_STATISTICS_update (plugin->env->stats,
1064 gettext_noop ("# bytes currently in TCP buffers"),
1065 msgbuf_size, GNUNET_NO);
1067 /* append pm to pending_messages list */
1068 GNUNET_CONTAINER_DLL_insert_tail (session->pending_messages_head,
1069 session->pending_messages_tail, pm);
1075 cont (cont_cls, &session->target, GNUNET_SYSERR);
1078 return GNUNET_SYSERR; /* session does not exist here */
1086 struct Session * result;
1090 session_lookup_it (void *cls,
1091 const GNUNET_HashCode * key,
1094 struct SessionItCtx * si_ctx = cls;
1095 struct Session * session = value;
1097 char * a1 = strdup (tcp_address_to_string(NULL, session->addr, session->addrlen));
1098 char * a2 = strdup (tcp_address_to_string(NULL, si_ctx->addr, si_ctx->addrlen));
1099 LOG (GNUNET_ERROR_TYPE_DEBUG,
1100 "Comparing: %s %u <-> %s %u\n",
1108 if (session->addrlen != si_ctx->addrlen)
1112 if (0 != memcmp (session->addr, si_ctx->addr, si_ctx->addrlen))
1117 a1 = strdup (tcp_address_to_string(NULL, session->addr, session->addrlen));
1118 a2 = strdup (tcp_address_to_string(NULL, si_ctx->addr, si_ctx->addrlen));
1119 LOG (GNUNET_ERROR_TYPE_DEBUG,
1120 "Comparing: %s %u <-> %s %u , OK!\n",
1128 /* Found existing session */
1129 si_ctx->result = session;
1135 * Task cleaning up a NAT connection attempt after timeout
1138 nat_connect_timeout (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1140 struct Session *session = cls;
1142 LOG (GNUNET_ERROR_TYPE_DEBUG,
1143 "NAT WAIT connection to `%4s' at `%s' could not be established, removing session\n",
1144 GNUNET_i2s (&session->target), tcp_address_to_string(NULL, session->addr, session->addrlen));
1145 disconnect_session (session);
1150 * Create a new session to transmit data to the target
1151 * This session will used to send data to this peer and the plugin will
1152 * notify us by calling the env->session_end function
1154 * @param cls closure
1155 * @param address pointer to the GNUNET_HELLO_Address
1156 * @return the session if the address is valid, NULL otherwise
1158 static struct Session *
1159 tcp_plugin_get_session (void *cls,
1160 const struct GNUNET_HELLO_Address *address)
1162 struct Plugin * plugin = cls;
1163 struct Session * session = NULL;
1167 struct GNUNET_CONNECTION_Handle *sa;
1168 struct sockaddr_in a4;
1169 struct sockaddr_in6 a6;
1170 const struct IPv4TcpAddress *t4;
1171 const struct IPv6TcpAddress *t6;
1172 struct GNUNET_ATS_Information ats;
1173 unsigned int is_natd = GNUNET_NO;
1176 GNUNET_assert (plugin != NULL);
1177 GNUNET_assert (address != NULL);
1178 addrlen = address->address_length;
1179 LOG (GNUNET_ERROR_TYPE_ERROR,
1180 "Trying to get session for `%s' address of peer `%s'\n",
1181 tcp_address_to_string(NULL, address->address, address->address_length),
1182 GNUNET_i2s (&address->peer));
1184 /* look for existing session */
1186 GNUNET_CONTAINER_multihashmap_contains(plugin->sessionmap, &address->peer.hashPubKey))
1188 struct SessionItCtx si_ctx;
1190 si_ctx.addr = (void *) address->address;
1191 si_ctx.addrlen = address->address_length;
1193 si_ctx.result = NULL;
1195 GNUNET_CONTAINER_multihashmap_get_multiple(plugin->sessionmap, &address->peer.hashPubKey, &session_lookup_it, &si_ctx);
1196 if (si_ctx.result != NULL)
1198 session = si_ctx.result;
1199 LOG (GNUNET_ERROR_TYPE_DEBUG,
1200 "Found exisiting session for `%s' address `%s' session %p\n",
1201 GNUNET_i2s (&address->peer),
1202 tcp_address_to_string(NULL, address->address, address->address_length),
1206 LOG (GNUNET_ERROR_TYPE_DEBUG,
1207 "Existing sessions did not match address `%s' or peer `%s'\n",
1208 tcp_address_to_string(NULL, address->address, address->address_length),
1209 GNUNET_i2s (&address->peer));
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 LOG (GNUNET_ERROR_TYPE_ERROR,
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)))
1282 LOG (GNUNET_ERROR_TYPE_DEBUG,
1283 "Found valid IPv4 NAT address (creating session)!\n") ;
1284 session = create_session (plugin, &address->peer, NULL, GNUNET_YES);
1285 session->addrlen = 0;
1286 session->addr = NULL;
1287 session->ats_address_network_type = ats.value;
1288 session->nat_connection_timeout = GNUNET_SCHEDULER_add_delayed(NAT_TIMEOUT,
1289 &nat_connect_timeout,
1291 GNUNET_assert (session != NULL);
1292 GNUNET_assert (GNUNET_CONTAINER_multihashmap_put
1293 (plugin->nat_wait_conns, &address->peer.hashPubKey, session,
1294 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY) == GNUNET_OK);
1296 LOG (GNUNET_ERROR_TYPE_DEBUG,
1297 "Created NAT WAIT connection to `%4s' at `%s'\n",
1298 GNUNET_i2s (&session->target), GNUNET_a2s (sb, sbs));
1300 if (GNUNET_OK == GNUNET_NAT_run_client (plugin->nat, &a4))
1304 LOG (GNUNET_ERROR_TYPE_DEBUG,
1305 "Running NAT client for `%4s' at `%s' failed\n",
1306 GNUNET_i2s (&session->target), GNUNET_a2s (sb, sbs));
1307 disconnect_session (session);
1312 /* create new outbound session */
1313 GNUNET_assert (0 != plugin->max_connections);
1314 sa = GNUNET_CONNECTION_create_from_sockaddr (af, sb, sbs);
1317 LOG (GNUNET_ERROR_TYPE_DEBUG,
1318 "Failed to create connection to `%4s' at `%s'\n",
1319 GNUNET_i2s (&session->target), GNUNET_a2s (sb, sbs));
1322 plugin->max_connections--;
1324 LOG (GNUNET_ERROR_TYPE_DEBUG,
1325 "Asked to transmit to `%4s', creating fresh session using address `%s'.\n",
1326 GNUNET_i2s (&address->peer), GNUNET_a2s (sb, sbs));
1328 session = create_session (plugin,
1330 GNUNET_SERVER_connect_socket (plugin->server, sa),
1332 session->addr = GNUNET_malloc (addrlen);
1333 memcpy (session->addr, address->address, addrlen);
1334 session->addrlen = addrlen;
1335 session->ats_address_network_type = ats.value;
1337 GNUNET_CONTAINER_multihashmap_put(plugin->sessionmap, &address->peer.hashPubKey, session, GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
1338 inc_sessions (plugin, session, __LINE__);
1339 LOG (GNUNET_ERROR_TYPE_DEBUG,
1340 "Creating new session for `%s' address `%s' session %p\n",
1341 GNUNET_i2s (&address->peer),
1342 tcp_address_to_string(NULL, address->address, address->address_length),
1344 /* Send TCP Welcome */
1345 process_pending_messages (session);
1352 session_disconnect_it (void *cls,
1353 const GNUNET_HashCode * key,
1356 struct Session *session = value;
1358 GNUNET_STATISTICS_update (session->plugin->env->stats,
1360 ("# transport-service disconnect requests for TCP"),
1362 disconnect_session (session);
1367 * Function that can be called to force a disconnect from the
1368 * specified neighbour. This should also cancel all previously
1369 * scheduled transmissions. Obviously the transmission may have been
1370 * partially completed already, which is OK. The plugin is supposed
1371 * to close the connection (if applicable) and no longer call the
1372 * transmit continuation(s).
1374 * Finally, plugin MUST NOT call the services's receive function to
1375 * notify the service that the connection to the specified target was
1376 * closed after a getting this call.
1378 * @param cls closure
1379 * @param target peer for which the last transmission is
1383 tcp_plugin_disconnect (void *cls, const struct GNUNET_PeerIdentity *target)
1385 struct Plugin *plugin = cls;
1387 LOG (GNUNET_ERROR_TYPE_DEBUG,
1388 "Disconnecting peer `%4s'\n", GNUNET_i2s (target));
1389 GNUNET_CONTAINER_multihashmap_get_multiple (plugin->sessionmap, &target->hashPubKey, &session_disconnect_it, plugin);
1390 GNUNET_CONTAINER_multihashmap_get_multiple (plugin->nat_wait_conns, &target->hashPubKey, &session_disconnect_it, plugin);
1395 * Context for address to string conversion.
1397 struct PrettyPrinterContext
1400 * Function to call with the result.
1402 GNUNET_TRANSPORT_AddressStringCallback asc;
1405 * Clsoure for 'asc'.
1410 * Port to add after the IP address.
1419 * Append our port and forward the result.
1421 * @param cls the 'struct PrettyPrinterContext*'
1422 * @param hostname hostname part of the address
1425 append_port (void *cls, const char *hostname)
1427 struct PrettyPrinterContext *ppc = cls;
1430 if (hostname == NULL)
1432 ppc->asc (ppc->asc_cls, NULL);
1436 if (GNUNET_YES == ppc->ipv6)
1437 GNUNET_asprintf (&ret, "[%s]:%d", hostname, ppc->port);
1439 GNUNET_asprintf (&ret, "%s:%d", hostname, ppc->port);
1440 ppc->asc (ppc->asc_cls, ret);
1446 * Convert the transports address to a nice, human-readable
1449 * @param cls closure
1450 * @param type name of the transport that generated the address
1451 * @param addr one of the addresses of the host, NULL for the last address
1452 * the specific address format depends on the transport
1453 * @param addrlen length of the address
1454 * @param numeric should (IP) addresses be displayed in numeric form?
1455 * @param timeout after how long should we give up?
1456 * @param asc function to call on each string
1457 * @param asc_cls closure for asc
1460 tcp_plugin_address_pretty_printer (void *cls, const char *type,
1461 const void *addr, size_t addrlen,
1463 struct GNUNET_TIME_Relative timeout,
1464 GNUNET_TRANSPORT_AddressStringCallback asc,
1467 struct PrettyPrinterContext *ppc;
1470 struct sockaddr_in a4;
1471 struct sockaddr_in6 a6;
1472 const struct IPv4TcpAddress *t4;
1473 const struct IPv6TcpAddress *t6;
1476 if (addrlen == sizeof (struct IPv6TcpAddress))
1479 memset (&a6, 0, sizeof (a6));
1480 a6.sin6_family = AF_INET6;
1481 a6.sin6_port = t6->t6_port;
1482 memcpy (&a6.sin6_addr, &t6->ipv6_addr, sizeof (struct in6_addr));
1483 port = ntohs (t6->t6_port);
1487 else if (addrlen == sizeof (struct IPv4TcpAddress))
1490 memset (&a4, 0, sizeof (a4));
1491 a4.sin_family = AF_INET;
1492 a4.sin_port = t4->t4_port;
1493 a4.sin_addr.s_addr = t4->ipv4_addr;
1494 port = ntohs (t4->t4_port);
1498 else if (0 == addrlen)
1500 asc (asc_cls, "<inbound connection>");
1501 asc (asc_cls, NULL);
1506 /* invalid address */
1507 GNUNET_break_op (0);
1508 asc (asc_cls, NULL);
1511 ppc = GNUNET_malloc (sizeof (struct PrettyPrinterContext));
1512 if (addrlen == sizeof (struct IPv6TcpAddress))
1513 ppc->ipv6 = GNUNET_YES;
1515 ppc->ipv6 = GNUNET_NO;
1517 ppc->asc_cls = asc_cls;
1519 GNUNET_RESOLVER_hostname_get (sb, sbs, !numeric, timeout, &append_port, ppc);
1524 * Check if the given port is plausible (must be either our listen
1525 * port or our advertised port), or any port if we are behind NAT
1526 * and do not have a port open. If it is neither, we return
1529 * @param plugin global variables
1530 * @param in_port port number to check
1531 * @return GNUNET_OK if port is either open_port or adv_port
1534 check_port (struct Plugin *plugin, uint16_t in_port)
1536 if ((in_port == plugin->adv_port) || (in_port == plugin->open_port))
1538 return GNUNET_SYSERR;
1543 * Function that will be called to check if a binary address for this
1544 * plugin is well-formed and corresponds to an address for THIS peer
1545 * (as per our configuration). Naturally, if absolutely necessary,
1546 * plugins can be a bit conservative in their answer, but in general
1547 * plugins should make sure that the address does not redirect
1548 * traffic to a 3rd party that might try to man-in-the-middle our
1551 * @param cls closure, our 'struct Plugin*'
1552 * @param addr pointer to the address
1553 * @param addrlen length of addr
1554 * @return GNUNET_OK if this is a plausible address for this peer
1555 * and transport, GNUNET_SYSERR if not
1558 tcp_plugin_check_address (void *cls, const void *addr, size_t addrlen)
1560 struct Plugin *plugin = cls;
1561 struct IPv4TcpAddress *v4;
1562 struct IPv6TcpAddress *v6;
1564 if ((addrlen != sizeof (struct IPv4TcpAddress)) &&
1565 (addrlen != sizeof (struct IPv6TcpAddress)))
1567 GNUNET_break_op (0);
1568 return GNUNET_SYSERR;
1570 if (addrlen == sizeof (struct IPv4TcpAddress))
1572 v4 = (struct IPv4TcpAddress *) addr;
1573 if (GNUNET_OK != check_port (plugin, ntohs (v4->t4_port)))
1574 return GNUNET_SYSERR;
1576 GNUNET_NAT_test_address (plugin->nat, &v4->ipv4_addr,
1577 sizeof (struct in_addr)))
1578 return GNUNET_SYSERR;
1582 v6 = (struct IPv6TcpAddress *) addr;
1583 if (IN6_IS_ADDR_LINKLOCAL (&v6->ipv6_addr))
1585 GNUNET_break_op (0);
1586 return GNUNET_SYSERR;
1588 if (GNUNET_OK != check_port (plugin, ntohs (v6->t6_port)))
1589 return GNUNET_SYSERR;
1591 GNUNET_NAT_test_address (plugin->nat, &v6->ipv6_addr,
1592 sizeof (struct in6_addr)))
1593 return GNUNET_SYSERR;
1600 * We've received a nat probe from this peer via TCP. Finish
1601 * creating the client session and resume sending of queued
1604 * @param cls closure
1605 * @param client identification of the client
1606 * @param message the actual message
1609 handle_tcp_nat_probe (void *cls, struct GNUNET_SERVER_Client *client,
1610 const struct GNUNET_MessageHeader *message)
1612 struct Plugin *plugin = cls;
1613 struct Session *session;
1614 const struct TCP_NAT_ProbeMessage *tcp_nat_probe;
1617 struct IPv4TcpAddress *t4;
1618 struct IPv6TcpAddress *t6;
1619 const struct sockaddr_in *s4;
1620 const struct sockaddr_in6 *s6;
1622 LOG (GNUNET_ERROR_TYPE_DEBUG, "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 LOG (GNUNET_ERROR_TYPE_DEBUG,
1654 "Did NOT find session for NAT probe!\n");
1655 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1658 LOG (GNUNET_ERROR_TYPE_DEBUG,
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;
1683 LOG (GNUNET_ERROR_TYPE_DEBUG,
1684 "Found address `%s' for incoming connection\n",
1685 GNUNET_a2s (vaddr, alen));
1686 switch (((const struct sockaddr *) vaddr)->sa_family)
1690 t4 = GNUNET_malloc (sizeof (struct IPv4TcpAddress));
1691 t4->t4_port = s4->sin_port;
1692 t4->ipv4_addr = s4->sin_addr.s_addr;
1694 session->addrlen = sizeof (struct IPv4TcpAddress);
1698 t6 = GNUNET_malloc (sizeof (struct IPv6TcpAddress));
1699 t6->t6_port = s6->sin6_port;
1700 memcpy (&t6->ipv6_addr, &s6->sin6_addr, sizeof (struct in6_addr));
1702 session->addrlen = sizeof (struct IPv6TcpAddress);
1705 GNUNET_break_op (0);
1706 LOG (GNUNET_ERROR_TYPE_DEBUG,
1707 "Bad address for incoming connection!\n");
1708 GNUNET_free (vaddr);
1710 GNUNET_SERVER_client_drop (client);
1711 GNUNET_free (session);
1712 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1715 GNUNET_free (vaddr);
1717 GNUNET_CONTAINER_multihashmap_put(plugin->sessionmap, &session->target.hashPubKey, session, GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
1718 inc_sessions (plugin, session, __LINE__);
1719 GNUNET_STATISTICS_update (plugin->env->stats,
1720 gettext_noop ("# TCP sessions active"), 1,
1722 process_pending_messages (session);
1723 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1728 * We've received a welcome from this peer via TCP. Possibly create a
1729 * fresh client record and send back our welcome.
1731 * @param cls closure
1732 * @param client identification of the client
1733 * @param message the actual message
1736 handle_tcp_welcome (void *cls, struct GNUNET_SERVER_Client *client,
1737 const struct GNUNET_MessageHeader *message)
1739 struct Plugin *plugin = cls;
1740 const struct WelcomeMessage *wm = (const struct WelcomeMessage *) message;
1741 struct Session *session;
1744 struct IPv4TcpAddress *t4;
1745 struct IPv6TcpAddress *t6;
1746 const struct sockaddr_in *s4;
1747 const struct sockaddr_in6 *s6;
1750 memcmp (&wm->clientIdentity, plugin->env->my_identity,
1751 sizeof (struct GNUNET_PeerIdentity)))
1753 /* refuse connections from ourselves */
1754 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1757 LOG (GNUNET_ERROR_TYPE_ERROR,
1758 "Received %s message from `%4s'\n", "WELCOME",
1759 GNUNET_i2s (&wm->clientIdentity));
1760 GNUNET_STATISTICS_update (plugin->env->stats,
1761 gettext_noop ("# TCP WELCOME messages received"), 1,
1763 session = lookup_session_by_client (plugin, client);
1764 if (session != NULL)
1766 if (GNUNET_OK == GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
1768 LOG (GNUNET_ERROR_TYPE_DEBUG,
1769 "Found existing session %p for peer `%s'\n",
1771 GNUNET_a2s (vaddr, alen));
1772 GNUNET_free (vaddr);
1777 GNUNET_SERVER_client_keep (client);
1778 session = create_session (plugin, &wm->clientIdentity, client, GNUNET_NO);
1779 session->inbound = GNUNET_YES;
1780 if (GNUNET_OK == GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
1782 if (alen == sizeof (struct sockaddr_in))
1785 t4 = GNUNET_malloc (sizeof (struct IPv4TcpAddress));
1786 t4->t4_port = s4->sin_port;
1787 t4->ipv4_addr = s4->sin_addr.s_addr;
1789 session->addrlen = sizeof (struct IPv4TcpAddress);
1791 else if (alen == sizeof (struct sockaddr_in6))
1794 t6 = GNUNET_malloc (sizeof (struct IPv6TcpAddress));
1795 t6->t6_port = s6->sin6_port;
1796 memcpy (&t6->ipv6_addr, &s6->sin6_addr, sizeof (struct in6_addr));
1798 session->addrlen = sizeof (struct IPv6TcpAddress);
1801 struct GNUNET_ATS_Information ats;
1802 ats = plugin->env->get_address_type (plugin->env->cls, vaddr ,alen);
1803 session->ats_address_network_type = ats.value;
1805 GNUNET_free (vaddr);
1809 LOG (GNUNET_ERROR_TYPE_DEBUG,
1810 "Did not obtain TCP socket address for incoming connection\n");
1812 GNUNET_CONTAINER_multihashmap_put(plugin->sessionmap, &wm->clientIdentity.hashPubKey, session, GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
1813 inc_sessions (plugin, session, __LINE__);
1816 if (session->expecting_welcome != GNUNET_YES)
1818 GNUNET_break_op (0);
1819 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1822 session->last_activity = GNUNET_TIME_absolute_get ();
1823 session->expecting_welcome = GNUNET_NO;
1826 process_pending_messages (session);
1828 GNUNET_SERVER_client_set_timeout (client,
1829 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1830 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1835 * Task to signal the server that we can continue
1836 * receiving from the TCP client now.
1838 * @param cls the 'struct Session*'
1839 * @param tc task context (unused)
1842 delayed_done (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1844 struct Session *session = cls;
1845 struct GNUNET_TIME_Relative delay;
1846 struct GNUNET_ATS_Information ats;
1848 session->receive_delay_task = GNUNET_SCHEDULER_NO_TASK;
1850 session->plugin->env->receive (session->plugin->env->cls,
1851 &session->target, NULL, &ats, 0, session,
1853 if (delay.rel_value == 0)
1854 GNUNET_SERVER_receive_done (session->client, GNUNET_OK);
1856 session->receive_delay_task =
1857 GNUNET_SCHEDULER_add_delayed (delay, &delayed_done, session);
1862 * We've received data for this peer via TCP. Unbox,
1863 * compute latency and forward.
1865 * @param cls closure
1866 * @param client identification of the client
1867 * @param message the actual message
1870 handle_tcp_data (void *cls, struct GNUNET_SERVER_Client *client,
1871 const struct GNUNET_MessageHeader *message)
1873 struct Plugin *plugin = cls;
1874 struct Session *session;
1875 struct GNUNET_TIME_Relative delay;
1878 type = ntohs (message->type);
1879 if ((GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME == type) ||
1880 (GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE == type))
1882 /* We don't want to propagate WELCOME and NAT Probe messages up! */
1883 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1886 session = lookup_session_by_client (plugin, client);
1887 if (NULL == session)
1889 /* No inbound session found */
1893 GNUNET_SERVER_client_get_address (client, &vaddr, &alen);
1894 LOG (GNUNET_ERROR_TYPE_ERROR,
1895 "Received unexpected %u bytes of type %u from `%s'\n",
1896 (unsigned int) ntohs (message->size),
1897 (unsigned int) ntohs (message->type),
1898 GNUNET_a2s(vaddr, alen));
1899 GNUNET_break_op (0);
1900 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1901 GNUNET_free_non_null(vaddr);
1904 else if (GNUNET_YES == session->expecting_welcome)
1906 /* Session is expecting WELCOME message */
1910 GNUNET_SERVER_client_get_address (client, &vaddr, &alen);
1911 LOG (GNUNET_ERROR_TYPE_ERROR,
1912 "Received unexpected %u bytes of type %u from `%s'\n",
1913 (unsigned int) ntohs (message->size),
1914 (unsigned int) ntohs (message->type),
1915 GNUNET_a2s(vaddr, alen));
1916 GNUNET_break_op (0);
1917 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1918 GNUNET_free_non_null(vaddr);
1922 session->last_activity = GNUNET_TIME_absolute_get ();
1923 LOG (GNUNET_ERROR_TYPE_DEBUG,
1924 "Passing %u bytes of type %u from `%4s' to transport service.\n",
1925 (unsigned int) ntohs (message->size),
1926 (unsigned int) ntohs (message->type),
1927 GNUNET_i2s (&session->target));
1929 GNUNET_STATISTICS_update (plugin->env->stats,
1930 gettext_noop ("# bytes received via TCP"),
1931 ntohs (message->size), GNUNET_NO);
1932 struct GNUNET_ATS_Information distance[2];
1934 distance[0].type = htonl (GNUNET_ATS_QUALITY_NET_DISTANCE);
1935 distance[0].value = htonl (1);
1936 distance[1].type = htonl (GNUNET_ATS_NETWORK_TYPE);
1937 distance[1].value = session->ats_address_network_type;
1938 GNUNET_break (ntohl(session->ats_address_network_type) != GNUNET_ATS_NET_UNSPECIFIED);
1940 delay = plugin->env->receive (plugin->env->cls,
1943 (const struct GNUNET_ATS_Information *) &distance,
1945 (GNUNET_YES == session->inbound) ? NULL : session->addr,
1946 (GNUNET_YES == session->inbound) ? 0 : session->addrlen);
1947 if (delay.rel_value == 0)
1949 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1953 LOG (GNUNET_ERROR_TYPE_DEBUG,
1954 "Throttling receiving from `%s' for %llu ms\n",
1955 GNUNET_i2s (&session->target),
1956 (unsigned long long) delay.rel_value);
1957 GNUNET_SERVER_disable_receive_done_warning (client);
1958 session->receive_delay_task =
1959 GNUNET_SCHEDULER_add_delayed (delay, &delayed_done, session);
1965 * Functions with this signature are called whenever a peer
1966 * is disconnected on the network level.
1968 * @param cls closure
1969 * @param client identification of the client
1972 disconnect_notify (void *cls, struct GNUNET_SERVER_Client *client)
1974 struct Plugin *plugin = cls;
1975 struct Session *session;
1979 plugin->max_connections++;
1980 session = lookup_session_by_client (plugin, client);
1981 if (session == NULL)
1982 return; /* unknown, nothing to do */
1983 LOG (GNUNET_ERROR_TYPE_DEBUG,
1984 "Destroying session of `%4s' with %s due to network-level disconnect.\n",
1985 GNUNET_i2s (&session->target),
1987 NULL) ? tcp_address_to_string (session->plugin,
1991 GNUNET_STATISTICS_update (session->plugin->env->stats,
1993 ("# network-level TCP disconnect events"), 1,
1995 disconnect_session (session);
2000 * We can now send a probe message, copy into buffer to really send.
2002 * @param cls closure, a struct TCPProbeContext
2003 * @param size max size to copy
2004 * @param buf buffer to copy message to
2005 * @return number of bytes copied into buf
2008 notify_send_probe (void *cls, size_t size, void *buf)
2010 struct TCPProbeContext *tcp_probe_ctx = cls;
2011 struct Plugin *plugin = tcp_probe_ctx->plugin;
2014 tcp_probe_ctx->transmit_handle = NULL;
2015 GNUNET_CONTAINER_DLL_remove (plugin->probe_head, plugin->probe_tail,
2019 GNUNET_CONNECTION_destroy (tcp_probe_ctx->sock);
2020 GNUNET_free (tcp_probe_ctx);
2023 GNUNET_assert (size >= sizeof (tcp_probe_ctx->message));
2024 memcpy (buf, &tcp_probe_ctx->message, sizeof (tcp_probe_ctx->message));
2025 GNUNET_SERVER_connect_socket (tcp_probe_ctx->plugin->server,
2026 tcp_probe_ctx->sock);
2027 ret = sizeof (tcp_probe_ctx->message);
2028 GNUNET_free (tcp_probe_ctx);
2034 * Function called by the NAT subsystem suggesting another peer wants
2035 * to connect to us via connection reversal. Try to connect back to the
2038 * @param cls closure
2039 * @param addr address to try
2040 * @param addrlen number of bytes in addr
2043 try_connection_reversal (void *cls, const struct sockaddr *addr,
2046 struct Plugin *plugin = cls;
2047 struct GNUNET_CONNECTION_Handle *sock;
2048 struct TCPProbeContext *tcp_probe_ctx;
2051 * We have received an ICMP response, ostensibly from a peer
2052 * that wants to connect to us! Send a message to establish a connection.
2054 sock = GNUNET_CONNECTION_create_from_sockaddr (AF_INET, addr, addrlen);
2057 /* failed for some odd reason (out of sockets?); ignore attempt */
2061 /* FIXME: do we need to track these probe context objects so that
2062 * we can clean them up on plugin unload? */
2063 tcp_probe_ctx = GNUNET_malloc (sizeof (struct TCPProbeContext));
2064 tcp_probe_ctx->message.header.size =
2065 htons (sizeof (struct TCP_NAT_ProbeMessage));
2066 tcp_probe_ctx->message.header.type =
2067 htons (GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE);
2068 memcpy (&tcp_probe_ctx->message.clientIdentity, plugin->env->my_identity,
2069 sizeof (struct GNUNET_PeerIdentity));
2070 tcp_probe_ctx->plugin = plugin;
2071 tcp_probe_ctx->sock = sock;
2072 GNUNET_CONTAINER_DLL_insert (plugin->probe_head, plugin->probe_tail,
2074 tcp_probe_ctx->transmit_handle =
2075 GNUNET_CONNECTION_notify_transmit_ready (sock,
2076 ntohs (tcp_probe_ctx->
2077 message.header.size),
2078 GNUNET_TIME_UNIT_FOREVER_REL,
2086 * Entry point for the plugin.
2088 * @param cls closure, the 'struct GNUNET_TRANSPORT_PluginEnvironment*'
2089 * @return the 'struct GNUNET_TRANSPORT_PluginFunctions*' or NULL on error
2092 libgnunet_plugin_transport_tcp_init (void *cls)
2094 static const struct GNUNET_SERVER_MessageHandler my_handlers[] = {
2095 {&handle_tcp_welcome, NULL, GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME,
2096 sizeof (struct WelcomeMessage)},
2097 {&handle_tcp_nat_probe, NULL, GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE,
2098 sizeof (struct TCP_NAT_ProbeMessage)},
2099 {&handle_tcp_data, NULL, GNUNET_MESSAGE_TYPE_ALL, 0},
2102 struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
2103 struct GNUNET_TRANSPORT_PluginFunctions *api;
2104 struct Plugin *plugin;
2105 struct GNUNET_SERVICE_Context *service;
2106 unsigned long long aport;
2107 unsigned long long bport;
2108 unsigned long long max_connections;
2110 struct GNUNET_TIME_Relative idle_timeout;
2112 struct sockaddr **addrs;
2113 socklen_t *addrlens;
2115 if (NULL == env->receive)
2117 /* run in 'stub' mode (i.e. as part of gnunet-peerinfo), don't fully
2118 initialze the plugin or the API */
2119 api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
2121 api->address_pretty_printer = &tcp_plugin_address_pretty_printer;
2122 api->address_to_string = &tcp_address_to_string;
2123 api->string_to_address = &tcp_string_to_address;
2128 GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-tcp",
2131 max_connections = 128;
2135 GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-tcp", "PORT",
2136 &bport)) || (bport > 65535) ||
2138 GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-tcp",
2139 "ADVERTISED-PORT", &aport)) &&
2142 LOG (GNUNET_ERROR_TYPE_ERROR,
2144 ("Require valid port number for service `%s' in configuration!\n"),
2154 service = GNUNET_SERVICE_start ("transport-tcp", env->cfg, GNUNET_SERVICE_OPTION_NONE);
2155 if (service == NULL)
2157 LOG (GNUNET_ERROR_TYPE_WARNING,
2158 _("Failed to start service.\n"));
2165 plugin = GNUNET_malloc (sizeof (struct Plugin));
2166 plugin->sessionmap = GNUNET_CONTAINER_multihashmap_create(max_connections);
2167 plugin->max_connections = max_connections;
2168 plugin->open_port = bport;
2169 plugin->adv_port = aport;
2171 plugin->lsock = NULL;
2172 if ((service != NULL) &&
2175 GNUNET_SERVICE_get_server_addresses ("transport-tcp", env->cfg, &addrs,
2179 GNUNET_NAT_register (env->cfg, GNUNET_YES, aport, (unsigned int) ret,
2180 (const struct sockaddr **) addrs, addrlens,
2181 &tcp_nat_port_map_callback,
2182 &try_connection_reversal, plugin);
2186 GNUNET_assert (addrs[ret] != NULL);
2187 GNUNET_free (addrs[ret]);
2189 GNUNET_free_non_null (addrs);
2190 GNUNET_free_non_null (addrlens);
2195 GNUNET_NAT_register (env->cfg, GNUNET_YES, 0, 0, NULL, NULL, NULL,
2196 &try_connection_reversal, plugin);
2198 api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
2200 api->send = &tcp_plugin_send;
2201 api->get_session = &tcp_plugin_get_session;
2203 api->disconnect = &tcp_plugin_disconnect;
2204 api->address_pretty_printer = &tcp_plugin_address_pretty_printer;
2205 api->check_address = &tcp_plugin_check_address;
2206 api->address_to_string = &tcp_address_to_string;
2207 api->string_to_address = &tcp_string_to_address;
2208 plugin->service = service;
2209 if (service != NULL)
2211 plugin->server = GNUNET_SERVICE_get_server (service);
2216 GNUNET_CONFIGURATION_get_value_time (env->cfg, "transport-tcp",
2217 "TIMEOUT", &idle_timeout))
2219 LOG (GNUNET_ERROR_TYPE_ERROR,
2220 _("Failed to find option %s in section %s!\n"),
2221 "TIMEOUT", "transport-tcp");
2222 if (plugin->nat != NULL)
2223 GNUNET_NAT_unregister (plugin->nat);
2224 GNUNET_free (plugin);
2229 GNUNET_SERVER_create_with_sockets (&plugin_tcp_access_check, plugin,
2230 NULL, idle_timeout, GNUNET_YES);
2232 plugin->handlers = GNUNET_malloc (sizeof (my_handlers));
2233 memcpy (plugin->handlers, my_handlers, sizeof (my_handlers));
2235 i < sizeof (my_handlers) / sizeof (struct GNUNET_SERVER_MessageHandler);
2237 plugin->handlers[i].callback_cls = plugin;
2238 GNUNET_SERVER_add_handlers (plugin->server, plugin->handlers);
2239 GNUNET_SERVER_disconnect_notify (plugin->server, &disconnect_notify, plugin);
2240 plugin->nat_wait_conns = GNUNET_CONTAINER_multihashmap_create (16);
2242 LOG (GNUNET_ERROR_TYPE_INFO,
2243 _("TCP transport listening on port %llu\n"), bport);
2245 LOG (GNUNET_ERROR_TYPE_INFO,
2247 ("TCP transport not listening on any port (client only)\n"));
2249 LOG (GNUNET_ERROR_TYPE_INFO,
2251 ("TCP transport advertises itself as being on port %llu\n"),
2253 /* Initially set connections to 0 */
2254 GNUNET_STATISTICS_set(plugin->env->stats,
2255 gettext_noop ("# TCP sessions active"), 0,
2262 * Exit point from the plugin.
2265 libgnunet_plugin_transport_tcp_done (void *cls)
2267 struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
2268 struct Plugin *plugin = api->cls;
2269 struct TCPProbeContext *tcp_probe;
2276 LOG (GNUNET_ERROR_TYPE_DEBUG, "Shutting down TCP plugin\n");
2278 /* Removing leftover sessions */
2279 GNUNET_CONTAINER_multihashmap_iterate(plugin->sessionmap, &session_disconnect_it, NULL);
2280 /* Removing leftover NAT sessions */
2281 GNUNET_CONTAINER_multihashmap_iterate(plugin->nat_wait_conns, &session_disconnect_it, NULL);
2283 if (plugin->service != NULL)
2284 GNUNET_SERVICE_stop (plugin->service);
2286 GNUNET_SERVER_destroy (plugin->server);
2287 GNUNET_free (plugin->handlers);
2288 if (plugin->nat != NULL)
2289 GNUNET_NAT_unregister (plugin->nat);
2290 while (NULL != (tcp_probe = plugin->probe_head))
2292 GNUNET_CONTAINER_DLL_remove (plugin->probe_head, plugin->probe_tail,
2294 GNUNET_CONNECTION_destroy (tcp_probe->sock);
2295 GNUNET_free (tcp_probe);
2297 GNUNET_CONTAINER_multihashmap_destroy (plugin->nat_wait_conns);
2298 GNUNET_CONTAINER_multihashmap_destroy (plugin->sessionmap);
2299 GNUNET_free (plugin);
2304 /* end of plugin_transport_tcp.c */