2 This file is part of GNUnet
3 (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 Christian Grothoff (and other contributing authors)
5 GNUnet is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published
7 by the Free Software Foundation; either version 3, or (at your
8 option) any later version.
10 GNUnet is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with GNUnet; see the file COPYING. If not, write to the
17 Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18 Boston, MA 02111-1307, USA.
21 * @file transport/plugin_transport_tcp.c
22 * @brief Implementation of the TCP transport service
23 * @author Christian Grothoff
26 #include "gnunet_hello_lib.h"
27 #include "gnunet_constants.h"
28 #include "gnunet_connection_lib.h"
29 #include "gnunet_container_lib.h"
30 #include "gnunet_nat_lib.h"
31 #include "gnunet_os_lib.h"
32 #include "gnunet_protocols.h"
33 #include "gnunet_resolver_service.h"
34 #include "gnunet_server_lib.h"
35 #include "gnunet_service_lib.h"
36 #include "gnunet_signatures.h"
37 #include "gnunet_statistics_service.h"
38 #include "gnunet_transport_service.h"
39 #include "gnunet_transport_plugin.h"
40 #include "transport.h"
42 #define DEBUG_TCP GNUNET_EXTRA_LOGGING
44 #define DEBUG_TCP_NAT GNUNET_EXTRA_LOGGING
48 * How long until we give up on establishing an NAT connection?
51 #define NAT_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 10)
54 GNUNET_NETWORK_STRUCT_BEGIN
57 * Initial handshake message for a session.
62 * Type is GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME.
64 struct GNUNET_MessageHeader header;
67 * Identity of the node connecting (TCP client)
69 struct GNUNET_PeerIdentity clientIdentity;
75 * Basically a WELCOME message, but with the purpose
76 * of giving the waiting peer a client handle to use
78 struct TCP_NAT_ProbeMessage
81 * Type is GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE.
83 struct GNUNET_MessageHeader header;
86 * Identity of the sender of the message.
88 struct GNUNET_PeerIdentity clientIdentity;
91 GNUNET_NETWORK_STRUCT_END
94 * Context for sending a NAT probe via TCP.
96 struct TCPProbeContext
100 * Active probes are kept in a DLL.
102 struct TCPProbeContext *next;
105 * Active probes are kept in a DLL.
107 struct TCPProbeContext *prev;
112 struct GNUNET_CONNECTION_Handle *sock;
115 * Message to be sent.
117 struct TCP_NAT_ProbeMessage message;
120 * Handle to the transmission.
122 struct GNUNET_CONNECTION_TransmitHandle *transmit_handle;
125 * Transport plugin handle.
127 struct Plugin *plugin;
131 GNUNET_NETWORK_STRUCT_BEGIN
134 * Network format for IPv4 addresses.
136 struct IPv4TcpAddress
139 * IPv4 address, in network byte order.
141 uint32_t ipv4_addr GNUNET_PACKED;
144 * Port number, in network byte order.
146 uint16_t t4_port GNUNET_PACKED;
152 * Network format for IPv6 addresses.
154 struct IPv6TcpAddress
159 struct in6_addr ipv6_addr GNUNET_PACKED;
162 * Port number, in network byte order.
164 uint16_t t6_port GNUNET_PACKED;
167 GNUNET_NETWORK_STRUCT_END
170 * Encapsulation of all of the state of the plugin.
176 * Information kept for each message that is yet to
179 struct PendingMessage
183 * This is a doubly-linked list.
185 struct PendingMessage *next;
188 * This is a doubly-linked list.
190 struct PendingMessage *prev;
193 * The pending message
198 * Continuation function to call once the message
199 * has been sent. Can be NULL if there is no
200 * continuation to call.
202 GNUNET_TRANSPORT_TransmitContinuation transmit_cont;
205 * Closure for transmit_cont.
207 void *transmit_cont_cls;
210 * Timeout value for the pending message.
212 struct GNUNET_TIME_Absolute timeout;
215 * So that the gnunet-service-transport can group messages together,
216 * these pending messages need to accept a message buffer and size
217 * instead of just a GNUNET_MessageHeader.
225 * Session handle for TCP connections.
233 struct SessionHeader header;
236 * Stored in a linked list.
238 struct Session *next;
241 * Pointer to the global plugin struct.
243 struct Plugin *plugin;
246 * The client (used to identify this connection)
248 struct GNUNET_SERVER_Client *client;
251 * Task cleaning up a NAT client connection establishment attempt;
253 GNUNET_SCHEDULER_TaskIdentifier nat_connection_timeout;
256 * Messages currently pending for transmission
257 * to this peer, if any.
259 struct PendingMessage *pending_messages_head;
262 * Messages currently pending for transmission
263 * to this peer, if any.
265 struct PendingMessage *pending_messages_tail;
268 * Handle for pending transmission request.
270 struct GNUNET_CONNECTION_TransmitHandle *transmit_handle;
273 * To whom are we talking to (set to our identity
274 * if we are still waiting for the welcome message)
276 struct GNUNET_PeerIdentity target;
279 * ID of task used to delay receiving more to throttle sender.
281 GNUNET_SCHEDULER_TaskIdentifier receive_delay_task;
284 * Address of the other peer (either based on our 'connect'
285 * call or on our 'accept' call).
287 * struct IPv4TcpAddress or struct IPv6TcpAddress
293 * Length of connect_addr.
298 * Last activity on this connection. Used to select preferred
301 struct GNUNET_TIME_Absolute last_activity;
304 * Are we still expecting the welcome message? (GNUNET_YES/GNUNET_NO)
306 int expecting_welcome;
309 * Was this a connection that was inbound (we accepted)? (GNUNET_YES/GNUNET_NO)
314 * Was this session created using NAT traversal?
319 * ATS network type in NBO
321 uint32_t ats_address_network_type;
326 * Encapsulation of all of the state of the plugin.
333 struct GNUNET_TRANSPORT_PluginEnvironment *env;
338 struct GNUNET_CONNECTION_Handle *lsock;
341 * Our handle to the NAT module.
343 struct GNUNET_NAT_Handle *nat;
345 struct GNUNET_CONTAINER_MultiHashMap * sessionmap;
348 * Handle to the network service.
350 struct GNUNET_SERVICE_Context *service;
353 * Handle to the server for this service.
355 struct GNUNET_SERVER_Handle *server;
358 * Copy of the handler array where the closures are
359 * set to this struct's instance.
361 struct GNUNET_SERVER_MessageHandler *handlers;
364 * Map of peers we have tried to contact behind a NAT
366 struct GNUNET_CONTAINER_MultiHashMap *nat_wait_conns;
369 * List of active TCP probes.
371 struct TCPProbeContext *probe_head;
374 * List of active TCP probes.
376 struct TCPProbeContext *probe_tail;
379 * Handle for (DYN)DNS lookup of our external IP.
381 struct GNUNET_RESOLVER_RequestHandle *ext_dns;
384 * How many more TCP sessions are we allowed to open right now?
386 unsigned long long max_connections;
389 * ID of task used to update our addresses when one expires.
391 GNUNET_SCHEDULER_TaskIdentifier address_update_task;
394 * Port that we are actually listening on.
399 * Port that the user said we would have visible to the
408 * Function to check if an inbound connection is acceptable.
409 * Mostly used to limit the total number of open connections
412 * @param cls the 'struct Plugin'
413 * @param ucred credentials, if available, otherwise NULL
414 * @param addr address
415 * @param addrlen length of address
416 * @return GNUNET_YES to allow, GNUNET_NO to deny, GNUNET_SYSERR
417 * for unknown address family (will be denied).
420 plugin_tcp_access_check (void *cls,
421 const struct GNUNET_CONNECTION_Credentials *ucred,
422 const struct sockaddr *addr, socklen_t addrlen)
424 struct Plugin *plugin = cls;
426 if (0 == plugin->max_connections)
428 plugin->max_connections--;
434 * Our external IP address/port mapping has changed.
436 * @param cls closure, the 'struct LocalAddrList'
437 * @param add_remove GNUNET_YES to mean the new public IP address, GNUNET_NO to mean
438 * the previous (now invalid) one
439 * @param addr either the previous or the new public IP address
440 * @param addrlen actual lenght of the address
443 tcp_nat_port_map_callback (void *cls, int add_remove,
444 const struct sockaddr *addr, socklen_t addrlen)
446 struct Plugin *plugin = cls;
447 struct IPv4TcpAddress t4;
448 struct IPv6TcpAddress t6;
452 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
453 "NPMC called with %d for address `%s'\n", add_remove,
454 GNUNET_a2s (addr, addrlen));
455 /* convert 'addr' to our internal format */
456 switch (addr->sa_family)
459 GNUNET_assert (addrlen == sizeof (struct sockaddr_in));
460 t4.ipv4_addr = ((struct sockaddr_in *) addr)->sin_addr.s_addr;
461 t4.t4_port = ((struct sockaddr_in *) addr)->sin_port;
466 GNUNET_assert (addrlen == sizeof (struct sockaddr_in6));
467 memcpy (&t6.ipv6_addr, &((struct sockaddr_in6 *) addr)->sin6_addr,
468 sizeof (struct in6_addr));
469 t6.t6_port = ((struct sockaddr_in6 *) addr)->sin6_port;
477 /* modify our published address list */
478 plugin->env->notify_address (plugin->env->cls, add_remove, arg, args);
483 * Function called for a quick conversion of the binary address to
484 * a numeric address. Note that the caller must not free the
485 * address and that the next call to this function is allowed
486 * to override the address again.
488 * @param cls closure ('struct Plugin*')
489 * @param addr binary address
490 * @param addrlen length of the address
491 * @return string representing the same address
494 tcp_address_to_string (void *cls, const void *addr, size_t addrlen)
496 static char rbuf[INET6_ADDRSTRLEN + 12];
497 char buf[INET6_ADDRSTRLEN];
501 const struct IPv4TcpAddress *t4;
502 const struct IPv6TcpAddress *t6;
506 if (addrlen == sizeof (struct IPv6TcpAddress))
510 port = ntohs (t6->t6_port);
511 memcpy (&a6, &t6->ipv6_addr, sizeof (a6));
514 else if (addrlen == sizeof (struct IPv4TcpAddress))
518 port = ntohs (t4->t4_port);
519 memcpy (&a4, &t4->ipv4_addr, sizeof (a4));
524 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, "tcp",
525 _("Unexpected address length: %u bytes\n"),
526 (unsigned int) addrlen);
530 if (NULL == inet_ntop (af, sb, buf, INET6_ADDRSTRLEN))
532 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "inet_ntop");
535 GNUNET_snprintf (rbuf, sizeof (rbuf), (af == AF_INET6) ? "[%s]:%u" : "%s:%u",
542 * Function called to convert a string address to
545 * @param cls closure ('struct Plugin*')
546 * @param addr string address
547 * @param addrlen length of the address
548 * @param buf location to store the buffer
549 * @param added location to store the number of bytes in the buffer.
550 * If the function returns GNUNET_SYSERR, its contents are undefined.
551 * @return GNUNET_OK on success, GNUNET_SYSERR on failure
554 tcp_string_to_address (void *cls, const char *addr, uint16_t addrlen,
555 void **buf, size_t *added)
557 struct sockaddr_storage socket_address;
558 int ret = GNUNET_STRINGS_to_address_ip (addr, addrlen,
561 if (ret != GNUNET_OK)
562 return GNUNET_SYSERR;
564 if (socket_address.ss_family == AF_INET)
566 struct IPv4TcpAddress *t4;
567 struct sockaddr_in *in4 = (struct sockaddr_in *) &socket_address;
568 t4 = GNUNET_malloc (sizeof (struct IPv4TcpAddress));
569 t4->ipv4_addr = in4->sin_addr.s_addr;
570 t4->t4_port = in4->sin_port;
572 *added = sizeof (struct IPv4TcpAddress);
574 else if (socket_address.ss_family == AF_INET6)
576 struct IPv6TcpAddress *t6;
577 struct sockaddr_in6 *in6 = (struct sockaddr_in6 *) &socket_address;
578 t6 = GNUNET_malloc (sizeof (struct IPv6TcpAddress));
579 t6->ipv6_addr = in6->sin6_addr;
580 t6->t6_port = in6->sin6_port;
582 *added = sizeof (struct IPv6TcpAddress);
584 return GNUNET_SYSERR;
588 struct SessionClientCtx
590 const struct GNUNET_SERVER_Client *client;
594 int session_lookup_by_client_it (void *cls,
595 const GNUNET_HashCode * key,
598 struct SessionClientCtx *sc_ctx = cls;
599 struct Session *s = value;
601 if (s->client == sc_ctx->client)
610 * Find the session handle for the given client.
612 * @param plugin the plugin
613 * @param client which client to find the session handle for
614 * @return NULL if no matching session exists
616 static struct Session *
617 lookup_session_by_client (struct Plugin *plugin,
618 const struct GNUNET_SERVER_Client *client)
620 struct SessionClientCtx sc_ctx;
621 sc_ctx.client = client;
624 GNUNET_CONTAINER_multihashmap_iterate (plugin->sessionmap, &session_lookup_by_client_it, &sc_ctx);
631 * Create a new session. Also queues a welcome message.
633 * @param plugin the plugin
634 * @param target peer to connect to
635 * @param client client to use
636 * @param is_nat this a NAT session, we should wait for a client to
637 * connect to us from an address, then assign that to
639 * @return new session object
641 static struct Session *
642 create_session (struct Plugin *plugin, const struct GNUNET_PeerIdentity *target,
643 struct GNUNET_SERVER_Client *client, int is_nat)
646 struct PendingMessage *pm;
647 struct WelcomeMessage welcome;
649 if (is_nat != GNUNET_YES)
650 GNUNET_assert (client != NULL);
652 GNUNET_assert (client == NULL);
654 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
655 "Creating new session for peer `%4s'\n",
656 GNUNET_i2s (target));
658 ret = GNUNET_malloc (sizeof (struct Session));
659 ret->last_activity = GNUNET_TIME_absolute_get ();
660 ret->plugin = plugin;
661 ret->is_nat = is_nat;
662 ret->client = client;
663 ret->target = *target;
664 ret->expecting_welcome = GNUNET_YES;
665 ret->ats_address_network_type = htonl (GNUNET_ATS_NET_UNSPECIFIED);
666 pm = GNUNET_malloc (sizeof (struct PendingMessage) +
667 sizeof (struct WelcomeMessage));
668 pm->msg = (const char *) &pm[1];
669 pm->message_size = sizeof (struct WelcomeMessage);
670 welcome.header.size = htons (sizeof (struct WelcomeMessage));
671 welcome.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME);
672 welcome.clientIdentity = *plugin->env->my_identity;
673 memcpy (&pm[1], &welcome, sizeof (welcome));
674 pm->timeout = GNUNET_TIME_UNIT_FOREVER_ABS;
675 GNUNET_STATISTICS_update (plugin->env->stats,
676 gettext_noop ("# bytes currently in TCP buffers"),
677 pm->message_size, GNUNET_NO);
678 GNUNET_CONTAINER_DLL_insert (ret->pending_messages_head,
679 ret->pending_messages_tail, pm);
680 if (is_nat != GNUNET_YES)
681 GNUNET_STATISTICS_update (plugin->env->stats,
682 gettext_noop ("# TCP sessions active"), 1,
689 * If we have pending messages, ask the server to
690 * transmit them (schedule the respective tasks, etc.)
692 * @param session for which session should we do this
695 process_pending_messages (struct Session *session);
699 * Function called to notify a client about the socket
700 * being ready to queue more data. "buf" will be
701 * NULL and "size" zero if the socket was closed for
702 * writing in the meantime.
705 * @param size number of bytes available in buf
706 * @param buf where the callee should write the message
707 * @return number of bytes written to buf
710 do_transmit (void *cls, size_t size, void *buf)
712 struct Session *session = cls;
713 struct GNUNET_PeerIdentity pid;
714 struct Plugin *plugin;
715 struct PendingMessage *pos;
716 struct PendingMessage *hd;
717 struct PendingMessage *tl;
718 struct GNUNET_TIME_Absolute now;
722 GNUNET_assert (session != NULL);
723 session->transmit_handle = NULL;
724 plugin = session->plugin;
728 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
729 "Timeout trying to transmit to peer `%4s', discarding message queue.\n",
730 GNUNET_i2s (&session->target));
732 /* timeout; cancel all messages that have already expired */
736 now = GNUNET_TIME_absolute_get ();
737 while ((NULL != (pos = session->pending_messages_head)) &&
738 (pos->timeout.abs_value <= now.abs_value))
740 GNUNET_CONTAINER_DLL_remove (session->pending_messages_head,
741 session->pending_messages_tail, pos);
743 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
744 "Failed to transmit %u byte message to `%4s'.\n",
745 pos->message_size, GNUNET_i2s (&session->target));
747 ret += pos->message_size;
748 GNUNET_CONTAINER_DLL_insert_after (hd, tl, tl, pos);
750 /* do this call before callbacks (so that if callbacks destroy
751 * session, they have a chance to cancel actions done by this
753 process_pending_messages (session);
754 pid = session->target;
755 /* no do callbacks and do not use session again since
756 * the callbacks may abort the session */
757 while (NULL != (pos = hd))
759 GNUNET_CONTAINER_DLL_remove (hd, tl, pos);
760 if (pos->transmit_cont != NULL)
761 pos->transmit_cont (pos->transmit_cont_cls, &pid, GNUNET_SYSERR);
764 GNUNET_STATISTICS_update (plugin->env->stats,
765 gettext_noop ("# bytes currently in TCP buffers"),
766 -(int64_t) ret, GNUNET_NO);
767 GNUNET_STATISTICS_update (plugin->env->stats,
769 ("# bytes discarded by TCP (timeout)"), ret,
773 /* copy all pending messages that would fit */
778 while (NULL != (pos = session->pending_messages_head))
780 if (ret + pos->message_size > size)
782 GNUNET_CONTAINER_DLL_remove (session->pending_messages_head,
783 session->pending_messages_tail, pos);
784 GNUNET_assert (size >= pos->message_size);
785 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
786 "Transmitting message of type %u\n",
787 ntohs (((struct GNUNET_MessageHeader *) pos->msg)->type));
788 /* FIXME: this memcpy can be up to 7% of our total runtime */
789 memcpy (cbuf, pos->msg, pos->message_size);
790 cbuf += pos->message_size;
791 ret += pos->message_size;
792 size -= pos->message_size;
793 GNUNET_CONTAINER_DLL_insert_tail (hd, tl, pos);
795 /* schedule 'continuation' before callbacks so that callbacks that
796 * cancel everything don't cause us to use a session that no longer
798 process_pending_messages (session);
799 session->last_activity = GNUNET_TIME_absolute_get ();
800 pid = session->target;
801 /* we'll now call callbacks that may cancel the session; hence
802 * we should not use 'session' after this point */
803 while (NULL != (pos = hd))
805 GNUNET_CONTAINER_DLL_remove (hd, tl, pos);
806 if (pos->transmit_cont != NULL)
807 pos->transmit_cont (pos->transmit_cont_cls, &pid, GNUNET_OK);
810 GNUNET_assert (hd == NULL);
811 GNUNET_assert (tl == NULL);
813 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp", "Transmitting %u bytes\n",
816 GNUNET_STATISTICS_update (plugin->env->stats,
817 gettext_noop ("# bytes currently in TCP buffers"),
818 -(int64_t) ret, GNUNET_NO);
819 GNUNET_STATISTICS_update (plugin->env->stats,
820 gettext_noop ("# bytes transmitted via TCP"), ret,
827 * If we have pending messages, ask the server to
828 * transmit them (schedule the respective tasks, etc.)
830 * @param session for which session should we do this
833 process_pending_messages (struct Session *session)
835 struct PendingMessage *pm;
837 GNUNET_assert (session->client != NULL);
838 if (session->transmit_handle != NULL)
840 if (NULL == (pm = session->pending_messages_head))
843 session->transmit_handle =
844 GNUNET_SERVER_notify_transmit_ready (session->client, pm->message_size,
845 GNUNET_TIME_absolute_get_remaining
846 (pm->timeout), &do_transmit,
852 * Functions with this signature are called whenever we need
853 * to close a session due to a disconnect or failure to
854 * establish a connection.
856 * @param session session to close down
859 disconnect_session (struct Session *session)
861 struct PendingMessage *pm;
862 struct Plugin * plugin = session->plugin;
864 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
865 "Disconnecting session %p for peer `%s' address `%s'\n",
867 GNUNET_i2s (&session->target),
868 tcp_address_to_string(NULL, session->addr, session->addrlen));
870 GNUNET_assert (GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(plugin->sessionmap, &session->target.hashPubKey, session) ||
871 GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(plugin->nat_wait_conns, &session->target.hashPubKey, session));
874 if (session->transmit_handle != NULL)
876 GNUNET_CONNECTION_notify_transmit_ready_cancel (session->transmit_handle);
877 session->transmit_handle = NULL;
879 session->plugin->env->session_end (session->plugin->env->cls,
880 &session->target, session);
882 if (session->nat_connection_timeout != GNUNET_SCHEDULER_NO_TASK)
884 GNUNET_SCHEDULER_cancel (session->nat_connection_timeout);
885 session->nat_connection_timeout = GNUNET_SCHEDULER_NO_TASK;
888 while (NULL != (pm = session->pending_messages_head))
891 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
893 NULL ? "Could not deliver message to `%4s'.\n" :
894 "Could not deliver message to `%4s', notifying.\n",
895 GNUNET_i2s (&session->target));
897 GNUNET_STATISTICS_update (session->plugin->env->stats,
898 gettext_noop ("# bytes currently in TCP buffers"),
899 -(int64_t) pm->message_size, GNUNET_NO);
900 GNUNET_STATISTICS_update (session->plugin->env->stats,
902 ("# bytes discarded by TCP (disconnect)"),
903 pm->message_size, GNUNET_NO);
904 GNUNET_CONTAINER_DLL_remove (session->pending_messages_head,
905 session->pending_messages_tail, pm);
906 if (NULL != pm->transmit_cont)
907 pm->transmit_cont (pm->transmit_cont_cls, &session->target,
911 if (session->receive_delay_task != GNUNET_SCHEDULER_NO_TASK)
913 GNUNET_SCHEDULER_cancel (session->receive_delay_task);
914 if (session->client != NULL)
915 GNUNET_SERVER_receive_done (session->client, GNUNET_SYSERR);
917 if (session->client != NULL)
919 GNUNET_SERVER_client_drop (session->client);
920 session->client = NULL;
922 GNUNET_STATISTICS_update (session->plugin->env->stats,
923 gettext_noop ("# TCP sessions active"), -1,
925 GNUNET_free_non_null (session->addr);
926 GNUNET_assert (NULL == session->transmit_handle);
927 GNUNET_free (session);
932 * Function that can be used by the transport service to transmit
933 * a message using the plugin. Note that in the case of a
934 * peer disconnecting, the continuation MUST be called
935 * prior to the disconnect notification itself. This function
936 * will be called with this peer's HELLO message to initiate
937 * a fresh connection to another peer.
940 * @param session which session must be used
941 * @param msgbuf the message to transmit
942 * @param msgbuf_size number of bytes in 'msgbuf'
943 * @param priority how important is the message (most plugins will
944 * ignore message priority and just FIFO)
945 * @param to how long to wait at most for the transmission (does not
946 * require plugins to discard the message after the timeout,
947 * just advisory for the desired delay; most plugins will ignore
949 * @param cont continuation to call once the message has
950 * been transmitted (or if the transport is ready
951 * for the next transmission call; or if the
952 * peer disconnected...); can be NULL
953 * @param cont_cls closure for cont
954 * @return number of bytes used (on the physical network, with overheads);
955 * -1 on hard errors (i.e. address invalid); 0 is a legal value
956 * and does NOT mean that the message was not transmitted (DV)
959 tcp_plugin_send (void *cls,
960 struct Session *session,
961 const char *msgbuf, size_t msgbuf_size,
962 unsigned int priority,
963 struct GNUNET_TIME_Relative to,
964 GNUNET_TRANSPORT_TransmitContinuation cont, void *cont_cls)
966 struct Plugin * plugin = cls;
967 struct PendingMessage *pm;
969 GNUNET_assert (plugin != NULL);
970 GNUNET_assert (session != NULL);
972 /* create new message entry */
973 pm = GNUNET_malloc (sizeof (struct PendingMessage) + msgbuf_size);
974 pm->msg = (const char *) &pm[1];
975 memcpy (&pm[1], msgbuf, msgbuf_size);
976 pm->message_size = msgbuf_size;
977 pm->timeout = GNUNET_TIME_relative_to_absolute (to);
978 pm->transmit_cont = cont;
979 pm->transmit_cont_cls = cont_cls;
982 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
983 "Asked to transmit %u bytes to `%s', added message to list.\n",
984 msgbuf_size, GNUNET_i2s (&session->target));
986 if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains_value(plugin->sessionmap, &session->target.hashPubKey, session))
988 GNUNET_assert (session->client != NULL);
990 GNUNET_SERVER_client_set_timeout (session->client,
991 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
992 GNUNET_STATISTICS_update (plugin->env->stats,
993 gettext_noop ("# bytes currently in TCP buffers"),
994 msgbuf_size, GNUNET_NO);
996 /* append pm to pending_messages list */
997 GNUNET_CONTAINER_DLL_insert_tail (session->pending_messages_head,
998 session->pending_messages_tail, pm);
1000 process_pending_messages (session);
1003 else if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains_value(plugin->nat_wait_conns, &session->target.hashPubKey, session))
1005 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1006 "This NAT WAIT session for peer `%s' is not yet ready!\n",
1007 GNUNET_i2s (&session->target));
1009 GNUNET_STATISTICS_update (plugin->env->stats,
1010 gettext_noop ("# bytes currently in TCP buffers"),
1011 msgbuf_size, GNUNET_NO);
1013 /* append pm to pending_messages list */
1014 GNUNET_CONTAINER_DLL_insert_tail (session->pending_messages_head,
1015 session->pending_messages_tail, pm);
1021 cont (cont_cls, &session->target, GNUNET_SYSERR);
1024 return GNUNET_SYSERR; /* session does not exist here */
1032 struct Session * result;
1035 int session_lookup_it (void *cls,
1036 const GNUNET_HashCode * key,
1039 struct SessionItCtx * si_ctx = cls;
1040 struct Session * session = value;
1042 char * a1 = strdup (tcp_address_to_string(NULL, session->addr, session->addrlen));
1043 char * a2 = strdup (tcp_address_to_string(NULL, si_ctx->addr, si_ctx->addrlen));
1044 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, "tcp",
1045 "Comparing: %s %u <-> %s %u\n",
1053 if (session->addrlen != si_ctx->addrlen)
1057 if (0 != memcmp (session->addr, si_ctx->addr, si_ctx->addrlen))
1062 a1 = strdup (tcp_address_to_string(NULL, session->addr, session->addrlen));
1063 a2 = strdup (tcp_address_to_string(NULL, si_ctx->addr, si_ctx->addrlen));
1064 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, "tcp",
1065 "Comparing: %s %u <-> %s %u , OK!\n",
1073 /* Found existing session */
1074 si_ctx->result = session;
1079 * Task cleaning up a NAT connection attempt after timeout
1083 nat_connect_timeout (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1085 struct Session *session = cls;
1087 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1088 "NAT WAIT connection to `%4s' at `%s' could not be established, removing session\n",
1089 GNUNET_i2s (&session->target), tcp_address_to_string(NULL, session->addr, session->addrlen));
1091 disconnect_session (session);
1096 * Create a new session to transmit data to the target
1097 * This session will used to send data to this peer and the plugin will
1098 * notify us by calling the env->session_end function
1100 * @param cls closure
1101 * @param address pointer to the GNUNET_HELLO_Address
1102 * @return the session if the address is valid, NULL otherwise
1104 static struct Session *
1105 tcp_plugin_get_session (void *cls,
1106 const struct GNUNET_HELLO_Address *address)
1108 struct Plugin * plugin = cls;
1109 struct Session * session = NULL;
1114 struct GNUNET_CONNECTION_Handle *sa;
1115 struct sockaddr_in a4;
1116 struct sockaddr_in6 a6;
1117 const struct IPv4TcpAddress *t4;
1118 const struct IPv6TcpAddress *t6;
1119 struct GNUNET_ATS_Information ats;
1120 unsigned int is_natd = GNUNET_NO;
1123 GNUNET_assert (plugin != NULL);
1124 GNUNET_assert (address != NULL);
1126 addrlen = address->address_length;
1128 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1129 "Trying to get session for `%s' address length %i\n",
1130 tcp_address_to_string(NULL, address->address, address->address_length),
1133 /* look for existing session */
1134 if (GNUNET_CONTAINER_multihashmap_contains(plugin->sessionmap, &address->peer.hashPubKey))
1136 struct SessionItCtx si_ctx;
1138 si_ctx.addr = (void *) address->address;
1139 si_ctx.addrlen = address->address_length;
1141 si_ctx.result = NULL;
1143 GNUNET_CONTAINER_multihashmap_get_multiple(plugin->sessionmap, &address->peer.hashPubKey, &session_lookup_it, &si_ctx);
1144 if (si_ctx.result != NULL)
1146 session = si_ctx.result;
1147 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1148 "Found exisiting session for `%s' address `%s' session %p\n",
1149 GNUNET_i2s (&address->peer),
1150 tcp_address_to_string(NULL, address->address, address->address_length),
1156 if (addrlen == sizeof (struct IPv6TcpAddress))
1158 GNUNET_assert (NULL != address->address); /* make static analysis happy */
1159 t6 = address->address;
1161 memset (&a6, 0, sizeof (a6));
1162 #if HAVE_SOCKADDR_IN_SIN_LEN
1163 a6.sin6_len = sizeof (a6);
1165 a6.sin6_family = AF_INET6;
1166 a6.sin6_port = t6->t6_port;
1167 if (t6->t6_port == 0)
1168 is_natd = GNUNET_YES;
1169 memcpy (&a6.sin6_addr, &t6->ipv6_addr, sizeof (struct in6_addr));
1173 else if (addrlen == sizeof (struct IPv4TcpAddress))
1175 GNUNET_assert (NULL != address->address); /* make static analysis happy */
1176 t4 = address->address;
1178 memset (&a4, 0, sizeof (a4));
1179 #if HAVE_SOCKADDR_IN_SIN_LEN
1180 a4.sin_len = sizeof (a4);
1182 a4.sin_family = AF_INET;
1183 a4.sin_port = t4->t4_port;
1184 if (t4->t4_port == 0)
1185 is_natd = GNUNET_YES;
1186 a4.sin_addr.s_addr = t4->ipv4_addr;
1192 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, "tcp",
1193 _("Address of unexpected length: %u\n"), addrlen);
1198 ats = plugin->env->get_address_type (plugin->env->cls, sb ,sbs);
1200 if ((is_natd == GNUNET_YES) && (addrlen == sizeof (struct IPv6TcpAddress)))
1202 /* NAT client only works with IPv4 addresses */
1206 if (0 == plugin->max_connections)
1212 if ((is_natd == GNUNET_YES) &&
1214 GNUNET_CONTAINER_multihashmap_contains (plugin->nat_wait_conns,
1215 &address->peer.hashPubKey)))
1217 /* Only do one NAT punch attempt per peer identity */
1221 if ((is_natd == GNUNET_YES) && (NULL != plugin->nat) &&
1223 GNUNET_CONTAINER_multihashmap_contains (plugin->nat_wait_conns,
1224 &address->peer.hashPubKey)))
1227 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1228 _("Found valid IPv4 NAT address (creating session)!\n"));
1230 session = create_session (plugin, &address->peer, NULL, GNUNET_YES);
1231 session->addrlen = 0;
1232 session->addr = NULL;
1233 session->ats_address_network_type = ats.value;
1234 session->nat_connection_timeout = GNUNET_SCHEDULER_add_delayed(NAT_TIMEOUT,
1235 &nat_connect_timeout,
1237 GNUNET_assert (session != NULL);
1239 GNUNET_assert (GNUNET_CONTAINER_multihashmap_put
1240 (plugin->nat_wait_conns, &address->peer.hashPubKey, session,
1241 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY) == GNUNET_OK);
1243 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1244 "Created NAT WAIT connection to `%4s' at `%s'\n",
1245 GNUNET_i2s (&session->target), GNUNET_a2s (sb, sbs));
1247 if (GNUNET_OK == GNUNET_NAT_run_client (plugin->nat, &a4))
1251 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1252 "Running NAT client for `%4s' at `%s' failed\n",
1253 GNUNET_i2s (&session->target), GNUNET_a2s (sb, sbs));
1255 disconnect_session (session);
1260 /* create new outbound session */
1261 GNUNET_assert (0 != plugin->max_connections);
1262 sa = GNUNET_CONNECTION_create_from_sockaddr (af, sb, sbs);
1266 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1267 "Failed to create connection to `%4s' at `%s'\n",
1268 GNUNET_i2s (&session->target), GNUNET_a2s (sb, sbs));
1272 plugin->max_connections--;
1274 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1275 "Asked to transmit to `%4s', creating fresh session using address `%s'.\n",
1276 GNUNET_i2s (&address->peer), GNUNET_a2s (sb, sbs));
1278 session = create_session (plugin,
1280 GNUNET_SERVER_connect_socket (plugin->server, sa),
1282 session->addr = GNUNET_malloc (addrlen);
1283 memcpy (session->addr, address->address, addrlen);
1284 session->addrlen = addrlen;
1285 session->ats_address_network_type = ats.value;
1287 GNUNET_CONTAINER_multihashmap_put(plugin->sessionmap, &address->peer.hashPubKey, session, GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
1289 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1290 "Creating new session for `%s' address `%s' session %p\n",
1291 GNUNET_i2s (&address->peer),
1292 tcp_address_to_string(NULL, address->address, address->address_length),
1295 /* Send TCP Welcome */
1296 process_pending_messages (session);
1302 int session_disconnect_it (void *cls,
1303 const GNUNET_HashCode * key,
1306 struct Session *session = value;
1308 GNUNET_STATISTICS_update (session->plugin->env->stats,
1310 ("# transport-service disconnect requests for TCP"),
1312 disconnect_session (session);
1317 * Function that can be called to force a disconnect from the
1318 * specified neighbour. This should also cancel all previously
1319 * scheduled transmissions. Obviously the transmission may have been
1320 * partially completed already, which is OK. The plugin is supposed
1321 * to close the connection (if applicable) and no longer call the
1322 * transmit continuation(s).
1324 * Finally, plugin MUST NOT call the services's receive function to
1325 * notify the service that the connection to the specified target was
1326 * closed after a getting this call.
1328 * @param cls closure
1329 * @param target peer for which the last transmission is
1333 tcp_plugin_disconnect (void *cls, const struct GNUNET_PeerIdentity *target)
1335 struct Plugin *plugin = cls;
1336 struct Session *nat_session = NULL;
1338 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1339 "Disconnecting peer `%4s'\n", GNUNET_i2s (target));
1341 GNUNET_CONTAINER_multihashmap_get_multiple (plugin->sessionmap, &target->hashPubKey, session_disconnect_it, plugin);
1343 nat_session = GNUNET_CONTAINER_multihashmap_get(plugin->nat_wait_conns, &target->hashPubKey);
1344 if (nat_session != NULL)
1346 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1347 "Cleaning up pending NAT session for peer `%4s'\n", GNUNET_i2s (target));
1348 disconnect_session (nat_session);
1354 * Context for address to string conversion.
1356 struct PrettyPrinterContext
1359 * Function to call with the result.
1361 GNUNET_TRANSPORT_AddressStringCallback asc;
1364 * Clsoure for 'asc'.
1369 * Port to add after the IP address.
1378 * Append our port and forward the result.
1380 * @param cls the 'struct PrettyPrinterContext*'
1381 * @param hostname hostname part of the address
1384 append_port (void *cls, const char *hostname)
1386 struct PrettyPrinterContext *ppc = cls;
1389 if (hostname == NULL)
1391 ppc->asc (ppc->asc_cls, NULL);
1395 if (GNUNET_YES == ppc->ipv6)
1396 GNUNET_asprintf (&ret, "[%s]:%d", hostname, ppc->port);
1398 GNUNET_asprintf (&ret, "%s:%d", hostname, ppc->port);
1399 ppc->asc (ppc->asc_cls, ret);
1405 * Convert the transports address to a nice, human-readable
1408 * @param cls closure
1409 * @param type name of the transport that generated the address
1410 * @param addr one of the addresses of the host, NULL for the last address
1411 * the specific address format depends on the transport
1412 * @param addrlen length of the address
1413 * @param numeric should (IP) addresses be displayed in numeric form?
1414 * @param timeout after how long should we give up?
1415 * @param asc function to call on each string
1416 * @param asc_cls closure for asc
1419 tcp_plugin_address_pretty_printer (void *cls, const char *type,
1420 const void *addr, size_t addrlen,
1422 struct GNUNET_TIME_Relative timeout,
1423 GNUNET_TRANSPORT_AddressStringCallback asc,
1426 struct PrettyPrinterContext *ppc;
1429 struct sockaddr_in a4;
1430 struct sockaddr_in6 a6;
1431 const struct IPv4TcpAddress *t4;
1432 const struct IPv6TcpAddress *t6;
1435 if (addrlen == sizeof (struct IPv6TcpAddress))
1438 memset (&a6, 0, sizeof (a6));
1439 a6.sin6_family = AF_INET6;
1440 a6.sin6_port = t6->t6_port;
1441 memcpy (&a6.sin6_addr, &t6->ipv6_addr, sizeof (struct in6_addr));
1442 port = ntohs (t6->t6_port);
1446 else if (addrlen == sizeof (struct IPv4TcpAddress))
1449 memset (&a4, 0, sizeof (a4));
1450 a4.sin_family = AF_INET;
1451 a4.sin_port = t4->t4_port;
1452 a4.sin_addr.s_addr = t4->ipv4_addr;
1453 port = ntohs (t4->t4_port);
1459 /* invalid address */
1460 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, "tcp",
1461 "Invalid address to string request: plugin `%s', address length: %u bytes\n");
1462 GNUNET_break_op (0);
1463 asc (asc_cls, NULL);
1466 ppc = GNUNET_malloc (sizeof (struct PrettyPrinterContext));
1467 if (addrlen == sizeof (struct IPv6TcpAddress))
1468 ppc->ipv6 = GNUNET_YES;
1470 ppc->ipv6 = GNUNET_NO;
1472 ppc->asc_cls = asc_cls;
1474 GNUNET_RESOLVER_hostname_get (sb, sbs, !numeric, timeout, &append_port, ppc);
1479 * Check if the given port is plausible (must be either our listen
1480 * port or our advertised port), or any port if we are behind NAT
1481 * and do not have a port open. If it is neither, we return
1484 * @param plugin global variables
1485 * @param in_port port number to check
1486 * @return GNUNET_OK if port is either open_port or adv_port
1489 check_port (struct Plugin *plugin, uint16_t in_port)
1491 if ((in_port == plugin->adv_port) || (in_port == plugin->open_port))
1493 return GNUNET_SYSERR;
1498 * Function that will be called to check if a binary address for this
1499 * plugin is well-formed and corresponds to an address for THIS peer
1500 * (as per our configuration). Naturally, if absolutely necessary,
1501 * plugins can be a bit conservative in their answer, but in general
1502 * plugins should make sure that the address does not redirect
1503 * traffic to a 3rd party that might try to man-in-the-middle our
1506 * @param cls closure, our 'struct Plugin*'
1507 * @param addr pointer to the address
1508 * @param addrlen length of addr
1509 * @return GNUNET_OK if this is a plausible address for this peer
1510 * and transport, GNUNET_SYSERR if not
1513 tcp_plugin_check_address (void *cls, const void *addr, size_t addrlen)
1515 struct Plugin *plugin = cls;
1516 struct IPv4TcpAddress *v4;
1517 struct IPv6TcpAddress *v6;
1519 if ((addrlen != sizeof (struct IPv4TcpAddress)) &&
1520 (addrlen != sizeof (struct IPv6TcpAddress)))
1522 GNUNET_break_op (0);
1523 return GNUNET_SYSERR;
1525 if (addrlen == sizeof (struct IPv4TcpAddress))
1527 v4 = (struct IPv4TcpAddress *) addr;
1528 if (GNUNET_OK != check_port (plugin, ntohs (v4->t4_port)))
1529 return GNUNET_SYSERR;
1531 GNUNET_NAT_test_address (plugin->nat, &v4->ipv4_addr,
1532 sizeof (struct in_addr)))
1533 return GNUNET_SYSERR;
1537 v6 = (struct IPv6TcpAddress *) addr;
1538 if (IN6_IS_ADDR_LINKLOCAL (&v6->ipv6_addr))
1540 GNUNET_break_op (0);
1541 return GNUNET_SYSERR;
1543 if (GNUNET_OK != check_port (plugin, ntohs (v6->t6_port)))
1544 return GNUNET_SYSERR;
1546 GNUNET_NAT_test_address (plugin->nat, &v6->ipv6_addr,
1547 sizeof (struct in6_addr)))
1548 return GNUNET_SYSERR;
1555 * We've received a nat probe from this peer via TCP. Finish
1556 * creating the client session and resume sending of queued
1559 * @param cls closure
1560 * @param client identification of the client
1561 * @param message the actual message
1564 handle_tcp_nat_probe (void *cls, struct GNUNET_SERVER_Client *client,
1565 const struct GNUNET_MessageHeader *message)
1567 struct Plugin *plugin = cls;
1568 struct Session *session;
1569 const struct TCP_NAT_ProbeMessage *tcp_nat_probe;
1572 struct IPv4TcpAddress *t4;
1573 struct IPv6TcpAddress *t6;
1574 const struct sockaddr_in *s4;
1575 const struct sockaddr_in6 *s6;
1577 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp", "received NAT probe\n");
1579 /* We have received a TCP NAT probe, meaning we (hopefully) initiated
1580 * a connection to this peer by running gnunet-nat-client. This peer
1581 * received the punch message and now wants us to use the new connection
1582 * as the default for that peer. Do so and then send a WELCOME message
1583 * so we can really be connected!
1585 if (ntohs (message->size) != sizeof (struct TCP_NAT_ProbeMessage))
1587 GNUNET_break_op (0);
1588 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1592 tcp_nat_probe = (const struct TCP_NAT_ProbeMessage *) message;
1594 memcmp (&tcp_nat_probe->clientIdentity, plugin->env->my_identity,
1595 sizeof (struct GNUNET_PeerIdentity)))
1597 /* refuse connections from ourselves */
1598 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1603 GNUNET_CONTAINER_multihashmap_get (plugin->nat_wait_conns,
1605 clientIdentity.hashPubKey);
1606 if (session == NULL)
1608 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1609 "Did NOT find session for NAT probe!\n");
1610 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1613 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1614 "Found session for NAT probe!\n");
1616 if (session->nat_connection_timeout != GNUNET_SCHEDULER_NO_TASK)
1618 GNUNET_SCHEDULER_cancel (session->nat_connection_timeout);
1619 session->nat_connection_timeout = GNUNET_SCHEDULER_NO_TASK;
1622 GNUNET_assert (GNUNET_CONTAINER_multihashmap_remove
1623 (plugin->nat_wait_conns,
1624 &tcp_nat_probe->clientIdentity.hashPubKey,
1625 session) == GNUNET_YES);
1626 if (GNUNET_OK != GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
1629 GNUNET_free (session);
1630 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1634 GNUNET_SERVER_client_keep (client);
1635 session->client = client;
1636 session->last_activity = GNUNET_TIME_absolute_get ();
1637 session->inbound = GNUNET_NO;
1640 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1641 "Found address `%s' for incoming connection\n",
1642 GNUNET_a2s (vaddr, alen));
1644 switch (((const struct sockaddr *) vaddr)->sa_family)
1648 t4 = GNUNET_malloc (sizeof (struct IPv4TcpAddress));
1649 t4->t4_port = s4->sin_port;
1650 t4->ipv4_addr = s4->sin_addr.s_addr;
1652 session->addrlen = sizeof (struct IPv4TcpAddress);
1656 t6 = GNUNET_malloc (sizeof (struct IPv6TcpAddress));
1657 t6->t6_port = s6->sin6_port;
1658 memcpy (&t6->ipv6_addr, &s6->sin6_addr, sizeof (struct in6_addr));
1660 session->addrlen = sizeof (struct IPv6TcpAddress);
1663 GNUNET_break_op (0);
1665 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1666 "Bad address for incoming connection!\n");
1667 GNUNET_free (vaddr);
1669 GNUNET_SERVER_client_drop (client);
1670 GNUNET_free (session);
1671 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1674 GNUNET_free (vaddr);
1676 GNUNET_CONTAINER_multihashmap_put(plugin->sessionmap, &session->target.hashPubKey, session, GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
1678 GNUNET_STATISTICS_update (plugin->env->stats,
1679 gettext_noop ("# TCP sessions active"), 1,
1681 process_pending_messages (session);
1682 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1687 * We've received a welcome from this peer via TCP. Possibly create a
1688 * fresh client record and send back our welcome.
1690 * @param cls closure
1691 * @param client identification of the client
1692 * @param message the actual message
1695 handle_tcp_welcome (void *cls, struct GNUNET_SERVER_Client *client,
1696 const struct GNUNET_MessageHeader *message)
1698 struct Plugin *plugin = cls;
1699 const struct WelcomeMessage *wm = (const struct WelcomeMessage *) message;
1700 struct Session *session;
1703 struct IPv4TcpAddress *t4;
1704 struct IPv6TcpAddress *t6;
1705 const struct sockaddr_in *s4;
1706 const struct sockaddr_in6 *s6;
1709 memcmp (&wm->clientIdentity, plugin->env->my_identity,
1710 sizeof (struct GNUNET_PeerIdentity)))
1712 /* refuse connections from ourselves */
1713 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1717 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1718 "Received %s message from `%4s'\n", "WELCOME",
1719 GNUNET_i2s (&wm->clientIdentity));
1720 GNUNET_STATISTICS_update (plugin->env->stats,
1721 gettext_noop ("# TCP WELCOME messages received"), 1,
1724 session = lookup_session_by_client (plugin, client);
1725 if (session != NULL)
1727 if (GNUNET_OK == GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
1729 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1730 "Found existing session %p for peer `%s'\n",
1732 GNUNET_a2s (vaddr, alen));
1733 GNUNET_free (vaddr);
1738 GNUNET_SERVER_client_keep (client);
1739 session = create_session (plugin, &wm->clientIdentity, client, GNUNET_NO);
1740 session->inbound = GNUNET_YES;
1742 if (GNUNET_OK == GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
1744 if (alen == sizeof (struct sockaddr_in))
1747 t4 = GNUNET_malloc (sizeof (struct IPv4TcpAddress));
1748 t4->t4_port = s4->sin_port;
1749 t4->ipv4_addr = s4->sin_addr.s_addr;
1751 session->addrlen = sizeof (struct IPv4TcpAddress);
1753 else if (alen == sizeof (struct sockaddr_in6))
1756 t6 = GNUNET_malloc (sizeof (struct IPv6TcpAddress));
1757 t6->t6_port = s6->sin6_port;
1758 memcpy (&t6->ipv6_addr, &s6->sin6_addr, sizeof (struct in6_addr));
1760 session->addrlen = sizeof (struct IPv6TcpAddress);
1763 struct GNUNET_ATS_Information ats;
1764 ats = plugin->env->get_address_type (plugin->env->cls, vaddr ,alen);
1765 session->ats_address_network_type = ats.value;
1767 GNUNET_free (vaddr);
1772 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1773 "Did not obtain TCP socket address for incoming connection\n");
1776 GNUNET_CONTAINER_multihashmap_put(plugin->sessionmap, &wm->clientIdentity.hashPubKey, session, GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
1779 if (session->expecting_welcome != GNUNET_YES)
1781 GNUNET_break_op (0);
1782 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1785 session->last_activity = GNUNET_TIME_absolute_get ();
1786 session->expecting_welcome = GNUNET_NO;
1789 process_pending_messages (session);
1791 GNUNET_SERVER_client_set_timeout (client,
1792 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1793 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1798 * Task to signal the server that we can continue
1799 * receiving from the TCP client now.
1801 * @param cls the 'struct Session*'
1802 * @param tc task context (unused)
1805 delayed_done (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1807 struct Session *session = cls;
1808 struct GNUNET_TIME_Relative delay;
1809 struct GNUNET_ATS_Information ats;
1811 session->receive_delay_task = GNUNET_SCHEDULER_NO_TASK;
1813 session->plugin->env->receive (session->plugin->env->cls,
1814 &session->target, NULL, &ats, 0, session,
1816 if (delay.rel_value == 0)
1817 GNUNET_SERVER_receive_done (session->client, GNUNET_OK);
1819 session->receive_delay_task =
1820 GNUNET_SCHEDULER_add_delayed (delay, &delayed_done, session);
1825 * We've received data for this peer via TCP. Unbox,
1826 * compute latency and forward.
1828 * @param cls closure
1829 * @param client identification of the client
1830 * @param message the actual message
1833 handle_tcp_data (void *cls, struct GNUNET_SERVER_Client *client,
1834 const struct GNUNET_MessageHeader *message)
1836 struct Plugin *plugin = cls;
1837 struct Session *session;
1838 struct GNUNET_TIME_Relative delay;
1841 type = ntohs (message->type);
1842 if ((GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME == type) ||
1843 (GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE == type))
1845 /* We don't want to propagate WELCOME and NAT Probe messages up! */
1846 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1849 session = lookup_session_by_client (plugin, client);
1850 if (NULL == session)
1852 /* No inbound session found */
1853 GNUNET_break_op (0);
1854 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1857 else if (GNUNET_YES == session->expecting_welcome)
1859 /* Session is expecting WELCOME message */
1862 GNUNET_SERVER_client_get_address (client, &vaddr, &alen);
1863 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, "tcp",
1864 "Received unexpected %u bytes of type %u from `%s'\n",
1865 (unsigned int) ntohs (message->size),
1866 (unsigned int) ntohs (message->type),
1867 GNUNET_a2s(vaddr, alen));
1868 GNUNET_break_op (0);
1869 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1873 session->last_activity = GNUNET_TIME_absolute_get ();
1875 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1876 "Passing %u bytes of type %u from `%4s' to transport service.\n",
1877 (unsigned int) ntohs (message->size),
1878 (unsigned int) ntohs (message->type),
1879 GNUNET_i2s (&session->target));
1881 GNUNET_STATISTICS_update (plugin->env->stats,
1882 gettext_noop ("# bytes received via TCP"),
1883 ntohs (message->size), GNUNET_NO);
1884 struct GNUNET_ATS_Information distance[2];
1886 distance[0].type = htonl (GNUNET_ATS_QUALITY_NET_DISTANCE);
1887 distance[0].value = htonl (1);
1888 distance[1].type = htonl (GNUNET_ATS_NETWORK_TYPE);
1889 distance[1].value = session->ats_address_network_type;
1890 GNUNET_break (ntohl(session->ats_address_network_type) != GNUNET_ATS_NET_UNSPECIFIED);
1892 delay = plugin->env->receive (plugin->env->cls,
1895 (const struct GNUNET_ATS_Information *) &distance,
1897 (GNUNET_YES == session->inbound) ? NULL : session->addr,
1898 (GNUNET_YES == session->inbound) ? 0 : session->addrlen);
1899 if (delay.rel_value == 0)
1901 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1906 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1907 "Throttling receiving from `%s' for %llu ms\n",
1908 GNUNET_i2s (&session->target),
1909 (unsigned long long) delay.rel_value);
1911 GNUNET_SERVER_disable_receive_done_warning (client);
1912 session->receive_delay_task =
1913 GNUNET_SCHEDULER_add_delayed (delay, &delayed_done, session);
1919 * Functions with this signature are called whenever a peer
1920 * is disconnected on the network level.
1922 * @param cls closure
1923 * @param client identification of the client
1926 disconnect_notify (void *cls, struct GNUNET_SERVER_Client *client)
1928 struct Plugin *plugin = cls;
1929 struct Session *session;
1933 plugin->max_connections++;
1934 session = lookup_session_by_client (plugin, client);
1935 if (session == NULL)
1936 return; /* unknown, nothing to do */
1938 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1939 "Destroying session of `%4s' with %s due to network-level disconnect.\n",
1940 GNUNET_i2s (&session->target),
1942 NULL) ? tcp_address_to_string (session->plugin,
1947 GNUNET_STATISTICS_update (session->plugin->env->stats,
1949 ("# network-level TCP disconnect events"), 1,
1951 disconnect_session (session);
1956 * We can now send a probe message, copy into buffer to really send.
1958 * @param cls closure, a struct TCPProbeContext
1959 * @param size max size to copy
1960 * @param buf buffer to copy message to
1961 * @return number of bytes copied into buf
1964 notify_send_probe (void *cls, size_t size, void *buf)
1966 struct TCPProbeContext *tcp_probe_ctx = cls;
1967 struct Plugin *plugin = tcp_probe_ctx->plugin;
1970 tcp_probe_ctx->transmit_handle = NULL;
1971 GNUNET_CONTAINER_DLL_remove (plugin->probe_head, plugin->probe_tail,
1975 GNUNET_CONNECTION_destroy (tcp_probe_ctx->sock, GNUNET_NO);
1976 GNUNET_free (tcp_probe_ctx);
1979 GNUNET_assert (size >= sizeof (tcp_probe_ctx->message));
1980 memcpy (buf, &tcp_probe_ctx->message, sizeof (tcp_probe_ctx->message));
1981 GNUNET_SERVER_connect_socket (tcp_probe_ctx->plugin->server,
1982 tcp_probe_ctx->sock);
1983 ret = sizeof (tcp_probe_ctx->message);
1984 GNUNET_free (tcp_probe_ctx);
1990 * Function called by the NAT subsystem suggesting another peer wants
1991 * to connect to us via connection reversal. Try to connect back to the
1994 * @param cls closure
1995 * @param addr address to try
1996 * @param addrlen number of bytes in addr
1999 try_connection_reversal (void *cls, const struct sockaddr *addr,
2002 struct Plugin *plugin = cls;
2003 struct GNUNET_CONNECTION_Handle *sock;
2004 struct TCPProbeContext *tcp_probe_ctx;
2007 * We have received an ICMP response, ostensibly from a peer
2008 * that wants to connect to us! Send a message to establish a connection.
2010 sock = GNUNET_CONNECTION_create_from_sockaddr (AF_INET, addr, addrlen);
2013 /* failed for some odd reason (out of sockets?); ignore attempt */
2017 /* FIXME: do we need to track these probe context objects so that
2018 * we can clean them up on plugin unload? */
2019 tcp_probe_ctx = GNUNET_malloc (sizeof (struct TCPProbeContext));
2020 tcp_probe_ctx->message.header.size =
2021 htons (sizeof (struct TCP_NAT_ProbeMessage));
2022 tcp_probe_ctx->message.header.type =
2023 htons (GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE);
2024 memcpy (&tcp_probe_ctx->message.clientIdentity, plugin->env->my_identity,
2025 sizeof (struct GNUNET_PeerIdentity));
2026 tcp_probe_ctx->plugin = plugin;
2027 tcp_probe_ctx->sock = sock;
2028 GNUNET_CONTAINER_DLL_insert (plugin->probe_head, plugin->probe_tail,
2030 tcp_probe_ctx->transmit_handle =
2031 GNUNET_CONNECTION_notify_transmit_ready (sock,
2032 ntohs (tcp_probe_ctx->
2033 message.header.size),
2034 GNUNET_TIME_UNIT_FOREVER_REL,
2042 * Entry point for the plugin.
2044 * @param cls closure, the 'struct GNUNET_TRANSPORT_PluginEnvironment*'
2045 * @return the 'struct GNUNET_TRANSPORT_PluginFunctions*' or NULL on error
2048 libgnunet_plugin_transport_tcp_init (void *cls)
2050 static const struct GNUNET_SERVER_MessageHandler my_handlers[] = {
2051 {&handle_tcp_welcome, NULL, GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME,
2052 sizeof (struct WelcomeMessage)},
2053 {&handle_tcp_nat_probe, NULL, GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE,
2054 sizeof (struct TCP_NAT_ProbeMessage)},
2055 {&handle_tcp_data, NULL, GNUNET_MESSAGE_TYPE_ALL, 0},
2058 struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
2059 struct GNUNET_TRANSPORT_PluginFunctions *api;
2060 struct Plugin *plugin;
2061 struct GNUNET_SERVICE_Context *service;
2062 unsigned long long aport;
2063 unsigned long long bport;
2064 unsigned long long max_connections;
2066 struct GNUNET_TIME_Relative idle_timeout;
2068 struct sockaddr **addrs;
2069 socklen_t *addrlens;
2071 if (NULL == env->receive)
2073 /* run in 'stub' mode (i.e. as part of gnunet-peerinfo), don't fully
2074 initialze the plugin or the API */
2075 api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
2077 api->address_pretty_printer = &tcp_plugin_address_pretty_printer;
2078 api->address_to_string = &tcp_address_to_string;
2079 api->string_to_address = &tcp_string_to_address;
2084 GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-tcp",
2087 max_connections = 128;
2091 GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-tcp", "PORT",
2092 &bport)) || (bport > 65535) ||
2094 GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-tcp",
2095 "ADVERTISED-PORT", &aport)) &&
2098 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, "tcp",
2100 ("Require valid port number for service `%s' in configuration!\n"),
2110 service = GNUNET_SERVICE_start ("transport-tcp", env->cfg);
2111 if (service == NULL)
2113 GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, "tcp",
2114 _("Failed to start service.\n"));
2121 plugin = GNUNET_malloc (sizeof (struct Plugin));
2122 plugin->sessionmap = GNUNET_CONTAINER_multihashmap_create(max_connections);
2123 plugin->max_connections = max_connections;
2124 plugin->open_port = bport;
2125 plugin->adv_port = aport;
2127 plugin->lsock = NULL;
2128 if ((service != NULL) &&
2131 GNUNET_SERVICE_get_server_addresses ("transport-tcp", env->cfg, &addrs,
2135 GNUNET_NAT_register (env->cfg, GNUNET_YES, aport, (unsigned int) ret,
2136 (const struct sockaddr **) addrs, addrlens,
2137 &tcp_nat_port_map_callback,
2138 &try_connection_reversal, plugin);
2142 GNUNET_assert (addrs[ret] != NULL);
2143 GNUNET_free (addrs[ret]);
2145 GNUNET_free_non_null (addrs);
2146 GNUNET_free_non_null (addrlens);
2151 GNUNET_NAT_register (env->cfg, GNUNET_YES, 0, 0, NULL, NULL, NULL,
2152 &try_connection_reversal, plugin);
2154 api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
2156 api->send = &tcp_plugin_send;
2157 api->get_session = &tcp_plugin_get_session;
2159 api->disconnect = &tcp_plugin_disconnect;
2160 api->address_pretty_printer = &tcp_plugin_address_pretty_printer;
2161 api->check_address = &tcp_plugin_check_address;
2162 api->address_to_string = &tcp_address_to_string;
2163 api->string_to_address = &tcp_string_to_address;
2164 plugin->service = service;
2165 if (service != NULL)
2167 plugin->server = GNUNET_SERVICE_get_server (service);
2172 GNUNET_CONFIGURATION_get_value_time (env->cfg, "transport-tcp",
2173 "TIMEOUT", &idle_timeout))
2175 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, "tcp",
2176 _("Failed to find option %s in section %s!\n"),
2177 "TIMEOUT", "transport-tcp");
2178 if (plugin->nat != NULL)
2179 GNUNET_NAT_unregister (plugin->nat);
2180 GNUNET_free (plugin);
2185 GNUNET_SERVER_create_with_sockets (&plugin_tcp_access_check, plugin,
2186 NULL, idle_timeout, GNUNET_YES);
2188 plugin->handlers = GNUNET_malloc (sizeof (my_handlers));
2189 memcpy (plugin->handlers, my_handlers, sizeof (my_handlers));
2191 i < sizeof (my_handlers) / sizeof (struct GNUNET_SERVER_MessageHandler);
2193 plugin->handlers[i].callback_cls = plugin;
2194 GNUNET_SERVER_add_handlers (plugin->server, plugin->handlers);
2195 GNUNET_SERVER_disconnect_notify (plugin->server, &disconnect_notify, plugin);
2196 plugin->nat_wait_conns = GNUNET_CONTAINER_multihashmap_create (16);
2198 GNUNET_log_from (GNUNET_ERROR_TYPE_INFO, "tcp",
2199 _("TCP transport listening on port %llu\n"), bport);
2201 GNUNET_log_from (GNUNET_ERROR_TYPE_INFO, "tcp",
2203 ("TCP transport not listening on any port (client only)\n"));
2205 GNUNET_log_from (GNUNET_ERROR_TYPE_INFO, "tcp",
2207 ("TCP transport advertises itself as being on port %llu\n"),
2209 /* Initially set connections to 0 */
2210 GNUNET_STATISTICS_set(plugin->env->stats,
2211 gettext_noop ("# TCP sessions active"), 0,
2218 * Exit point from the plugin.
2221 libgnunet_plugin_transport_tcp_done (void *cls)
2223 struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
2224 struct Plugin *plugin = api->cls;
2225 struct TCPProbeContext *tcp_probe;
2232 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp", "Shutting down TCP plugin\n");
2234 /* Removing leftover sessions */
2235 GNUNET_CONTAINER_multihashmap_iterate(plugin->sessionmap, &session_disconnect_it, NULL);
2236 /* Removing leftover NAT sessions */
2237 GNUNET_CONTAINER_multihashmap_iterate(plugin->nat_wait_conns, &session_disconnect_it, NULL);
2239 if (plugin->service != NULL)
2240 GNUNET_SERVICE_stop (plugin->service);
2242 GNUNET_SERVER_destroy (plugin->server);
2243 GNUNET_free (plugin->handlers);
2244 if (plugin->nat != NULL)
2245 GNUNET_NAT_unregister (plugin->nat);
2246 while (NULL != (tcp_probe = plugin->probe_head))
2248 GNUNET_CONTAINER_DLL_remove (plugin->probe_head, plugin->probe_tail,
2250 GNUNET_CONNECTION_destroy (tcp_probe->sock, GNUNET_NO);
2251 GNUNET_free (tcp_probe);
2253 GNUNET_CONTAINER_multihashmap_destroy (plugin->nat_wait_conns);
2254 GNUNET_CONTAINER_multihashmap_destroy (plugin->sessionmap);
2255 GNUNET_free (plugin);
2260 /* end of plugin_transport_tcp.c */