2 This file is part of GNUnet
3 (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 Christian Grothoff (and other contributing authors)
5 GNUnet is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published
7 by the Free Software Foundation; either version 3, or (at your
8 option) any later version.
10 GNUnet is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with GNUnet; see the file COPYING. If not, write to the
17 Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18 Boston, MA 02111-1307, USA.
21 * @file transport/plugin_transport_tcp.c
22 * @brief Implementation of the TCP transport service
23 * @author Christian Grothoff
26 #include "gnunet_hello_lib.h"
27 #include "gnunet_constants.h"
28 #include "gnunet_connection_lib.h"
29 #include "gnunet_container_lib.h"
30 #include "gnunet_nat_lib.h"
31 #include "gnunet_os_lib.h"
32 #include "gnunet_protocols.h"
33 #include "gnunet_resolver_service.h"
34 #include "gnunet_server_lib.h"
35 #include "gnunet_service_lib.h"
36 #include "gnunet_signatures.h"
37 #include "gnunet_statistics_service.h"
38 #include "gnunet_transport_service.h"
39 #include "gnunet_transport_plugin.h"
40 #include "transport.h"
42 #define DEBUG_TCP GNUNET_EXTRA_LOGGING
44 #define DEBUG_TCP_NAT GNUNET_EXTRA_LOGGING
46 GNUNET_NETWORK_STRUCT_BEGIN
49 * Initial handshake message for a session.
54 * Type is GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME.
56 struct GNUNET_MessageHeader header;
59 * Identity of the node connecting (TCP client)
61 struct GNUNET_PeerIdentity clientIdentity;
67 * Basically a WELCOME message, but with the purpose
68 * of giving the waiting peer a client handle to use
70 struct TCP_NAT_ProbeMessage
73 * Type is GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE.
75 struct GNUNET_MessageHeader header;
78 * Identity of the sender of the message.
80 struct GNUNET_PeerIdentity clientIdentity;
83 GNUNET_NETWORK_STRUCT_END
86 * Context for sending a NAT probe via TCP.
88 struct TCPProbeContext
92 * Active probes are kept in a DLL.
94 struct TCPProbeContext *next;
97 * Active probes are kept in a DLL.
99 struct TCPProbeContext *prev;
104 struct GNUNET_CONNECTION_Handle *sock;
107 * Message to be sent.
109 struct TCP_NAT_ProbeMessage message;
112 * Handle to the transmission.
114 struct GNUNET_CONNECTION_TransmitHandle *transmit_handle;
117 * Transport plugin handle.
119 struct Plugin *plugin;
123 GNUNET_NETWORK_STRUCT_BEGIN
126 * Network format for IPv4 addresses.
128 struct IPv4TcpAddress
131 * IPv4 address, in network byte order.
133 uint32_t ipv4_addr GNUNET_PACKED;
136 * Port number, in network byte order.
138 uint16_t t4_port GNUNET_PACKED;
144 * Network format for IPv6 addresses.
146 struct IPv6TcpAddress
151 struct in6_addr ipv6_addr GNUNET_PACKED;
154 * Port number, in network byte order.
156 uint16_t t6_port GNUNET_PACKED;
159 GNUNET_NETWORK_STRUCT_END
162 * Encapsulation of all of the state of the plugin.
168 * Information kept for each message that is yet to
171 struct PendingMessage
175 * This is a doubly-linked list.
177 struct PendingMessage *next;
180 * This is a doubly-linked list.
182 struct PendingMessage *prev;
185 * The pending message
190 * Continuation function to call once the message
191 * has been sent. Can be NULL if there is no
192 * continuation to call.
194 GNUNET_TRANSPORT_TransmitContinuation transmit_cont;
197 * Closure for transmit_cont.
199 void *transmit_cont_cls;
202 * Timeout value for the pending message.
204 struct GNUNET_TIME_Absolute timeout;
207 * So that the gnunet-service-transport can group messages together,
208 * these pending messages need to accept a message buffer and size
209 * instead of just a GNUNET_MessageHeader.
217 * Session handle for TCP connections.
225 struct SessionHeader header;
228 * Stored in a linked list.
230 struct Session *next;
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 * Messages currently pending for transmission
244 * to this peer, if any.
246 struct PendingMessage *pending_messages_head;
249 * Messages currently pending for transmission
250 * to this peer, if any.
252 struct PendingMessage *pending_messages_tail;
255 * Handle for pending transmission request.
257 struct GNUNET_CONNECTION_TransmitHandle *transmit_handle;
260 * To whom are we talking to (set to our identity
261 * if we are still waiting for the welcome message)
263 struct GNUNET_PeerIdentity target;
266 * ID of task used to delay receiving more to throttle sender.
268 GNUNET_SCHEDULER_TaskIdentifier receive_delay_task;
271 * Address of the other peer (either based on our 'connect'
272 * call or on our 'accept' call).
274 * struct IPv4TcpAddress or struct IPv6TcpAddress
280 * Length of connect_addr.
285 * Last activity on this connection. Used to select preferred
288 struct GNUNET_TIME_Absolute last_activity;
291 * Are we still expecting the welcome message? (GNUNET_YES/GNUNET_NO)
293 int expecting_welcome;
296 * Was this a connection that was inbound (we accepted)? (GNUNET_YES/GNUNET_NO)
301 * Was this session created using NAT traversal?
306 * ATS network type in NBO
308 uint32_t ats_address_network_type;
313 * Encapsulation of all of the state of the plugin.
320 struct GNUNET_TRANSPORT_PluginEnvironment *env;
325 struct GNUNET_CONNECTION_Handle *lsock;
328 * Our handle to the NAT module.
330 struct GNUNET_NAT_Handle *nat;
332 struct GNUNET_CONTAINER_MultiHashMap * sessionmap;
335 * Handle to the network service.
337 struct GNUNET_SERVICE_Context *service;
340 * Handle to the server for this service.
342 struct GNUNET_SERVER_Handle *server;
345 * Copy of the handler array where the closures are
346 * set to this struct's instance.
348 struct GNUNET_SERVER_MessageHandler *handlers;
351 * Map of peers we have tried to contact behind a NAT
353 struct GNUNET_CONTAINER_MultiHashMap *nat_wait_conns;
356 * List of active TCP probes.
358 struct TCPProbeContext *probe_head;
361 * List of active TCP probes.
363 struct TCPProbeContext *probe_tail;
366 * Handle for (DYN)DNS lookup of our external IP.
368 struct GNUNET_RESOLVER_RequestHandle *ext_dns;
371 * How many more TCP sessions are we allowed to open right now?
373 unsigned long long max_connections;
376 * ID of task used to update our addresses when one expires.
378 GNUNET_SCHEDULER_TaskIdentifier address_update_task;
381 * Port that we are actually listening on.
386 * Port that the user said we would have visible to the
395 * Function to check if an inbound connection is acceptable.
396 * Mostly used to limit the total number of open connections
399 * @param cls the 'struct Plugin'
400 * @param ucred credentials, if available, otherwise NULL
401 * @param addr address
402 * @param addrlen length of address
403 * @return GNUNET_YES to allow, GNUNET_NO to deny, GNUNET_SYSERR
404 * for unknown address family (will be denied).
407 plugin_tcp_access_check (void *cls,
408 const struct GNUNET_CONNECTION_Credentials *ucred,
409 const struct sockaddr *addr, socklen_t addrlen)
411 struct Plugin *plugin = cls;
413 if (0 == plugin->max_connections)
415 plugin->max_connections--;
421 * Our external IP address/port mapping has changed.
423 * @param cls closure, the 'struct LocalAddrList'
424 * @param add_remove GNUNET_YES to mean the new public IP address, GNUNET_NO to mean
425 * the previous (now invalid) one
426 * @param addr either the previous or the new public IP address
427 * @param addrlen actual lenght of the address
430 tcp_nat_port_map_callback (void *cls, int add_remove,
431 const struct sockaddr *addr, socklen_t addrlen)
433 struct Plugin *plugin = cls;
434 struct IPv4TcpAddress t4;
435 struct IPv6TcpAddress t6;
439 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
440 "NPMC called with %d for address `%s'\n", add_remove,
441 GNUNET_a2s (addr, addrlen));
442 /* convert 'addr' to our internal format */
443 switch (addr->sa_family)
446 GNUNET_assert (addrlen == sizeof (struct sockaddr_in));
447 t4.ipv4_addr = ((struct sockaddr_in *) addr)->sin_addr.s_addr;
448 t4.t4_port = ((struct sockaddr_in *) addr)->sin_port;
453 GNUNET_assert (addrlen == sizeof (struct sockaddr_in6));
454 memcpy (&t6.ipv6_addr, &((struct sockaddr_in6 *) addr)->sin6_addr,
455 sizeof (struct in6_addr));
456 t6.t6_port = ((struct sockaddr_in6 *) addr)->sin6_port;
464 /* modify our published address list */
465 plugin->env->notify_address (plugin->env->cls, add_remove, arg, args);
470 * Function called for a quick conversion of the binary address to
471 * a numeric address. Note that the caller must not free the
472 * address and that the next call to this function is allowed
473 * to override the address again.
475 * @param cls closure ('struct Plugin*')
476 * @param addr binary address
477 * @param addrlen length of the address
478 * @return string representing the same address
481 tcp_address_to_string (void *cls, const void *addr, size_t addrlen)
483 static char rbuf[INET6_ADDRSTRLEN + 12];
484 char buf[INET6_ADDRSTRLEN];
488 const struct IPv4TcpAddress *t4;
489 const struct IPv6TcpAddress *t6;
493 if (addrlen == sizeof (struct IPv6TcpAddress))
497 port = ntohs (t6->t6_port);
498 memcpy (&a6, &t6->ipv6_addr, sizeof (a6));
501 else if (addrlen == sizeof (struct IPv4TcpAddress))
505 port = ntohs (t4->t4_port);
506 memcpy (&a4, &t4->ipv4_addr, sizeof (a4));
511 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, "tcp",
512 _("Unexpected address length: %u bytes\n"),
513 (unsigned int) addrlen);
517 if (NULL == inet_ntop (af, sb, buf, INET6_ADDRSTRLEN))
519 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "inet_ntop");
522 GNUNET_snprintf (rbuf, sizeof (rbuf), (af == AF_INET6) ? "[%s]:%u" : "%s:%u",
528 struct SessionClientCtx
530 const struct GNUNET_SERVER_Client *client;
534 int session_lookup_by_client_it (void *cls,
535 const GNUNET_HashCode * key,
538 struct SessionClientCtx *sc_ctx = cls;
539 struct Session *s = value;
541 if (s->client == sc_ctx->client)
550 * Find the session handle for the given client.
552 * @param plugin the plugin
553 * @param client which client to find the session handle for
554 * @return NULL if no matching session exists
556 static struct Session *
557 lookup_session_by_client (struct Plugin *plugin,
558 const struct GNUNET_SERVER_Client *client)
560 struct SessionClientCtx sc_ctx;
561 sc_ctx.client = client;
564 GNUNET_CONTAINER_multihashmap_iterate (plugin->sessionmap, &session_lookup_by_client_it, &sc_ctx);
571 * Create a new session. Also queues a welcome message.
573 * @param plugin the plugin
574 * @param target peer to connect to
575 * @param client client to use
576 * @param is_nat this a NAT session, we should wait for a client to
577 * connect to us from an address, then assign that to
579 * @return new session object
581 static struct Session *
582 create_session (struct Plugin *plugin, const struct GNUNET_PeerIdentity *target,
583 struct GNUNET_SERVER_Client *client, int is_nat)
586 struct PendingMessage *pm;
587 struct WelcomeMessage welcome;
589 if (is_nat != GNUNET_YES)
590 GNUNET_assert (client != NULL);
592 GNUNET_assert (client == NULL);
594 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
595 "Creating new session for peer `%4s'\n",
596 GNUNET_i2s (target));
598 ret = GNUNET_malloc (sizeof (struct Session));
599 ret->last_activity = GNUNET_TIME_absolute_get ();
600 ret->plugin = plugin;
601 ret->is_nat = is_nat;
602 ret->client = client;
603 ret->target = *target;
604 ret->expecting_welcome = GNUNET_YES;
605 ret->ats_address_network_type = htonl (GNUNET_ATS_NET_UNSPECIFIED);
606 pm = GNUNET_malloc (sizeof (struct PendingMessage) +
607 sizeof (struct WelcomeMessage));
608 pm->msg = (const char *) &pm[1];
609 pm->message_size = sizeof (struct WelcomeMessage);
610 welcome.header.size = htons (sizeof (struct WelcomeMessage));
611 welcome.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME);
612 welcome.clientIdentity = *plugin->env->my_identity;
613 memcpy (&pm[1], &welcome, sizeof (welcome));
614 pm->timeout = GNUNET_TIME_UNIT_FOREVER_ABS;
615 GNUNET_STATISTICS_update (plugin->env->stats,
616 gettext_noop ("# bytes currently in TCP buffers"),
617 pm->message_size, GNUNET_NO);
618 GNUNET_CONTAINER_DLL_insert (ret->pending_messages_head,
619 ret->pending_messages_tail, pm);
620 if (is_nat != GNUNET_YES)
621 GNUNET_STATISTICS_update (plugin->env->stats,
622 gettext_noop ("# TCP sessions active"), 1,
629 * If we have pending messages, ask the server to
630 * transmit them (schedule the respective tasks, etc.)
632 * @param session for which session should we do this
635 process_pending_messages (struct Session *session);
639 * Function called to notify a client about the socket
640 * being ready to queue more data. "buf" will be
641 * NULL and "size" zero if the socket was closed for
642 * writing in the meantime.
645 * @param size number of bytes available in buf
646 * @param buf where the callee should write the message
647 * @return number of bytes written to buf
650 do_transmit (void *cls, size_t size, void *buf)
652 struct Session *session = cls;
653 struct GNUNET_PeerIdentity pid;
654 struct Plugin *plugin;
655 struct PendingMessage *pos;
656 struct PendingMessage *hd;
657 struct PendingMessage *tl;
658 struct GNUNET_TIME_Absolute now;
662 GNUNET_assert (session != NULL);
663 session->transmit_handle = NULL;
664 plugin = session->plugin;
668 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
669 "Timeout trying to transmit to peer `%4s', discarding message queue.\n",
670 GNUNET_i2s (&session->target));
672 /* timeout; cancel all messages that have already expired */
676 now = GNUNET_TIME_absolute_get ();
677 while ((NULL != (pos = session->pending_messages_head)) &&
678 (pos->timeout.abs_value <= now.abs_value))
680 GNUNET_CONTAINER_DLL_remove (session->pending_messages_head,
681 session->pending_messages_tail, pos);
683 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
684 "Failed to transmit %u byte message to `%4s'.\n",
685 pos->message_size, GNUNET_i2s (&session->target));
687 ret += pos->message_size;
688 GNUNET_CONTAINER_DLL_insert_after (hd, tl, tl, pos);
690 /* do this call before callbacks (so that if callbacks destroy
691 * session, they have a chance to cancel actions done by this
693 process_pending_messages (session);
694 pid = session->target;
695 /* no do callbacks and do not use session again since
696 * the callbacks may abort the session */
697 while (NULL != (pos = hd))
699 GNUNET_CONTAINER_DLL_remove (hd, tl, pos);
700 if (pos->transmit_cont != NULL)
701 pos->transmit_cont (pos->transmit_cont_cls, &pid, GNUNET_SYSERR);
704 GNUNET_STATISTICS_update (plugin->env->stats,
705 gettext_noop ("# bytes currently in TCP buffers"),
706 -(int64_t) ret, GNUNET_NO);
707 GNUNET_STATISTICS_update (plugin->env->stats,
709 ("# bytes discarded by TCP (timeout)"), ret,
713 /* copy all pending messages that would fit */
718 while (NULL != (pos = session->pending_messages_head))
720 if (ret + pos->message_size > size)
722 GNUNET_CONTAINER_DLL_remove (session->pending_messages_head,
723 session->pending_messages_tail, pos);
724 GNUNET_assert (size >= pos->message_size);
725 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
726 "Transmitting message of type %u\n",
727 ntohs (((struct GNUNET_MessageHeader *) pos->msg)->type));
728 /* FIXME: this memcpy can be up to 7% of our total runtime */
729 memcpy (cbuf, pos->msg, pos->message_size);
730 cbuf += pos->message_size;
731 ret += pos->message_size;
732 size -= pos->message_size;
733 GNUNET_CONTAINER_DLL_insert_tail (hd, tl, pos);
735 /* schedule 'continuation' before callbacks so that callbacks that
736 * cancel everything don't cause us to use a session that no longer
738 process_pending_messages (session);
739 session->last_activity = GNUNET_TIME_absolute_get ();
740 pid = session->target;
741 /* we'll now call callbacks that may cancel the session; hence
742 * we should not use 'session' after this point */
743 while (NULL != (pos = hd))
745 GNUNET_CONTAINER_DLL_remove (hd, tl, pos);
746 if (pos->transmit_cont != NULL)
747 pos->transmit_cont (pos->transmit_cont_cls, &pid, GNUNET_OK);
750 GNUNET_assert (hd == NULL);
751 GNUNET_assert (tl == NULL);
753 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp", "Transmitting %u bytes\n",
756 GNUNET_STATISTICS_update (plugin->env->stats,
757 gettext_noop ("# bytes currently in TCP buffers"),
758 -(int64_t) ret, GNUNET_NO);
759 GNUNET_STATISTICS_update (plugin->env->stats,
760 gettext_noop ("# bytes transmitted via TCP"), ret,
767 * If we have pending messages, ask the server to
768 * transmit them (schedule the respective tasks, etc.)
770 * @param session for which session should we do this
773 process_pending_messages (struct Session *session)
775 struct PendingMessage *pm;
777 GNUNET_assert (session->client != NULL);
778 if (session->transmit_handle != NULL)
780 if (NULL == (pm = session->pending_messages_head))
783 session->transmit_handle =
784 GNUNET_SERVER_notify_transmit_ready (session->client, pm->message_size,
785 GNUNET_TIME_absolute_get_remaining
786 (pm->timeout), &do_transmit,
792 * Functions with this signature are called whenever we need
793 * to close a session due to a disconnect or failure to
794 * establish a connection.
796 * @param session session to close down
799 disconnect_session (struct Session *session)
801 struct PendingMessage *pm;
802 struct Plugin * plugin = session->plugin;
804 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
805 "Disconnecting session %p for peer `%s' address `%s'\n",
807 GNUNET_i2s (&session->target),
808 tcp_address_to_string(NULL, session->addr, session->addrlen));
810 GNUNET_assert (GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(plugin->sessionmap, &session->target.hashPubKey, session));
813 if (session->transmit_handle != NULL)
815 GNUNET_CONNECTION_notify_transmit_ready_cancel (session->transmit_handle);
816 session->transmit_handle = NULL;
818 session->plugin->env->session_end (session->plugin->env->cls,
819 &session->target, session);
820 while (NULL != (pm = session->pending_messages_head))
823 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
825 NULL ? "Could not deliver message to `%4s'.\n" :
826 "Could not deliver message to `%4s', notifying.\n",
827 GNUNET_i2s (&session->target));
829 GNUNET_STATISTICS_update (session->plugin->env->stats,
830 gettext_noop ("# bytes currently in TCP buffers"),
831 -(int64_t) pm->message_size, GNUNET_NO);
832 GNUNET_STATISTICS_update (session->plugin->env->stats,
834 ("# bytes discarded by TCP (disconnect)"),
835 pm->message_size, GNUNET_NO);
836 GNUNET_CONTAINER_DLL_remove (session->pending_messages_head,
837 session->pending_messages_tail, pm);
838 if (NULL != pm->transmit_cont)
839 pm->transmit_cont (pm->transmit_cont_cls, &session->target,
843 GNUNET_break (session->client != NULL);
844 if (session->receive_delay_task != GNUNET_SCHEDULER_NO_TASK)
846 GNUNET_SCHEDULER_cancel (session->receive_delay_task);
847 if (session->client != NULL)
848 GNUNET_SERVER_receive_done (session->client, GNUNET_SYSERR);
850 if (session->client != NULL)
852 GNUNET_SERVER_client_drop (session->client);
853 session->client = NULL;
855 GNUNET_STATISTICS_update (session->plugin->env->stats,
856 gettext_noop ("# TCP sessions active"), -1,
858 GNUNET_free_non_null (session->addr);
859 GNUNET_assert (NULL == session->transmit_handle);
860 GNUNET_free (session);
865 * Function that can be used by the transport service to transmit
866 * a message using the plugin. Note that in the case of a
867 * peer disconnecting, the continuation MUST be called
868 * prior to the disconnect notification itself. This function
869 * will be called with this peer's HELLO message to initiate
870 * a fresh connection to another peer.
873 * @param session which session must be used
874 * @param msgbuf the message to transmit
875 * @param msgbuf_size number of bytes in 'msgbuf'
876 * @param priority how important is the message (most plugins will
877 * ignore message priority and just FIFO)
878 * @param to how long to wait at most for the transmission (does not
879 * require plugins to discard the message after the timeout,
880 * just advisory for the desired delay; most plugins will ignore
882 * @param cont continuation to call once the message has
883 * been transmitted (or if the transport is ready
884 * for the next transmission call; or if the
885 * peer disconnected...); can be NULL
886 * @param cont_cls closure for cont
887 * @return number of bytes used (on the physical network, with overheads);
888 * -1 on hard errors (i.e. address invalid); 0 is a legal value
889 * and does NOT mean that the message was not transmitted (DV)
892 tcp_plugin_send (void *cls,
893 struct Session *session,
894 const char *msgbuf, size_t msgbuf_size,
895 unsigned int priority,
896 struct GNUNET_TIME_Relative to,
897 GNUNET_TRANSPORT_TransmitContinuation cont, void *cont_cls)
899 struct Plugin * plugin = cls;
900 struct PendingMessage *pm;
902 GNUNET_assert (plugin != NULL);
903 GNUNET_assert (session != NULL);
904 GNUNET_assert (session->client != NULL);
906 GNUNET_SERVER_client_set_timeout (session->client,
907 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
908 GNUNET_STATISTICS_update (plugin->env->stats,
909 gettext_noop ("# bytes currently in TCP buffers"),
910 msgbuf_size, GNUNET_NO);
911 /* create new message entry */
912 pm = GNUNET_malloc (sizeof (struct PendingMessage) + msgbuf_size);
913 pm->msg = (const char *) &pm[1];
914 memcpy (&pm[1], msgbuf, msgbuf_size);
915 pm->message_size = msgbuf_size;
916 pm->timeout = GNUNET_TIME_relative_to_absolute (to);
917 pm->transmit_cont = cont;
918 pm->transmit_cont_cls = cont_cls;
920 /* append pm to pending_messages list */
921 GNUNET_CONTAINER_DLL_insert_tail (session->pending_messages_head,
922 session->pending_messages_tail, pm);
924 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
925 "Asked to transmit %u bytes to `%s', added message to list.\n",
926 msgbuf_size, GNUNET_i2s (&session->target));
928 process_pending_messages (session);
936 struct Session * result;
939 int session_lookup_it (void *cls,
940 const GNUNET_HashCode * key,
943 struct SessionItCtx * si_ctx = cls;
944 struct Session * session = value;
946 char * a1 = strdup (tcp_address_to_string(NULL, session->addr, session->addrlen));
947 char * a2 = strdup (tcp_address_to_string(NULL, si_ctx->addr, si_ctx->addrlen));
948 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, "tcp",
949 "Comparing: %s %u <-> %s %u\n",
957 if (session->addrlen != si_ctx->addrlen)
961 if (0 != memcmp (session->addr, si_ctx->addr, si_ctx->addrlen))
966 a1 = strdup (tcp_address_to_string(NULL, session->addr, session->addrlen));
967 a2 = strdup (tcp_address_to_string(NULL, si_ctx->addr, si_ctx->addrlen));
968 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, "tcp",
969 "Comparing: %s %u <-> %s %u , OK!\n",
977 /* Found existing session */
978 si_ctx->result = session;
984 * Create a new session to transmit data to the target
985 * This session will used to send data to this peer and the plugin will
986 * notify us by calling the env->session_end function
989 * @param address pointer to the GNUNET_HELLO_Address
990 * @return the session if the address is valid, NULL otherwise
992 static struct Session *
993 tcp_plugin_get_session (void *cls,
994 const struct GNUNET_HELLO_Address *address)
996 struct Plugin * plugin = cls;
997 struct Session * session = NULL;
1002 struct GNUNET_CONNECTION_Handle *sa;
1003 struct sockaddr_in a4;
1004 struct sockaddr_in6 a6;
1005 const struct IPv4TcpAddress *t4;
1006 const struct IPv6TcpAddress *t6;
1007 struct GNUNET_ATS_Information ats;
1008 unsigned int is_natd = GNUNET_NO;
1011 GNUNET_assert (plugin != NULL);
1012 GNUNET_assert (address != NULL);
1014 addrlen = address->address_length;
1016 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1017 "Trying to get session for `%s' address length %i\n",
1018 tcp_address_to_string(NULL, address->address, address->address_length),
1021 /* look for existing session */
1022 if (GNUNET_CONTAINER_multihashmap_contains(plugin->sessionmap, &address->peer.hashPubKey))
1024 struct SessionItCtx si_ctx;
1026 si_ctx.addr = (void *) address->address;
1027 si_ctx.addrlen = address->address_length;
1029 si_ctx.result = NULL;
1031 GNUNET_CONTAINER_multihashmap_get_multiple(plugin->sessionmap, &address->peer.hashPubKey, &session_lookup_it, &si_ctx);
1032 if (si_ctx.result != NULL)
1034 session = si_ctx.result;
1035 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1036 "Found exisiting session for `%s' address `%s' session %p\n",
1037 GNUNET_i2s (&address->peer),
1038 tcp_address_to_string(NULL, address->address, address->address_length),
1044 if (addrlen == sizeof (struct IPv6TcpAddress))
1046 GNUNET_assert (NULL != address->address); /* make static analysis happy */
1047 t6 = address->address;
1049 memset (&a6, 0, sizeof (a6));
1050 #if HAVE_SOCKADDR_IN_SIN_LEN
1051 a6.sin6_len = sizeof (a6);
1053 a6.sin6_family = AF_INET6;
1054 a6.sin6_port = t6->t6_port;
1055 if (t6->t6_port == 0)
1056 is_natd = GNUNET_YES;
1057 memcpy (&a6.sin6_addr, &t6->ipv6_addr, sizeof (struct in6_addr));
1061 else if (addrlen == sizeof (struct IPv4TcpAddress))
1063 GNUNET_assert (NULL != address->address); /* make static analysis happy */
1064 t4 = address->address;
1066 memset (&a4, 0, sizeof (a4));
1067 #if HAVE_SOCKADDR_IN_SIN_LEN
1068 a4.sin_len = sizeof (a4);
1070 a4.sin_family = AF_INET;
1071 a4.sin_port = t4->t4_port;
1072 if (t4->t4_port == 0)
1073 is_natd = GNUNET_YES;
1074 a4.sin_addr.s_addr = t4->ipv4_addr;
1080 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, "tcp",
1081 _("Address of unexpected length: %u\n"), addrlen);
1086 ats = plugin->env->get_address_type (plugin->env->cls, sb ,sbs);
1088 if ((is_natd == GNUNET_YES) && (addrlen == sizeof (struct IPv6TcpAddress)))
1090 /* NAT client only works with IPv4 addresses */
1094 if (0 == plugin->max_connections)
1100 if ((is_natd == GNUNET_YES) &&
1102 GNUNET_CONTAINER_multihashmap_contains (plugin->nat_wait_conns,
1103 &address->peer.hashPubKey)))
1105 /* Only do one NAT punch attempt per peer identity */
1109 if ((is_natd == GNUNET_YES) && (NULL != plugin->nat) &&
1111 GNUNET_CONTAINER_multihashmap_contains (plugin->nat_wait_conns,
1112 &address->peer.hashPubKey)))
1115 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1116 _("Found valid IPv4 NAT address (creating session)!\n"));
1118 session = create_session (plugin, &address->peer, NULL, GNUNET_YES);
1119 session->addrlen = 0;
1120 session->addr = NULL;
1121 session->ats_address_network_type = ats.value;
1122 GNUNET_assert (session != NULL);
1124 GNUNET_assert (GNUNET_CONTAINER_multihashmap_put
1125 (plugin->nat_wait_conns, &address->peer.hashPubKey, session,
1126 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY) == GNUNET_OK);
1128 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1129 "Created NAT WAIT connection to `%4s' at `%s'\n",
1130 GNUNET_i2s (&session->target), GNUNET_a2s (sb, sbs));
1132 GNUNET_NAT_run_client (plugin->nat, &a4);
1136 /* create new outbound session */
1137 GNUNET_assert (0 != plugin->max_connections);
1138 sa = GNUNET_CONNECTION_create_from_sockaddr (af, sb, sbs);
1142 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1143 "Failed to create connection to `%4s' at `%s'\n",
1144 GNUNET_i2s (&session->target), GNUNET_a2s (sb, sbs));
1148 plugin->max_connections--;
1150 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1151 "Asked to transmit to `%4s', creating fresh session using address `%s'.\n",
1152 GNUNET_i2s (&address->peer), GNUNET_a2s (sb, sbs));
1154 session = create_session (plugin,
1156 GNUNET_SERVER_connect_socket (plugin->server, sa),
1158 session->addr = GNUNET_malloc (addrlen);
1159 memcpy (session->addr, address->address, addrlen);
1160 session->addrlen = addrlen;
1161 session->ats_address_network_type = ats.value;
1163 GNUNET_CONTAINER_multihashmap_put(plugin->sessionmap, &address->peer.hashPubKey, session, GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
1165 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1166 "Creating new session for `%s' address `%s' session %p\n",
1167 GNUNET_i2s (&address->peer),
1168 tcp_address_to_string(NULL, address->address, address->address_length),
1171 /* Send TCP Welcome */
1172 process_pending_messages (session);
1178 int session_disconnect_it (void *cls,
1179 const GNUNET_HashCode * key,
1182 struct Session *session = value;
1184 GNUNET_STATISTICS_update (session->plugin->env->stats,
1186 ("# transport-service disconnect requests for TCP"),
1188 disconnect_session (session);
1192 int session_nat_disconnect_it (void *cls,
1193 const GNUNET_HashCode * key,
1196 struct Session *session = value;
1198 if (session != NULL)
1200 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1201 "Cleaning up pending NAT session for peer `%4s'\n", GNUNET_i2s (&session->target));
1202 GNUNET_assert (GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove (session->plugin->nat_wait_conns, &session->target.hashPubKey, session));
1203 GNUNET_SERVER_client_drop (session->client);
1204 GNUNET_SERVER_receive_done (session->client, GNUNET_SYSERR);
1205 GNUNET_free (session);
1213 * Function that can be called to force a disconnect from the
1214 * specified neighbour. This should also cancel all previously
1215 * scheduled transmissions. Obviously the transmission may have been
1216 * partially completed already, which is OK. The plugin is supposed
1217 * to close the connection (if applicable) and no longer call the
1218 * transmit continuation(s).
1220 * Finally, plugin MUST NOT call the services's receive function to
1221 * notify the service that the connection to the specified target was
1222 * closed after a getting this call.
1224 * @param cls closure
1225 * @param target peer for which the last transmission is
1229 tcp_plugin_disconnect (void *cls, const struct GNUNET_PeerIdentity *target)
1231 struct Plugin *plugin = cls;
1232 struct Session *nat_session = NULL;
1234 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1235 "Disconnecting peer `%4s'\n", GNUNET_i2s (target));
1237 GNUNET_CONTAINER_multihashmap_get_multiple (plugin->sessionmap, &target->hashPubKey, session_disconnect_it, plugin);
1239 nat_session = GNUNET_CONTAINER_multihashmap_get(plugin->nat_wait_conns, &target->hashPubKey);
1240 if (nat_session != NULL)
1242 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1243 "Cleaning up pending NAT session for peer `%4s'\n", GNUNET_i2s (target));
1244 GNUNET_assert (GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove (plugin->nat_wait_conns, &target->hashPubKey, nat_session));
1245 GNUNET_SERVER_client_drop (nat_session->client);
1246 GNUNET_SERVER_receive_done (nat_session->client, GNUNET_SYSERR);
1247 GNUNET_free (nat_session);
1253 * Context for address to string conversion.
1255 struct PrettyPrinterContext
1258 * Function to call with the result.
1260 GNUNET_TRANSPORT_AddressStringCallback asc;
1263 * Clsoure for 'asc'.
1268 * Port to add after the IP address.
1275 * Append our port and forward the result.
1277 * @param cls the 'struct PrettyPrinterContext*'
1278 * @param hostname hostname part of the address
1281 append_port (void *cls, const char *hostname)
1283 struct PrettyPrinterContext *ppc = cls;
1286 if (hostname == NULL)
1288 ppc->asc (ppc->asc_cls, NULL);
1292 GNUNET_asprintf (&ret, "%s:%d", hostname, ppc->port);
1293 ppc->asc (ppc->asc_cls, ret);
1299 * Convert the transports address to a nice, human-readable
1302 * @param cls closure
1303 * @param type name of the transport that generated the address
1304 * @param addr one of the addresses of the host, NULL for the last address
1305 * the specific address format depends on the transport
1306 * @param addrlen length of the address
1307 * @param numeric should (IP) addresses be displayed in numeric form?
1308 * @param timeout after how long should we give up?
1309 * @param asc function to call on each string
1310 * @param asc_cls closure for asc
1313 tcp_plugin_address_pretty_printer (void *cls, const char *type,
1314 const void *addr, size_t addrlen,
1316 struct GNUNET_TIME_Relative timeout,
1317 GNUNET_TRANSPORT_AddressStringCallback asc,
1320 struct PrettyPrinterContext *ppc;
1323 struct sockaddr_in a4;
1324 struct sockaddr_in6 a6;
1325 const struct IPv4TcpAddress *t4;
1326 const struct IPv6TcpAddress *t6;
1329 if (addrlen == sizeof (struct IPv6TcpAddress))
1332 memset (&a6, 0, sizeof (a6));
1333 a6.sin6_family = AF_INET6;
1334 a6.sin6_port = t6->t6_port;
1335 memcpy (&a6.sin6_addr, &t6->ipv6_addr, sizeof (struct in6_addr));
1336 port = ntohs (t6->t6_port);
1340 else if (addrlen == sizeof (struct IPv4TcpAddress))
1343 memset (&a4, 0, sizeof (a4));
1344 a4.sin_family = AF_INET;
1345 a4.sin_port = t4->t4_port;
1346 a4.sin_addr.s_addr = t4->ipv4_addr;
1347 port = ntohs (t4->t4_port);
1353 /* invalid address */
1354 GNUNET_break_op (0);
1355 asc (asc_cls, NULL);
1358 ppc = GNUNET_malloc (sizeof (struct PrettyPrinterContext));
1360 ppc->asc_cls = asc_cls;
1362 GNUNET_RESOLVER_hostname_get (sb, sbs, !numeric, timeout, &append_port, ppc);
1367 * Check if the given port is plausible (must be either our listen
1368 * port or our advertised port), or any port if we are behind NAT
1369 * and do not have a port open. If it is neither, we return
1372 * @param plugin global variables
1373 * @param in_port port number to check
1374 * @return GNUNET_OK if port is either open_port or adv_port
1377 check_port (struct Plugin *plugin, uint16_t in_port)
1379 if ((in_port == plugin->adv_port) || (in_port == plugin->open_port))
1381 return GNUNET_SYSERR;
1386 * Function that will be called to check if a binary address for this
1387 * plugin is well-formed and corresponds to an address for THIS peer
1388 * (as per our configuration). Naturally, if absolutely necessary,
1389 * plugins can be a bit conservative in their answer, but in general
1390 * plugins should make sure that the address does not redirect
1391 * traffic to a 3rd party that might try to man-in-the-middle our
1394 * @param cls closure, our 'struct Plugin*'
1395 * @param addr pointer to the address
1396 * @param addrlen length of addr
1397 * @return GNUNET_OK if this is a plausible address for this peer
1398 * and transport, GNUNET_SYSERR if not
1401 tcp_plugin_check_address (void *cls, const void *addr, size_t addrlen)
1403 struct Plugin *plugin = cls;
1404 struct IPv4TcpAddress *v4;
1405 struct IPv6TcpAddress *v6;
1407 if ((addrlen != sizeof (struct IPv4TcpAddress)) &&
1408 (addrlen != sizeof (struct IPv6TcpAddress)))
1410 GNUNET_break_op (0);
1411 return GNUNET_SYSERR;
1413 if (addrlen == sizeof (struct IPv4TcpAddress))
1415 v4 = (struct IPv4TcpAddress *) addr;
1416 if (GNUNET_OK != check_port (plugin, ntohs (v4->t4_port)))
1417 return GNUNET_SYSERR;
1419 GNUNET_NAT_test_address (plugin->nat, &v4->ipv4_addr,
1420 sizeof (struct in_addr)))
1421 return GNUNET_SYSERR;
1425 v6 = (struct IPv6TcpAddress *) addr;
1426 if (IN6_IS_ADDR_LINKLOCAL (&v6->ipv6_addr))
1428 GNUNET_break_op (0);
1429 return GNUNET_SYSERR;
1431 if (GNUNET_OK != check_port (plugin, ntohs (v6->t6_port)))
1432 return GNUNET_SYSERR;
1434 GNUNET_NAT_test_address (plugin->nat, &v6->ipv6_addr,
1435 sizeof (struct in6_addr)))
1436 return GNUNET_SYSERR;
1443 * We've received a nat probe from this peer via TCP. Finish
1444 * creating the client session and resume sending of queued
1447 * @param cls closure
1448 * @param client identification of the client
1449 * @param message the actual message
1452 handle_tcp_nat_probe (void *cls, struct GNUNET_SERVER_Client *client,
1453 const struct GNUNET_MessageHeader *message)
1455 struct Plugin *plugin = cls;
1456 struct Session *session;
1457 const struct TCP_NAT_ProbeMessage *tcp_nat_probe;
1460 struct IPv4TcpAddress *t4;
1461 struct IPv6TcpAddress *t6;
1462 const struct sockaddr_in *s4;
1463 const struct sockaddr_in6 *s6;
1465 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp", "received NAT probe\n");
1467 /* We have received a TCP NAT probe, meaning we (hopefully) initiated
1468 * a connection to this peer by running gnunet-nat-client. This peer
1469 * received the punch message and now wants us to use the new connection
1470 * as the default for that peer. Do so and then send a WELCOME message
1471 * so we can really be connected!
1473 if (ntohs (message->size) != sizeof (struct TCP_NAT_ProbeMessage))
1475 GNUNET_break_op (0);
1476 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1480 tcp_nat_probe = (const struct TCP_NAT_ProbeMessage *) message;
1482 memcmp (&tcp_nat_probe->clientIdentity, plugin->env->my_identity,
1483 sizeof (struct GNUNET_PeerIdentity)))
1485 /* refuse connections from ourselves */
1486 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1491 GNUNET_CONTAINER_multihashmap_get (plugin->nat_wait_conns,
1493 clientIdentity.hashPubKey);
1494 if (session == NULL)
1496 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1497 "Did NOT find session for NAT probe!\n");
1498 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1501 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1502 "Found session for NAT probe!\n");
1504 GNUNET_assert (GNUNET_CONTAINER_multihashmap_remove
1505 (plugin->nat_wait_conns,
1506 &tcp_nat_probe->clientIdentity.hashPubKey,
1507 session) == GNUNET_YES);
1508 if (GNUNET_OK != GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
1511 GNUNET_free (session);
1512 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1516 GNUNET_SERVER_client_keep (client);
1517 session->client = client;
1518 session->last_activity = GNUNET_TIME_absolute_get ();
1519 session->inbound = GNUNET_NO;
1522 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1523 "Found address `%s' for incoming connection\n",
1524 GNUNET_a2s (vaddr, alen));
1526 switch (((const struct sockaddr *) vaddr)->sa_family)
1530 t4 = GNUNET_malloc (sizeof (struct IPv4TcpAddress));
1531 t4->t4_port = s4->sin_port;
1532 t4->ipv4_addr = s4->sin_addr.s_addr;
1534 session->addrlen = sizeof (struct IPv4TcpAddress);
1538 t6 = GNUNET_malloc (sizeof (struct IPv6TcpAddress));
1539 t6->t6_port = s6->sin6_port;
1540 memcpy (&t6->ipv6_addr, &s6->sin6_addr, sizeof (struct in6_addr));
1542 session->addrlen = sizeof (struct IPv6TcpAddress);
1545 GNUNET_break_op (0);
1547 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1548 "Bad address for incoming connection!\n");
1549 GNUNET_free (vaddr);
1551 GNUNET_SERVER_client_drop (client);
1552 GNUNET_free (session);
1553 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1556 GNUNET_free (vaddr);
1558 GNUNET_CONTAINER_multihashmap_put(plugin->sessionmap, &session->target.hashPubKey, session, GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
1560 GNUNET_STATISTICS_update (plugin->env->stats,
1561 gettext_noop ("# TCP sessions active"), 1,
1563 process_pending_messages (session);
1564 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1569 * We've received a welcome from this peer via TCP. Possibly create a
1570 * fresh client record and send back our welcome.
1572 * @param cls closure
1573 * @param client identification of the client
1574 * @param message the actual message
1577 handle_tcp_welcome (void *cls, struct GNUNET_SERVER_Client *client,
1578 const struct GNUNET_MessageHeader *message)
1580 struct Plugin *plugin = cls;
1581 const struct WelcomeMessage *wm = (const struct WelcomeMessage *) message;
1582 struct Session *session;
1585 struct IPv4TcpAddress *t4;
1586 struct IPv6TcpAddress *t6;
1587 const struct sockaddr_in *s4;
1588 const struct sockaddr_in6 *s6;
1591 memcmp (&wm->clientIdentity, plugin->env->my_identity,
1592 sizeof (struct GNUNET_PeerIdentity)))
1594 /* refuse connections from ourselves */
1595 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1599 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1600 "Received %s message from `%4s'\n", "WELCOME",
1601 GNUNET_i2s (&wm->clientIdentity));
1602 GNUNET_STATISTICS_update (plugin->env->stats,
1603 gettext_noop ("# TCP WELCOME messages received"), 1,
1606 session = lookup_session_by_client (plugin, client);
1607 if (session != NULL)
1609 if (GNUNET_OK == GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
1611 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1612 "Found existing session %p for peer `%s'\n",
1614 GNUNET_a2s (vaddr, alen));
1615 GNUNET_free (vaddr);
1620 GNUNET_SERVER_client_keep (client);
1621 session = create_session (plugin, &wm->clientIdentity, client, GNUNET_NO);
1622 session->inbound = GNUNET_YES;
1624 if (GNUNET_OK == GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
1626 if (alen == sizeof (struct sockaddr_in))
1629 t4 = GNUNET_malloc (sizeof (struct IPv4TcpAddress));
1630 t4->t4_port = s4->sin_port;
1631 t4->ipv4_addr = s4->sin_addr.s_addr;
1633 session->addrlen = sizeof (struct IPv4TcpAddress);
1635 else if (alen == sizeof (struct sockaddr_in6))
1638 t6 = GNUNET_malloc (sizeof (struct IPv6TcpAddress));
1639 t6->t6_port = s6->sin6_port;
1640 memcpy (&t6->ipv6_addr, &s6->sin6_addr, sizeof (struct in6_addr));
1642 session->addrlen = sizeof (struct IPv6TcpAddress);
1645 struct GNUNET_ATS_Information ats;
1646 ats = plugin->env->get_address_type (plugin->env->cls, vaddr ,alen);
1647 session->ats_address_network_type = ats.value;
1649 GNUNET_free (vaddr);
1654 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1655 "Did not obtain TCP socket address for incoming connection\n");
1658 GNUNET_CONTAINER_multihashmap_put(plugin->sessionmap, &wm->clientIdentity.hashPubKey, session, GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
1661 if (session->expecting_welcome != GNUNET_YES)
1663 GNUNET_break_op (0);
1664 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1667 session->last_activity = GNUNET_TIME_absolute_get ();
1668 session->expecting_welcome = GNUNET_NO;
1671 process_pending_messages (session);
1673 GNUNET_SERVER_client_set_timeout (client,
1674 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1675 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1680 * Task to signal the server that we can continue
1681 * receiving from the TCP client now.
1683 * @param cls the 'struct Session*'
1684 * @param tc task context (unused)
1687 delayed_done (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1689 struct Session *session = cls;
1690 struct GNUNET_TIME_Relative delay;
1691 struct GNUNET_ATS_Information ats;
1693 session->receive_delay_task = GNUNET_SCHEDULER_NO_TASK;
1695 session->plugin->env->receive (session->plugin->env->cls,
1696 &session->target, NULL, &ats, 0, session,
1698 if (delay.rel_value == 0)
1699 GNUNET_SERVER_receive_done (session->client, GNUNET_OK);
1701 session->receive_delay_task =
1702 GNUNET_SCHEDULER_add_delayed (delay, &delayed_done, session);
1707 * We've received data for this peer via TCP. Unbox,
1708 * compute latency and forward.
1710 * @param cls closure
1711 * @param client identification of the client
1712 * @param message the actual message
1715 handle_tcp_data (void *cls, struct GNUNET_SERVER_Client *client,
1716 const struct GNUNET_MessageHeader *message)
1718 struct Plugin *plugin = cls;
1719 struct Session *session;
1720 struct GNUNET_TIME_Relative delay;
1723 type = ntohs (message->type);
1724 if ((GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME == type) ||
1725 (GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE == type))
1727 /* We don't want to propagate WELCOME and NAT Probe messages up! */
1728 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1731 session = lookup_session_by_client (plugin, client);
1732 if (NULL == session)
1734 /* No inbound session found */
1735 GNUNET_break_op (0);
1736 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1739 else if (GNUNET_YES == session->expecting_welcome)
1741 /* Session is expecting WELCOME message */
1742 GNUNET_break_op (0);
1743 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1747 session->last_activity = GNUNET_TIME_absolute_get ();
1749 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1750 "Passing %u bytes of type %u from `%4s' to transport service.\n",
1751 (unsigned int) ntohs (message->size),
1752 (unsigned int) ntohs (message->type),
1753 GNUNET_i2s (&session->target));
1755 GNUNET_STATISTICS_update (plugin->env->stats,
1756 gettext_noop ("# bytes received via TCP"),
1757 ntohs (message->size), GNUNET_NO);
1758 struct GNUNET_ATS_Information distance[2];
1760 distance[0].type = htonl (GNUNET_ATS_QUALITY_NET_DISTANCE);
1761 distance[0].value = htonl (1);
1762 distance[1].type = htonl (GNUNET_ATS_NETWORK_TYPE);
1763 distance[1].value = session->ats_address_network_type;
1764 GNUNET_break (ntohl(session->ats_address_network_type) != GNUNET_ATS_NET_UNSPECIFIED);
1766 delay = plugin->env->receive (plugin->env->cls,
1769 (const struct GNUNET_ATS_Information *) &distance,
1771 (GNUNET_YES == session->inbound) ? NULL : session->addr,
1772 (GNUNET_YES == session->inbound) ? 0 : session->addrlen);
1773 if (delay.rel_value == 0)
1775 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1780 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1781 "Throttling receiving from `%s' for %llu ms\n",
1782 GNUNET_i2s (&session->target),
1783 (unsigned long long) delay.rel_value);
1785 GNUNET_SERVER_disable_receive_done_warning (client);
1786 session->receive_delay_task =
1787 GNUNET_SCHEDULER_add_delayed (delay, &delayed_done, session);
1793 * Functions with this signature are called whenever a peer
1794 * is disconnected on the network level.
1796 * @param cls closure
1797 * @param client identification of the client
1800 disconnect_notify (void *cls, struct GNUNET_SERVER_Client *client)
1802 struct Plugin *plugin = cls;
1803 struct Session *session;
1807 plugin->max_connections++;
1808 session = lookup_session_by_client (plugin, client);
1809 if (session == NULL)
1810 return; /* unknown, nothing to do */
1812 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1813 "Destroying session of `%4s' with %s due to network-level disconnect.\n",
1814 GNUNET_i2s (&session->target),
1816 NULL) ? tcp_address_to_string (session->plugin,
1821 GNUNET_STATISTICS_update (session->plugin->env->stats,
1823 ("# network-level TCP disconnect events"), 1,
1825 disconnect_session (session);
1830 * We can now send a probe message, copy into buffer to really send.
1832 * @param cls closure, a struct TCPProbeContext
1833 * @param size max size to copy
1834 * @param buf buffer to copy message to
1835 * @return number of bytes copied into buf
1838 notify_send_probe (void *cls, size_t size, void *buf)
1840 struct TCPProbeContext *tcp_probe_ctx = cls;
1841 struct Plugin *plugin = tcp_probe_ctx->plugin;
1844 tcp_probe_ctx->transmit_handle = NULL;
1845 GNUNET_CONTAINER_DLL_remove (plugin->probe_head, plugin->probe_tail,
1849 GNUNET_CONNECTION_destroy (tcp_probe_ctx->sock, GNUNET_NO);
1850 GNUNET_free (tcp_probe_ctx);
1853 GNUNET_assert (size >= sizeof (tcp_probe_ctx->message));
1854 memcpy (buf, &tcp_probe_ctx->message, sizeof (tcp_probe_ctx->message));
1855 GNUNET_SERVER_connect_socket (tcp_probe_ctx->plugin->server,
1856 tcp_probe_ctx->sock);
1857 ret = sizeof (tcp_probe_ctx->message);
1858 GNUNET_free (tcp_probe_ctx);
1864 * Function called by the NAT subsystem suggesting another peer wants
1865 * to connect to us via connection reversal. Try to connect back to the
1868 * @param cls closure
1869 * @param addr address to try
1870 * @param addrlen number of bytes in addr
1873 try_connection_reversal (void *cls, const struct sockaddr *addr,
1876 struct Plugin *plugin = cls;
1877 struct GNUNET_CONNECTION_Handle *sock;
1878 struct TCPProbeContext *tcp_probe_ctx;
1881 * We have received an ICMP response, ostensibly from a peer
1882 * that wants to connect to us! Send a message to establish a connection.
1884 sock = GNUNET_CONNECTION_create_from_sockaddr (AF_INET, addr, addrlen);
1887 /* failed for some odd reason (out of sockets?); ignore attempt */
1891 /* FIXME: do we need to track these probe context objects so that
1892 * we can clean them up on plugin unload? */
1893 tcp_probe_ctx = GNUNET_malloc (sizeof (struct TCPProbeContext));
1894 tcp_probe_ctx->message.header.size =
1895 htons (sizeof (struct TCP_NAT_ProbeMessage));
1896 tcp_probe_ctx->message.header.type =
1897 htons (GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE);
1898 memcpy (&tcp_probe_ctx->message.clientIdentity, plugin->env->my_identity,
1899 sizeof (struct GNUNET_PeerIdentity));
1900 tcp_probe_ctx->plugin = plugin;
1901 tcp_probe_ctx->sock = sock;
1902 GNUNET_CONTAINER_DLL_insert (plugin->probe_head, plugin->probe_tail,
1904 tcp_probe_ctx->transmit_handle =
1905 GNUNET_CONNECTION_notify_transmit_ready (sock,
1906 ntohs (tcp_probe_ctx->
1907 message.header.size),
1908 GNUNET_TIME_UNIT_FOREVER_REL,
1916 * Entry point for the plugin.
1918 * @param cls closure, the 'struct GNUNET_TRANSPORT_PluginEnvironment*'
1919 * @return the 'struct GNUNET_TRANSPORT_PluginFunctions*' or NULL on error
1922 libgnunet_plugin_transport_tcp_init (void *cls)
1924 static const struct GNUNET_SERVER_MessageHandler my_handlers[] = {
1925 {&handle_tcp_welcome, NULL, GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME,
1926 sizeof (struct WelcomeMessage)},
1927 {&handle_tcp_nat_probe, NULL, GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE,
1928 sizeof (struct TCP_NAT_ProbeMessage)},
1929 {&handle_tcp_data, NULL, GNUNET_MESSAGE_TYPE_ALL, 0},
1932 struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
1933 struct GNUNET_TRANSPORT_PluginFunctions *api;
1934 struct Plugin *plugin;
1935 struct GNUNET_SERVICE_Context *service;
1936 unsigned long long aport;
1937 unsigned long long bport;
1938 unsigned long long max_connections;
1940 struct GNUNET_TIME_Relative idle_timeout;
1942 struct sockaddr **addrs;
1943 socklen_t *addrlens;
1946 GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-tcp",
1949 max_connections = 128;
1953 GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-tcp", "PORT",
1954 &bport)) || (bport > 65535) ||
1956 GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-tcp",
1957 "ADVERTISED-PORT", &aport)) &&
1960 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, "tcp",
1962 ("Require valid port number for service `%s' in configuration!\n"),
1972 service = GNUNET_SERVICE_start ("transport-tcp", env->cfg);
1973 if (service == NULL)
1975 GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, "tcp",
1976 _("Failed to start service.\n"));
1985 plugin = GNUNET_malloc (sizeof (struct Plugin));
1986 plugin->sessionmap = GNUNET_CONTAINER_multihashmap_create(max_connections);
1987 plugin->max_connections = max_connections;
1988 plugin->open_port = bport;
1989 plugin->adv_port = aport;
1991 plugin->lsock = NULL;
1992 if ((service != NULL) &&
1995 GNUNET_SERVICE_get_server_addresses ("transport-tcp", env->cfg, &addrs,
1999 GNUNET_NAT_register (env->cfg, GNUNET_YES, aport, (unsigned int) ret,
2000 (const struct sockaddr **) addrs, addrlens,
2001 &tcp_nat_port_map_callback,
2002 &try_connection_reversal, plugin);
2006 GNUNET_assert (addrs[ret] != NULL);
2007 GNUNET_free (addrs[ret]);
2009 GNUNET_free_non_null (addrs);
2010 GNUNET_free_non_null (addrlens);
2015 GNUNET_NAT_register (env->cfg, GNUNET_YES, 0, 0, NULL, NULL, NULL,
2016 &try_connection_reversal, plugin);
2018 api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
2020 api->send = &tcp_plugin_send;
2021 api->get_session = &tcp_plugin_get_session;
2023 api->disconnect = &tcp_plugin_disconnect;
2024 api->address_pretty_printer = &tcp_plugin_address_pretty_printer;
2025 api->check_address = &tcp_plugin_check_address;
2026 api->address_to_string = &tcp_address_to_string;
2027 plugin->service = service;
2028 if (service != NULL)
2030 plugin->server = GNUNET_SERVICE_get_server (service);
2035 GNUNET_CONFIGURATION_get_value_time (env->cfg, "transport-tcp",
2036 "TIMEOUT", &idle_timeout))
2038 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, "tcp",
2039 _("Failed to find option %s in section %s!\n"),
2040 "TIMEOUT", "transport-tcp");
2041 if (plugin->nat != NULL)
2042 GNUNET_NAT_unregister (plugin->nat);
2043 GNUNET_free (plugin);
2048 GNUNET_SERVER_create_with_sockets (&plugin_tcp_access_check, plugin,
2049 NULL, idle_timeout, GNUNET_YES);
2051 plugin->handlers = GNUNET_malloc (sizeof (my_handlers));
2052 memcpy (plugin->handlers, my_handlers, sizeof (my_handlers));
2054 i < sizeof (my_handlers) / sizeof (struct GNUNET_SERVER_MessageHandler);
2056 plugin->handlers[i].callback_cls = plugin;
2057 GNUNET_SERVER_add_handlers (plugin->server, plugin->handlers);
2058 GNUNET_SERVER_disconnect_notify (plugin->server, &disconnect_notify, plugin);
2059 plugin->nat_wait_conns = GNUNET_CONTAINER_multihashmap_create (16);
2061 GNUNET_log_from (GNUNET_ERROR_TYPE_INFO, "tcp",
2062 _("TCP transport listening on port %llu\n"), bport);
2064 GNUNET_log_from (GNUNET_ERROR_TYPE_INFO, "tcp",
2066 ("TCP transport not listening on any port (client only)\n"));
2068 GNUNET_log_from (GNUNET_ERROR_TYPE_INFO, "tcp",
2070 ("TCP transport advertises itself as being on port %llu\n"),
2077 * Exit point from the plugin.
2080 libgnunet_plugin_transport_tcp_done (void *cls)
2082 struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
2083 struct Plugin *plugin = api->cls;
2084 struct TCPProbeContext *tcp_probe;
2086 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp", "Shutting down TCP plugin\n");
2089 /* Removing leftover sessions */
2090 GNUNET_CONTAINER_multihashmap_iterate(plugin->sessionmap, &session_disconnect_it, NULL);
2091 /* Removing leftover NAT sessions */
2092 GNUNET_CONTAINER_multihashmap_iterate(plugin->nat_wait_conns, &session_nat_disconnect_it, NULL);
2094 if (plugin->service != NULL)
2095 GNUNET_SERVICE_stop (plugin->service);
2097 GNUNET_SERVER_destroy (plugin->server);
2098 GNUNET_free (plugin->handlers);
2099 if (plugin->nat != NULL)
2100 GNUNET_NAT_unregister (plugin->nat);
2101 while (NULL != (tcp_probe = plugin->probe_head))
2103 GNUNET_CONTAINER_DLL_remove (plugin->probe_head, plugin->probe_tail,
2105 GNUNET_CONNECTION_destroy (tcp_probe->sock, GNUNET_NO);
2106 GNUNET_free (tcp_probe);
2108 GNUNET_CONTAINER_multihashmap_destroy (plugin->nat_wait_conns);
2109 GNUNET_CONTAINER_multihashmap_destroy (plugin->sessionmap);
2110 GNUNET_free (plugin);
2115 /* end of plugin_transport_tcp.c */