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
47 * Initial handshake message for a session.
52 * Type is GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME.
54 struct GNUNET_MessageHeader header;
57 * Identity of the node connecting (TCP client)
59 struct GNUNET_PeerIdentity clientIdentity;
65 * Basically a WELCOME message, but with the purpose
66 * of giving the waiting peer a client handle to use
68 struct TCP_NAT_ProbeMessage
71 * Type is GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE.
73 struct GNUNET_MessageHeader header;
76 * Identity of the sender of the message.
78 struct GNUNET_PeerIdentity clientIdentity;
84 * Context for sending a NAT probe via TCP.
86 struct TCPProbeContext
90 * Active probes are kept in a DLL.
92 struct TCPProbeContext *next;
95 * Active probes are kept in a DLL.
97 struct TCPProbeContext *prev;
102 struct GNUNET_CONNECTION_Handle *sock;
105 * Message to be sent.
107 struct TCP_NAT_ProbeMessage message;
110 * Handle to the transmission.
112 struct GNUNET_CONNECTION_TransmitHandle *transmit_handle;
115 * Transport plugin handle.
117 struct Plugin *plugin;
122 * Network format for IPv4 addresses.
124 struct IPv4TcpAddress
127 * IPv4 address, in network byte order.
129 uint32_t ipv4_addr GNUNET_PACKED;
132 * Port number, in network byte order.
134 uint16_t t4_port GNUNET_PACKED;
140 * Network format for IPv6 addresses.
142 struct IPv6TcpAddress
147 struct in6_addr ipv6_addr GNUNET_PACKED;
150 * Port number, in network byte order.
152 uint16_t t6_port GNUNET_PACKED;
158 * Encapsulation of all of the state of the plugin.
164 * Information kept for each message that is yet to
167 struct PendingMessage
171 * This is a doubly-linked list.
173 struct PendingMessage *next;
176 * This is a doubly-linked list.
178 struct PendingMessage *prev;
181 * The pending message
186 * Continuation function to call once the message
187 * has been sent. Can be NULL if there is no
188 * continuation to call.
190 GNUNET_TRANSPORT_TransmitContinuation transmit_cont;
193 * Closure for transmit_cont.
195 void *transmit_cont_cls;
198 * Timeout value for the pending message.
200 struct GNUNET_TIME_Absolute timeout;
203 * So that the gnunet-service-transport can group messages together,
204 * these pending messages need to accept a message buffer and size
205 * instead of just a GNUNET_MessageHeader.
213 * Session handle for TCP connections.
221 struct SessionHeader header;
224 * Stored in a linked list.
226 struct Session *next;
229 * Pointer to the global plugin struct.
231 struct Plugin *plugin;
234 * The client (used to identify this connection)
236 struct GNUNET_SERVER_Client *client;
239 * Messages currently pending for transmission
240 * to this peer, if any.
242 struct PendingMessage *pending_messages_head;
245 * Messages currently pending for transmission
246 * to this peer, if any.
248 struct PendingMessage *pending_messages_tail;
251 * Handle for pending transmission request.
253 struct GNUNET_CONNECTION_TransmitHandle *transmit_handle;
256 * To whom are we talking to (set to our identity
257 * if we are still waiting for the welcome message)
259 struct GNUNET_PeerIdentity target;
262 * ID of task used to delay receiving more to throttle sender.
264 GNUNET_SCHEDULER_TaskIdentifier receive_delay_task;
267 * Address of the other peer (either based on our 'connect'
268 * call or on our 'accept' call).
273 * Last activity on this connection. Used to select preferred
276 struct GNUNET_TIME_Absolute last_activity;
279 * Length of connect_addr.
284 * Are we still expecting the welcome message? (GNUNET_YES/GNUNET_NO)
286 int expecting_welcome;
289 * Was this a connection that was inbound (we accepted)? (GNUNET_YES/GNUNET_NO)
294 * Was this session created using NAT traversal?
299 * ATS network type in NBO
301 uint32_t ats_address_network_type;
306 * Encapsulation of all of the state of the plugin.
313 struct GNUNET_TRANSPORT_PluginEnvironment *env;
318 struct GNUNET_CONNECTION_Handle *lsock;
321 * Our handle to the NAT module.
323 struct GNUNET_NAT_Handle *nat;
326 * List of open TCP sessions.
328 struct Session *sessions;
330 struct GNUNET_CONTAINER_MultiHashMap * sessionmap;
333 * Handle to the network service.
335 struct GNUNET_SERVICE_Context *service;
338 * Handle to the server for this service.
340 struct GNUNET_SERVER_Handle *server;
343 * Copy of the handler array where the closures are
344 * set to this struct's instance.
346 struct GNUNET_SERVER_MessageHandler *handlers;
349 * Map of peers we have tried to contact behind a NAT
351 struct GNUNET_CONTAINER_MultiHashMap *nat_wait_conns;
354 * List of active TCP probes.
356 struct TCPProbeContext *probe_head;
359 * List of active TCP probes.
361 struct TCPProbeContext *probe_tail;
364 * Handle for (DYN)DNS lookup of our external IP.
366 struct GNUNET_RESOLVER_RequestHandle *ext_dns;
369 * How many more TCP sessions are we allowed to open right now?
371 unsigned long long max_connections;
374 * ID of task used to update our addresses when one expires.
376 GNUNET_SCHEDULER_TaskIdentifier address_update_task;
379 * Port that we are actually listening on.
384 * Port that the user said we would have visible to the
393 * Function to check if an inbound connection is acceptable.
394 * Mostly used to limit the total number of open connections
397 * @param cls the 'struct Plugin'
398 * @param ucred credentials, if available, otherwise NULL
399 * @param addr address
400 * @param addrlen length of address
401 * @return GNUNET_YES to allow, GNUNET_NO to deny, GNUNET_SYSERR
402 * for unknown address family (will be denied).
405 plugin_tcp_access_check (void *cls,
406 const struct GNUNET_CONNECTION_Credentials *ucred,
407 const struct sockaddr *addr, socklen_t addrlen)
409 struct Plugin *plugin = cls;
411 if (0 == plugin->max_connections)
413 plugin->max_connections--;
419 * Our external IP address/port mapping has changed.
421 * @param cls closure, the 'struct LocalAddrList'
422 * @param add_remove GNUNET_YES to mean the new public IP address, GNUNET_NO to mean
423 * the previous (now invalid) one
424 * @param addr either the previous or the new public IP address
425 * @param addrlen actual lenght of the address
428 tcp_nat_port_map_callback (void *cls, int add_remove,
429 const struct sockaddr *addr, socklen_t addrlen)
431 struct Plugin *plugin = cls;
432 struct IPv4TcpAddress t4;
433 struct IPv6TcpAddress t6;
437 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
438 "NPMC called with %d for address `%s'\n", add_remove,
439 GNUNET_a2s (addr, addrlen));
440 /* convert 'addr' to our internal format */
441 switch (addr->sa_family)
444 GNUNET_assert (addrlen == sizeof (struct sockaddr_in));
445 t4.ipv4_addr = ((struct sockaddr_in *) addr)->sin_addr.s_addr;
446 t4.t4_port = ((struct sockaddr_in *) addr)->sin_port;
451 GNUNET_assert (addrlen == sizeof (struct sockaddr_in6));
452 memcpy (&t6.ipv6_addr, &((struct sockaddr_in6 *) addr)->sin6_addr,
453 sizeof (struct in6_addr));
454 t6.t6_port = ((struct sockaddr_in6 *) addr)->sin6_port;
462 /* modify our published address list */
463 plugin->env->notify_address (plugin->env->cls, add_remove, arg, args);
468 * Function called for a quick conversion of the binary address to
469 * a numeric address. Note that the caller must not free the
470 * address and that the next call to this function is allowed
471 * to override the address again.
473 * @param cls closure ('struct Plugin*')
474 * @param addr binary address
475 * @param addrlen length of the address
476 * @return string representing the same address
479 tcp_address_to_string (void *cls, const void *addr, size_t addrlen)
481 static char rbuf[INET6_ADDRSTRLEN + 12];
482 char buf[INET6_ADDRSTRLEN];
486 const struct IPv4TcpAddress *t4;
487 const struct IPv6TcpAddress *t6;
491 if (addrlen == sizeof (struct IPv6TcpAddress))
495 port = ntohs (t6->t6_port);
496 memcpy (&a6, &t6->ipv6_addr, sizeof (a6));
499 else if (addrlen == sizeof (struct IPv4TcpAddress))
503 port = ntohs (t4->t4_port);
504 memcpy (&a4, &t4->ipv4_addr, sizeof (a4));
509 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, "tcp",
510 _("Unexpected address length: %u bytes\n"),
511 (unsigned int) addrlen);
515 if (NULL == inet_ntop (af, sb, buf, INET6_ADDRSTRLEN))
517 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "inet_ntop");
520 GNUNET_snprintf (rbuf, sizeof (rbuf), (af == AF_INET6) ? "[%s]:%u" : "%s:%u",
527 * Find the session handle for the given client.
529 * @param plugin the plugin
530 * @param client which client to find the session handle for
531 * @return NULL if no matching session exists
533 static struct Session *
534 find_session_by_client (struct Plugin *plugin,
535 const struct GNUNET_SERVER_Client *client)
539 ret = plugin->sessions;
540 while ((ret != NULL) && (client != ret->client))
547 * Create a new session. Also queues a welcome message.
549 * @param plugin the plugin
550 * @param target peer to connect to
551 * @param client client to use
552 * @param is_nat this a NAT session, we should wait for a client to
553 * connect to us from an address, then assign that to
555 * @return new session object
557 static struct Session *
558 create_session (struct Plugin *plugin, const struct GNUNET_PeerIdentity *target,
559 struct GNUNET_SERVER_Client *client, int is_nat)
562 struct PendingMessage *pm;
563 struct WelcomeMessage welcome;
565 if (is_nat != GNUNET_YES)
566 GNUNET_assert (client != NULL);
568 GNUNET_assert (client == NULL);
570 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
571 "Creating new session for peer `%4s'\n",
572 GNUNET_i2s (target));
574 ret = GNUNET_malloc (sizeof (struct Session));
575 ret->last_activity = GNUNET_TIME_absolute_get ();
576 ret->plugin = plugin;
577 ret->is_nat = is_nat;
578 if (is_nat != GNUNET_YES) /* If not a NAT WAIT conn, add it to global list */
580 ret->next = plugin->sessions;
581 plugin->sessions = ret;
583 ret->client = client;
584 ret->target = *target;
585 ret->expecting_welcome = GNUNET_YES;
586 ret->ats_address_network_type = htonl (GNUNET_ATS_NET_UNSPECIFIED);
587 pm = GNUNET_malloc (sizeof (struct PendingMessage) +
588 sizeof (struct WelcomeMessage));
589 pm->msg = (const char *) &pm[1];
590 pm->message_size = sizeof (struct WelcomeMessage);
591 welcome.header.size = htons (sizeof (struct WelcomeMessage));
592 welcome.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME);
593 welcome.clientIdentity = *plugin->env->my_identity;
594 memcpy (&pm[1], &welcome, sizeof (welcome));
595 pm->timeout = GNUNET_TIME_UNIT_FOREVER_ABS;
596 GNUNET_STATISTICS_update (plugin->env->stats,
597 gettext_noop ("# bytes currently in TCP buffers"),
598 pm->message_size, GNUNET_NO);
599 GNUNET_CONTAINER_DLL_insert (ret->pending_messages_head,
600 ret->pending_messages_tail, pm);
601 if (is_nat != GNUNET_YES)
602 GNUNET_STATISTICS_update (plugin->env->stats,
603 gettext_noop ("# TCP sessions active"), 1,
610 * If we have pending messages, ask the server to
611 * transmit them (schedule the respective tasks, etc.)
613 * @param session for which session should we do this
616 process_pending_messages (struct Session *session);
620 * Function called to notify a client about the socket
621 * being ready to queue more data. "buf" will be
622 * NULL and "size" zero if the socket was closed for
623 * writing in the meantime.
626 * @param size number of bytes available in buf
627 * @param buf where the callee should write the message
628 * @return number of bytes written to buf
631 do_transmit (void *cls, size_t size, void *buf)
633 struct Session *session = cls;
634 struct GNUNET_PeerIdentity pid;
635 struct Plugin *plugin;
636 struct PendingMessage *pos;
637 struct PendingMessage *hd;
638 struct PendingMessage *tl;
639 struct GNUNET_TIME_Absolute now;
643 GNUNET_assert (session != NULL);
644 session->transmit_handle = NULL;
645 plugin = session->plugin;
649 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
650 "Timeout trying to transmit to peer `%4s', discarding message queue.\n",
651 GNUNET_i2s (&session->target));
653 /* timeout; cancel all messages that have already expired */
657 now = GNUNET_TIME_absolute_get ();
658 while ((NULL != (pos = session->pending_messages_head)) &&
659 (pos->timeout.abs_value <= now.abs_value))
661 GNUNET_CONTAINER_DLL_remove (session->pending_messages_head,
662 session->pending_messages_tail, pos);
664 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
665 "Failed to transmit %u byte message to `%4s'.\n",
666 pos->message_size, GNUNET_i2s (&session->target));
668 ret += pos->message_size;
669 GNUNET_CONTAINER_DLL_insert_after (hd, tl, tl, pos);
671 /* do this call before callbacks (so that if callbacks destroy
672 * session, they have a chance to cancel actions done by this
674 process_pending_messages (session);
675 pid = session->target;
676 /* no do callbacks and do not use session again since
677 * the callbacks may abort the session */
678 while (NULL != (pos = hd))
680 GNUNET_CONTAINER_DLL_remove (hd, tl, pos);
681 if (pos->transmit_cont != NULL)
682 pos->transmit_cont (pos->transmit_cont_cls, &pid, GNUNET_SYSERR);
685 GNUNET_STATISTICS_update (plugin->env->stats,
686 gettext_noop ("# bytes currently in TCP buffers"),
687 -(int64_t) ret, GNUNET_NO);
688 GNUNET_STATISTICS_update (plugin->env->stats,
690 ("# bytes discarded by TCP (timeout)"), ret,
694 /* copy all pending messages that would fit */
699 while (NULL != (pos = session->pending_messages_head))
701 if (ret + pos->message_size > size)
703 GNUNET_CONTAINER_DLL_remove (session->pending_messages_head,
704 session->pending_messages_tail, pos);
705 GNUNET_assert (size >= pos->message_size);
706 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
707 "Transmitting message of type %u\n",
708 ntohs (((struct GNUNET_MessageHeader *) pos->msg)->type));
709 /* FIXME: this memcpy can be up to 7% of our total runtime */
710 memcpy (cbuf, pos->msg, pos->message_size);
711 cbuf += pos->message_size;
712 ret += pos->message_size;
713 size -= pos->message_size;
714 GNUNET_CONTAINER_DLL_insert_tail (hd, tl, pos);
716 /* schedule 'continuation' before callbacks so that callbacks that
717 * cancel everything don't cause us to use a session that no longer
719 process_pending_messages (session);
720 session->last_activity = GNUNET_TIME_absolute_get ();
721 pid = session->target;
722 /* we'll now call callbacks that may cancel the session; hence
723 * we should not use 'session' after this point */
724 while (NULL != (pos = hd))
726 GNUNET_CONTAINER_DLL_remove (hd, tl, pos);
727 if (pos->transmit_cont != NULL)
728 pos->transmit_cont (pos->transmit_cont_cls, &pid, GNUNET_OK);
731 GNUNET_assert (hd == NULL);
732 GNUNET_assert (tl == NULL);
734 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp", "Transmitting %u bytes\n",
737 GNUNET_STATISTICS_update (plugin->env->stats,
738 gettext_noop ("# bytes currently in TCP buffers"),
739 -(int64_t) ret, GNUNET_NO);
740 GNUNET_STATISTICS_update (plugin->env->stats,
741 gettext_noop ("# bytes transmitted via TCP"), ret,
748 * If we have pending messages, ask the server to
749 * transmit them (schedule the respective tasks, etc.)
751 * @param session for which session should we do this
754 process_pending_messages (struct Session *session)
756 struct PendingMessage *pm;
758 GNUNET_assert (session->client != NULL);
759 if (session->transmit_handle != NULL)
761 if (NULL == (pm = session->pending_messages_head))
764 session->transmit_handle =
765 GNUNET_SERVER_notify_transmit_ready (session->client, pm->message_size,
766 GNUNET_TIME_absolute_get_remaining
767 (pm->timeout), &do_transmit,
773 * Functions with this signature are called whenever we need
774 * to close a session due to a disconnect or failure to
775 * establish a connection.
777 * @param session session to close down
780 disconnect_session (struct Session *session)
782 struct Session *prev;
784 struct PendingMessage *pm;
787 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
788 "Disconnecting from `%4s' at %s.\n",
789 GNUNET_i2s (&session->target),
790 (session->connect_addr !=
791 NULL) ? tcp_address_to_string (session->plugin,
792 session->connect_addr,
793 session->connect_alen) :
796 /* remove from session list */
798 pos = session->plugin->sessions;
799 while (pos != session)
805 session->plugin->sessions = session->next;
807 prev->next = session->next;
810 if (session->transmit_handle != NULL)
812 GNUNET_CONNECTION_notify_transmit_ready_cancel (session->transmit_handle);
813 session->transmit_handle = NULL;
815 session->plugin->env->session_end (session->plugin->env->cls,
816 &session->target, session);
817 while (NULL != (pm = session->pending_messages_head))
820 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
822 NULL ? "Could not deliver message to `%4s'.\n" :
823 "Could not deliver message to `%4s', notifying.\n",
824 GNUNET_i2s (&session->target));
826 GNUNET_STATISTICS_update (session->plugin->env->stats,
827 gettext_noop ("# bytes currently in TCP buffers"),
828 -(int64_t) pm->message_size, GNUNET_NO);
829 GNUNET_STATISTICS_update (session->plugin->env->stats,
831 ("# bytes discarded by TCP (disconnect)"),
832 pm->message_size, GNUNET_NO);
833 GNUNET_CONTAINER_DLL_remove (session->pending_messages_head,
834 session->pending_messages_tail, pm);
835 if (NULL != pm->transmit_cont)
836 pm->transmit_cont (pm->transmit_cont_cls, &session->target,
840 GNUNET_break (session->client != NULL);
841 if (session->receive_delay_task != GNUNET_SCHEDULER_NO_TASK)
843 GNUNET_SCHEDULER_cancel (session->receive_delay_task);
844 if (session->client != NULL)
845 GNUNET_SERVER_receive_done (session->client, GNUNET_SYSERR);
847 if (session->client != NULL)
849 GNUNET_SERVER_client_drop (session->client);
850 session->client = NULL;
852 GNUNET_STATISTICS_update (session->plugin->env->stats,
853 gettext_noop ("# TCP sessions active"), -1,
855 GNUNET_free_non_null (session->connect_addr);
856 GNUNET_assert (NULL == session->transmit_handle);
857 GNUNET_free (session);
862 * Given two otherwise equivalent sessions, pick the better one.
864 * @param s1 one session (also default)
865 * @param s2 other session
866 * @return "better" session (more active)
868 static struct Session *
869 select_better_session (struct Session *s1, struct Session *s2)
875 if ((s1->expecting_welcome == GNUNET_NO) &&
876 (s2->expecting_welcome == GNUNET_YES))
878 if ((s1->expecting_welcome == GNUNET_YES) &&
879 (s2->expecting_welcome == GNUNET_NO))
881 if (s1->last_activity.abs_value < s2->last_activity.abs_value)
883 if (s1->last_activity.abs_value > s2->last_activity.abs_value)
885 if ((GNUNET_YES == s1->inbound) && (GNUNET_NO == s2->inbound))
887 if ((GNUNET_NO == s1->inbound) && (GNUNET_YES == s2->inbound))
895 * Function that can be used by the transport service to transmit
896 * a message using the plugin. Note that in the case of a
897 * peer disconnecting, the continuation MUST be called
898 * prior to the disconnect notification itself. This function
899 * will be called with this peer's HELLO message to initiate
900 * a fresh connection to another peer.
903 * @param target who should receive this message
904 * @param msg the message to transmit
905 * @param msgbuf_size number of bytes in 'msg'
906 * @param priority how important is the message (most plugins will
907 * ignore message priority and just FIFO)
908 * @param timeout how long to wait at most for the transmission (does not
909 * require plugins to discard the message after the timeout,
910 * just advisory for the desired delay; most plugins will ignore
912 * @param session which session must be used (or NULL for "any")
913 * @param addr the address to use (can be NULL if the plugin
914 * is "on its own" (i.e. re-use existing TCP connection))
915 * @param addrlen length of the address in bytes
916 * @param force_address GNUNET_YES if the plugin MUST use the given address,
917 * GNUNET_NO means the plugin may use any other address and
918 * GNUNET_SYSERR means that only reliable existing
919 * bi-directional connections should be used (regardless
921 * @param cont continuation to call once the message has
922 * been transmitted (or if the transport is ready
923 * for the next transmission call; or if the
924 * peer disconnected...); can be NULL
925 * @param cont_cls closure for cont
926 * @return number of bytes used (on the physical network, with overheads);
927 * -1 on hard errors (i.e. address invalid); 0 is a legal value
928 * and does NOT mean that the message was not transmitted (DV and NAT)
931 tcp_plugin_send (void *cls, const struct GNUNET_PeerIdentity *target,
932 const char *msg, size_t msgbuf_size, uint32_t priority,
933 struct GNUNET_TIME_Relative timeout, struct Session *session,
934 const void *addr, size_t addrlen, int force_address,
935 GNUNET_TRANSPORT_TransmitContinuation cont, void *cont_cls)
937 struct Plugin *plugin = cls;
938 struct Session *cand_session;
939 struct Session *next;
940 struct PendingMessage *pm;
941 struct GNUNET_CONNECTION_Handle *sa;
945 struct sockaddr_in a4;
946 struct sockaddr_in6 a6;
947 const struct IPv4TcpAddress *t4;
948 const struct IPv6TcpAddress *t6;
949 unsigned int is_natd;
951 GNUNET_STATISTICS_update (plugin->env->stats,
952 gettext_noop ("# bytes TCP was asked to transmit"),
953 msgbuf_size, GNUNET_NO);
954 /* FIXME: we could do this cheaper with a hash table
955 * where we could restrict the iteration to entries that match
956 * the target peer... */
961 next = plugin->sessions;
962 while (NULL != (session = next))
964 next = session->next;
965 GNUNET_assert (session->client != NULL);
967 memcmp (target, &session->target,
968 sizeof (struct GNUNET_PeerIdentity)))
970 if (((GNUNET_SYSERR == force_address) &&
971 (session->expecting_welcome == GNUNET_NO)) ||
972 (GNUNET_NO == force_address))
974 cand_session = select_better_session (cand_session, session);
977 if (GNUNET_SYSERR == force_address)
979 GNUNET_break (GNUNET_YES == force_address);
985 if ((addrlen != session->connect_alen) && (session->is_nat == GNUNET_NO))
987 if ((0 != memcmp (session->connect_addr, addr, addrlen)) &&
988 (session->is_nat == GNUNET_NO))
990 cand_session = select_better_session (cand_session, session);
992 session = cand_session;
994 if ((session == NULL) && (addrlen == 0))
997 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
998 "Asked to transmit to `%4s' without address and I have no existing connection (failing).\n",
999 GNUNET_i2s (target));
1001 GNUNET_STATISTICS_update (plugin->env->stats,
1003 ("# bytes discarded by TCP (no address and no connection)"),
1004 msgbuf_size, GNUNET_NO);
1007 if (session == NULL)
1009 if (addrlen == sizeof (struct IPv6TcpAddress))
1011 GNUNET_assert (NULL != addr); /* make static analysis happy */
1014 memset (&a6, 0, sizeof (a6));
1015 #if HAVE_SOCKADDR_IN_SIN_LEN
1016 a6.sin6_len = sizeof (a6);
1018 a6.sin6_family = AF_INET6;
1019 a6.sin6_port = t6->t6_port;
1020 if (t6->t6_port == 0)
1021 is_natd = GNUNET_YES;
1022 memcpy (&a6.sin6_addr, &t6->ipv6_addr, sizeof (struct in6_addr));
1026 else if (addrlen == sizeof (struct IPv4TcpAddress))
1028 GNUNET_assert (NULL != addr); /* make static analysis happy */
1031 memset (&a4, 0, sizeof (a4));
1032 #if HAVE_SOCKADDR_IN_SIN_LEN
1033 a4.sin_len = sizeof (a4);
1035 a4.sin_family = AF_INET;
1036 a4.sin_port = t4->t4_port;
1037 if (t4->t4_port == 0)
1038 is_natd = GNUNET_YES;
1039 a4.sin_addr.s_addr = t4->ipv4_addr;
1045 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, "tcp",
1046 _("Address of unexpected length: %u\n"), addrlen);
1051 if ((is_natd == GNUNET_YES) && (addrlen == sizeof (struct IPv6TcpAddress)))
1052 return -1; /* NAT client only works with IPv4 addresses */
1053 if (0 == plugin->max_connections)
1054 return -1; /* saturated */
1056 if ((is_natd == GNUNET_YES) && (NULL != plugin->nat) &&
1058 GNUNET_CONTAINER_multihashmap_contains (plugin->nat_wait_conns,
1059 &target->hashPubKey)))
1062 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1063 _("Found valid IPv4 NAT address (creating session)!\n"));
1065 session = create_session (plugin, target, NULL, GNUNET_YES);
1066 GNUNET_assert (session != NULL);
1068 /* create new message entry */
1069 pm = GNUNET_malloc (sizeof (struct PendingMessage) + msgbuf_size);
1070 /* FIXME: the memset of this malloc can be up to 2% of our total runtime */
1071 pm->msg = (const char *) &pm[1];
1072 memcpy (&pm[1], msg, msgbuf_size);
1073 /* FIXME: this memcpy can be up to 7% of our total run-time
1074 * (for transport service) */
1075 pm->message_size = msgbuf_size;
1076 pm->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1077 pm->transmit_cont = cont;
1078 pm->transmit_cont_cls = cont_cls;
1080 /* append pm to pending_messages list */
1081 GNUNET_CONTAINER_DLL_insert_tail (session->pending_messages_head,
1082 session->pending_messages_tail, pm);
1084 GNUNET_assert (GNUNET_CONTAINER_multihashmap_put
1085 (plugin->nat_wait_conns, &target->hashPubKey, session,
1086 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY) ==
1089 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1090 "Created NAT WAIT connection to `%4s' at `%s'\n",
1091 GNUNET_i2s (target), GNUNET_a2s (sb, sbs));
1093 GNUNET_NAT_run_client (plugin->nat, &a4);
1096 if ((is_natd == GNUNET_YES) &&
1098 GNUNET_CONTAINER_multihashmap_contains (plugin->nat_wait_conns,
1099 &target->hashPubKey)))
1101 /* Only do one NAT punch attempt per peer identity */
1104 sa = GNUNET_CONNECTION_create_from_sockaddr (af, sb, sbs);
1108 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1109 "Failed to create connection to `%4s' at `%s'\n",
1110 GNUNET_i2s (target), GNUNET_a2s (sb, sbs));
1112 GNUNET_STATISTICS_update (plugin->env->stats,
1114 ("# bytes discarded by TCP (failed to connect)"),
1115 msgbuf_size, GNUNET_NO);
1118 GNUNET_assert (0 != plugin->max_connections);
1119 plugin->max_connections--;
1121 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1122 "Asked to transmit to `%4s', creating fresh session using address `%s'.\n",
1123 GNUNET_i2s (target), GNUNET_a2s (sb, sbs));
1126 create_session (plugin, target,
1127 GNUNET_SERVER_connect_socket (plugin->server, sa),
1129 session->connect_addr = GNUNET_malloc (addrlen);
1130 memcpy (session->connect_addr, addr, addrlen);
1131 session->connect_alen = addrlen;
1134 struct GNUNET_ATS_Information ats;
1135 ats = plugin->env->get_address_type (plugin->env->cls, sb ,sbs);
1136 session->ats_address_network_type = ats.value;
1141 else /* session != NULL */
1143 /* check if session is valid */
1144 struct Session *ses = plugin->sessions;
1147 memcmp (target, &session->target, sizeof (struct GNUNET_PeerIdentity)))
1150 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1151 "Got session %p for `%s', but should be for peer `%s'!\n",
1152 session, GNUNET_i2s (&session->target),
1153 GNUNET_h2s (&target->hashPubKey));
1157 while ((ses != NULL) && (ses != session))
1164 GNUNET_assert (session != NULL);
1165 GNUNET_assert (session->client != NULL);
1166 GNUNET_SERVER_client_set_timeout (session->client,
1167 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1168 GNUNET_STATISTICS_update (plugin->env->stats,
1169 gettext_noop ("# bytes currently in TCP buffers"),
1170 msgbuf_size, GNUNET_NO);
1171 /* create new message entry */
1172 pm = GNUNET_malloc (sizeof (struct PendingMessage) + msgbuf_size);
1173 pm->msg = (const char *) &pm[1];
1174 memcpy (&pm[1], msg, msgbuf_size);
1175 pm->message_size = msgbuf_size;
1176 pm->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1177 pm->transmit_cont = cont;
1178 pm->transmit_cont_cls = cont_cls;
1180 /* append pm to pending_messages list */
1181 GNUNET_CONTAINER_DLL_insert_tail (session->pending_messages_head,
1182 session->pending_messages_tail, pm);
1184 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1185 "Asked to transmit %u bytes to `%s', added message to list.\n",
1186 msgbuf_size, GNUNET_i2s (target));
1188 process_pending_messages (session);
1193 * Function that can be used by the transport service to transmit
1194 * a message using the plugin. Note that in the case of a
1195 * peer disconnecting, the continuation MUST be called
1196 * prior to the disconnect notification itself. This function
1197 * will be called with this peer's HELLO message to initiate
1198 * a fresh connection to another peer.
1200 * @param cls closure
1201 * @param target who should receive this message
1202 * @param msg the message to transmit
1203 * @param msgbuf_size number of bytes in 'msg'
1204 * @param priority how important is the message (most plugins will
1205 * ignore message priority and just FIFO)
1206 * @param timeout how long to wait at most for the transmission (does not
1207 * require plugins to discard the message after the timeout,
1208 * just advisory for the desired delay; most plugins will ignore
1210 * @param session which session must be used (or NULL for "any")
1211 * @param addr the address to use (can be NULL if the plugin
1212 * is "on its own" (i.e. re-use existing TCP connection))
1213 * @param addrlen length of the address in bytes
1214 * @param force_address GNUNET_YES if the plugin MUST use the given address,
1215 * GNUNET_NO means the plugin may use any other address and
1216 * GNUNET_SYSERR means that only reliable existing
1217 * bi-directional connections should be used (regardless
1219 * @param cont continuation to call once the message has
1220 * been transmitted (or if the transport is ready
1221 * for the next transmission call; or if the
1222 * peer disconnected...); can be NULL
1223 * @param cont_cls closure for cont
1224 * @return number of bytes used (on the physical network, with overheads);
1225 * -1 on hard errors (i.e. address invalid); 0 is a legal value
1226 * and does NOT mean that the message was not transmitted (DV and NAT)
1229 tcp_plugin_send_new (void *cls,
1231 GNUNET_PeerIdentity *
1236 struct GNUNET_TIME_Relative timeout,
1237 struct Session * session,
1238 GNUNET_TRANSPORT_TransmitContinuation
1239 cont, void *cont_cls)
1241 struct Plugin * plugin = cls;
1242 struct PendingMessage *pm;
1244 GNUNET_assert (session != NULL);
1245 GNUNET_assert (session->client != NULL);
1247 GNUNET_SERVER_client_set_timeout (session->client,
1248 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1249 GNUNET_STATISTICS_update (plugin->env->stats,
1250 gettext_noop ("# bytes currently in TCP buffers"),
1251 msgbuf_size, GNUNET_NO);
1252 /* create new message entry */
1253 pm = GNUNET_malloc (sizeof (struct PendingMessage) + msgbuf_size);
1254 pm->msg = (const char *) &pm[1];
1255 memcpy (&pm[1], msg, msgbuf_size);
1256 pm->message_size = msgbuf_size;
1257 pm->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1258 pm->transmit_cont = cont;
1259 pm->transmit_cont_cls = cont_cls;
1261 /* append pm to pending_messages list */
1262 GNUNET_CONTAINER_DLL_insert_tail (session->pending_messages_head,
1263 session->pending_messages_tail, pm);
1265 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1266 "Asked to transmit %u bytes to `%s', added message to list.\n",
1267 msgbuf_size, GNUNET_i2s (target));
1269 process_pending_messages (session);
1277 struct Session * result;
1280 int session_it (void *cls,
1281 const GNUNET_HashCode * key,
1284 struct SessionItCtx * si_ctx = cls;
1285 struct Session * session = value;
1287 if (session->connect_alen != si_ctx->addrlen)
1289 if (0 != memcmp (&session->connect_addr, si_ctx->addr, si_ctx->addrlen))
1292 /* Found existing session */
1293 si_ctx->result = session;
1299 * Create a new session to transmit data to the target
1300 * This session will used to send data to this peer and the plugin will
1301 * notify us by calling the env->session_end function
1303 * @param cls closure
1304 * @param target the neighbour id
1305 * @param addr pointer to the address
1306 * @param addrlen length of addr
1307 * @return the session if the address is valid, NULL otherwise
1309 const void * tcp_plugin_create_session (void *cls,
1310 const struct GNUNET_PeerIdentity *target,
1314 struct Plugin * plugin = cls;
1315 struct Session * session = NULL;
1320 struct GNUNET_CONNECTION_Handle *sa;
1321 struct sockaddr_in a4;
1322 struct sockaddr_in6 a6;
1323 const struct IPv4TcpAddress *t4;
1324 const struct IPv6TcpAddress *t6;
1325 unsigned int is_natd;
1327 if (addrlen == sizeof (struct IPv6TcpAddress))
1329 GNUNET_assert (NULL != addr); /* make static analysis happy */
1332 memset (&a6, 0, sizeof (a6));
1333 #if HAVE_SOCKADDR_IN_SIN_LEN
1334 a6.sin6_len = sizeof (a6);
1336 a6.sin6_family = AF_INET6;
1337 a6.sin6_port = t6->t6_port;
1338 if (t6->t6_port == 0)
1339 is_natd = GNUNET_YES;
1340 memcpy (&a6.sin6_addr, &t6->ipv6_addr, sizeof (struct in6_addr));
1344 else if (addrlen == sizeof (struct IPv4TcpAddress))
1346 GNUNET_assert (NULL != addr); /* make static analysis happy */
1349 memset (&a4, 0, sizeof (a4));
1350 #if HAVE_SOCKADDR_IN_SIN_LEN
1351 a4.sin_len = sizeof (a4);
1353 a4.sin_family = AF_INET;
1354 a4.sin_port = t4->t4_port;
1355 if (t4->t4_port == 0)
1356 is_natd = GNUNET_YES;
1357 a4.sin_addr.s_addr = t4->ipv4_addr;
1363 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, "tcp",
1364 _("Address of unexpected length: %u\n"), addrlen);
1369 /* look for existing session */
1370 if (GNUNET_CONTAINER_multihashmap_contains(plugin->sessionmap, &target->hashPubKey))
1372 struct SessionItCtx si_ctx;
1374 si_ctx.addrlen = sbs;
1375 GNUNET_CONTAINER_multihashmap_get_multiple(plugin->sessionmap, &target->hashPubKey, &session_it, &si_ctx);
1376 if (si_ctx.result != NULL)
1377 session = si_ctx.result;
1381 if ((is_natd == GNUNET_YES) && (addrlen == sizeof (struct IPv6TcpAddress)))
1382 return NULL; /* NAT client only works with IPv4 addresses */
1384 if (0 == plugin->max_connections)
1385 return NULL; /* saturated */
1387 if ((is_natd == GNUNET_YES) &&
1389 GNUNET_CONTAINER_multihashmap_contains (plugin->nat_wait_conns,
1390 &target->hashPubKey)))
1391 return NULL; /* Only do one NAT punch attempt per peer identity */
1393 if ((is_natd == GNUNET_YES) && (NULL != plugin->nat) &&
1395 GNUNET_CONTAINER_multihashmap_contains (plugin->nat_wait_conns,
1396 &target->hashPubKey)))
1399 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1400 _("Found valid IPv4 NAT address (creating session)!\n"));
1402 session = create_session (plugin, target, NULL, GNUNET_YES);
1403 GNUNET_assert (session != NULL);
1405 GNUNET_assert (GNUNET_CONTAINER_multihashmap_put
1406 (plugin->nat_wait_conns, &target->hashPubKey, session,
1407 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY) == GNUNET_OK);
1409 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1410 "Created NAT WAIT connection to `%4s' at `%s'\n",
1411 GNUNET_i2s (target), GNUNET_a2s (sb, sbs));
1413 GNUNET_NAT_run_client (plugin->nat, &a4);
1417 /* create new outbound session */
1418 GNUNET_assert (0 != plugin->max_connections);
1419 sa = GNUNET_CONNECTION_create_from_sockaddr (af, sb, sbs);
1423 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1424 "Failed to create connection to `%4s' at `%s'\n",
1425 GNUNET_i2s (target), GNUNET_a2s (sb, sbs));
1429 plugin->max_connections--;
1431 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1432 "Asked to transmit to `%4s', creating fresh session using address `%s'.\n",
1433 GNUNET_i2s (target), GNUNET_a2s (sb, sbs));
1435 session = create_session (plugin,
1437 GNUNET_SERVER_connect_socket (plugin->server, sa),
1439 session->connect_addr = GNUNET_malloc (addrlen);
1440 memcpy (session->connect_addr, addr, addrlen);
1441 session->connect_alen = addrlen;
1444 struct GNUNET_ATS_Information ats;
1445 ats = plugin->env->get_address_type (plugin->env->cls, sb ,sbs);
1446 session->ats_address_network_type = ats.value;
1451 GNUNET_CONTAINER_multihashmap_put(plugin->sessionmap, &target->hashPubKey, session, GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
1453 /* Send TCP Welcome */
1454 process_pending_messages (session);
1461 * Function that can be called to force a disconnect from the
1462 * specified neighbour. This should also cancel all previously
1463 * scheduled transmissions. Obviously the transmission may have been
1464 * partially completed already, which is OK. The plugin is supposed
1465 * to close the connection (if applicable) and no longer call the
1466 * transmit continuation(s).
1468 * Finally, plugin MUST NOT call the services's receive function to
1469 * notify the service that the connection to the specified target was
1470 * closed after a getting this call.
1472 * @param cls closure
1473 * @param target peer for which the last transmission is
1477 tcp_plugin_disconnect (void *cls, const struct GNUNET_PeerIdentity *target)
1479 struct Plugin *plugin = cls;
1480 struct Session *session;
1481 struct Session *next;
1482 struct PendingMessage *pm;
1485 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1486 "Asked to cancel session with `%4s'\n", GNUNET_i2s (target));
1488 next = plugin->sessions;
1489 while (NULL != (session = next))
1491 next = session->next;
1493 memcmp (target, &session->target, sizeof (struct GNUNET_PeerIdentity)))
1495 pm = session->pending_messages_head;
1498 pm->transmit_cont = NULL;
1499 pm->transmit_cont_cls = NULL;
1502 GNUNET_STATISTICS_update (session->plugin->env->stats,
1504 ("# transport-service disconnect requests for TCP"),
1506 disconnect_session (session);
1512 * Context for address to string conversion.
1514 struct PrettyPrinterContext
1517 * Function to call with the result.
1519 GNUNET_TRANSPORT_AddressStringCallback asc;
1522 * Clsoure for 'asc'.
1527 * Port to add after the IP address.
1534 * Append our port and forward the result.
1536 * @param cls the 'struct PrettyPrinterContext*'
1537 * @param hostname hostname part of the address
1540 append_port (void *cls, const char *hostname)
1542 struct PrettyPrinterContext *ppc = cls;
1545 if (hostname == NULL)
1547 ppc->asc (ppc->asc_cls, NULL);
1551 GNUNET_asprintf (&ret, "%s:%d", hostname, ppc->port);
1552 ppc->asc (ppc->asc_cls, ret);
1558 * Convert the transports address to a nice, human-readable
1561 * @param cls closure
1562 * @param type name of the transport that generated the address
1563 * @param addr one of the addresses of the host, NULL for the last address
1564 * the specific address format depends on the transport
1565 * @param addrlen length of the address
1566 * @param numeric should (IP) addresses be displayed in numeric form?
1567 * @param timeout after how long should we give up?
1568 * @param asc function to call on each string
1569 * @param asc_cls closure for asc
1572 tcp_plugin_address_pretty_printer (void *cls, const char *type,
1573 const void *addr, size_t addrlen,
1575 struct GNUNET_TIME_Relative timeout,
1576 GNUNET_TRANSPORT_AddressStringCallback asc,
1579 struct PrettyPrinterContext *ppc;
1582 struct sockaddr_in a4;
1583 struct sockaddr_in6 a6;
1584 const struct IPv4TcpAddress *t4;
1585 const struct IPv6TcpAddress *t6;
1588 if (addrlen == sizeof (struct IPv6TcpAddress))
1591 memset (&a6, 0, sizeof (a6));
1592 a6.sin6_family = AF_INET6;
1593 a6.sin6_port = t6->t6_port;
1594 memcpy (&a6.sin6_addr, &t6->ipv6_addr, sizeof (struct in6_addr));
1595 port = ntohs (t6->t6_port);
1599 else if (addrlen == sizeof (struct IPv4TcpAddress))
1602 memset (&a4, 0, sizeof (a4));
1603 a4.sin_family = AF_INET;
1604 a4.sin_port = t4->t4_port;
1605 a4.sin_addr.s_addr = t4->ipv4_addr;
1606 port = ntohs (t4->t4_port);
1612 /* invalid address */
1613 GNUNET_break_op (0);
1614 asc (asc_cls, NULL);
1617 ppc = GNUNET_malloc (sizeof (struct PrettyPrinterContext));
1619 ppc->asc_cls = asc_cls;
1621 GNUNET_RESOLVER_hostname_get (sb, sbs, !numeric, timeout, &append_port, ppc);
1626 * Check if the given port is plausible (must be either our listen
1627 * port or our advertised port), or any port if we are behind NAT
1628 * and do not have a port open. If it is neither, we return
1631 * @param plugin global variables
1632 * @param in_port port number to check
1633 * @return GNUNET_OK if port is either open_port or adv_port
1636 check_port (struct Plugin *plugin, uint16_t in_port)
1638 if ((in_port == plugin->adv_port) || (in_port == plugin->open_port))
1640 return GNUNET_SYSERR;
1645 * Function that will be called to check if a binary address for this
1646 * plugin is well-formed and corresponds to an address for THIS peer
1647 * (as per our configuration). Naturally, if absolutely necessary,
1648 * plugins can be a bit conservative in their answer, but in general
1649 * plugins should make sure that the address does not redirect
1650 * traffic to a 3rd party that might try to man-in-the-middle our
1653 * @param cls closure, our 'struct Plugin*'
1654 * @param addr pointer to the address
1655 * @param addrlen length of addr
1656 * @return GNUNET_OK if this is a plausible address for this peer
1657 * and transport, GNUNET_SYSERR if not
1660 tcp_plugin_check_address (void *cls, const void *addr, size_t addrlen)
1662 struct Plugin *plugin = cls;
1663 struct IPv4TcpAddress *v4;
1664 struct IPv6TcpAddress *v6;
1666 if ((addrlen != sizeof (struct IPv4TcpAddress)) &&
1667 (addrlen != sizeof (struct IPv6TcpAddress)))
1669 GNUNET_break_op (0);
1670 return GNUNET_SYSERR;
1672 if (addrlen == sizeof (struct IPv4TcpAddress))
1674 v4 = (struct IPv4TcpAddress *) addr;
1675 if (GNUNET_OK != check_port (plugin, ntohs (v4->t4_port)))
1676 return GNUNET_SYSERR;
1678 GNUNET_NAT_test_address (plugin->nat, &v4->ipv4_addr,
1679 sizeof (struct in_addr)))
1680 return GNUNET_SYSERR;
1684 v6 = (struct IPv6TcpAddress *) addr;
1685 if (IN6_IS_ADDR_LINKLOCAL (&v6->ipv6_addr))
1687 GNUNET_break_op (0);
1688 return GNUNET_SYSERR;
1690 if (GNUNET_OK != check_port (plugin, ntohs (v6->t6_port)))
1691 return GNUNET_SYSERR;
1693 GNUNET_NAT_test_address (plugin->nat, &v6->ipv6_addr,
1694 sizeof (struct in6_addr)))
1695 return GNUNET_SYSERR;
1702 * We've received a nat probe from this peer via TCP. Finish
1703 * creating the client session and resume sending of queued
1706 * @param cls closure
1707 * @param client identification of the client
1708 * @param message the actual message
1711 handle_tcp_nat_probe (void *cls, struct GNUNET_SERVER_Client *client,
1712 const struct GNUNET_MessageHeader *message)
1714 struct Plugin *plugin = cls;
1715 struct Session *session;
1716 const struct TCP_NAT_ProbeMessage *tcp_nat_probe;
1719 struct IPv4TcpAddress *t4;
1720 struct IPv6TcpAddress *t6;
1721 const struct sockaddr_in *s4;
1722 const struct sockaddr_in6 *s6;
1725 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp", "received NAT probe\n");
1727 /* We have received a TCP NAT probe, meaning we (hopefully) initiated
1728 * a connection to this peer by running gnunet-nat-client. This peer
1729 * received the punch message and now wants us to use the new connection
1730 * as the default for that peer. Do so and then send a WELCOME message
1731 * so we can really be connected!
1733 if (ntohs (message->size) != sizeof (struct TCP_NAT_ProbeMessage))
1735 GNUNET_break_op (0);
1736 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1740 tcp_nat_probe = (const struct TCP_NAT_ProbeMessage *) message;
1742 memcmp (&tcp_nat_probe->clientIdentity, plugin->env->my_identity,
1743 sizeof (struct GNUNET_PeerIdentity)))
1745 /* refuse connections from ourselves */
1746 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1751 GNUNET_CONTAINER_multihashmap_get (plugin->nat_wait_conns,
1753 clientIdentity.hashPubKey);
1754 if (session == NULL)
1757 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1758 "Did NOT find session for NAT probe!\n");
1760 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1764 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1765 "Found session for NAT probe!\n");
1767 GNUNET_assert (GNUNET_CONTAINER_multihashmap_remove
1768 (plugin->nat_wait_conns,
1769 &tcp_nat_probe->clientIdentity.hashPubKey,
1770 session) == GNUNET_YES);
1771 if (GNUNET_OK != GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
1774 GNUNET_free (session);
1775 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1779 GNUNET_SERVER_client_keep (client);
1780 session->client = client;
1781 session->last_activity = GNUNET_TIME_absolute_get ();
1782 session->inbound = GNUNET_NO;
1785 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1786 "Found address `%s' for incoming connection\n",
1787 GNUNET_a2s (vaddr, alen));
1789 switch (((const struct sockaddr *) vaddr)->sa_family)
1793 t4 = GNUNET_malloc (sizeof (struct IPv4TcpAddress));
1794 t4->t4_port = s4->sin_port;
1795 t4->ipv4_addr = s4->sin_addr.s_addr;
1796 session->connect_addr = t4;
1797 session->connect_alen = sizeof (struct IPv4TcpAddress);
1801 t6 = GNUNET_malloc (sizeof (struct IPv6TcpAddress));
1802 t6->t6_port = s6->sin6_port;
1803 memcpy (&t6->ipv6_addr, &s6->sin6_addr, sizeof (struct in6_addr));
1804 session->connect_addr = t6;
1805 session->connect_alen = sizeof (struct IPv6TcpAddress);
1808 GNUNET_break_op (0);
1810 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1811 "Bad address for incoming connection!\n");
1813 GNUNET_free (vaddr);
1814 GNUNET_SERVER_client_drop (client);
1815 GNUNET_free (session);
1816 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1819 GNUNET_free (vaddr);
1821 session->next = plugin->sessions;
1822 plugin->sessions = session;
1823 GNUNET_STATISTICS_update (plugin->env->stats,
1824 gettext_noop ("# TCP sessions active"), 1,
1826 process_pending_messages (session);
1827 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1832 * We've received a welcome from this peer via TCP. Possibly create a
1833 * fresh client record and send back our welcome.
1835 * @param cls closure
1836 * @param client identification of the client
1837 * @param message the actual message
1840 handle_tcp_welcome (void *cls, struct GNUNET_SERVER_Client *client,
1841 const struct GNUNET_MessageHeader *message)
1843 struct Plugin *plugin = cls;
1844 const struct WelcomeMessage *wm = (const struct WelcomeMessage *) message;
1845 struct Session *session;
1848 struct IPv4TcpAddress *t4;
1849 struct IPv6TcpAddress *t6;
1850 const struct sockaddr_in *s4;
1851 const struct sockaddr_in6 *s6;
1854 memcmp (&wm->clientIdentity, plugin->env->my_identity,
1855 sizeof (struct GNUNET_PeerIdentity)))
1857 /* refuse connections from ourselves */
1858 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1862 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1863 "Received %s message from `%4s'.\n", "WELCOME",
1864 GNUNET_i2s (&wm->clientIdentity));
1866 GNUNET_STATISTICS_update (plugin->env->stats,
1867 gettext_noop ("# TCP WELCOME messages received"), 1,
1869 session = find_session_by_client (plugin, client);
1871 if (session == NULL)
1874 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1875 "Received %s message from a `%4s', creating new session\n",
1876 "WELCOME", GNUNET_i2s (&wm->clientIdentity));
1878 GNUNET_SERVER_client_keep (client);
1879 session = create_session (plugin, &wm->clientIdentity, client, GNUNET_NO);
1880 session->inbound = GNUNET_YES;
1881 if (GNUNET_OK == GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
1884 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1885 "Found address `%s' for incoming connection\n",
1886 GNUNET_a2s (vaddr, alen));
1889 if (alen == sizeof (struct sockaddr_in))
1892 t4 = GNUNET_malloc (sizeof (struct IPv4TcpAddress));
1893 t4->t4_port = s4->sin_port;
1894 t4->ipv4_addr = s4->sin_addr.s_addr;
1895 session->connect_addr = t4;
1896 session->connect_alen = sizeof (struct IPv4TcpAddress);
1898 else if (alen == sizeof (struct sockaddr_in6))
1901 t6 = GNUNET_malloc (sizeof (struct IPv6TcpAddress));
1902 t6->t6_port = s6->sin6_port;
1903 memcpy (&t6->ipv6_addr, &s6->sin6_addr, sizeof (struct in6_addr));
1904 session->connect_addr = t6;
1905 session->connect_alen = sizeof (struct IPv6TcpAddress);
1908 struct GNUNET_ATS_Information ats;
1909 ats = plugin->env->get_address_type (plugin->env->cls, vaddr ,alen);
1910 session->ats_address_network_type = ats.value;
1912 GNUNET_free (vaddr);
1917 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1918 "Did not obtain TCP socket address for incoming connection\n");
1921 process_pending_messages (session);
1926 if (GNUNET_OK == GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
1928 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1929 "Found address `%s' (already have session)\n",
1930 GNUNET_a2s (vaddr, alen));
1931 GNUNET_free (vaddr);
1936 if (session->expecting_welcome != GNUNET_YES)
1938 GNUNET_break_op (0);
1939 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1942 session->last_activity = GNUNET_TIME_absolute_get ();
1943 session->expecting_welcome = GNUNET_NO;
1944 GNUNET_SERVER_client_set_timeout (client,
1945 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1946 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1951 * Task to signal the server that we can continue
1952 * receiving from the TCP client now.
1954 * @param cls the 'struct Session*'
1955 * @param tc task context (unused)
1958 delayed_done (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1960 struct Session *session = cls;
1961 struct GNUNET_TIME_Relative delay;
1962 struct GNUNET_ATS_Information ats;
1964 session->receive_delay_task = GNUNET_SCHEDULER_NO_TASK;
1966 session->plugin->env->receive (session->plugin->env->cls,
1967 &session->target, NULL, &ats, 0, session,
1969 if (delay.rel_value == 0)
1970 GNUNET_SERVER_receive_done (session->client, GNUNET_OK);
1972 session->receive_delay_task =
1973 GNUNET_SCHEDULER_add_delayed (delay, &delayed_done, session);
1978 * We've received data for this peer via TCP. Unbox,
1979 * compute latency and forward.
1981 * @param cls closure
1982 * @param client identification of the client
1983 * @param message the actual message
1986 handle_tcp_data (void *cls, struct GNUNET_SERVER_Client *client,
1987 const struct GNUNET_MessageHeader *message)
1989 struct Plugin *plugin = cls;
1990 struct Session *session;
1991 struct GNUNET_TIME_Relative delay;
1994 type = ntohs (message->type);
1995 if ((GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME == type) ||
1996 (GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE == type))
1998 /* We don't want to propagate WELCOME and NAT Probe messages up! */
1999 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2002 session = find_session_by_client (plugin, client);
2003 if ((NULL == session) || (GNUNET_YES == session->expecting_welcome))
2005 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2008 session->last_activity = GNUNET_TIME_absolute_get ();
2010 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
2011 "Passing %u bytes of type %u from `%4s' to transport service.\n",
2012 (unsigned int) ntohs (message->size),
2013 (unsigned int) ntohs (message->type),
2014 GNUNET_i2s (&session->target));
2016 GNUNET_STATISTICS_update (plugin->env->stats,
2017 gettext_noop ("# bytes received via TCP"),
2018 ntohs (message->size), GNUNET_NO);
2019 struct GNUNET_ATS_Information distance[2];
2021 distance[0].type = htonl (GNUNET_ATS_QUALITY_NET_DISTANCE);
2022 distance[0].value = htonl (1);
2023 distance[1].type = htonl (GNUNET_ATS_NETWORK_TYPE);
2024 distance[1].value = session->ats_address_network_type;
2025 GNUNET_break (ntohl(session->ats_address_network_type) != GNUNET_ATS_NET_UNSPECIFIED);
2028 plugin->env->receive (plugin->env->cls, &session->target, message,
2029 (const struct GNUNET_ATS_Information *) &distance,
2032 session->inbound) ? NULL : session->connect_addr,
2034 session->inbound) ? 0 : session->connect_alen);
2035 if (delay.rel_value == 0)
2037 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2042 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
2043 "Throttling receiving from `%s' for %llu ms\n",
2044 GNUNET_i2s (&session->target),
2045 (unsigned long long) delay.rel_value);
2047 GNUNET_SERVER_disable_receive_done_warning (client);
2048 session->receive_delay_task =
2049 GNUNET_SCHEDULER_add_delayed (delay, &delayed_done, session);
2055 * Functions with this signature are called whenever a peer
2056 * is disconnected on the network level.
2058 * @param cls closure
2059 * @param client identification of the client
2062 disconnect_notify (void *cls, struct GNUNET_SERVER_Client *client)
2064 struct Plugin *plugin = cls;
2065 struct Session *session;
2069 plugin->max_connections++;
2070 session = find_session_by_client (plugin, client);
2071 if (session == NULL)
2072 return; /* unknown, nothing to do */
2074 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
2075 "Destroying session of `%4s' with %s due to network-level disconnect.\n",
2076 GNUNET_i2s (&session->target),
2077 (session->connect_addr !=
2078 NULL) ? tcp_address_to_string (session->plugin,
2079 session->connect_addr,
2080 session->connect_alen) :
2083 GNUNET_STATISTICS_update (session->plugin->env->stats,
2085 ("# network-level TCP disconnect events"), 1,
2087 disconnect_session (session);
2092 * We can now send a probe message, copy into buffer to really send.
2094 * @param cls closure, a struct TCPProbeContext
2095 * @param size max size to copy
2096 * @param buf buffer to copy message to
2097 * @return number of bytes copied into buf
2100 notify_send_probe (void *cls, size_t size, void *buf)
2102 struct TCPProbeContext *tcp_probe_ctx = cls;
2103 struct Plugin *plugin = tcp_probe_ctx->plugin;
2106 tcp_probe_ctx->transmit_handle = NULL;
2107 GNUNET_CONTAINER_DLL_remove (plugin->probe_head, plugin->probe_tail,
2111 GNUNET_CONNECTION_destroy (tcp_probe_ctx->sock, GNUNET_NO);
2112 GNUNET_free (tcp_probe_ctx);
2115 GNUNET_assert (size >= sizeof (tcp_probe_ctx->message));
2116 memcpy (buf, &tcp_probe_ctx->message, sizeof (tcp_probe_ctx->message));
2117 GNUNET_SERVER_connect_socket (tcp_probe_ctx->plugin->server,
2118 tcp_probe_ctx->sock);
2119 ret = sizeof (tcp_probe_ctx->message);
2120 GNUNET_free (tcp_probe_ctx);
2126 * Function called by the NAT subsystem suggesting another peer wants
2127 * to connect to us via connection reversal. Try to connect back to the
2130 * @param cls closure
2131 * @param addr address to try
2132 * @param addrlen number of bytes in addr
2135 try_connection_reversal (void *cls, const struct sockaddr *addr,
2138 struct Plugin *plugin = cls;
2139 struct GNUNET_CONNECTION_Handle *sock;
2140 struct TCPProbeContext *tcp_probe_ctx;
2143 * We have received an ICMP response, ostensibly from a peer
2144 * that wants to connect to us! Send a message to establish a connection.
2146 sock = GNUNET_CONNECTION_create_from_sockaddr (AF_INET, addr, addrlen);
2149 /* failed for some odd reason (out of sockets?); ignore attempt */
2153 /* FIXME: do we need to track these probe context objects so that
2154 * we can clean them up on plugin unload? */
2155 tcp_probe_ctx = GNUNET_malloc (sizeof (struct TCPProbeContext));
2156 tcp_probe_ctx->message.header.size =
2157 htons (sizeof (struct TCP_NAT_ProbeMessage));
2158 tcp_probe_ctx->message.header.type =
2159 htons (GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE);
2160 memcpy (&tcp_probe_ctx->message.clientIdentity, plugin->env->my_identity,
2161 sizeof (struct GNUNET_PeerIdentity));
2162 tcp_probe_ctx->plugin = plugin;
2163 tcp_probe_ctx->sock = sock;
2164 GNUNET_CONTAINER_DLL_insert (plugin->probe_head, plugin->probe_tail,
2166 tcp_probe_ctx->transmit_handle =
2167 GNUNET_CONNECTION_notify_transmit_ready (sock,
2168 ntohs (tcp_probe_ctx->
2169 message.header.size),
2170 GNUNET_TIME_UNIT_FOREVER_REL,
2178 * Entry point for the plugin.
2180 * @param cls closure, the 'struct GNUNET_TRANSPORT_PluginEnvironment*'
2181 * @return the 'struct GNUNET_TRANSPORT_PluginFunctions*' or NULL on error
2184 libgnunet_plugin_transport_tcp_init (void *cls)
2186 static const struct GNUNET_SERVER_MessageHandler my_handlers[] = {
2187 {&handle_tcp_welcome, NULL, GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME,
2188 sizeof (struct WelcomeMessage)},
2189 {&handle_tcp_nat_probe, NULL, GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE,
2190 sizeof (struct TCP_NAT_ProbeMessage)},
2191 {&handle_tcp_data, NULL, GNUNET_MESSAGE_TYPE_ALL, 0},
2194 struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
2195 struct GNUNET_TRANSPORT_PluginFunctions *api;
2196 struct Plugin *plugin;
2197 struct GNUNET_SERVICE_Context *service;
2198 unsigned long long aport;
2199 unsigned long long bport;
2200 unsigned long long max_connections;
2202 struct GNUNET_TIME_Relative idle_timeout;
2204 struct sockaddr **addrs;
2205 socklen_t *addrlens;
2208 GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-tcp",
2211 max_connections = 128;
2215 GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-tcp", "PORT",
2216 &bport)) || (bport > 65535) ||
2218 GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-tcp",
2219 "ADVERTISED-PORT", &aport)) &&
2222 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, "tcp",
2224 ("Require valid port number for service `%s' in configuration!\n"),
2234 service = GNUNET_SERVICE_start ("transport-tcp", env->cfg);
2235 if (service == NULL)
2237 GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, "tcp",
2238 _("Failed to start service.\n"));
2247 plugin = GNUNET_malloc (sizeof (struct Plugin));
2248 plugin->sessionmap = GNUNET_CONTAINER_multihashmap_create(max_connections);
2249 plugin->max_connections = max_connections;
2250 plugin->open_port = bport;
2251 plugin->adv_port = aport;
2253 plugin->lsock = NULL;
2254 if ((service != NULL) &&
2257 GNUNET_SERVICE_get_server_addresses ("transport-tcp", env->cfg, &addrs,
2261 GNUNET_NAT_register (env->cfg, GNUNET_YES, aport, (unsigned int) ret,
2262 (const struct sockaddr **) addrs, addrlens,
2263 &tcp_nat_port_map_callback,
2264 &try_connection_reversal, plugin);
2268 GNUNET_assert (addrs[ret] != NULL);
2269 GNUNET_free (addrs[ret]);
2271 GNUNET_free_non_null (addrs);
2272 GNUNET_free_non_null (addrlens);
2277 GNUNET_NAT_register (env->cfg, GNUNET_YES, 0, 0, NULL, NULL, NULL,
2278 &try_connection_reversal, plugin);
2280 api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
2282 api->send = &tcp_plugin_send;
2284 api->send_with_session = &tcp_plugin_send_new;
2285 api->create_session = &tcp_plugin_create_session;
2287 api->disconnect = &tcp_plugin_disconnect;
2288 api->address_pretty_printer = &tcp_plugin_address_pretty_printer;
2289 api->check_address = &tcp_plugin_check_address;
2290 api->address_to_string = &tcp_address_to_string;
2291 plugin->service = service;
2292 if (service != NULL)
2294 plugin->server = GNUNET_SERVICE_get_server (service);
2299 GNUNET_CONFIGURATION_get_value_time (env->cfg, "transport-tcp",
2300 "TIMEOUT", &idle_timeout))
2302 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, "tcp",
2303 _("Failed to find option %s in section %s!\n"),
2304 "TIMEOUT", "transport-tcp");
2305 if (plugin->nat != NULL)
2306 GNUNET_NAT_unregister (plugin->nat);
2307 GNUNET_free (plugin);
2312 GNUNET_SERVER_create_with_sockets (&plugin_tcp_access_check, plugin,
2313 NULL, idle_timeout, GNUNET_YES);
2315 plugin->handlers = GNUNET_malloc (sizeof (my_handlers));
2316 memcpy (plugin->handlers, my_handlers, sizeof (my_handlers));
2318 i < sizeof (my_handlers) / sizeof (struct GNUNET_SERVER_MessageHandler);
2320 plugin->handlers[i].callback_cls = plugin;
2321 GNUNET_SERVER_add_handlers (plugin->server, plugin->handlers);
2322 GNUNET_SERVER_disconnect_notify (plugin->server, &disconnect_notify, plugin);
2323 plugin->nat_wait_conns = GNUNET_CONTAINER_multihashmap_create (16);
2325 GNUNET_log_from (GNUNET_ERROR_TYPE_INFO, "tcp",
2326 _("TCP transport listening on port %llu\n"), bport);
2328 GNUNET_log_from (GNUNET_ERROR_TYPE_INFO, "tcp",
2330 ("TCP transport not listening on any port (client only)\n"));
2332 GNUNET_log_from (GNUNET_ERROR_TYPE_INFO, "tcp",
2334 ("TCP transport advertises itself as being on port %llu\n"),
2341 * Exit point from the plugin.
2344 libgnunet_plugin_transport_tcp_done (void *cls)
2346 struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
2347 struct Plugin *plugin = api->cls;
2348 struct Session *session;
2349 struct TCPProbeContext *tcp_probe;
2351 while (NULL != (session = plugin->sessions))
2352 disconnect_session (session);
2353 if (plugin->service != NULL)
2354 GNUNET_SERVICE_stop (plugin->service);
2356 GNUNET_SERVER_destroy (plugin->server);
2357 GNUNET_free (plugin->handlers);
2358 if (plugin->nat != NULL)
2359 GNUNET_NAT_unregister (plugin->nat);
2360 while (NULL != (tcp_probe = plugin->probe_head))
2362 GNUNET_CONTAINER_DLL_remove (plugin->probe_head, plugin->probe_tail,
2364 GNUNET_CONNECTION_destroy (tcp_probe->sock, GNUNET_NO);
2365 GNUNET_free (tcp_probe);
2367 GNUNET_CONTAINER_multihashmap_destroy (plugin->nat_wait_conns);
2368 GNUNET_CONTAINER_multihashmap_destroy (plugin->sessionmap);
2369 GNUNET_free (plugin);
2374 /* end of plugin_transport_tcp.c */