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_NO
44 #define DEBUG_TCP_NAT GNUNET_NO
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?
302 * Encapsulation of all of the state of the plugin.
309 struct GNUNET_TRANSPORT_PluginEnvironment *env;
314 struct GNUNET_CONNECTION_Handle *lsock;
317 * Our handle to the NAT module.
319 struct GNUNET_NAT_Handle *nat;
322 * List of open TCP sessions.
324 struct Session *sessions;
327 * Handle to the network service.
329 struct GNUNET_SERVICE_Context *service;
332 * Handle to the server for this service.
334 struct GNUNET_SERVER_Handle *server;
337 * Copy of the handler array where the closures are
338 * set to this struct's instance.
340 struct GNUNET_SERVER_MessageHandler *handlers;
343 * Map of peers we have tried to contact behind a NAT
345 struct GNUNET_CONTAINER_MultiHashMap *nat_wait_conns;
348 * List of active TCP probes.
350 struct TCPProbeContext *probe_head;
353 * List of active TCP probes.
355 struct TCPProbeContext *probe_tail;
358 * Handle for (DYN)DNS lookup of our external IP.
360 struct GNUNET_RESOLVER_RequestHandle *ext_dns;
363 * How many more TCP sessions are we allowed to open right now?
365 unsigned long long max_connections;
368 * ID of task used to update our addresses when one expires.
370 GNUNET_SCHEDULER_TaskIdentifier address_update_task;
373 * Port that we are actually listening on.
378 * Port that the user said we would have visible to the
387 * Function to check if an inbound connection is acceptable.
388 * Mostly used to limit the total number of open connections
391 * @param cls the 'struct Plugin'
392 * @param ucred credentials, if available, otherwise NULL
393 * @param addr address
394 * @param addrlen length of address
395 * @return GNUNET_YES to allow, GNUNET_NO to deny, GNUNET_SYSERR
396 * for unknown address family (will be denied).
399 plugin_tcp_access_check (void *cls,
400 const struct GNUNET_CONNECTION_Credentials *ucred,
401 const struct sockaddr *addr, socklen_t addrlen)
403 struct Plugin *plugin = cls;
405 if (0 == plugin->max_connections)
407 plugin->max_connections--;
413 * Our external IP address/port mapping has changed.
415 * @param cls closure, the 'struct LocalAddrList'
416 * @param add_remove GNUNET_YES to mean the new public IP address, GNUNET_NO to mean
417 * the previous (now invalid) one
418 * @param addr either the previous or the new public IP address
419 * @param addrlen actual lenght of the address
422 tcp_nat_port_map_callback (void *cls, int add_remove,
423 const struct sockaddr *addr, socklen_t addrlen)
425 struct Plugin *plugin = cls;
426 struct IPv4TcpAddress t4;
427 struct IPv6TcpAddress t6;
431 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
432 "NPMC called with %d for address `%s'\n", add_remove,
433 GNUNET_a2s (addr, addrlen));
434 /* convert 'addr' to our internal format */
435 switch (addr->sa_family)
438 GNUNET_assert (addrlen == sizeof (struct sockaddr_in));
439 t4.ipv4_addr = ((struct sockaddr_in *) addr)->sin_addr.s_addr;
440 t4.t4_port = ((struct sockaddr_in *) addr)->sin_port;
445 GNUNET_assert (addrlen == sizeof (struct sockaddr_in6));
446 memcpy (&t6.ipv6_addr, &((struct sockaddr_in6 *) addr)->sin6_addr,
447 sizeof (struct in6_addr));
448 t6.t6_port = ((struct sockaddr_in6 *) addr)->sin6_port;
456 /* modify our published address list */
457 plugin->env->notify_address (plugin->env->cls, add_remove, arg, args);
462 * Function called for a quick conversion of the binary address to
463 * a numeric address. Note that the caller must not free the
464 * address and that the next call to this function is allowed
465 * to override the address again.
467 * @param cls closure ('struct Plugin*')
468 * @param addr binary address
469 * @param addrlen length of the address
470 * @return string representing the same address
473 tcp_address_to_string (void *cls, const void *addr, size_t addrlen)
475 static char rbuf[INET6_ADDRSTRLEN + 12];
476 char buf[INET6_ADDRSTRLEN];
480 const struct IPv4TcpAddress *t4;
481 const struct IPv6TcpAddress *t6;
485 if (addrlen == sizeof (struct IPv6TcpAddress))
489 port = ntohs (t6->t6_port);
490 memcpy (&a6, &t6->ipv6_addr, sizeof (a6));
493 else if (addrlen == sizeof (struct IPv4TcpAddress))
497 port = ntohs (t4->t4_port);
498 memcpy (&a4, &t4->ipv4_addr, sizeof (a4));
503 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, "tcp",
504 _("Unexpected address length: %u bytes\n"),
505 (unsigned int) addrlen);
509 if (NULL == inet_ntop (af, sb, buf, INET6_ADDRSTRLEN))
511 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "inet_ntop");
514 GNUNET_snprintf (rbuf, sizeof (rbuf), (af == AF_INET6) ? "[%s]:%u" : "%s:%u",
521 * Find the session handle for the given client.
523 * @param plugin the plugin
524 * @param client which client to find the session handle for
525 * @return NULL if no matching session exists
527 static struct Session *
528 find_session_by_client (struct Plugin *plugin,
529 const struct GNUNET_SERVER_Client *client)
533 ret = plugin->sessions;
534 while ((ret != NULL) && (client != ret->client))
541 * Create a new session. Also queues a welcome message.
543 * @param plugin the plugin
544 * @param target peer to connect to
545 * @param client client to use
546 * @param is_nat this a NAT session, we should wait for a client to
547 * connect to us from an address, then assign that to
549 * @return new session object
551 static struct Session *
552 create_session (struct Plugin *plugin, const struct GNUNET_PeerIdentity *target,
553 struct GNUNET_SERVER_Client *client, int is_nat)
556 struct PendingMessage *pm;
557 struct WelcomeMessage welcome;
559 if (is_nat != GNUNET_YES)
560 GNUNET_assert (client != NULL);
562 GNUNET_assert (client == NULL);
564 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
565 "Creating new session for peer `%4s'\n",
566 GNUNET_i2s (target));
568 ret = GNUNET_malloc (sizeof (struct Session));
569 ret->last_activity = GNUNET_TIME_absolute_get ();
570 ret->plugin = plugin;
571 ret->is_nat = is_nat;
572 if (is_nat != GNUNET_YES) /* If not a NAT WAIT conn, add it to global list */
574 ret->next = plugin->sessions;
575 plugin->sessions = ret;
577 ret->client = client;
578 ret->target = *target;
579 ret->expecting_welcome = GNUNET_YES;
580 pm = GNUNET_malloc (sizeof (struct PendingMessage) +
581 sizeof (struct WelcomeMessage));
582 pm->msg = (const char *) &pm[1];
583 pm->message_size = sizeof (struct WelcomeMessage);
584 welcome.header.size = htons (sizeof (struct WelcomeMessage));
585 welcome.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME);
586 welcome.clientIdentity = *plugin->env->my_identity;
587 memcpy (&pm[1], &welcome, sizeof (welcome));
588 pm->timeout = GNUNET_TIME_UNIT_FOREVER_ABS;
589 GNUNET_STATISTICS_update (plugin->env->stats,
590 gettext_noop ("# bytes currently in TCP buffers"),
591 pm->message_size, GNUNET_NO);
592 GNUNET_CONTAINER_DLL_insert (ret->pending_messages_head,
593 ret->pending_messages_tail, pm);
594 if (is_nat != GNUNET_YES)
595 GNUNET_STATISTICS_update (plugin->env->stats,
596 gettext_noop ("# TCP sessions active"), 1,
603 * If we have pending messages, ask the server to
604 * transmit them (schedule the respective tasks, etc.)
606 * @param session for which session should we do this
609 process_pending_messages (struct Session *session);
613 * Function called to notify a client about the socket
614 * being ready to queue more data. "buf" will be
615 * NULL and "size" zero if the socket was closed for
616 * writing in the meantime.
619 * @param size number of bytes available in buf
620 * @param buf where the callee should write the message
621 * @return number of bytes written to buf
624 do_transmit (void *cls, size_t size, void *buf)
626 struct Session *session = cls;
627 struct GNUNET_PeerIdentity pid;
628 struct Plugin *plugin;
629 struct PendingMessage *pos;
630 struct PendingMessage *hd;
631 struct PendingMessage *tl;
632 struct GNUNET_TIME_Absolute now;
636 GNUNET_assert (session != NULL);
637 session->transmit_handle = NULL;
638 plugin = session->plugin;
642 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
643 "Timeout trying to transmit to peer `%4s', discarding message queue.\n",
644 GNUNET_i2s (&session->target));
646 /* timeout; cancel all messages that have already expired */
650 now = GNUNET_TIME_absolute_get ();
651 while ((NULL != (pos = session->pending_messages_head)) &&
652 (pos->timeout.abs_value <= now.abs_value))
654 GNUNET_CONTAINER_DLL_remove (session->pending_messages_head,
655 session->pending_messages_tail, pos);
657 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
658 "Failed to transmit %u byte message to `%4s'.\n",
659 pos->message_size, GNUNET_i2s (&session->target));
661 ret += pos->message_size;
662 GNUNET_CONTAINER_DLL_insert_after (hd, tl, tl, pos);
664 /* do this call before callbacks (so that if callbacks destroy
665 * session, they have a chance to cancel actions done by this
667 process_pending_messages (session);
668 pid = session->target;
669 /* no do callbacks and do not use session again since
670 * the callbacks may abort the session */
671 while (NULL != (pos = hd))
673 GNUNET_CONTAINER_DLL_remove (hd, tl, pos);
674 if (pos->transmit_cont != NULL)
675 pos->transmit_cont (pos->transmit_cont_cls, &pid, GNUNET_SYSERR);
678 GNUNET_STATISTICS_update (plugin->env->stats,
679 gettext_noop ("# bytes currently in TCP buffers"),
680 -(int64_t) ret, GNUNET_NO);
681 GNUNET_STATISTICS_update (plugin->env->stats,
683 ("# bytes discarded by TCP (timeout)"), ret,
687 /* copy all pending messages that would fit */
692 while (NULL != (pos = session->pending_messages_head))
694 if (ret + pos->message_size > size)
696 GNUNET_CONTAINER_DLL_remove (session->pending_messages_head,
697 session->pending_messages_tail, pos);
698 GNUNET_assert (size >= pos->message_size);
699 /* FIXME: this memcpy can be up to 7% of our total runtime */
700 memcpy (cbuf, pos->msg, pos->message_size);
701 cbuf += pos->message_size;
702 ret += pos->message_size;
703 size -= pos->message_size;
704 GNUNET_CONTAINER_DLL_insert_after (hd, tl, tl, pos);
706 /* schedule 'continuation' before callbacks so that callbacks that
707 * cancel everything don't cause us to use a session that no longer
709 process_pending_messages (session);
710 session->last_activity = GNUNET_TIME_absolute_get ();
711 pid = session->target;
712 /* we'll now call callbacks that may cancel the session; hence
713 * we should not use 'session' after this point */
714 while (NULL != (pos = hd))
716 GNUNET_CONTAINER_DLL_remove (hd, tl, pos);
717 if (pos->transmit_cont != NULL)
718 pos->transmit_cont (pos->transmit_cont_cls, &pid, GNUNET_OK);
721 GNUNET_assert (hd == NULL);
722 GNUNET_assert (tl == NULL);
724 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp", "Transmitting %u bytes\n",
727 GNUNET_STATISTICS_update (plugin->env->stats,
728 gettext_noop ("# bytes currently in TCP buffers"),
729 -(int64_t) ret, GNUNET_NO);
730 GNUNET_STATISTICS_update (plugin->env->stats,
731 gettext_noop ("# bytes transmitted via TCP"), ret,
738 * If we have pending messages, ask the server to
739 * transmit them (schedule the respective tasks, etc.)
741 * @param session for which session should we do this
744 process_pending_messages (struct Session *session)
746 struct PendingMessage *pm;
748 GNUNET_assert (session->client != NULL);
749 if (session->transmit_handle != NULL)
751 if (NULL == (pm = session->pending_messages_head))
754 session->transmit_handle =
755 GNUNET_SERVER_notify_transmit_ready (session->client, pm->message_size,
756 GNUNET_TIME_absolute_get_remaining
757 (pm->timeout), &do_transmit,
763 * Functions with this signature are called whenever we need
764 * to close a session due to a disconnect or failure to
765 * establish a connection.
767 * @param session session to close down
770 disconnect_session (struct Session *session)
772 struct Session *prev;
774 struct PendingMessage *pm;
777 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
778 "Disconnecting from `%4s' at %s.\n",
779 GNUNET_i2s (&session->target),
780 (session->connect_addr !=
781 NULL) ? tcp_address_to_string (session->plugin,
782 session->connect_addr,
783 session->connect_alen) :
786 /* remove from session list */
788 pos = session->plugin->sessions;
789 while (pos != session)
795 session->plugin->sessions = session->next;
797 prev->next = session->next;
800 if (session->transmit_handle != NULL)
802 GNUNET_CONNECTION_notify_transmit_ready_cancel (session->transmit_handle);
803 session->transmit_handle = NULL;
805 session->plugin->env->session_end (session->plugin->env->cls,
806 &session->target, session);
807 while (NULL != (pm = session->pending_messages_head))
810 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
812 NULL ? "Could not deliver message to `%4s'.\n" :
813 "Could not deliver message to `%4s', notifying.\n",
814 GNUNET_i2s (&session->target));
816 GNUNET_STATISTICS_update (session->plugin->env->stats,
817 gettext_noop ("# bytes currently in TCP buffers"),
818 -(int64_t) pm->message_size, GNUNET_NO);
819 GNUNET_STATISTICS_update (session->plugin->env->stats,
821 ("# bytes discarded by TCP (disconnect)"),
822 pm->message_size, GNUNET_NO);
823 GNUNET_CONTAINER_DLL_remove (session->pending_messages_head,
824 session->pending_messages_tail, pm);
825 if (NULL != pm->transmit_cont)
826 pm->transmit_cont (pm->transmit_cont_cls, &session->target,
830 GNUNET_break (session->client != NULL);
831 if (session->receive_delay_task != GNUNET_SCHEDULER_NO_TASK)
833 GNUNET_SCHEDULER_cancel (session->receive_delay_task);
834 if (session->client != NULL)
835 GNUNET_SERVER_receive_done (session->client, GNUNET_SYSERR);
837 if (session->client != NULL)
839 GNUNET_SERVER_client_drop (session->client);
840 session->client = NULL;
842 GNUNET_STATISTICS_update (session->plugin->env->stats,
843 gettext_noop ("# TCP sessions active"), -1,
845 GNUNET_free_non_null (session->connect_addr);
846 GNUNET_assert (NULL == session->transmit_handle);
847 GNUNET_free (session);
852 * Given two otherwise equivalent sessions, pick the better one.
854 * @param s1 one session (also default)
855 * @param s2 other session
856 * @return "better" session (more active)
858 static struct Session *
859 select_better_session (struct Session *s1, struct Session *s2)
865 if ((s1->expecting_welcome == GNUNET_NO) &&
866 (s2->expecting_welcome == GNUNET_YES))
868 if ((s1->expecting_welcome == GNUNET_YES) &&
869 (s2->expecting_welcome == GNUNET_NO))
871 if (s1->last_activity.abs_value < s2->last_activity.abs_value)
873 if (s1->last_activity.abs_value > s2->last_activity.abs_value)
875 if ((GNUNET_YES == s1->inbound) && (GNUNET_NO == s2->inbound))
877 if ((GNUNET_NO == s1->inbound) && (GNUNET_YES == s2->inbound))
885 * Function that can be used by the transport service to transmit
886 * a message using the plugin. Note that in the case of a
887 * peer disconnecting, the continuation MUST be called
888 * prior to the disconnect notification itself. This function
889 * will be called with this peer's HELLO message to initiate
890 * a fresh connection to another peer.
893 * @param target who should receive this message
894 * @param msg the message to transmit
895 * @param msgbuf_size number of bytes in 'msg'
896 * @param priority how important is the message (most plugins will
897 * ignore message priority and just FIFO)
898 * @param timeout how long to wait at most for the transmission (does not
899 * require plugins to discard the message after the timeout,
900 * just advisory for the desired delay; most plugins will ignore
902 * @param session which session must be used (or NULL for "any")
903 * @param addr the address to use (can be NULL if the plugin
904 * is "on its own" (i.e. re-use existing TCP connection))
905 * @param addrlen length of the address in bytes
906 * @param force_address GNUNET_YES if the plugin MUST use the given address,
907 * GNUNET_NO means the plugin may use any other address and
908 * GNUNET_SYSERR means that only reliable existing
909 * bi-directional connections should be used (regardless
911 * @param cont continuation to call once the message has
912 * been transmitted (or if the transport is ready
913 * for the next transmission call; or if the
914 * peer disconnected...); can be NULL
915 * @param cont_cls closure for cont
916 * @return number of bytes used (on the physical network, with overheads);
917 * -1 on hard errors (i.e. address invalid); 0 is a legal value
918 * and does NOT mean that the message was not transmitted (DV and NAT)
921 tcp_plugin_send (void *cls, const struct GNUNET_PeerIdentity *target,
922 const char *msg, size_t msgbuf_size, uint32_t priority,
923 struct GNUNET_TIME_Relative timeout, struct Session *session,
924 const void *addr, size_t addrlen, int force_address,
925 GNUNET_TRANSPORT_TransmitContinuation cont, void *cont_cls)
927 struct Plugin *plugin = cls;
928 struct Session *cand_session;
929 struct Session *next;
930 struct PendingMessage *pm;
931 struct GNUNET_CONNECTION_Handle *sa;
935 struct sockaddr_in a4;
936 struct sockaddr_in6 a6;
937 const struct IPv4TcpAddress *t4;
938 const struct IPv6TcpAddress *t6;
939 unsigned int is_natd;
941 GNUNET_STATISTICS_update (plugin->env->stats,
942 gettext_noop ("# bytes TCP was asked to transmit"),
943 msgbuf_size, GNUNET_NO);
944 /* FIXME: we could do this cheaper with a hash table
945 * where we could restrict the iteration to entries that match
946 * the target peer... */
951 next = plugin->sessions;
952 while (NULL != (session = next))
954 next = session->next;
955 GNUNET_assert (session->client != NULL);
957 memcmp (target, &session->target,
958 sizeof (struct GNUNET_PeerIdentity)))
960 if (((GNUNET_SYSERR == force_address) &&
961 (session->expecting_welcome == GNUNET_NO)) ||
962 (GNUNET_NO == force_address))
964 cand_session = select_better_session (cand_session, session);
967 if (GNUNET_SYSERR == force_address)
969 GNUNET_break (GNUNET_YES == force_address);
975 if ((addrlen != session->connect_alen) && (session->is_nat == GNUNET_NO))
977 if ((0 != memcmp (session->connect_addr, addr, addrlen)) &&
978 (session->is_nat == GNUNET_NO))
980 cand_session = select_better_session (cand_session, session);
982 session = cand_session;
984 if ((session == NULL) && (addr == NULL))
987 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
988 "Asked to transmit to `%4s' without address and I have no existing connection (failing).\n",
989 GNUNET_i2s (target));
991 GNUNET_STATISTICS_update (plugin->env->stats,
993 ("# bytes discarded by TCP (no address and no connection)"),
994 msgbuf_size, GNUNET_NO);
999 if (addrlen == sizeof (struct IPv6TcpAddress))
1003 memset (&a6, 0, sizeof (a6));
1004 #if HAVE_SOCKADDR_IN_SIN_LEN
1005 a6.sin6_len = sizeof (a6);
1007 a6.sin6_family = AF_INET6;
1008 a6.sin6_port = t6->t6_port;
1009 if (t6->t6_port == 0)
1010 is_natd = GNUNET_YES;
1011 memcpy (&a6.sin6_addr, &t6->ipv6_addr, sizeof (struct in6_addr));
1015 else if (addrlen == sizeof (struct IPv4TcpAddress))
1019 memset (&a4, 0, sizeof (a4));
1020 #if HAVE_SOCKADDR_IN_SIN_LEN
1021 a4.sin_len = sizeof (a4);
1023 a4.sin_family = AF_INET;
1024 a4.sin_port = t4->t4_port;
1025 if (t4->t4_port == 0)
1026 is_natd = GNUNET_YES;
1027 a4.sin_addr.s_addr = t4->ipv4_addr;
1033 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, "tcp",
1034 _("Address of unexpected length: %u\n"), addrlen);
1039 if ((is_natd == GNUNET_YES) && (addrlen == sizeof (struct IPv6TcpAddress)))
1040 return -1; /* NAT client only works with IPv4 addresses */
1041 if (0 == plugin->max_connections)
1042 return -1; /* saturated */
1044 if ((is_natd == GNUNET_YES) && (NULL != plugin->nat) &&
1046 GNUNET_CONTAINER_multihashmap_contains (plugin->nat_wait_conns,
1047 &target->hashPubKey)))
1050 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1051 _("Found valid IPv4 NAT address (creating session)!\n"));
1053 session = create_session (plugin, target, NULL, GNUNET_YES);
1054 GNUNET_assert (session != NULL);
1056 /* create new message entry */
1057 pm = GNUNET_malloc (sizeof (struct PendingMessage) + msgbuf_size);
1058 /* FIXME: the memset of this malloc can be up to 2% of our total runtime */
1059 pm->msg = (const char *) &pm[1];
1060 memcpy (&pm[1], msg, msgbuf_size);
1061 /* FIXME: this memcpy can be up to 7% of our total run-time
1062 * (for transport service) */
1063 pm->message_size = msgbuf_size;
1064 pm->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1065 pm->transmit_cont = cont;
1066 pm->transmit_cont_cls = cont_cls;
1068 /* append pm to pending_messages list */
1069 GNUNET_CONTAINER_DLL_insert_after (session->pending_messages_head,
1070 session->pending_messages_tail,
1071 session->pending_messages_tail, pm);
1073 GNUNET_assert (GNUNET_CONTAINER_multihashmap_put
1074 (plugin->nat_wait_conns, &target->hashPubKey, session,
1075 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY) ==
1078 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1079 "Created NAT WAIT connection to `%4s' at `%s'\n",
1080 GNUNET_i2s (target), GNUNET_a2s (sb, sbs));
1082 GNUNET_NAT_run_client (plugin->nat, &a4);
1085 if ((is_natd == GNUNET_YES) &&
1087 GNUNET_CONTAINER_multihashmap_contains (plugin->nat_wait_conns,
1088 &target->hashPubKey)))
1090 /* Only do one NAT punch attempt per peer identity */
1093 sa = GNUNET_CONNECTION_create_from_sockaddr (af, sb, sbs);
1097 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1098 "Failed to create connection to `%4s' at `%s'\n",
1099 GNUNET_i2s (target), GNUNET_a2s (sb, sbs));
1101 GNUNET_STATISTICS_update (plugin->env->stats,
1103 ("# bytes discarded by TCP (failed to connect)"),
1104 msgbuf_size, GNUNET_NO);
1107 GNUNET_assert (0 != plugin->max_connections);
1108 plugin->max_connections--;
1110 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1111 "Asked to transmit to `%4s', creating fresh session using address `%s'.\n",
1112 GNUNET_i2s (target), GNUNET_a2s (sb, sbs));
1115 create_session (plugin, target,
1116 GNUNET_SERVER_connect_socket (plugin->server, sa),
1118 session->connect_addr = GNUNET_malloc (addrlen);
1119 memcpy (session->connect_addr, addr, addrlen);
1120 session->connect_alen = addrlen;
1122 else /* session != NULL */
1124 /* check if session is valid */
1125 struct Session *ses = plugin->sessions;
1127 while ((ses != NULL) && (ses != session))
1135 GNUNET_assert (session != NULL);
1136 GNUNET_assert (session->client != NULL);
1139 GNUNET_SERVER_client_set_timeout (session->client,
1140 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1141 GNUNET_STATISTICS_update (plugin->env->stats,
1142 gettext_noop ("# bytes currently in TCP buffers"),
1143 msgbuf_size, GNUNET_NO);
1144 /* create new message entry */
1145 pm = GNUNET_malloc (sizeof (struct PendingMessage) + msgbuf_size);
1146 pm->msg = (const char *) &pm[1];
1147 memcpy (&pm[1], msg, msgbuf_size);
1148 pm->message_size = msgbuf_size;
1149 pm->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1150 pm->transmit_cont = cont;
1151 pm->transmit_cont_cls = cont_cls;
1153 /* append pm to pending_messages list */
1154 GNUNET_CONTAINER_DLL_insert_after (session->pending_messages_head,
1155 session->pending_messages_tail,
1156 session->pending_messages_tail, pm);
1158 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1159 "Asked to transmit %u bytes to `%s', added message to list.\n",
1160 msgbuf_size, GNUNET_i2s (target));
1162 process_pending_messages (session);
1168 * Function that can be called to force a disconnect from the
1169 * specified neighbour. This should also cancel all previously
1170 * scheduled transmissions. Obviously the transmission may have been
1171 * partially completed already, which is OK. The plugin is supposed
1172 * to close the connection (if applicable) and no longer call the
1173 * transmit continuation(s).
1175 * Finally, plugin MUST NOT call the services's receive function to
1176 * notify the service that the connection to the specified target was
1177 * closed after a getting this call.
1179 * @param cls closure
1180 * @param target peer for which the last transmission is
1184 tcp_plugin_disconnect (void *cls, const struct GNUNET_PeerIdentity *target)
1186 struct Plugin *plugin = cls;
1187 struct Session *session;
1188 struct Session *next;
1189 struct PendingMessage *pm;
1192 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1193 "Asked to cancel session with `%4s'\n", GNUNET_i2s (target));
1195 next = plugin->sessions;
1196 while (NULL != (session = next))
1198 next = session->next;
1200 memcmp (target, &session->target, sizeof (struct GNUNET_PeerIdentity)))
1202 pm = session->pending_messages_head;
1205 pm->transmit_cont = NULL;
1206 pm->transmit_cont_cls = NULL;
1209 GNUNET_STATISTICS_update (session->plugin->env->stats,
1211 ("# transport-service disconnect requests for TCP"),
1213 disconnect_session (session);
1219 * Context for address to string conversion.
1221 struct PrettyPrinterContext
1224 * Function to call with the result.
1226 GNUNET_TRANSPORT_AddressStringCallback asc;
1229 * Clsoure for 'asc'.
1234 * Port to add after the IP address.
1241 * Append our port and forward the result.
1243 * @param cls the 'struct PrettyPrinterContext*'
1244 * @param hostname hostname part of the address
1247 append_port (void *cls, const char *hostname)
1249 struct PrettyPrinterContext *ppc = cls;
1252 if (hostname == NULL)
1254 ppc->asc (ppc->asc_cls, NULL);
1258 GNUNET_asprintf (&ret, "%s:%d", hostname, ppc->port);
1259 ppc->asc (ppc->asc_cls, ret);
1265 * Convert the transports address to a nice, human-readable
1268 * @param cls closure
1269 * @param type name of the transport that generated the address
1270 * @param addr one of the addresses of the host, NULL for the last address
1271 * the specific address format depends on the transport
1272 * @param addrlen length of the address
1273 * @param numeric should (IP) addresses be displayed in numeric form?
1274 * @param timeout after how long should we give up?
1275 * @param asc function to call on each string
1276 * @param asc_cls closure for asc
1279 tcp_plugin_address_pretty_printer (void *cls, const char *type,
1280 const void *addr, size_t addrlen,
1282 struct GNUNET_TIME_Relative timeout,
1283 GNUNET_TRANSPORT_AddressStringCallback asc,
1286 struct PrettyPrinterContext *ppc;
1289 struct sockaddr_in a4;
1290 struct sockaddr_in6 a6;
1291 const struct IPv4TcpAddress *t4;
1292 const struct IPv6TcpAddress *t6;
1295 if (addrlen == sizeof (struct IPv6TcpAddress))
1298 memset (&a6, 0, sizeof (a6));
1299 a6.sin6_family = AF_INET6;
1300 a6.sin6_port = t6->t6_port;
1301 memcpy (&a6.sin6_addr, &t6->ipv6_addr, sizeof (struct in6_addr));
1302 port = ntohs (t6->t6_port);
1306 else if (addrlen == sizeof (struct IPv4TcpAddress))
1309 memset (&a4, 0, sizeof (a4));
1310 a4.sin_family = AF_INET;
1311 a4.sin_port = t4->t4_port;
1312 a4.sin_addr.s_addr = t4->ipv4_addr;
1313 port = ntohs (t4->t4_port);
1319 /* invalid address */
1320 GNUNET_break_op (0);
1321 asc (asc_cls, NULL);
1324 ppc = GNUNET_malloc (sizeof (struct PrettyPrinterContext));
1326 ppc->asc_cls = asc_cls;
1328 GNUNET_RESOLVER_hostname_get (sb, sbs, !numeric, timeout, &append_port, ppc);
1333 * Check if the given port is plausible (must be either our listen
1334 * port or our advertised port), or any port if we are behind NAT
1335 * and do not have a port open. If it is neither, we return
1338 * @param plugin global variables
1339 * @param in_port port number to check
1340 * @return GNUNET_OK if port is either open_port or adv_port
1343 check_port (struct Plugin *plugin, uint16_t in_port)
1345 if ((in_port == plugin->adv_port) || (in_port == plugin->open_port))
1347 return GNUNET_SYSERR;
1352 * Function that will be called to check if a binary address for this
1353 * plugin is well-formed and corresponds to an address for THIS peer
1354 * (as per our configuration). Naturally, if absolutely necessary,
1355 * plugins can be a bit conservative in their answer, but in general
1356 * plugins should make sure that the address does not redirect
1357 * traffic to a 3rd party that might try to man-in-the-middle our
1360 * @param cls closure, our 'struct Plugin*'
1361 * @param addr pointer to the address
1362 * @param addrlen length of addr
1363 * @return GNUNET_OK if this is a plausible address for this peer
1364 * and transport, GNUNET_SYSERR if not
1367 tcp_plugin_check_address (void *cls, const void *addr, size_t addrlen)
1369 struct Plugin *plugin = cls;
1370 struct IPv4TcpAddress *v4;
1371 struct IPv6TcpAddress *v6;
1373 if ((addrlen != sizeof (struct IPv4TcpAddress)) &&
1374 (addrlen != sizeof (struct IPv6TcpAddress)))
1376 GNUNET_break_op (0);
1377 return GNUNET_SYSERR;
1379 if (addrlen == sizeof (struct IPv4TcpAddress))
1381 v4 = (struct IPv4TcpAddress *) addr;
1382 if (GNUNET_OK != check_port (plugin, ntohs (v4->t4_port)))
1383 return GNUNET_SYSERR;
1385 GNUNET_NAT_test_address (plugin->nat, &v4->ipv4_addr,
1386 sizeof (struct in_addr)))
1387 return GNUNET_SYSERR;
1391 v6 = (struct IPv6TcpAddress *) addr;
1392 if (IN6_IS_ADDR_LINKLOCAL (&v6->ipv6_addr))
1394 GNUNET_break_op (0);
1395 return GNUNET_SYSERR;
1397 if (GNUNET_OK != check_port (plugin, ntohs (v6->t6_port)))
1398 return GNUNET_SYSERR;
1400 GNUNET_NAT_test_address (plugin->nat, &v6->ipv6_addr,
1401 sizeof (struct in6_addr)))
1402 return GNUNET_SYSERR;
1409 * We've received a nat probe from this peer via TCP. Finish
1410 * creating the client session and resume sending of queued
1413 * @param cls closure
1414 * @param client identification of the client
1415 * @param message the actual message
1418 handle_tcp_nat_probe (void *cls, struct GNUNET_SERVER_Client *client,
1419 const struct GNUNET_MessageHeader *message)
1421 struct Plugin *plugin = cls;
1422 struct Session *session;
1423 const struct TCP_NAT_ProbeMessage *tcp_nat_probe;
1426 struct IPv4TcpAddress *t4;
1427 struct IPv6TcpAddress *t6;
1428 const struct sockaddr_in *s4;
1429 const struct sockaddr_in6 *s6;
1432 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp", "received NAT probe\n");
1434 /* We have received a TCP NAT probe, meaning we (hopefully) initiated
1435 * a connection to this peer by running gnunet-nat-client. This peer
1436 * received the punch message and now wants us to use the new connection
1437 * as the default for that peer. Do so and then send a WELCOME message
1438 * so we can really be connected!
1440 if (ntohs (message->size) != sizeof (struct TCP_NAT_ProbeMessage))
1442 GNUNET_break_op (0);
1443 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1447 tcp_nat_probe = (const struct TCP_NAT_ProbeMessage *) message;
1449 memcmp (&tcp_nat_probe->clientIdentity, plugin->env->my_identity,
1450 sizeof (struct GNUNET_PeerIdentity)))
1452 /* refuse connections from ourselves */
1453 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1458 GNUNET_CONTAINER_multihashmap_get (plugin->nat_wait_conns,
1460 clientIdentity.hashPubKey);
1461 if (session == NULL)
1464 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1465 "Did NOT find session for NAT probe!\n");
1467 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1471 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1472 "Found session for NAT probe!\n");
1474 GNUNET_assert (GNUNET_CONTAINER_multihashmap_remove
1475 (plugin->nat_wait_conns,
1476 &tcp_nat_probe->clientIdentity.hashPubKey,
1477 session) == GNUNET_YES);
1478 if (GNUNET_OK != GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
1481 GNUNET_free (session);
1482 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1486 GNUNET_SERVER_client_keep (client);
1487 session->client = client;
1488 session->last_activity = GNUNET_TIME_absolute_get ();
1489 session->inbound = GNUNET_NO;
1492 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1493 "Found address `%s' for incoming connection\n",
1494 GNUNET_a2s (vaddr, alen));
1496 switch (((const struct sockaddr *) vaddr)->sa_family)
1500 t4 = GNUNET_malloc (sizeof (struct IPv4TcpAddress));
1501 t4->t4_port = s4->sin_port;
1502 t4->ipv4_addr = s4->sin_addr.s_addr;
1503 session->connect_addr = t4;
1504 session->connect_alen = sizeof (struct IPv4TcpAddress);
1508 t6 = GNUNET_malloc (sizeof (struct IPv6TcpAddress));
1509 t6->t6_port = s6->sin6_port;
1510 memcpy (&t6->ipv6_addr, &s6->sin6_addr, sizeof (struct in6_addr));
1511 session->connect_addr = t6;
1512 session->connect_alen = sizeof (struct IPv6TcpAddress);
1515 GNUNET_break_op (0);
1517 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1518 "Bad address for incoming connection!\n");
1520 GNUNET_free (vaddr);
1521 GNUNET_SERVER_client_drop (client);
1522 GNUNET_free (session);
1523 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1526 GNUNET_free (vaddr);
1528 session->next = plugin->sessions;
1529 plugin->sessions = session;
1530 GNUNET_STATISTICS_update (plugin->env->stats,
1531 gettext_noop ("# TCP sessions active"), 1,
1533 process_pending_messages (session);
1534 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1539 * We've received a welcome from this peer via TCP. Possibly create a
1540 * fresh client record and send back our welcome.
1542 * @param cls closure
1543 * @param client identification of the client
1544 * @param message the actual message
1547 handle_tcp_welcome (void *cls, struct GNUNET_SERVER_Client *client,
1548 const struct GNUNET_MessageHeader *message)
1550 struct Plugin *plugin = cls;
1551 const struct WelcomeMessage *wm = (const struct WelcomeMessage *) message;
1552 struct Session *session;
1555 struct IPv4TcpAddress *t4;
1556 struct IPv6TcpAddress *t6;
1557 const struct sockaddr_in *s4;
1558 const struct sockaddr_in6 *s6;
1561 memcmp (&wm->clientIdentity, plugin->env->my_identity,
1562 sizeof (struct GNUNET_PeerIdentity)))
1564 /* refuse connections from ourselves */
1565 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1569 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1570 "Received %s message from `%4s'.\n", "WELCOME",
1571 GNUNET_i2s (&wm->clientIdentity));
1573 GNUNET_STATISTICS_update (plugin->env->stats,
1574 gettext_noop ("# TCP WELCOME messages received"), 1,
1576 session = find_session_by_client (plugin, client);
1578 if (session == NULL)
1581 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1582 "Received %s message from a `%4s', creating new session\n",
1583 "WELCOME", GNUNET_i2s (&wm->clientIdentity));
1585 GNUNET_SERVER_client_keep (client);
1586 session = create_session (plugin, &wm->clientIdentity, client, GNUNET_NO);
1587 session->inbound = GNUNET_YES;
1588 if (GNUNET_OK == GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
1591 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1592 "Found address `%s' for incoming connection\n",
1593 GNUNET_a2s (vaddr, alen));
1595 if (alen == sizeof (struct sockaddr_in))
1598 t4 = GNUNET_malloc (sizeof (struct IPv4TcpAddress));
1599 t4->t4_port = s4->sin_port;
1600 t4->ipv4_addr = s4->sin_addr.s_addr;
1601 session->connect_addr = t4;
1602 session->connect_alen = sizeof (struct IPv4TcpAddress);
1604 else if (alen == sizeof (struct sockaddr_in6))
1607 t6 = GNUNET_malloc (sizeof (struct IPv6TcpAddress));
1608 t6->t6_port = s6->sin6_port;
1609 memcpy (&t6->ipv6_addr, &s6->sin6_addr, sizeof (struct in6_addr));
1610 session->connect_addr = t6;
1611 session->connect_alen = sizeof (struct IPv6TcpAddress);
1614 GNUNET_free (vaddr);
1619 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1620 "Did not obtain TCP socket address for incoming connection\n");
1623 process_pending_messages (session);
1628 if (GNUNET_OK == GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
1630 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1631 "Found address `%s' (already have session)\n",
1632 GNUNET_a2s (vaddr, alen));
1633 GNUNET_free (vaddr);
1638 if (session->expecting_welcome != GNUNET_YES)
1640 GNUNET_break_op (0);
1641 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1644 session->last_activity = GNUNET_TIME_absolute_get ();
1645 session->expecting_welcome = GNUNET_NO;
1646 GNUNET_SERVER_client_set_timeout (client,
1647 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1648 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1653 * Task to signal the server that we can continue
1654 * receiving from the TCP client now.
1656 * @param cls the 'struct Session*'
1657 * @param tc task context (unused)
1660 delayed_done (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1662 struct Session *session = cls;
1663 struct GNUNET_TIME_Relative delay;
1664 struct GNUNET_TRANSPORT_ATS_Information ats;
1666 ats.type = htonl (GNUNET_TRANSPORT_ATS_ARRAY_TERMINATOR);
1667 ats.value = htonl (0);
1669 session->receive_delay_task = GNUNET_SCHEDULER_NO_TASK;
1671 session->plugin->env->receive (session->plugin->env->cls,
1672 &session->target, NULL, &ats, 1, session,
1674 if (delay.rel_value == 0)
1675 GNUNET_SERVER_receive_done (session->client, GNUNET_OK);
1677 session->receive_delay_task =
1678 GNUNET_SCHEDULER_add_delayed (delay, &delayed_done, session);
1683 * We've received data for this peer via TCP. Unbox,
1684 * compute latency and forward.
1686 * @param cls closure
1687 * @param client identification of the client
1688 * @param message the actual message
1691 handle_tcp_data (void *cls, struct GNUNET_SERVER_Client *client,
1692 const struct GNUNET_MessageHeader *message)
1694 struct Plugin *plugin = cls;
1695 struct Session *session;
1696 struct GNUNET_TIME_Relative delay;
1699 type = ntohs (message->type);
1700 if ((GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME == type) ||
1701 (GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE == type))
1703 /* We don't want to propagate WELCOME and NAT Probe messages up! */
1704 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1707 session = find_session_by_client (plugin, client);
1708 if ((NULL == session) || (GNUNET_YES == session->expecting_welcome))
1710 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1713 session->last_activity = GNUNET_TIME_absolute_get ();
1715 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1716 "Passing %u bytes of type %u from `%4s' to transport service.\n",
1717 (unsigned int) ntohs (message->size),
1718 (unsigned int) ntohs (message->type),
1719 GNUNET_i2s (&session->target));
1721 GNUNET_STATISTICS_update (plugin->env->stats,
1722 gettext_noop ("# bytes received via TCP"),
1723 ntohs (message->size), GNUNET_NO);
1724 struct GNUNET_TRANSPORT_ATS_Information distance[2];
1726 distance[0].type = htonl (GNUNET_TRANSPORT_ATS_QUALITY_NET_DISTANCE);
1727 distance[0].value = htonl (1);
1728 distance[1].type = htonl (GNUNET_TRANSPORT_ATS_ARRAY_TERMINATOR);
1729 distance[1].value = htonl (0);
1731 plugin->env->receive (plugin->env->cls, &session->target, message,
1732 (const struct GNUNET_TRANSPORT_ATS_Information *)
1733 &distance, 2, session,
1735 session->inbound) ? NULL : session->connect_addr,
1737 session->inbound) ? 0 : session->connect_alen);
1738 if (delay.rel_value == 0)
1740 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1745 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1746 "Throttling receiving from `%s' for %llu ms\n",
1747 GNUNET_i2s (&session->target),
1748 (unsigned long long) delay.rel_value);
1750 GNUNET_SERVER_disable_receive_done_warning (client);
1751 session->receive_delay_task =
1752 GNUNET_SCHEDULER_add_delayed (delay, &delayed_done, session);
1758 * Functions with this signature are called whenever a peer
1759 * is disconnected on the network level.
1761 * @param cls closure
1762 * @param client identification of the client
1765 disconnect_notify (void *cls, struct GNUNET_SERVER_Client *client)
1767 struct Plugin *plugin = cls;
1768 struct Session *session;
1772 plugin->max_connections++;
1773 session = find_session_by_client (plugin, client);
1774 if (session == NULL)
1775 return; /* unknown, nothing to do */
1777 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1778 "Destroying session of `%4s' with %s due to network-level disconnect.\n",
1779 GNUNET_i2s (&session->target),
1780 (session->connect_addr !=
1781 NULL) ? tcp_address_to_string (session->plugin,
1782 session->connect_addr,
1783 session->connect_alen) :
1786 GNUNET_STATISTICS_update (session->plugin->env->stats,
1788 ("# network-level TCP disconnect events"), 1,
1790 disconnect_session (session);
1795 * We can now send a probe message, copy into buffer to really send.
1797 * @param cls closure, a struct TCPProbeContext
1798 * @param size max size to copy
1799 * @param buf buffer to copy message to
1800 * @return number of bytes copied into buf
1803 notify_send_probe (void *cls, size_t size, void *buf)
1805 struct TCPProbeContext *tcp_probe_ctx = cls;
1806 struct Plugin *plugin = tcp_probe_ctx->plugin;
1809 tcp_probe_ctx->transmit_handle = NULL;
1810 GNUNET_CONTAINER_DLL_remove (plugin->probe_head, plugin->probe_tail,
1814 GNUNET_CONNECTION_destroy (tcp_probe_ctx->sock, GNUNET_NO);
1815 GNUNET_free (tcp_probe_ctx);
1818 GNUNET_assert (size >= sizeof (tcp_probe_ctx->message));
1819 memcpy (buf, &tcp_probe_ctx->message, sizeof (tcp_probe_ctx->message));
1820 GNUNET_SERVER_connect_socket (tcp_probe_ctx->plugin->server,
1821 tcp_probe_ctx->sock);
1822 ret = sizeof (tcp_probe_ctx->message);
1823 GNUNET_free (tcp_probe_ctx);
1829 * Function called by the NAT subsystem suggesting another peer wants
1830 * to connect to us via connection reversal. Try to connect back to the
1833 * @param cls closure
1834 * @param addr address to try
1835 * @param addrlen number of bytes in addr
1838 try_connection_reversal (void *cls, const struct sockaddr *addr,
1841 struct Plugin *plugin = cls;
1842 struct GNUNET_CONNECTION_Handle *sock;
1843 struct TCPProbeContext *tcp_probe_ctx;
1846 * We have received an ICMP response, ostensibly from a peer
1847 * that wants to connect to us! Send a message to establish a connection.
1849 sock = GNUNET_CONNECTION_create_from_sockaddr (AF_INET, addr, addrlen);
1852 /* failed for some odd reason (out of sockets?); ignore attempt */
1856 /* FIXME: do we need to track these probe context objects so that
1857 * we can clean them up on plugin unload? */
1858 tcp_probe_ctx = GNUNET_malloc (sizeof (struct TCPProbeContext));
1859 tcp_probe_ctx->message.header.size =
1860 htons (sizeof (struct TCP_NAT_ProbeMessage));
1861 tcp_probe_ctx->message.header.type =
1862 htons (GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE);
1863 memcpy (&tcp_probe_ctx->message.clientIdentity, plugin->env->my_identity,
1864 sizeof (struct GNUNET_PeerIdentity));
1865 tcp_probe_ctx->plugin = plugin;
1866 tcp_probe_ctx->sock = sock;
1867 GNUNET_CONTAINER_DLL_insert (plugin->probe_head, plugin->probe_tail,
1869 tcp_probe_ctx->transmit_handle =
1870 GNUNET_CONNECTION_notify_transmit_ready (sock,
1871 ntohs (tcp_probe_ctx->
1872 message.header.size),
1873 GNUNET_TIME_UNIT_FOREVER_REL,
1881 * Entry point for the plugin.
1883 * @param cls closure, the 'struct GNUNET_TRANSPORT_PluginEnvironment*'
1884 * @return the 'struct GNUNET_TRANSPORT_PluginFunctions*' or NULL on error
1887 libgnunet_plugin_transport_tcp_init (void *cls)
1889 static const struct GNUNET_SERVER_MessageHandler my_handlers[] = {
1890 {&handle_tcp_welcome, NULL, GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME,
1891 sizeof (struct WelcomeMessage)},
1892 {&handle_tcp_nat_probe, NULL, GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE,
1893 sizeof (struct TCP_NAT_ProbeMessage)},
1894 {&handle_tcp_data, NULL, GNUNET_MESSAGE_TYPE_ALL, 0},
1897 struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
1898 struct GNUNET_TRANSPORT_PluginFunctions *api;
1899 struct Plugin *plugin;
1900 struct GNUNET_SERVICE_Context *service;
1901 unsigned long long aport;
1902 unsigned long long bport;
1903 unsigned long long max_connections;
1905 struct GNUNET_TIME_Relative idle_timeout;
1907 struct sockaddr **addrs;
1908 socklen_t *addrlens;
1911 GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-tcp",
1914 max_connections = 128;
1918 GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-tcp", "PORT",
1919 &bport)) || (bport > 65535) ||
1921 GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-tcp",
1922 "ADVERTISED-PORT", &aport)) &&
1925 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, "tcp",
1927 ("Require valid port number for service `%s' in configuration!\n"),
1937 service = GNUNET_SERVICE_start ("transport-tcp", env->cfg);
1938 if (service == NULL)
1940 GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, "tcp",
1941 _("Failed to start service.\n"));
1950 plugin = GNUNET_malloc (sizeof (struct Plugin));
1951 plugin->max_connections = max_connections;
1952 plugin->open_port = bport;
1953 plugin->adv_port = aport;
1955 plugin->lsock = NULL;
1956 if ((service != NULL) &&
1959 GNUNET_SERVICE_get_server_addresses ("transport-tcp", env->cfg, &addrs,
1963 GNUNET_NAT_register (env->cfg, GNUNET_YES, aport, (unsigned int) ret,
1964 (const struct sockaddr **) addrs, addrlens,
1965 &tcp_nat_port_map_callback,
1966 &try_connection_reversal, plugin);
1970 GNUNET_assert (addrs[ret] != NULL);
1971 GNUNET_free (addrs[ret]);
1973 GNUNET_free_non_null (addrs);
1974 GNUNET_free_non_null (addrlens);
1979 GNUNET_NAT_register (env->cfg, GNUNET_YES, 0, 0, NULL, NULL, NULL,
1980 &try_connection_reversal, plugin);
1982 api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
1984 api->send = &tcp_plugin_send;
1985 api->disconnect = &tcp_plugin_disconnect;
1986 api->address_pretty_printer = &tcp_plugin_address_pretty_printer;
1987 api->check_address = &tcp_plugin_check_address;
1988 api->address_to_string = &tcp_address_to_string;
1989 plugin->service = service;
1990 if (service != NULL)
1992 plugin->server = GNUNET_SERVICE_get_server (service);
1997 GNUNET_CONFIGURATION_get_value_time (env->cfg, "transport-tcp",
1998 "TIMEOUT", &idle_timeout))
2000 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, "tcp",
2001 _("Failed to find option %s in section %s!\n"),
2002 "TIMEOUT", "transport-tcp");
2003 if (plugin->nat != NULL)
2004 GNUNET_NAT_unregister (plugin->nat);
2005 GNUNET_free (plugin);
2010 GNUNET_SERVER_create_with_sockets (&plugin_tcp_access_check, plugin,
2011 NULL, idle_timeout, GNUNET_YES);
2013 plugin->handlers = GNUNET_malloc (sizeof (my_handlers));
2014 memcpy (plugin->handlers, my_handlers, sizeof (my_handlers));
2016 i < sizeof (my_handlers) / sizeof (struct GNUNET_SERVER_MessageHandler);
2018 plugin->handlers[i].callback_cls = plugin;
2019 GNUNET_SERVER_add_handlers (plugin->server, plugin->handlers);
2020 GNUNET_SERVER_disconnect_notify (plugin->server, &disconnect_notify, plugin);
2021 plugin->nat_wait_conns = GNUNET_CONTAINER_multihashmap_create (16);
2023 GNUNET_log_from (GNUNET_ERROR_TYPE_INFO, "tcp",
2024 _("TCP transport listening on port %llu\n"), bport);
2026 GNUNET_log_from (GNUNET_ERROR_TYPE_INFO, "tcp",
2028 ("TCP transport not listening on any port (client only)\n"));
2030 GNUNET_log_from (GNUNET_ERROR_TYPE_INFO, "tcp",
2032 ("TCP transport advertises itself as being on port %llu\n"),
2039 * Exit point from the plugin.
2042 libgnunet_plugin_transport_tcp_done (void *cls)
2044 struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
2045 struct Plugin *plugin = api->cls;
2046 struct Session *session;
2047 struct TCPProbeContext *tcp_probe;
2049 while (NULL != (session = plugin->sessions))
2050 disconnect_session (session);
2051 if (plugin->service != NULL)
2052 GNUNET_SERVICE_stop (plugin->service);
2054 GNUNET_SERVER_destroy (plugin->server);
2055 GNUNET_free (plugin->handlers);
2056 if (plugin->nat != NULL)
2057 GNUNET_NAT_unregister (plugin->nat);
2058 while (NULL != (tcp_probe = plugin->probe_head))
2060 GNUNET_CONTAINER_DLL_remove (plugin->probe_head, plugin->probe_tail,
2062 GNUNET_CONNECTION_destroy (tcp_probe->sock, GNUNET_NO);
2063 GNUNET_free (tcp_probe);
2065 GNUNET_CONTAINER_multihashmap_destroy (plugin->nat_wait_conns);
2066 GNUNET_free (plugin);
2071 /* end of plugin_transport_tcp.c */