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).
277 * Last activity on this connection. Used to select preferred
280 struct GNUNET_TIME_Absolute last_activity;
283 * Length of connect_addr.
288 * Are we still expecting the welcome message? (GNUNET_YES/GNUNET_NO)
290 int expecting_welcome;
293 * Was this a connection that was inbound (we accepted)? (GNUNET_YES/GNUNET_NO)
298 * Was this session created using NAT traversal?
303 * ATS network type in NBO
305 uint32_t ats_address_network_type;
310 * Encapsulation of all of the state of the plugin.
317 struct GNUNET_TRANSPORT_PluginEnvironment *env;
322 struct GNUNET_CONNECTION_Handle *lsock;
325 * Our handle to the NAT module.
327 struct GNUNET_NAT_Handle *nat;
330 * List of open TCP sessions.
332 struct Session *sessions;
334 struct GNUNET_CONTAINER_MultiHashMap * sessionmap;
337 * Handle to the network service.
339 struct GNUNET_SERVICE_Context *service;
342 * Handle to the server for this service.
344 struct GNUNET_SERVER_Handle *server;
347 * Copy of the handler array where the closures are
348 * set to this struct's instance.
350 struct GNUNET_SERVER_MessageHandler *handlers;
353 * Map of peers we have tried to contact behind a NAT
355 struct GNUNET_CONTAINER_MultiHashMap *nat_wait_conns;
358 * List of active TCP probes.
360 struct TCPProbeContext *probe_head;
363 * List of active TCP probes.
365 struct TCPProbeContext *probe_tail;
368 * Handle for (DYN)DNS lookup of our external IP.
370 struct GNUNET_RESOLVER_RequestHandle *ext_dns;
373 * How many more TCP sessions are we allowed to open right now?
375 unsigned long long max_connections;
378 * ID of task used to update our addresses when one expires.
380 GNUNET_SCHEDULER_TaskIdentifier address_update_task;
383 * Port that we are actually listening on.
388 * Port that the user said we would have visible to the
397 * Function to check if an inbound connection is acceptable.
398 * Mostly used to limit the total number of open connections
401 * @param cls the 'struct Plugin'
402 * @param ucred credentials, if available, otherwise NULL
403 * @param addr address
404 * @param addrlen length of address
405 * @return GNUNET_YES to allow, GNUNET_NO to deny, GNUNET_SYSERR
406 * for unknown address family (will be denied).
409 plugin_tcp_access_check (void *cls,
410 const struct GNUNET_CONNECTION_Credentials *ucred,
411 const struct sockaddr *addr, socklen_t addrlen)
413 struct Plugin *plugin = cls;
415 if (0 == plugin->max_connections)
417 plugin->max_connections--;
423 * Our external IP address/port mapping has changed.
425 * @param cls closure, the 'struct LocalAddrList'
426 * @param add_remove GNUNET_YES to mean the new public IP address, GNUNET_NO to mean
427 * the previous (now invalid) one
428 * @param addr either the previous or the new public IP address
429 * @param addrlen actual lenght of the address
432 tcp_nat_port_map_callback (void *cls, int add_remove,
433 const struct sockaddr *addr, socklen_t addrlen)
435 struct Plugin *plugin = cls;
436 struct IPv4TcpAddress t4;
437 struct IPv6TcpAddress t6;
441 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
442 "NPMC called with %d for address `%s'\n", add_remove,
443 GNUNET_a2s (addr, addrlen));
444 /* convert 'addr' to our internal format */
445 switch (addr->sa_family)
448 GNUNET_assert (addrlen == sizeof (struct sockaddr_in));
449 t4.ipv4_addr = ((struct sockaddr_in *) addr)->sin_addr.s_addr;
450 t4.t4_port = ((struct sockaddr_in *) addr)->sin_port;
455 GNUNET_assert (addrlen == sizeof (struct sockaddr_in6));
456 memcpy (&t6.ipv6_addr, &((struct sockaddr_in6 *) addr)->sin6_addr,
457 sizeof (struct in6_addr));
458 t6.t6_port = ((struct sockaddr_in6 *) addr)->sin6_port;
466 /* modify our published address list */
467 plugin->env->notify_address (plugin->env->cls, add_remove, arg, args);
472 * Function called for a quick conversion of the binary address to
473 * a numeric address. Note that the caller must not free the
474 * address and that the next call to this function is allowed
475 * to override the address again.
477 * @param cls closure ('struct Plugin*')
478 * @param addr binary address
479 * @param addrlen length of the address
480 * @return string representing the same address
483 tcp_address_to_string (void *cls, const void *addr, size_t addrlen)
485 static char rbuf[INET6_ADDRSTRLEN + 12];
486 char buf[INET6_ADDRSTRLEN];
490 const struct IPv4TcpAddress *t4;
491 const struct IPv6TcpAddress *t6;
495 if (addrlen == sizeof (struct IPv6TcpAddress))
499 port = ntohs (t6->t6_port);
500 memcpy (&a6, &t6->ipv6_addr, sizeof (a6));
503 else if (addrlen == sizeof (struct IPv4TcpAddress))
507 port = ntohs (t4->t4_port);
508 memcpy (&a4, &t4->ipv4_addr, sizeof (a4));
513 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, "tcp",
514 _("Unexpected address length: %u bytes\n"),
515 (unsigned int) addrlen);
519 if (NULL == inet_ntop (af, sb, buf, INET6_ADDRSTRLEN))
521 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "inet_ntop");
524 GNUNET_snprintf (rbuf, sizeof (rbuf), (af == AF_INET6) ? "[%s]:%u" : "%s:%u",
531 * Find the session handle for the given client.
533 * @param plugin the plugin
534 * @param client which client to find the session handle for
535 * @return NULL if no matching session exists
537 static struct Session *
538 find_session_by_client (struct Plugin *plugin,
539 const struct GNUNET_SERVER_Client *client)
543 ret = plugin->sessions;
544 while ((ret != NULL) && (client != ret->client))
551 * Create a new session. Also queues a welcome message.
553 * @param plugin the plugin
554 * @param target peer to connect to
555 * @param client client to use
556 * @param is_nat this a NAT session, we should wait for a client to
557 * connect to us from an address, then assign that to
559 * @return new session object
561 static struct Session *
562 create_session (struct Plugin *plugin, const struct GNUNET_PeerIdentity *target,
563 struct GNUNET_SERVER_Client *client, int is_nat)
566 struct PendingMessage *pm;
567 struct WelcomeMessage welcome;
569 if (is_nat != GNUNET_YES)
570 GNUNET_assert (client != NULL);
572 GNUNET_assert (client == NULL);
574 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
575 "Creating new session for peer `%4s'\n",
576 GNUNET_i2s (target));
578 ret = GNUNET_malloc (sizeof (struct Session));
579 ret->last_activity = GNUNET_TIME_absolute_get ();
580 ret->plugin = plugin;
581 ret->is_nat = is_nat;
582 if (is_nat != GNUNET_YES) /* If not a NAT WAIT conn, add it to global list */
584 ret->next = plugin->sessions;
585 plugin->sessions = ret;
587 ret->client = client;
588 ret->target = *target;
589 ret->expecting_welcome = GNUNET_YES;
590 ret->ats_address_network_type = htonl (GNUNET_ATS_NET_UNSPECIFIED);
591 pm = GNUNET_malloc (sizeof (struct PendingMessage) +
592 sizeof (struct WelcomeMessage));
593 pm->msg = (const char *) &pm[1];
594 pm->message_size = sizeof (struct WelcomeMessage);
595 welcome.header.size = htons (sizeof (struct WelcomeMessage));
596 welcome.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME);
597 welcome.clientIdentity = *plugin->env->my_identity;
598 memcpy (&pm[1], &welcome, sizeof (welcome));
599 pm->timeout = GNUNET_TIME_UNIT_FOREVER_ABS;
600 GNUNET_STATISTICS_update (plugin->env->stats,
601 gettext_noop ("# bytes currently in TCP buffers"),
602 pm->message_size, GNUNET_NO);
603 GNUNET_CONTAINER_DLL_insert (ret->pending_messages_head,
604 ret->pending_messages_tail, pm);
605 if (is_nat != GNUNET_YES)
606 GNUNET_STATISTICS_update (plugin->env->stats,
607 gettext_noop ("# TCP sessions active"), 1,
614 * If we have pending messages, ask the server to
615 * transmit them (schedule the respective tasks, etc.)
617 * @param session for which session should we do this
620 process_pending_messages (struct Session *session);
624 * Function called to notify a client about the socket
625 * being ready to queue more data. "buf" will be
626 * NULL and "size" zero if the socket was closed for
627 * writing in the meantime.
630 * @param size number of bytes available in buf
631 * @param buf where the callee should write the message
632 * @return number of bytes written to buf
635 do_transmit (void *cls, size_t size, void *buf)
637 struct Session *session = cls;
638 struct GNUNET_PeerIdentity pid;
639 struct Plugin *plugin;
640 struct PendingMessage *pos;
641 struct PendingMessage *hd;
642 struct PendingMessage *tl;
643 struct GNUNET_TIME_Absolute now;
647 GNUNET_assert (session != NULL);
648 session->transmit_handle = NULL;
649 plugin = session->plugin;
653 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
654 "Timeout trying to transmit to peer `%4s', discarding message queue.\n",
655 GNUNET_i2s (&session->target));
657 /* timeout; cancel all messages that have already expired */
661 now = GNUNET_TIME_absolute_get ();
662 while ((NULL != (pos = session->pending_messages_head)) &&
663 (pos->timeout.abs_value <= now.abs_value))
665 GNUNET_CONTAINER_DLL_remove (session->pending_messages_head,
666 session->pending_messages_tail, pos);
668 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
669 "Failed to transmit %u byte message to `%4s'.\n",
670 pos->message_size, GNUNET_i2s (&session->target));
672 ret += pos->message_size;
673 GNUNET_CONTAINER_DLL_insert_after (hd, tl, tl, pos);
675 /* do this call before callbacks (so that if callbacks destroy
676 * session, they have a chance to cancel actions done by this
678 process_pending_messages (session);
679 pid = session->target;
680 /* no do callbacks and do not use session again since
681 * the callbacks may abort the session */
682 while (NULL != (pos = hd))
684 GNUNET_CONTAINER_DLL_remove (hd, tl, pos);
685 if (pos->transmit_cont != NULL)
686 pos->transmit_cont (pos->transmit_cont_cls, &pid, GNUNET_SYSERR);
689 GNUNET_STATISTICS_update (plugin->env->stats,
690 gettext_noop ("# bytes currently in TCP buffers"),
691 -(int64_t) ret, GNUNET_NO);
692 GNUNET_STATISTICS_update (plugin->env->stats,
694 ("# bytes discarded by TCP (timeout)"), ret,
698 /* copy all pending messages that would fit */
703 while (NULL != (pos = session->pending_messages_head))
705 if (ret + pos->message_size > size)
707 GNUNET_CONTAINER_DLL_remove (session->pending_messages_head,
708 session->pending_messages_tail, pos);
709 GNUNET_assert (size >= pos->message_size);
710 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
711 "Transmitting message of type %u\n",
712 ntohs (((struct GNUNET_MessageHeader *) pos->msg)->type));
713 /* FIXME: this memcpy can be up to 7% of our total runtime */
714 memcpy (cbuf, pos->msg, pos->message_size);
715 cbuf += pos->message_size;
716 ret += pos->message_size;
717 size -= pos->message_size;
718 GNUNET_CONTAINER_DLL_insert_tail (hd, tl, pos);
720 /* schedule 'continuation' before callbacks so that callbacks that
721 * cancel everything don't cause us to use a session that no longer
723 process_pending_messages (session);
724 session->last_activity = GNUNET_TIME_absolute_get ();
725 pid = session->target;
726 /* we'll now call callbacks that may cancel the session; hence
727 * we should not use 'session' after this point */
728 while (NULL != (pos = hd))
730 GNUNET_CONTAINER_DLL_remove (hd, tl, pos);
731 if (pos->transmit_cont != NULL)
732 pos->transmit_cont (pos->transmit_cont_cls, &pid, GNUNET_OK);
735 GNUNET_assert (hd == NULL);
736 GNUNET_assert (tl == NULL);
738 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp", "Transmitting %u bytes\n",
741 GNUNET_STATISTICS_update (plugin->env->stats,
742 gettext_noop ("# bytes currently in TCP buffers"),
743 -(int64_t) ret, GNUNET_NO);
744 GNUNET_STATISTICS_update (plugin->env->stats,
745 gettext_noop ("# bytes transmitted via TCP"), ret,
752 * If we have pending messages, ask the server to
753 * transmit them (schedule the respective tasks, etc.)
755 * @param session for which session should we do this
758 process_pending_messages (struct Session *session)
760 struct PendingMessage *pm;
762 GNUNET_assert (session->client != NULL);
763 if (session->transmit_handle != NULL)
765 if (NULL == (pm = session->pending_messages_head))
768 session->transmit_handle =
769 GNUNET_SERVER_notify_transmit_ready (session->client, pm->message_size,
770 GNUNET_TIME_absolute_get_remaining
771 (pm->timeout), &do_transmit,
777 * Functions with this signature are called whenever we need
778 * to close a session due to a disconnect or failure to
779 * establish a connection.
781 * @param session session to close down
784 disconnect_session (struct Session *session)
786 struct Session *prev;
788 struct PendingMessage *pm;
791 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
792 "Disconnecting from `%4s' at %s.\n",
793 GNUNET_i2s (&session->target),
794 (session->connect_addr !=
795 NULL) ? tcp_address_to_string (session->plugin,
796 session->connect_addr,
797 session->connect_alen) :
800 /* remove from session list */
802 pos = session->plugin->sessions;
803 while (pos != session)
809 session->plugin->sessions = session->next;
811 prev->next = session->next;
814 if (session->transmit_handle != NULL)
816 GNUNET_CONNECTION_notify_transmit_ready_cancel (session->transmit_handle);
817 session->transmit_handle = NULL;
819 session->plugin->env->session_end (session->plugin->env->cls,
820 &session->target, session);
821 while (NULL != (pm = session->pending_messages_head))
824 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
826 NULL ? "Could not deliver message to `%4s'.\n" :
827 "Could not deliver message to `%4s', notifying.\n",
828 GNUNET_i2s (&session->target));
830 GNUNET_STATISTICS_update (session->plugin->env->stats,
831 gettext_noop ("# bytes currently in TCP buffers"),
832 -(int64_t) pm->message_size, GNUNET_NO);
833 GNUNET_STATISTICS_update (session->plugin->env->stats,
835 ("# bytes discarded by TCP (disconnect)"),
836 pm->message_size, GNUNET_NO);
837 GNUNET_CONTAINER_DLL_remove (session->pending_messages_head,
838 session->pending_messages_tail, pm);
839 if (NULL != pm->transmit_cont)
840 pm->transmit_cont (pm->transmit_cont_cls, &session->target,
844 GNUNET_break (session->client != NULL);
845 if (session->receive_delay_task != GNUNET_SCHEDULER_NO_TASK)
847 GNUNET_SCHEDULER_cancel (session->receive_delay_task);
848 if (session->client != NULL)
849 GNUNET_SERVER_receive_done (session->client, GNUNET_SYSERR);
851 if (session->client != NULL)
853 GNUNET_SERVER_client_drop (session->client);
854 session->client = NULL;
856 GNUNET_STATISTICS_update (session->plugin->env->stats,
857 gettext_noop ("# TCP sessions active"), -1,
859 GNUNET_free_non_null (session->connect_addr);
860 GNUNET_assert (NULL == session->transmit_handle);
861 GNUNET_free (session);
866 * Given two otherwise equivalent sessions, pick the better one.
868 * @param s1 one session (also default)
869 * @param s2 other session
870 * @return "better" session (more active)
872 static struct Session *
873 select_better_session (struct Session *s1, struct Session *s2)
879 if ((s1->expecting_welcome == GNUNET_NO) &&
880 (s2->expecting_welcome == GNUNET_YES))
882 if ((s1->expecting_welcome == GNUNET_YES) &&
883 (s2->expecting_welcome == GNUNET_NO))
885 if (s1->last_activity.abs_value < s2->last_activity.abs_value)
887 if (s1->last_activity.abs_value > s2->last_activity.abs_value)
889 if ((GNUNET_YES == s1->inbound) && (GNUNET_NO == s2->inbound))
891 if ((GNUNET_NO == s1->inbound) && (GNUNET_YES == s2->inbound))
899 * Function that can be used by the transport service to transmit
900 * a message using the plugin. Note that in the case of a
901 * peer disconnecting, the continuation MUST be called
902 * prior to the disconnect notification itself. This function
903 * will be called with this peer's HELLO message to initiate
904 * a fresh connection to another peer.
907 * @param target who should receive this message
908 * @param msg the message to transmit
909 * @param msgbuf_size number of bytes in 'msg'
910 * @param priority how important is the message (most plugins will
911 * ignore message priority and just FIFO)
912 * @param timeout how long to wait at most for the transmission (does not
913 * require plugins to discard the message after the timeout,
914 * just advisory for the desired delay; most plugins will ignore
916 * @param session which session must be used (or NULL for "any")
917 * @param addr the address to use (can be NULL if the plugin
918 * is "on its own" (i.e. re-use existing TCP connection))
919 * @param addrlen length of the address in bytes
920 * @param force_address GNUNET_YES if the plugin MUST use the given address,
921 * GNUNET_NO means the plugin may use any other address and
922 * GNUNET_SYSERR means that only reliable existing
923 * bi-directional connections should be used (regardless
925 * @param cont continuation to call once the message has
926 * been transmitted (or if the transport is ready
927 * for the next transmission call; or if the
928 * peer disconnected...); can be NULL
929 * @param cont_cls closure for cont
930 * @return number of bytes used (on the physical network, with overheads);
931 * -1 on hard errors (i.e. address invalid); 0 is a legal value
932 * and does NOT mean that the message was not transmitted (DV and NAT)
935 tcp_plugin_send (void *cls, const struct GNUNET_PeerIdentity *target,
936 const char *msg, size_t msgbuf_size, uint32_t priority,
937 struct GNUNET_TIME_Relative timeout, struct Session *session,
938 const void *addr, size_t addrlen, int force_address,
939 GNUNET_TRANSPORT_TransmitContinuation cont, void *cont_cls)
941 struct Plugin *plugin = cls;
942 struct Session *cand_session;
943 struct Session *next;
944 struct PendingMessage *pm;
945 struct GNUNET_CONNECTION_Handle *sa;
949 struct sockaddr_in a4;
950 struct sockaddr_in6 a6;
951 const struct IPv4TcpAddress *t4;
952 const struct IPv6TcpAddress *t6;
953 unsigned int is_natd;
955 GNUNET_STATISTICS_update (plugin->env->stats,
956 gettext_noop ("# bytes TCP was asked to transmit"),
957 msgbuf_size, GNUNET_NO);
958 /* FIXME: we could do this cheaper with a hash table
959 * where we could restrict the iteration to entries that match
960 * the target peer... */
965 next = plugin->sessions;
966 while (NULL != (session = next))
968 next = session->next;
969 GNUNET_assert (session->client != NULL);
971 memcmp (target, &session->target,
972 sizeof (struct GNUNET_PeerIdentity)))
974 if (((GNUNET_SYSERR == force_address) &&
975 (session->expecting_welcome == GNUNET_NO)) ||
976 (GNUNET_NO == force_address))
978 cand_session = select_better_session (cand_session, session);
981 if (GNUNET_SYSERR == force_address)
983 GNUNET_break (GNUNET_YES == force_address);
989 if ((addrlen != session->connect_alen) && (session->is_nat == GNUNET_NO))
991 if ((0 != memcmp (session->connect_addr, addr, addrlen)) &&
992 (session->is_nat == GNUNET_NO))
994 cand_session = select_better_session (cand_session, session);
996 session = cand_session;
998 if ((session == NULL) && (addrlen == 0))
1001 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1002 "Asked to transmit to `%4s' without address and I have no existing connection (failing).\n",
1003 GNUNET_i2s (target));
1005 GNUNET_STATISTICS_update (plugin->env->stats,
1007 ("# bytes discarded by TCP (no address and no connection)"),
1008 msgbuf_size, GNUNET_NO);
1011 if (session == NULL)
1013 if (addrlen == sizeof (struct IPv6TcpAddress))
1015 GNUNET_assert (NULL != addr); /* make static analysis happy */
1018 memset (&a6, 0, sizeof (a6));
1019 #if HAVE_SOCKADDR_IN_SIN_LEN
1020 a6.sin6_len = sizeof (a6);
1022 a6.sin6_family = AF_INET6;
1023 a6.sin6_port = t6->t6_port;
1024 if (t6->t6_port == 0)
1025 is_natd = GNUNET_YES;
1026 memcpy (&a6.sin6_addr, &t6->ipv6_addr, sizeof (struct in6_addr));
1030 else if (addrlen == sizeof (struct IPv4TcpAddress))
1032 GNUNET_assert (NULL != addr); /* make static analysis happy */
1035 memset (&a4, 0, sizeof (a4));
1036 #if HAVE_SOCKADDR_IN_SIN_LEN
1037 a4.sin_len = sizeof (a4);
1039 a4.sin_family = AF_INET;
1040 a4.sin_port = t4->t4_port;
1041 if (t4->t4_port == 0)
1042 is_natd = GNUNET_YES;
1043 a4.sin_addr.s_addr = t4->ipv4_addr;
1049 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, "tcp",
1050 _("Address of unexpected length: %u\n"), addrlen);
1055 if ((is_natd == GNUNET_YES) && (addrlen == sizeof (struct IPv6TcpAddress)))
1056 return -1; /* NAT client only works with IPv4 addresses */
1057 if (0 == plugin->max_connections)
1058 return -1; /* saturated */
1060 if ((is_natd == GNUNET_YES) && (NULL != plugin->nat) &&
1062 GNUNET_CONTAINER_multihashmap_contains (plugin->nat_wait_conns,
1063 &target->hashPubKey)))
1066 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1067 _("Found valid IPv4 NAT address (creating session)!\n"));
1069 session = create_session (plugin, target, NULL, GNUNET_YES);
1070 GNUNET_assert (session != NULL);
1072 /* create new message entry */
1073 pm = GNUNET_malloc (sizeof (struct PendingMessage) + msgbuf_size);
1074 /* FIXME: the memset of this malloc can be up to 2% of our total runtime */
1075 pm->msg = (const char *) &pm[1];
1076 memcpy (&pm[1], msg, msgbuf_size);
1077 /* FIXME: this memcpy can be up to 7% of our total run-time
1078 * (for transport service) */
1079 pm->message_size = msgbuf_size;
1080 pm->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1081 pm->transmit_cont = cont;
1082 pm->transmit_cont_cls = cont_cls;
1084 /* append pm to pending_messages list */
1085 GNUNET_CONTAINER_DLL_insert_tail (session->pending_messages_head,
1086 session->pending_messages_tail, pm);
1088 GNUNET_assert (GNUNET_CONTAINER_multihashmap_put
1089 (plugin->nat_wait_conns, &target->hashPubKey, session,
1090 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY) ==
1093 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1094 "Created NAT WAIT connection to `%4s' at `%s'\n",
1095 GNUNET_i2s (target), GNUNET_a2s (sb, sbs));
1097 GNUNET_NAT_run_client (plugin->nat, &a4);
1100 if ((is_natd == GNUNET_YES) &&
1102 GNUNET_CONTAINER_multihashmap_contains (plugin->nat_wait_conns,
1103 &target->hashPubKey)))
1105 /* Only do one NAT punch attempt per peer identity */
1108 sa = GNUNET_CONNECTION_create_from_sockaddr (af, sb, sbs);
1112 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1113 "Failed to create connection to `%4s' at `%s'\n",
1114 GNUNET_i2s (target), GNUNET_a2s (sb, sbs));
1116 GNUNET_STATISTICS_update (plugin->env->stats,
1118 ("# bytes discarded by TCP (failed to connect)"),
1119 msgbuf_size, GNUNET_NO);
1122 GNUNET_assert (0 != plugin->max_connections);
1123 plugin->max_connections--;
1125 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1126 "Asked to transmit to `%4s', creating fresh session using address `%s'.\n",
1127 GNUNET_i2s (target), GNUNET_a2s (sb, sbs));
1130 create_session (plugin, target,
1131 GNUNET_SERVER_connect_socket (plugin->server, sa),
1133 session->connect_addr = GNUNET_malloc (addrlen);
1134 memcpy (session->connect_addr, addr, addrlen);
1135 session->connect_alen = addrlen;
1138 struct GNUNET_ATS_Information ats;
1139 ats = plugin->env->get_address_type (plugin->env->cls, sb ,sbs);
1140 session->ats_address_network_type = ats.value;
1145 else /* session != NULL */
1147 /* check if session is valid */
1148 struct Session *ses = plugin->sessions;
1151 memcmp (target, &session->target, sizeof (struct GNUNET_PeerIdentity)))
1154 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1155 "Got session %p for `%s', but should be for peer `%s'!\n",
1156 session, GNUNET_i2s (&session->target),
1157 GNUNET_h2s (&target->hashPubKey));
1161 while ((ses != NULL) && (ses != session))
1168 GNUNET_assert (session != NULL);
1169 GNUNET_assert (session->client != NULL);
1170 GNUNET_SERVER_client_set_timeout (session->client,
1171 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1172 GNUNET_STATISTICS_update (plugin->env->stats,
1173 gettext_noop ("# bytes currently in TCP buffers"),
1174 msgbuf_size, GNUNET_NO);
1175 /* create new message entry */
1176 pm = GNUNET_malloc (sizeof (struct PendingMessage) + msgbuf_size);
1177 pm->msg = (const char *) &pm[1];
1178 memcpy (&pm[1], msg, msgbuf_size);
1179 pm->message_size = msgbuf_size;
1180 pm->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1181 pm->transmit_cont = cont;
1182 pm->transmit_cont_cls = cont_cls;
1184 /* append pm to pending_messages list */
1185 GNUNET_CONTAINER_DLL_insert_tail (session->pending_messages_head,
1186 session->pending_messages_tail, pm);
1188 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1189 "Asked to transmit %u bytes to `%s', added message to list.\n",
1190 msgbuf_size, GNUNET_i2s (target));
1192 process_pending_messages (session);
1197 * Function that can be used by the transport service to transmit
1198 * a message using the plugin. Note that in the case of a
1199 * peer disconnecting, the continuation MUST be called
1200 * prior to the disconnect notification itself. This function
1201 * will be called with this peer's HELLO message to initiate
1202 * a fresh connection to another peer.
1204 * @param cls closure
1205 * @param target who should receive this message
1206 * @param msg the message to transmit
1207 * @param msgbuf_size number of bytes in 'msg'
1208 * @param priority how important is the message (most plugins will
1209 * ignore message priority and just FIFO)
1210 * @param timeout how long to wait at most for the transmission (does not
1211 * require plugins to discard the message after the timeout,
1212 * just advisory for the desired delay; most plugins will ignore
1214 * @param session which session must be used (or NULL for "any")
1215 * @param addr the address to use (can be NULL if the plugin
1216 * is "on its own" (i.e. re-use existing TCP connection))
1217 * @param addrlen length of the address in bytes
1218 * @param force_address GNUNET_YES if the plugin MUST use the given address,
1219 * GNUNET_NO means the plugin may use any other address and
1220 * GNUNET_SYSERR means that only reliable existing
1221 * bi-directional connections should be used (regardless
1223 * @param cont continuation to call once the message has
1224 * been transmitted (or if the transport is ready
1225 * for the next transmission call; or if the
1226 * peer disconnected...); can be NULL
1227 * @param cont_cls closure for cont
1228 * @return number of bytes used (on the physical network, with overheads);
1229 * -1 on hard errors (i.e. address invalid); 0 is a legal value
1230 * and does NOT mean that the message was not transmitted (DV and NAT)
1233 tcp_plugin_send_new (void *cls,
1234 struct Session *session,
1235 const char *msgbuf, size_t msgbuf_size,
1236 unsigned int priority,
1237 struct GNUNET_TIME_Relative to,
1238 GNUNET_TRANSPORT_TransmitContinuation cont, void *cont_cls)
1240 struct Plugin * plugin = cls;
1241 struct PendingMessage *pm;
1243 GNUNET_assert (session != NULL);
1244 GNUNET_assert (session->client != NULL);
1246 GNUNET_SERVER_client_set_timeout (session->client,
1247 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1248 GNUNET_STATISTICS_update (plugin->env->stats,
1249 gettext_noop ("# bytes currently in TCP buffers"),
1250 msgbuf_size, GNUNET_NO);
1251 /* create new message entry */
1252 pm = GNUNET_malloc (sizeof (struct PendingMessage) + msgbuf_size);
1253 pm->msg = (const char *) &pm[1];
1254 memcpy (&pm[1], msgbuf, msgbuf_size);
1255 pm->message_size = msgbuf_size;
1256 pm->timeout = GNUNET_TIME_relative_to_absolute (to);
1257 pm->transmit_cont = cont;
1258 pm->transmit_cont_cls = cont_cls;
1260 /* append pm to pending_messages list */
1261 GNUNET_CONTAINER_DLL_insert_tail (session->pending_messages_head,
1262 session->pending_messages_tail, pm);
1264 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1265 "Asked to transmit %u bytes to `%s', added message to list.\n",
1266 msgbuf_size, GNUNET_i2s (target));
1268 process_pending_messages (session);
1276 struct Session * result;
1279 int session_it (void *cls,
1280 const GNUNET_HashCode * key,
1283 struct SessionItCtx * si_ctx = cls;
1284 struct Session * session = value;
1286 if (session->connect_alen != si_ctx->addrlen)
1288 if (0 != memcmp (&session->connect_addr, si_ctx->addr, si_ctx->addrlen))
1291 /* Found existing session */
1292 si_ctx->result = session;
1298 * Create a new session to transmit data to the target
1299 * This session will used to send data to this peer and the plugin will
1300 * notify us by calling the env->session_end function
1302 * @param cls closure
1303 * @param target the neighbour id
1304 * @param addr pointer to the address
1305 * @param addrlen length of addr
1306 * @return the session if the address is valid, NULL otherwise
1308 static struct Session *
1309 tcp_plugin_create_session (void *cls,
1310 const struct GNUNET_HELLO_Address *address)
1312 struct Plugin * plugin = cls;
1313 struct Session * session = NULL;
1318 struct GNUNET_CONNECTION_Handle *sa;
1319 struct sockaddr_in a4;
1320 struct sockaddr_in6 a6;
1321 const struct IPv4TcpAddress *t4;
1322 const struct IPv6TcpAddress *t6;
1323 unsigned int is_natd = GNUNET_NO;
1324 size_t addrlen = address->address_length;
1326 GNUNET_assert (plugin != NULL);
1327 GNUNET_assert (address != NULL);
1329 if (addrlen == sizeof (struct IPv6TcpAddress))
1331 GNUNET_assert (NULL != address->address); /* make static analysis happy */
1332 t6 = address->address;
1334 memset (&a6, 0, sizeof (a6));
1335 #if HAVE_SOCKADDR_IN_SIN_LEN
1336 a6.sin6_len = sizeof (a6);
1338 a6.sin6_family = AF_INET6;
1339 a6.sin6_port = t6->t6_port;
1340 if (t6->t6_port == 0)
1341 is_natd = GNUNET_YES;
1342 memcpy (&a6.sin6_addr, &t6->ipv6_addr, sizeof (struct in6_addr));
1346 else if (addrlen == sizeof (struct IPv4TcpAddress))
1348 GNUNET_assert (NULL != address->address); /* make static analysis happy */
1349 t4 = address->address;
1351 memset (&a4, 0, sizeof (a4));
1352 #if HAVE_SOCKADDR_IN_SIN_LEN
1353 a4.sin_len = sizeof (a4);
1355 a4.sin_family = AF_INET;
1356 a4.sin_port = t4->t4_port;
1357 if (t4->t4_port == 0)
1358 is_natd = GNUNET_YES;
1359 a4.sin_addr.s_addr = t4->ipv4_addr;
1365 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, "tcp",
1366 _("Address of unexpected length: %u\n"), addrlen);
1371 /* look for existing session */
1372 if (GNUNET_CONTAINER_multihashmap_contains(plugin->sessionmap, &address->peer.hashPubKey))
1374 struct SessionItCtx si_ctx;
1376 si_ctx.addrlen = sbs;
1377 GNUNET_CONTAINER_multihashmap_get_multiple(plugin->sessionmap, &address->peer.hashPubKey, &session_it, &si_ctx);
1378 if (si_ctx.result != NULL)
1379 session = si_ctx.result;
1383 if ((is_natd == GNUNET_YES) && (addrlen == sizeof (struct IPv6TcpAddress)))
1384 return NULL; /* NAT client only works with IPv4 addresses */
1386 if (0 == plugin->max_connections)
1387 return NULL; /* saturated */
1389 if ((is_natd == GNUNET_YES) &&
1391 GNUNET_CONTAINER_multihashmap_contains (plugin->nat_wait_conns,
1392 &address->peer.hashPubKey)))
1393 return NULL; /* Only do one NAT punch attempt per peer identity */
1395 if ((is_natd == GNUNET_YES) && (NULL != plugin->nat) &&
1397 GNUNET_CONTAINER_multihashmap_contains (plugin->nat_wait_conns,
1398 &address->peer.hashPubKey)))
1401 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1402 _("Found valid IPv4 NAT address (creating session)!\n"));
1404 session = create_session (plugin, &address->peer, NULL, GNUNET_YES);
1405 GNUNET_assert (session != NULL);
1407 GNUNET_assert (GNUNET_CONTAINER_multihashmap_put
1408 (plugin->nat_wait_conns, &address->peer.hashPubKey, session,
1409 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY) == GNUNET_OK);
1411 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1412 "Created NAT WAIT connection to `%4s' at `%s'\n",
1413 GNUNET_i2s (target), GNUNET_a2s (sb, sbs));
1415 GNUNET_NAT_run_client (plugin->nat, &a4);
1419 /* create new outbound session */
1420 GNUNET_assert (0 != plugin->max_connections);
1421 sa = GNUNET_CONNECTION_create_from_sockaddr (af, sb, sbs);
1425 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1426 "Failed to create connection to `%4s' at `%s'\n",
1427 GNUNET_i2s (target), GNUNET_a2s (sb, sbs));
1431 plugin->max_connections--;
1433 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1434 "Asked to transmit to `%4s', creating fresh session using address `%s'.\n",
1435 GNUNET_i2s (target), GNUNET_a2s (sb, sbs));
1437 session = create_session (plugin,
1439 GNUNET_SERVER_connect_socket (plugin->server, sa),
1441 session->connect_addr = GNUNET_malloc (addrlen);
1442 memcpy (session->connect_addr, address->address, addrlen);
1443 session->connect_alen = addrlen;
1446 struct GNUNET_ATS_Information ats;
1447 ats = plugin->env->get_address_type (plugin->env->cls, sb ,sbs);
1448 session->ats_address_network_type = ats.value;
1453 GNUNET_CONTAINER_multihashmap_put(plugin->sessionmap, &address->peer.hashPubKey, session, GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
1455 /* Send TCP Welcome */
1456 process_pending_messages (session);
1463 * Function that can be called to force a disconnect from the
1464 * specified neighbour. This should also cancel all previously
1465 * scheduled transmissions. Obviously the transmission may have been
1466 * partially completed already, which is OK. The plugin is supposed
1467 * to close the connection (if applicable) and no longer call the
1468 * transmit continuation(s).
1470 * Finally, plugin MUST NOT call the services's receive function to
1471 * notify the service that the connection to the specified target was
1472 * closed after a getting this call.
1474 * @param cls closure
1475 * @param target peer for which the last transmission is
1479 tcp_plugin_disconnect (void *cls, const struct GNUNET_PeerIdentity *target)
1481 struct Plugin *plugin = cls;
1482 struct Session *session;
1483 struct Session *next;
1484 struct PendingMessage *pm;
1487 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1488 "Asked to cancel session with `%4s'\n", GNUNET_i2s (target));
1490 next = plugin->sessions;
1491 while (NULL != (session = next))
1493 next = session->next;
1495 memcmp (target, &session->target, sizeof (struct GNUNET_PeerIdentity)))
1497 pm = session->pending_messages_head;
1500 pm->transmit_cont = NULL;
1501 pm->transmit_cont_cls = NULL;
1504 GNUNET_STATISTICS_update (session->plugin->env->stats,
1506 ("# transport-service disconnect requests for TCP"),
1508 disconnect_session (session);
1514 * Context for address to string conversion.
1516 struct PrettyPrinterContext
1519 * Function to call with the result.
1521 GNUNET_TRANSPORT_AddressStringCallback asc;
1524 * Clsoure for 'asc'.
1529 * Port to add after the IP address.
1536 * Append our port and forward the result.
1538 * @param cls the 'struct PrettyPrinterContext*'
1539 * @param hostname hostname part of the address
1542 append_port (void *cls, const char *hostname)
1544 struct PrettyPrinterContext *ppc = cls;
1547 if (hostname == NULL)
1549 ppc->asc (ppc->asc_cls, NULL);
1553 GNUNET_asprintf (&ret, "%s:%d", hostname, ppc->port);
1554 ppc->asc (ppc->asc_cls, ret);
1560 * Convert the transports address to a nice, human-readable
1563 * @param cls closure
1564 * @param type name of the transport that generated the address
1565 * @param addr one of the addresses of the host, NULL for the last address
1566 * the specific address format depends on the transport
1567 * @param addrlen length of the address
1568 * @param numeric should (IP) addresses be displayed in numeric form?
1569 * @param timeout after how long should we give up?
1570 * @param asc function to call on each string
1571 * @param asc_cls closure for asc
1574 tcp_plugin_address_pretty_printer (void *cls, const char *type,
1575 const void *addr, size_t addrlen,
1577 struct GNUNET_TIME_Relative timeout,
1578 GNUNET_TRANSPORT_AddressStringCallback asc,
1581 struct PrettyPrinterContext *ppc;
1584 struct sockaddr_in a4;
1585 struct sockaddr_in6 a6;
1586 const struct IPv4TcpAddress *t4;
1587 const struct IPv6TcpAddress *t6;
1590 if (addrlen == sizeof (struct IPv6TcpAddress))
1593 memset (&a6, 0, sizeof (a6));
1594 a6.sin6_family = AF_INET6;
1595 a6.sin6_port = t6->t6_port;
1596 memcpy (&a6.sin6_addr, &t6->ipv6_addr, sizeof (struct in6_addr));
1597 port = ntohs (t6->t6_port);
1601 else if (addrlen == sizeof (struct IPv4TcpAddress))
1604 memset (&a4, 0, sizeof (a4));
1605 a4.sin_family = AF_INET;
1606 a4.sin_port = t4->t4_port;
1607 a4.sin_addr.s_addr = t4->ipv4_addr;
1608 port = ntohs (t4->t4_port);
1614 /* invalid address */
1615 GNUNET_break_op (0);
1616 asc (asc_cls, NULL);
1619 ppc = GNUNET_malloc (sizeof (struct PrettyPrinterContext));
1621 ppc->asc_cls = asc_cls;
1623 GNUNET_RESOLVER_hostname_get (sb, sbs, !numeric, timeout, &append_port, ppc);
1628 * Check if the given port is plausible (must be either our listen
1629 * port or our advertised port), or any port if we are behind NAT
1630 * and do not have a port open. If it is neither, we return
1633 * @param plugin global variables
1634 * @param in_port port number to check
1635 * @return GNUNET_OK if port is either open_port or adv_port
1638 check_port (struct Plugin *plugin, uint16_t in_port)
1640 if ((in_port == plugin->adv_port) || (in_port == plugin->open_port))
1642 return GNUNET_SYSERR;
1647 * Function that will be called to check if a binary address for this
1648 * plugin is well-formed and corresponds to an address for THIS peer
1649 * (as per our configuration). Naturally, if absolutely necessary,
1650 * plugins can be a bit conservative in their answer, but in general
1651 * plugins should make sure that the address does not redirect
1652 * traffic to a 3rd party that might try to man-in-the-middle our
1655 * @param cls closure, our 'struct Plugin*'
1656 * @param addr pointer to the address
1657 * @param addrlen length of addr
1658 * @return GNUNET_OK if this is a plausible address for this peer
1659 * and transport, GNUNET_SYSERR if not
1662 tcp_plugin_check_address (void *cls, const void *addr, size_t addrlen)
1664 struct Plugin *plugin = cls;
1665 struct IPv4TcpAddress *v4;
1666 struct IPv6TcpAddress *v6;
1668 if ((addrlen != sizeof (struct IPv4TcpAddress)) &&
1669 (addrlen != sizeof (struct IPv6TcpAddress)))
1671 GNUNET_break_op (0);
1672 return GNUNET_SYSERR;
1674 if (addrlen == sizeof (struct IPv4TcpAddress))
1676 v4 = (struct IPv4TcpAddress *) addr;
1677 if (GNUNET_OK != check_port (plugin, ntohs (v4->t4_port)))
1678 return GNUNET_SYSERR;
1680 GNUNET_NAT_test_address (plugin->nat, &v4->ipv4_addr,
1681 sizeof (struct in_addr)))
1682 return GNUNET_SYSERR;
1686 v6 = (struct IPv6TcpAddress *) addr;
1687 if (IN6_IS_ADDR_LINKLOCAL (&v6->ipv6_addr))
1689 GNUNET_break_op (0);
1690 return GNUNET_SYSERR;
1692 if (GNUNET_OK != check_port (plugin, ntohs (v6->t6_port)))
1693 return GNUNET_SYSERR;
1695 GNUNET_NAT_test_address (plugin->nat, &v6->ipv6_addr,
1696 sizeof (struct in6_addr)))
1697 return GNUNET_SYSERR;
1704 * We've received a nat probe from this peer via TCP. Finish
1705 * creating the client session and resume sending of queued
1708 * @param cls closure
1709 * @param client identification of the client
1710 * @param message the actual message
1713 handle_tcp_nat_probe (void *cls, struct GNUNET_SERVER_Client *client,
1714 const struct GNUNET_MessageHeader *message)
1716 struct Plugin *plugin = cls;
1717 struct Session *session;
1718 const struct TCP_NAT_ProbeMessage *tcp_nat_probe;
1721 struct IPv4TcpAddress *t4;
1722 struct IPv6TcpAddress *t6;
1723 const struct sockaddr_in *s4;
1724 const struct sockaddr_in6 *s6;
1727 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp", "received NAT probe\n");
1729 /* We have received a TCP NAT probe, meaning we (hopefully) initiated
1730 * a connection to this peer by running gnunet-nat-client. This peer
1731 * received the punch message and now wants us to use the new connection
1732 * as the default for that peer. Do so and then send a WELCOME message
1733 * so we can really be connected!
1735 if (ntohs (message->size) != sizeof (struct TCP_NAT_ProbeMessage))
1737 GNUNET_break_op (0);
1738 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1742 tcp_nat_probe = (const struct TCP_NAT_ProbeMessage *) message;
1744 memcmp (&tcp_nat_probe->clientIdentity, plugin->env->my_identity,
1745 sizeof (struct GNUNET_PeerIdentity)))
1747 /* refuse connections from ourselves */
1748 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1753 GNUNET_CONTAINER_multihashmap_get (plugin->nat_wait_conns,
1755 clientIdentity.hashPubKey);
1756 if (session == NULL)
1759 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1760 "Did NOT find session for NAT probe!\n");
1762 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1766 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1767 "Found session for NAT probe!\n");
1769 GNUNET_assert (GNUNET_CONTAINER_multihashmap_remove
1770 (plugin->nat_wait_conns,
1771 &tcp_nat_probe->clientIdentity.hashPubKey,
1772 session) == GNUNET_YES);
1773 if (GNUNET_OK != GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
1776 GNUNET_free (session);
1777 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1781 GNUNET_SERVER_client_keep (client);
1782 session->client = client;
1783 session->last_activity = GNUNET_TIME_absolute_get ();
1784 session->inbound = GNUNET_NO;
1787 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1788 "Found address `%s' for incoming connection\n",
1789 GNUNET_a2s (vaddr, alen));
1791 switch (((const struct sockaddr *) vaddr)->sa_family)
1795 t4 = GNUNET_malloc (sizeof (struct IPv4TcpAddress));
1796 t4->t4_port = s4->sin_port;
1797 t4->ipv4_addr = s4->sin_addr.s_addr;
1798 session->connect_addr = t4;
1799 session->connect_alen = sizeof (struct IPv4TcpAddress);
1803 t6 = GNUNET_malloc (sizeof (struct IPv6TcpAddress));
1804 t6->t6_port = s6->sin6_port;
1805 memcpy (&t6->ipv6_addr, &s6->sin6_addr, sizeof (struct in6_addr));
1806 session->connect_addr = t6;
1807 session->connect_alen = sizeof (struct IPv6TcpAddress);
1810 GNUNET_break_op (0);
1812 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1813 "Bad address for incoming connection!\n");
1815 GNUNET_free (vaddr);
1816 GNUNET_SERVER_client_drop (client);
1817 GNUNET_free (session);
1818 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1821 GNUNET_free (vaddr);
1823 session->next = plugin->sessions;
1824 plugin->sessions = session;
1825 GNUNET_STATISTICS_update (plugin->env->stats,
1826 gettext_noop ("# TCP sessions active"), 1,
1828 process_pending_messages (session);
1829 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1834 * We've received a welcome from this peer via TCP. Possibly create a
1835 * fresh client record and send back our welcome.
1837 * @param cls closure
1838 * @param client identification of the client
1839 * @param message the actual message
1842 handle_tcp_welcome (void *cls, struct GNUNET_SERVER_Client *client,
1843 const struct GNUNET_MessageHeader *message)
1845 struct Plugin *plugin = cls;
1846 const struct WelcomeMessage *wm = (const struct WelcomeMessage *) message;
1847 struct Session *session;
1850 struct IPv4TcpAddress *t4;
1851 struct IPv6TcpAddress *t6;
1852 const struct sockaddr_in *s4;
1853 const struct sockaddr_in6 *s6;
1856 memcmp (&wm->clientIdentity, plugin->env->my_identity,
1857 sizeof (struct GNUNET_PeerIdentity)))
1859 /* refuse connections from ourselves */
1860 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1864 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1865 "Received %s message from `%4s'.\n", "WELCOME",
1866 GNUNET_i2s (&wm->clientIdentity));
1868 GNUNET_STATISTICS_update (plugin->env->stats,
1869 gettext_noop ("# TCP WELCOME messages received"), 1,
1871 session = find_session_by_client (plugin, client);
1873 if (session == NULL)
1876 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1877 "Received %s message from a `%4s', creating new session\n",
1878 "WELCOME", GNUNET_i2s (&wm->clientIdentity));
1880 GNUNET_SERVER_client_keep (client);
1881 session = create_session (plugin, &wm->clientIdentity, client, GNUNET_NO);
1882 session->inbound = GNUNET_YES;
1883 if (GNUNET_OK == GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
1886 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1887 "Found address `%s' for incoming connection\n",
1888 GNUNET_a2s (vaddr, alen));
1891 if (alen == sizeof (struct sockaddr_in))
1894 t4 = GNUNET_malloc (sizeof (struct IPv4TcpAddress));
1895 t4->t4_port = s4->sin_port;
1896 t4->ipv4_addr = s4->sin_addr.s_addr;
1897 session->connect_addr = t4;
1898 session->connect_alen = sizeof (struct IPv4TcpAddress);
1900 else if (alen == sizeof (struct sockaddr_in6))
1903 t6 = GNUNET_malloc (sizeof (struct IPv6TcpAddress));
1904 t6->t6_port = s6->sin6_port;
1905 memcpy (&t6->ipv6_addr, &s6->sin6_addr, sizeof (struct in6_addr));
1906 session->connect_addr = t6;
1907 session->connect_alen = sizeof (struct IPv6TcpAddress);
1910 struct GNUNET_ATS_Information ats;
1911 ats = plugin->env->get_address_type (plugin->env->cls, vaddr ,alen);
1912 session->ats_address_network_type = ats.value;
1914 GNUNET_free (vaddr);
1919 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1920 "Did not obtain TCP socket address for incoming connection\n");
1923 process_pending_messages (session);
1928 if (GNUNET_OK == GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
1930 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1931 "Found address `%s' (already have session)\n",
1932 GNUNET_a2s (vaddr, alen));
1933 GNUNET_free (vaddr);
1938 if (session->expecting_welcome != GNUNET_YES)
1940 GNUNET_break_op (0);
1941 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1944 session->last_activity = GNUNET_TIME_absolute_get ();
1945 session->expecting_welcome = GNUNET_NO;
1946 GNUNET_SERVER_client_set_timeout (client,
1947 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1948 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1953 * Task to signal the server that we can continue
1954 * receiving from the TCP client now.
1956 * @param cls the 'struct Session*'
1957 * @param tc task context (unused)
1960 delayed_done (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1962 struct Session *session = cls;
1963 struct GNUNET_TIME_Relative delay;
1964 struct GNUNET_ATS_Information ats;
1966 session->receive_delay_task = GNUNET_SCHEDULER_NO_TASK;
1968 session->plugin->env->receive (session->plugin->env->cls,
1969 &session->target, NULL, &ats, 0, session,
1971 if (delay.rel_value == 0)
1972 GNUNET_SERVER_receive_done (session->client, GNUNET_OK);
1974 session->receive_delay_task =
1975 GNUNET_SCHEDULER_add_delayed (delay, &delayed_done, session);
1980 * We've received data for this peer via TCP. Unbox,
1981 * compute latency and forward.
1983 * @param cls closure
1984 * @param client identification of the client
1985 * @param message the actual message
1988 handle_tcp_data (void *cls, struct GNUNET_SERVER_Client *client,
1989 const struct GNUNET_MessageHeader *message)
1991 struct Plugin *plugin = cls;
1992 struct Session *session;
1993 struct GNUNET_TIME_Relative delay;
1996 type = ntohs (message->type);
1997 if ((GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME == type) ||
1998 (GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE == type))
2000 /* We don't want to propagate WELCOME and NAT Probe messages up! */
2001 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2004 session = find_session_by_client (plugin, client);
2005 if ((NULL == session) || (GNUNET_YES == session->expecting_welcome))
2007 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2010 session->last_activity = GNUNET_TIME_absolute_get ();
2012 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
2013 "Passing %u bytes of type %u from `%4s' to transport service.\n",
2014 (unsigned int) ntohs (message->size),
2015 (unsigned int) ntohs (message->type),
2016 GNUNET_i2s (&session->target));
2018 GNUNET_STATISTICS_update (plugin->env->stats,
2019 gettext_noop ("# bytes received via TCP"),
2020 ntohs (message->size), GNUNET_NO);
2021 struct GNUNET_ATS_Information distance[2];
2023 distance[0].type = htonl (GNUNET_ATS_QUALITY_NET_DISTANCE);
2024 distance[0].value = htonl (1);
2025 distance[1].type = htonl (GNUNET_ATS_NETWORK_TYPE);
2026 distance[1].value = session->ats_address_network_type;
2027 GNUNET_break (ntohl(session->ats_address_network_type) != GNUNET_ATS_NET_UNSPECIFIED);
2030 plugin->env->receive (plugin->env->cls, &session->target, message,
2031 (const struct GNUNET_ATS_Information *) &distance,
2034 session->inbound) ? NULL : session->connect_addr,
2036 session->inbound) ? 0 : session->connect_alen);
2037 if (delay.rel_value == 0)
2039 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2044 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
2045 "Throttling receiving from `%s' for %llu ms\n",
2046 GNUNET_i2s (&session->target),
2047 (unsigned long long) delay.rel_value);
2049 GNUNET_SERVER_disable_receive_done_warning (client);
2050 session->receive_delay_task =
2051 GNUNET_SCHEDULER_add_delayed (delay, &delayed_done, session);
2057 * Functions with this signature are called whenever a peer
2058 * is disconnected on the network level.
2060 * @param cls closure
2061 * @param client identification of the client
2064 disconnect_notify (void *cls, struct GNUNET_SERVER_Client *client)
2066 struct Plugin *plugin = cls;
2067 struct Session *session;
2071 plugin->max_connections++;
2072 session = find_session_by_client (plugin, client);
2073 if (session == NULL)
2074 return; /* unknown, nothing to do */
2076 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
2077 "Destroying session of `%4s' with %s due to network-level disconnect.\n",
2078 GNUNET_i2s (&session->target),
2079 (session->connect_addr !=
2080 NULL) ? tcp_address_to_string (session->plugin,
2081 session->connect_addr,
2082 session->connect_alen) :
2085 GNUNET_STATISTICS_update (session->plugin->env->stats,
2087 ("# network-level TCP disconnect events"), 1,
2089 disconnect_session (session);
2094 * We can now send a probe message, copy into buffer to really send.
2096 * @param cls closure, a struct TCPProbeContext
2097 * @param size max size to copy
2098 * @param buf buffer to copy message to
2099 * @return number of bytes copied into buf
2102 notify_send_probe (void *cls, size_t size, void *buf)
2104 struct TCPProbeContext *tcp_probe_ctx = cls;
2105 struct Plugin *plugin = tcp_probe_ctx->plugin;
2108 tcp_probe_ctx->transmit_handle = NULL;
2109 GNUNET_CONTAINER_DLL_remove (plugin->probe_head, plugin->probe_tail,
2113 GNUNET_CONNECTION_destroy (tcp_probe_ctx->sock, GNUNET_NO);
2114 GNUNET_free (tcp_probe_ctx);
2117 GNUNET_assert (size >= sizeof (tcp_probe_ctx->message));
2118 memcpy (buf, &tcp_probe_ctx->message, sizeof (tcp_probe_ctx->message));
2119 GNUNET_SERVER_connect_socket (tcp_probe_ctx->plugin->server,
2120 tcp_probe_ctx->sock);
2121 ret = sizeof (tcp_probe_ctx->message);
2122 GNUNET_free (tcp_probe_ctx);
2128 * Function called by the NAT subsystem suggesting another peer wants
2129 * to connect to us via connection reversal. Try to connect back to the
2132 * @param cls closure
2133 * @param addr address to try
2134 * @param addrlen number of bytes in addr
2137 try_connection_reversal (void *cls, const struct sockaddr *addr,
2140 struct Plugin *plugin = cls;
2141 struct GNUNET_CONNECTION_Handle *sock;
2142 struct TCPProbeContext *tcp_probe_ctx;
2145 * We have received an ICMP response, ostensibly from a peer
2146 * that wants to connect to us! Send a message to establish a connection.
2148 sock = GNUNET_CONNECTION_create_from_sockaddr (AF_INET, addr, addrlen);
2151 /* failed for some odd reason (out of sockets?); ignore attempt */
2155 /* FIXME: do we need to track these probe context objects so that
2156 * we can clean them up on plugin unload? */
2157 tcp_probe_ctx = GNUNET_malloc (sizeof (struct TCPProbeContext));
2158 tcp_probe_ctx->message.header.size =
2159 htons (sizeof (struct TCP_NAT_ProbeMessage));
2160 tcp_probe_ctx->message.header.type =
2161 htons (GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE);
2162 memcpy (&tcp_probe_ctx->message.clientIdentity, plugin->env->my_identity,
2163 sizeof (struct GNUNET_PeerIdentity));
2164 tcp_probe_ctx->plugin = plugin;
2165 tcp_probe_ctx->sock = sock;
2166 GNUNET_CONTAINER_DLL_insert (plugin->probe_head, plugin->probe_tail,
2168 tcp_probe_ctx->transmit_handle =
2169 GNUNET_CONNECTION_notify_transmit_ready (sock,
2170 ntohs (tcp_probe_ctx->
2171 message.header.size),
2172 GNUNET_TIME_UNIT_FOREVER_REL,
2180 * Entry point for the plugin.
2182 * @param cls closure, the 'struct GNUNET_TRANSPORT_PluginEnvironment*'
2183 * @return the 'struct GNUNET_TRANSPORT_PluginFunctions*' or NULL on error
2186 libgnunet_plugin_transport_tcp_init (void *cls)
2188 static const struct GNUNET_SERVER_MessageHandler my_handlers[] = {
2189 {&handle_tcp_welcome, NULL, GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME,
2190 sizeof (struct WelcomeMessage)},
2191 {&handle_tcp_nat_probe, NULL, GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE,
2192 sizeof (struct TCP_NAT_ProbeMessage)},
2193 {&handle_tcp_data, NULL, GNUNET_MESSAGE_TYPE_ALL, 0},
2196 struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
2197 struct GNUNET_TRANSPORT_PluginFunctions *api;
2198 struct Plugin *plugin;
2199 struct GNUNET_SERVICE_Context *service;
2200 unsigned long long aport;
2201 unsigned long long bport;
2202 unsigned long long max_connections;
2204 struct GNUNET_TIME_Relative idle_timeout;
2206 struct sockaddr **addrs;
2207 socklen_t *addrlens;
2210 GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-tcp",
2213 max_connections = 128;
2217 GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-tcp", "PORT",
2218 &bport)) || (bport > 65535) ||
2220 GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-tcp",
2221 "ADVERTISED-PORT", &aport)) &&
2224 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, "tcp",
2226 ("Require valid port number for service `%s' in configuration!\n"),
2236 service = GNUNET_SERVICE_start ("transport-tcp", env->cfg);
2237 if (service == NULL)
2239 GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, "tcp",
2240 _("Failed to start service.\n"));
2249 plugin = GNUNET_malloc (sizeof (struct Plugin));
2250 plugin->sessionmap = GNUNET_CONTAINER_multihashmap_create(max_connections);
2251 plugin->max_connections = max_connections;
2252 plugin->open_port = bport;
2253 plugin->adv_port = aport;
2255 plugin->lsock = NULL;
2256 if ((service != NULL) &&
2259 GNUNET_SERVICE_get_server_addresses ("transport-tcp", env->cfg, &addrs,
2263 GNUNET_NAT_register (env->cfg, GNUNET_YES, aport, (unsigned int) ret,
2264 (const struct sockaddr **) addrs, addrlens,
2265 &tcp_nat_port_map_callback,
2266 &try_connection_reversal, plugin);
2270 GNUNET_assert (addrs[ret] != NULL);
2271 GNUNET_free (addrs[ret]);
2273 GNUNET_free_non_null (addrs);
2274 GNUNET_free_non_null (addrlens);
2279 GNUNET_NAT_register (env->cfg, GNUNET_YES, 0, 0, NULL, NULL, NULL,
2280 &try_connection_reversal, plugin);
2282 api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
2284 api->send = &tcp_plugin_send;
2286 api->send_with_session = &tcp_plugin_send_new;
2287 api->get_session = &tcp_plugin_create_session;
2289 api->disconnect = &tcp_plugin_disconnect;
2290 api->address_pretty_printer = &tcp_plugin_address_pretty_printer;
2291 api->check_address = &tcp_plugin_check_address;
2292 api->address_to_string = &tcp_address_to_string;
2293 plugin->service = service;
2294 if (service != NULL)
2296 plugin->server = GNUNET_SERVICE_get_server (service);
2301 GNUNET_CONFIGURATION_get_value_time (env->cfg, "transport-tcp",
2302 "TIMEOUT", &idle_timeout))
2304 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, "tcp",
2305 _("Failed to find option %s in section %s!\n"),
2306 "TIMEOUT", "transport-tcp");
2307 if (plugin->nat != NULL)
2308 GNUNET_NAT_unregister (plugin->nat);
2309 GNUNET_free (plugin);
2314 GNUNET_SERVER_create_with_sockets (&plugin_tcp_access_check, plugin,
2315 NULL, idle_timeout, GNUNET_YES);
2317 plugin->handlers = GNUNET_malloc (sizeof (my_handlers));
2318 memcpy (plugin->handlers, my_handlers, sizeof (my_handlers));
2320 i < sizeof (my_handlers) / sizeof (struct GNUNET_SERVER_MessageHandler);
2322 plugin->handlers[i].callback_cls = plugin;
2323 GNUNET_SERVER_add_handlers (plugin->server, plugin->handlers);
2324 GNUNET_SERVER_disconnect_notify (plugin->server, &disconnect_notify, plugin);
2325 plugin->nat_wait_conns = GNUNET_CONTAINER_multihashmap_create (16);
2327 GNUNET_log_from (GNUNET_ERROR_TYPE_INFO, "tcp",
2328 _("TCP transport listening on port %llu\n"), bport);
2330 GNUNET_log_from (GNUNET_ERROR_TYPE_INFO, "tcp",
2332 ("TCP transport not listening on any port (client only)\n"));
2334 GNUNET_log_from (GNUNET_ERROR_TYPE_INFO, "tcp",
2336 ("TCP transport advertises itself as being on port %llu\n"),
2343 * Exit point from the plugin.
2346 libgnunet_plugin_transport_tcp_done (void *cls)
2348 struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
2349 struct Plugin *plugin = api->cls;
2350 struct Session *session;
2351 struct TCPProbeContext *tcp_probe;
2353 while (NULL != (session = plugin->sessions))
2354 disconnect_session (session);
2355 if (plugin->service != NULL)
2356 GNUNET_SERVICE_stop (plugin->service);
2358 GNUNET_SERVER_destroy (plugin->server);
2359 GNUNET_free (plugin->handlers);
2360 if (plugin->nat != NULL)
2361 GNUNET_NAT_unregister (plugin->nat);
2362 while (NULL != (tcp_probe = plugin->probe_head))
2364 GNUNET_CONTAINER_DLL_remove (plugin->probe_head, plugin->probe_tail,
2366 GNUNET_CONNECTION_destroy (tcp_probe->sock, GNUNET_NO);
2367 GNUNET_free (tcp_probe);
2369 GNUNET_CONTAINER_multihashmap_destroy (plugin->nat_wait_conns);
2370 GNUNET_CONTAINER_multihashmap_destroy (plugin->sessionmap);
2371 GNUNET_free (plugin);
2376 /* end of plugin_transport_tcp.c */