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;
331 * Handle to the network service.
333 struct GNUNET_SERVICE_Context *service;
336 * Handle to the server for this service.
338 struct GNUNET_SERVER_Handle *server;
341 * Copy of the handler array where the closures are
342 * set to this struct's instance.
344 struct GNUNET_SERVER_MessageHandler *handlers;
347 * Map of peers we have tried to contact behind a NAT
349 struct GNUNET_CONTAINER_MultiHashMap *nat_wait_conns;
352 * List of active TCP probes.
354 struct TCPProbeContext *probe_head;
357 * List of active TCP probes.
359 struct TCPProbeContext *probe_tail;
362 * Handle for (DYN)DNS lookup of our external IP.
364 struct GNUNET_RESOLVER_RequestHandle *ext_dns;
367 * How many more TCP sessions are we allowed to open right now?
369 unsigned long long max_connections;
372 * ID of task used to update our addresses when one expires.
374 GNUNET_SCHEDULER_TaskIdentifier address_update_task;
377 * Port that we are actually listening on.
382 * Port that the user said we would have visible to the
391 * Function to check if an inbound connection is acceptable.
392 * Mostly used to limit the total number of open connections
395 * @param cls the 'struct Plugin'
396 * @param ucred credentials, if available, otherwise NULL
397 * @param addr address
398 * @param addrlen length of address
399 * @return GNUNET_YES to allow, GNUNET_NO to deny, GNUNET_SYSERR
400 * for unknown address family (will be denied).
403 plugin_tcp_access_check (void *cls,
404 const struct GNUNET_CONNECTION_Credentials *ucred,
405 const struct sockaddr *addr, socklen_t addrlen)
407 struct Plugin *plugin = cls;
409 if (0 == plugin->max_connections)
411 plugin->max_connections--;
417 * Our external IP address/port mapping has changed.
419 * @param cls closure, the 'struct LocalAddrList'
420 * @param add_remove GNUNET_YES to mean the new public IP address, GNUNET_NO to mean
421 * the previous (now invalid) one
422 * @param addr either the previous or the new public IP address
423 * @param addrlen actual lenght of the address
426 tcp_nat_port_map_callback (void *cls, int add_remove,
427 const struct sockaddr *addr, socklen_t addrlen)
429 struct Plugin *plugin = cls;
430 struct IPv4TcpAddress t4;
431 struct IPv6TcpAddress t6;
435 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
436 "NPMC called with %d for address `%s'\n", add_remove,
437 GNUNET_a2s (addr, addrlen));
438 /* convert 'addr' to our internal format */
439 switch (addr->sa_family)
442 GNUNET_assert (addrlen == sizeof (struct sockaddr_in));
443 t4.ipv4_addr = ((struct sockaddr_in *) addr)->sin_addr.s_addr;
444 t4.t4_port = ((struct sockaddr_in *) addr)->sin_port;
449 GNUNET_assert (addrlen == sizeof (struct sockaddr_in6));
450 memcpy (&t6.ipv6_addr, &((struct sockaddr_in6 *) addr)->sin6_addr,
451 sizeof (struct in6_addr));
452 t6.t6_port = ((struct sockaddr_in6 *) addr)->sin6_port;
460 /* modify our published address list */
461 plugin->env->notify_address (plugin->env->cls, add_remove, arg, args);
466 * Function called for a quick conversion of the binary address to
467 * a numeric address. Note that the caller must not free the
468 * address and that the next call to this function is allowed
469 * to override the address again.
471 * @param cls closure ('struct Plugin*')
472 * @param addr binary address
473 * @param addrlen length of the address
474 * @return string representing the same address
477 tcp_address_to_string (void *cls, const void *addr, size_t addrlen)
479 static char rbuf[INET6_ADDRSTRLEN + 12];
480 char buf[INET6_ADDRSTRLEN];
484 const struct IPv4TcpAddress *t4;
485 const struct IPv6TcpAddress *t6;
489 if (addrlen == sizeof (struct IPv6TcpAddress))
493 port = ntohs (t6->t6_port);
494 memcpy (&a6, &t6->ipv6_addr, sizeof (a6));
497 else if (addrlen == sizeof (struct IPv4TcpAddress))
501 port = ntohs (t4->t4_port);
502 memcpy (&a4, &t4->ipv4_addr, sizeof (a4));
507 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, "tcp",
508 _("Unexpected address length: %u bytes\n"),
509 (unsigned int) addrlen);
513 if (NULL == inet_ntop (af, sb, buf, INET6_ADDRSTRLEN))
515 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "inet_ntop");
518 GNUNET_snprintf (rbuf, sizeof (rbuf), (af == AF_INET6) ? "[%s]:%u" : "%s:%u",
525 * Find the session handle for the given client.
527 * @param plugin the plugin
528 * @param client which client to find the session handle for
529 * @return NULL if no matching session exists
531 static struct Session *
532 find_session_by_client (struct Plugin *plugin,
533 const struct GNUNET_SERVER_Client *client)
537 ret = plugin->sessions;
538 while ((ret != NULL) && (client != ret->client))
545 * Create a new session. Also queues a welcome message.
547 * @param plugin the plugin
548 * @param target peer to connect to
549 * @param client client to use
550 * @param is_nat this a NAT session, we should wait for a client to
551 * connect to us from an address, then assign that to
553 * @return new session object
555 static struct Session *
556 create_session (struct Plugin *plugin, const struct GNUNET_PeerIdentity *target,
557 struct GNUNET_SERVER_Client *client, int is_nat)
560 struct PendingMessage *pm;
561 struct WelcomeMessage welcome;
563 if (is_nat != GNUNET_YES)
564 GNUNET_assert (client != NULL);
566 GNUNET_assert (client == NULL);
568 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
569 "Creating new session for peer `%4s'\n",
570 GNUNET_i2s (target));
572 ret = GNUNET_malloc (sizeof (struct Session));
573 ret->last_activity = GNUNET_TIME_absolute_get ();
574 ret->plugin = plugin;
575 ret->is_nat = is_nat;
576 if (is_nat != GNUNET_YES) /* If not a NAT WAIT conn, add it to global list */
578 ret->next = plugin->sessions;
579 plugin->sessions = ret;
581 ret->client = client;
582 ret->target = *target;
583 ret->expecting_welcome = GNUNET_YES;
584 pm = GNUNET_malloc (sizeof (struct PendingMessage) +
585 sizeof (struct WelcomeMessage));
586 pm->msg = (const char *) &pm[1];
587 pm->message_size = sizeof (struct WelcomeMessage);
588 welcome.header.size = htons (sizeof (struct WelcomeMessage));
589 welcome.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME);
590 welcome.clientIdentity = *plugin->env->my_identity;
591 memcpy (&pm[1], &welcome, sizeof (welcome));
592 pm->timeout = GNUNET_TIME_UNIT_FOREVER_ABS;
593 GNUNET_STATISTICS_update (plugin->env->stats,
594 gettext_noop ("# bytes currently in TCP buffers"),
595 pm->message_size, GNUNET_NO);
596 GNUNET_CONTAINER_DLL_insert (ret->pending_messages_head,
597 ret->pending_messages_tail, pm);
598 if (is_nat != GNUNET_YES)
599 GNUNET_STATISTICS_update (plugin->env->stats,
600 gettext_noop ("# TCP sessions active"), 1,
607 * If we have pending messages, ask the server to
608 * transmit them (schedule the respective tasks, etc.)
610 * @param session for which session should we do this
613 process_pending_messages (struct Session *session);
617 * Function called to notify a client about the socket
618 * being ready to queue more data. "buf" will be
619 * NULL and "size" zero if the socket was closed for
620 * writing in the meantime.
623 * @param size number of bytes available in buf
624 * @param buf where the callee should write the message
625 * @return number of bytes written to buf
628 do_transmit (void *cls, size_t size, void *buf)
630 struct Session *session = cls;
631 struct GNUNET_PeerIdentity pid;
632 struct Plugin *plugin;
633 struct PendingMessage *pos;
634 struct PendingMessage *hd;
635 struct PendingMessage *tl;
636 struct GNUNET_TIME_Absolute now;
640 GNUNET_assert (session != NULL);
641 session->transmit_handle = NULL;
642 plugin = session->plugin;
646 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
647 "Timeout trying to transmit to peer `%4s', discarding message queue.\n",
648 GNUNET_i2s (&session->target));
650 /* timeout; cancel all messages that have already expired */
654 now = GNUNET_TIME_absolute_get ();
655 while ((NULL != (pos = session->pending_messages_head)) &&
656 (pos->timeout.abs_value <= now.abs_value))
658 GNUNET_CONTAINER_DLL_remove (session->pending_messages_head,
659 session->pending_messages_tail, pos);
661 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
662 "Failed to transmit %u byte message to `%4s'.\n",
663 pos->message_size, GNUNET_i2s (&session->target));
665 ret += pos->message_size;
666 GNUNET_CONTAINER_DLL_insert_after (hd, tl, tl, pos);
668 /* do this call before callbacks (so that if callbacks destroy
669 * session, they have a chance to cancel actions done by this
671 process_pending_messages (session);
672 pid = session->target;
673 /* no do callbacks and do not use session again since
674 * the callbacks may abort the session */
675 while (NULL != (pos = hd))
677 GNUNET_CONTAINER_DLL_remove (hd, tl, pos);
678 if (pos->transmit_cont != NULL)
679 pos->transmit_cont (pos->transmit_cont_cls, &pid, GNUNET_SYSERR);
682 GNUNET_STATISTICS_update (plugin->env->stats,
683 gettext_noop ("# bytes currently in TCP buffers"),
684 -(int64_t) ret, GNUNET_NO);
685 GNUNET_STATISTICS_update (plugin->env->stats,
687 ("# bytes discarded by TCP (timeout)"), ret,
691 /* copy all pending messages that would fit */
696 while (NULL != (pos = session->pending_messages_head))
698 if (ret + pos->message_size > size)
700 GNUNET_CONTAINER_DLL_remove (session->pending_messages_head,
701 session->pending_messages_tail, pos);
702 GNUNET_assert (size >= pos->message_size);
703 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
704 "Transmitting message of type %u\n",
705 ntohs (((struct GNUNET_MessageHeader *) pos->msg)->type));
706 /* FIXME: this memcpy can be up to 7% of our total runtime */
707 memcpy (cbuf, pos->msg, pos->message_size);
708 cbuf += pos->message_size;
709 ret += pos->message_size;
710 size -= pos->message_size;
711 GNUNET_CONTAINER_DLL_insert_tail (hd, tl, pos);
713 /* schedule 'continuation' before callbacks so that callbacks that
714 * cancel everything don't cause us to use a session that no longer
716 process_pending_messages (session);
717 session->last_activity = GNUNET_TIME_absolute_get ();
718 pid = session->target;
719 /* we'll now call callbacks that may cancel the session; hence
720 * we should not use 'session' after this point */
721 while (NULL != (pos = hd))
723 GNUNET_CONTAINER_DLL_remove (hd, tl, pos);
724 if (pos->transmit_cont != NULL)
725 pos->transmit_cont (pos->transmit_cont_cls, &pid, GNUNET_OK);
728 GNUNET_assert (hd == NULL);
729 GNUNET_assert (tl == NULL);
731 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp", "Transmitting %u bytes\n",
734 GNUNET_STATISTICS_update (plugin->env->stats,
735 gettext_noop ("# bytes currently in TCP buffers"),
736 -(int64_t) ret, GNUNET_NO);
737 GNUNET_STATISTICS_update (plugin->env->stats,
738 gettext_noop ("# bytes transmitted via TCP"), ret,
745 * If we have pending messages, ask the server to
746 * transmit them (schedule the respective tasks, etc.)
748 * @param session for which session should we do this
751 process_pending_messages (struct Session *session)
753 struct PendingMessage *pm;
755 GNUNET_assert (session->client != NULL);
756 if (session->transmit_handle != NULL)
758 if (NULL == (pm = session->pending_messages_head))
761 session->transmit_handle =
762 GNUNET_SERVER_notify_transmit_ready (session->client, pm->message_size,
763 GNUNET_TIME_absolute_get_remaining
764 (pm->timeout), &do_transmit,
770 * Functions with this signature are called whenever we need
771 * to close a session due to a disconnect or failure to
772 * establish a connection.
774 * @param session session to close down
777 disconnect_session (struct Session *session)
779 struct Session *prev;
781 struct PendingMessage *pm;
784 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
785 "Disconnecting from `%4s' at %s.\n",
786 GNUNET_i2s (&session->target),
787 (session->connect_addr !=
788 NULL) ? tcp_address_to_string (session->plugin,
789 session->connect_addr,
790 session->connect_alen) :
793 /* remove from session list */
795 pos = session->plugin->sessions;
796 while (pos != session)
802 session->plugin->sessions = session->next;
804 prev->next = session->next;
807 if (session->transmit_handle != NULL)
809 GNUNET_CONNECTION_notify_transmit_ready_cancel (session->transmit_handle);
810 session->transmit_handle = NULL;
812 session->plugin->env->session_end (session->plugin->env->cls,
813 &session->target, session);
814 while (NULL != (pm = session->pending_messages_head))
817 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
819 NULL ? "Could not deliver message to `%4s'.\n" :
820 "Could not deliver message to `%4s', notifying.\n",
821 GNUNET_i2s (&session->target));
823 GNUNET_STATISTICS_update (session->plugin->env->stats,
824 gettext_noop ("# bytes currently in TCP buffers"),
825 -(int64_t) pm->message_size, GNUNET_NO);
826 GNUNET_STATISTICS_update (session->plugin->env->stats,
828 ("# bytes discarded by TCP (disconnect)"),
829 pm->message_size, GNUNET_NO);
830 GNUNET_CONTAINER_DLL_remove (session->pending_messages_head,
831 session->pending_messages_tail, pm);
832 if (NULL != pm->transmit_cont)
833 pm->transmit_cont (pm->transmit_cont_cls, &session->target,
837 GNUNET_break (session->client != NULL);
838 if (session->receive_delay_task != GNUNET_SCHEDULER_NO_TASK)
840 GNUNET_SCHEDULER_cancel (session->receive_delay_task);
841 if (session->client != NULL)
842 GNUNET_SERVER_receive_done (session->client, GNUNET_SYSERR);
844 if (session->client != NULL)
846 GNUNET_SERVER_client_drop (session->client);
847 session->client = NULL;
849 GNUNET_STATISTICS_update (session->plugin->env->stats,
850 gettext_noop ("# TCP sessions active"), -1,
852 GNUNET_free_non_null (session->connect_addr);
853 GNUNET_assert (NULL == session->transmit_handle);
854 GNUNET_free (session);
859 * Given two otherwise equivalent sessions, pick the better one.
861 * @param s1 one session (also default)
862 * @param s2 other session
863 * @return "better" session (more active)
865 static struct Session *
866 select_better_session (struct Session *s1, struct Session *s2)
872 if ((s1->expecting_welcome == GNUNET_NO) &&
873 (s2->expecting_welcome == GNUNET_YES))
875 if ((s1->expecting_welcome == GNUNET_YES) &&
876 (s2->expecting_welcome == GNUNET_NO))
878 if (s1->last_activity.abs_value < s2->last_activity.abs_value)
880 if (s1->last_activity.abs_value > s2->last_activity.abs_value)
882 if ((GNUNET_YES == s1->inbound) && (GNUNET_NO == s2->inbound))
884 if ((GNUNET_NO == s1->inbound) && (GNUNET_YES == s2->inbound))
892 * Function that can be used by the transport service to transmit
893 * a message using the plugin. Note that in the case of a
894 * peer disconnecting, the continuation MUST be called
895 * prior to the disconnect notification itself. This function
896 * will be called with this peer's HELLO message to initiate
897 * a fresh connection to another peer.
900 * @param target who should receive this message
901 * @param msg the message to transmit
902 * @param msgbuf_size number of bytes in 'msg'
903 * @param priority how important is the message (most plugins will
904 * ignore message priority and just FIFO)
905 * @param timeout how long to wait at most for the transmission (does not
906 * require plugins to discard the message after the timeout,
907 * just advisory for the desired delay; most plugins will ignore
909 * @param session which session must be used (or NULL for "any")
910 * @param addr the address to use (can be NULL if the plugin
911 * is "on its own" (i.e. re-use existing TCP connection))
912 * @param addrlen length of the address in bytes
913 * @param force_address GNUNET_YES if the plugin MUST use the given address,
914 * GNUNET_NO means the plugin may use any other address and
915 * GNUNET_SYSERR means that only reliable existing
916 * bi-directional connections should be used (regardless
918 * @param cont continuation to call once the message has
919 * been transmitted (or if the transport is ready
920 * for the next transmission call; or if the
921 * peer disconnected...); can be NULL
922 * @param cont_cls closure for cont
923 * @return number of bytes used (on the physical network, with overheads);
924 * -1 on hard errors (i.e. address invalid); 0 is a legal value
925 * and does NOT mean that the message was not transmitted (DV and NAT)
928 tcp_plugin_send (void *cls, const struct GNUNET_PeerIdentity *target,
929 const char *msg, size_t msgbuf_size, uint32_t priority,
930 struct GNUNET_TIME_Relative timeout, struct Session *session,
931 const void *addr, size_t addrlen, int force_address,
932 GNUNET_TRANSPORT_TransmitContinuation cont, void *cont_cls)
934 struct Plugin *plugin = cls;
935 struct Session *cand_session;
936 struct Session *next;
937 struct PendingMessage *pm;
938 struct GNUNET_CONNECTION_Handle *sa;
942 struct sockaddr_in a4;
943 struct sockaddr_in6 a6;
944 const struct IPv4TcpAddress *t4;
945 const struct IPv6TcpAddress *t6;
946 unsigned int is_natd;
948 GNUNET_STATISTICS_update (plugin->env->stats,
949 gettext_noop ("# bytes TCP was asked to transmit"),
950 msgbuf_size, GNUNET_NO);
951 /* FIXME: we could do this cheaper with a hash table
952 * where we could restrict the iteration to entries that match
953 * the target peer... */
958 next = plugin->sessions;
959 while (NULL != (session = next))
961 next = session->next;
962 GNUNET_assert (session->client != NULL);
964 memcmp (target, &session->target,
965 sizeof (struct GNUNET_PeerIdentity)))
967 if (((GNUNET_SYSERR == force_address) &&
968 (session->expecting_welcome == GNUNET_NO)) ||
969 (GNUNET_NO == force_address))
971 cand_session = select_better_session (cand_session, session);
974 if (GNUNET_SYSERR == force_address)
976 GNUNET_break (GNUNET_YES == force_address);
982 if ((addrlen != session->connect_alen) && (session->is_nat == GNUNET_NO))
984 if ((0 != memcmp (session->connect_addr, addr, addrlen)) &&
985 (session->is_nat == GNUNET_NO))
987 cand_session = select_better_session (cand_session, session);
989 session = cand_session;
991 if ((session == NULL) && (addrlen == 0))
994 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
995 "Asked to transmit to `%4s' without address and I have no existing connection (failing).\n",
996 GNUNET_i2s (target));
998 GNUNET_STATISTICS_update (plugin->env->stats,
1000 ("# bytes discarded by TCP (no address and no connection)"),
1001 msgbuf_size, GNUNET_NO);
1004 if (session == NULL)
1006 if (addrlen == sizeof (struct IPv6TcpAddress))
1008 GNUNET_assert (NULL != addr); /* make static analysis happy */
1011 memset (&a6, 0, sizeof (a6));
1012 #if HAVE_SOCKADDR_IN_SIN_LEN
1013 a6.sin6_len = sizeof (a6);
1015 a6.sin6_family = AF_INET6;
1016 a6.sin6_port = t6->t6_port;
1017 if (t6->t6_port == 0)
1018 is_natd = GNUNET_YES;
1019 memcpy (&a6.sin6_addr, &t6->ipv6_addr, sizeof (struct in6_addr));
1023 else if (addrlen == sizeof (struct IPv4TcpAddress))
1025 GNUNET_assert (NULL != addr); /* make static analysis happy */
1028 memset (&a4, 0, sizeof (a4));
1029 #if HAVE_SOCKADDR_IN_SIN_LEN
1030 a4.sin_len = sizeof (a4);
1032 a4.sin_family = AF_INET;
1033 a4.sin_port = t4->t4_port;
1034 if (t4->t4_port == 0)
1035 is_natd = GNUNET_YES;
1036 a4.sin_addr.s_addr = t4->ipv4_addr;
1042 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, "tcp",
1043 _("Address of unexpected length: %u\n"), addrlen);
1048 if ((is_natd == GNUNET_YES) && (addrlen == sizeof (struct IPv6TcpAddress)))
1049 return -1; /* NAT client only works with IPv4 addresses */
1050 if (0 == plugin->max_connections)
1051 return -1; /* saturated */
1053 if ((is_natd == GNUNET_YES) && (NULL != plugin->nat) &&
1055 GNUNET_CONTAINER_multihashmap_contains (plugin->nat_wait_conns,
1056 &target->hashPubKey)))
1059 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1060 _("Found valid IPv4 NAT address (creating session)!\n"));
1062 session = create_session (plugin, target, NULL, GNUNET_YES);
1063 GNUNET_assert (session != NULL);
1065 /* create new message entry */
1066 pm = GNUNET_malloc (sizeof (struct PendingMessage) + msgbuf_size);
1067 /* FIXME: the memset of this malloc can be up to 2% of our total runtime */
1068 pm->msg = (const char *) &pm[1];
1069 memcpy (&pm[1], msg, msgbuf_size);
1070 /* FIXME: this memcpy can be up to 7% of our total run-time
1071 * (for transport service) */
1072 pm->message_size = msgbuf_size;
1073 pm->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1074 pm->transmit_cont = cont;
1075 pm->transmit_cont_cls = cont_cls;
1077 /* append pm to pending_messages list */
1078 GNUNET_CONTAINER_DLL_insert_tail (session->pending_messages_head,
1079 session->pending_messages_tail, pm);
1081 GNUNET_assert (GNUNET_CONTAINER_multihashmap_put
1082 (plugin->nat_wait_conns, &target->hashPubKey, session,
1083 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY) ==
1086 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1087 "Created NAT WAIT connection to `%4s' at `%s'\n",
1088 GNUNET_i2s (target), GNUNET_a2s (sb, sbs));
1090 GNUNET_NAT_run_client (plugin->nat, &a4);
1093 if ((is_natd == GNUNET_YES) &&
1095 GNUNET_CONTAINER_multihashmap_contains (plugin->nat_wait_conns,
1096 &target->hashPubKey)))
1098 /* Only do one NAT punch attempt per peer identity */
1101 sa = GNUNET_CONNECTION_create_from_sockaddr (af, sb, sbs);
1105 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1106 "Failed to create connection to `%4s' at `%s'\n",
1107 GNUNET_i2s (target), GNUNET_a2s (sb, sbs));
1109 GNUNET_STATISTICS_update (plugin->env->stats,
1111 ("# bytes discarded by TCP (failed to connect)"),
1112 msgbuf_size, GNUNET_NO);
1115 GNUNET_assert (0 != plugin->max_connections);
1116 plugin->max_connections--;
1118 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1119 "Asked to transmit to `%4s', creating fresh session using address `%s'.\n",
1120 GNUNET_i2s (target), GNUNET_a2s (sb, sbs));
1123 create_session (plugin, target,
1124 GNUNET_SERVER_connect_socket (plugin->server, sa),
1126 session->connect_addr = GNUNET_malloc (addrlen);
1127 memcpy (session->connect_addr, addr, addrlen);
1128 session->connect_alen = addrlen;
1131 struct GNUNET_ATS_Information ats;
1132 ats = plugin->env->get_address_type (plugin->env->cls, sb ,sbs);
1133 session->ats_address_network_type = ats.value;
1138 else /* session != NULL */
1140 /* check if session is valid */
1141 struct Session *ses = plugin->sessions;
1144 memcmp (target, &session->target, sizeof (struct GNUNET_PeerIdentity)))
1147 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1148 "Got session %p for `%s', but should be for peer `%s'!\n",
1149 session, GNUNET_i2s (&session->target),
1150 GNUNET_h2s (&target->hashPubKey));
1154 while ((ses != NULL) && (ses != session))
1161 GNUNET_assert (session != NULL);
1162 GNUNET_assert (session->client != NULL);
1165 GNUNET_SERVER_client_set_timeout (session->client,
1166 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1167 GNUNET_STATISTICS_update (plugin->env->stats,
1168 gettext_noop ("# bytes currently in TCP buffers"),
1169 msgbuf_size, GNUNET_NO);
1170 /* create new message entry */
1171 pm = GNUNET_malloc (sizeof (struct PendingMessage) + msgbuf_size);
1172 pm->msg = (const char *) &pm[1];
1173 memcpy (&pm[1], msg, msgbuf_size);
1174 pm->message_size = msgbuf_size;
1175 pm->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1176 pm->transmit_cont = cont;
1177 pm->transmit_cont_cls = cont_cls;
1179 /* append pm to pending_messages list */
1180 GNUNET_CONTAINER_DLL_insert_tail (session->pending_messages_head,
1181 session->pending_messages_tail, pm);
1183 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1184 "Asked to transmit %u bytes to `%s', added message to list.\n",
1185 msgbuf_size, GNUNET_i2s (target));
1187 process_pending_messages (session);
1193 * Function that can be called to force a disconnect from the
1194 * specified neighbour. This should also cancel all previously
1195 * scheduled transmissions. Obviously the transmission may have been
1196 * partially completed already, which is OK. The plugin is supposed
1197 * to close the connection (if applicable) and no longer call the
1198 * transmit continuation(s).
1200 * Finally, plugin MUST NOT call the services's receive function to
1201 * notify the service that the connection to the specified target was
1202 * closed after a getting this call.
1204 * @param cls closure
1205 * @param target peer for which the last transmission is
1209 tcp_plugin_disconnect (void *cls, const struct GNUNET_PeerIdentity *target)
1211 struct Plugin *plugin = cls;
1212 struct Session *session;
1213 struct Session *next;
1214 struct PendingMessage *pm;
1217 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1218 "Asked to cancel session with `%4s'\n", GNUNET_i2s (target));
1220 next = plugin->sessions;
1221 while (NULL != (session = next))
1223 next = session->next;
1225 memcmp (target, &session->target, sizeof (struct GNUNET_PeerIdentity)))
1227 pm = session->pending_messages_head;
1230 pm->transmit_cont = NULL;
1231 pm->transmit_cont_cls = NULL;
1234 GNUNET_STATISTICS_update (session->plugin->env->stats,
1236 ("# transport-service disconnect requests for TCP"),
1238 disconnect_session (session);
1244 * Context for address to string conversion.
1246 struct PrettyPrinterContext
1249 * Function to call with the result.
1251 GNUNET_TRANSPORT_AddressStringCallback asc;
1254 * Clsoure for 'asc'.
1259 * Port to add after the IP address.
1266 * Append our port and forward the result.
1268 * @param cls the 'struct PrettyPrinterContext*'
1269 * @param hostname hostname part of the address
1272 append_port (void *cls, const char *hostname)
1274 struct PrettyPrinterContext *ppc = cls;
1277 if (hostname == NULL)
1279 ppc->asc (ppc->asc_cls, NULL);
1283 GNUNET_asprintf (&ret, "%s:%d", hostname, ppc->port);
1284 ppc->asc (ppc->asc_cls, ret);
1290 * Convert the transports address to a nice, human-readable
1293 * @param cls closure
1294 * @param type name of the transport that generated the address
1295 * @param addr one of the addresses of the host, NULL for the last address
1296 * the specific address format depends on the transport
1297 * @param addrlen length of the address
1298 * @param numeric should (IP) addresses be displayed in numeric form?
1299 * @param timeout after how long should we give up?
1300 * @param asc function to call on each string
1301 * @param asc_cls closure for asc
1304 tcp_plugin_address_pretty_printer (void *cls, const char *type,
1305 const void *addr, size_t addrlen,
1307 struct GNUNET_TIME_Relative timeout,
1308 GNUNET_TRANSPORT_AddressStringCallback asc,
1311 struct PrettyPrinterContext *ppc;
1314 struct sockaddr_in a4;
1315 struct sockaddr_in6 a6;
1316 const struct IPv4TcpAddress *t4;
1317 const struct IPv6TcpAddress *t6;
1320 if (addrlen == sizeof (struct IPv6TcpAddress))
1323 memset (&a6, 0, sizeof (a6));
1324 a6.sin6_family = AF_INET6;
1325 a6.sin6_port = t6->t6_port;
1326 memcpy (&a6.sin6_addr, &t6->ipv6_addr, sizeof (struct in6_addr));
1327 port = ntohs (t6->t6_port);
1331 else if (addrlen == sizeof (struct IPv4TcpAddress))
1334 memset (&a4, 0, sizeof (a4));
1335 a4.sin_family = AF_INET;
1336 a4.sin_port = t4->t4_port;
1337 a4.sin_addr.s_addr = t4->ipv4_addr;
1338 port = ntohs (t4->t4_port);
1344 /* invalid address */
1345 GNUNET_break_op (0);
1346 asc (asc_cls, NULL);
1349 ppc = GNUNET_malloc (sizeof (struct PrettyPrinterContext));
1351 ppc->asc_cls = asc_cls;
1353 GNUNET_RESOLVER_hostname_get (sb, sbs, !numeric, timeout, &append_port, ppc);
1358 * Check if the given port is plausible (must be either our listen
1359 * port or our advertised port), or any port if we are behind NAT
1360 * and do not have a port open. If it is neither, we return
1363 * @param plugin global variables
1364 * @param in_port port number to check
1365 * @return GNUNET_OK if port is either open_port or adv_port
1368 check_port (struct Plugin *plugin, uint16_t in_port)
1370 if ((in_port == plugin->adv_port) || (in_port == plugin->open_port))
1372 return GNUNET_SYSERR;
1377 * Function that will be called to check if a binary address for this
1378 * plugin is well-formed and corresponds to an address for THIS peer
1379 * (as per our configuration). Naturally, if absolutely necessary,
1380 * plugins can be a bit conservative in their answer, but in general
1381 * plugins should make sure that the address does not redirect
1382 * traffic to a 3rd party that might try to man-in-the-middle our
1385 * @param cls closure, our 'struct Plugin*'
1386 * @param addr pointer to the address
1387 * @param addrlen length of addr
1388 * @return GNUNET_OK if this is a plausible address for this peer
1389 * and transport, GNUNET_SYSERR if not
1392 tcp_plugin_check_address (void *cls, const void *addr, size_t addrlen)
1394 struct Plugin *plugin = cls;
1395 struct IPv4TcpAddress *v4;
1396 struct IPv6TcpAddress *v6;
1398 if ((addrlen != sizeof (struct IPv4TcpAddress)) &&
1399 (addrlen != sizeof (struct IPv6TcpAddress)))
1401 GNUNET_break_op (0);
1402 return GNUNET_SYSERR;
1404 if (addrlen == sizeof (struct IPv4TcpAddress))
1406 v4 = (struct IPv4TcpAddress *) addr;
1407 if (GNUNET_OK != check_port (plugin, ntohs (v4->t4_port)))
1408 return GNUNET_SYSERR;
1410 GNUNET_NAT_test_address (plugin->nat, &v4->ipv4_addr,
1411 sizeof (struct in_addr)))
1412 return GNUNET_SYSERR;
1416 v6 = (struct IPv6TcpAddress *) addr;
1417 if (IN6_IS_ADDR_LINKLOCAL (&v6->ipv6_addr))
1419 GNUNET_break_op (0);
1420 return GNUNET_SYSERR;
1422 if (GNUNET_OK != check_port (plugin, ntohs (v6->t6_port)))
1423 return GNUNET_SYSERR;
1425 GNUNET_NAT_test_address (plugin->nat, &v6->ipv6_addr,
1426 sizeof (struct in6_addr)))
1427 return GNUNET_SYSERR;
1434 * We've received a nat probe from this peer via TCP. Finish
1435 * creating the client session and resume sending of queued
1438 * @param cls closure
1439 * @param client identification of the client
1440 * @param message the actual message
1443 handle_tcp_nat_probe (void *cls, struct GNUNET_SERVER_Client *client,
1444 const struct GNUNET_MessageHeader *message)
1446 struct Plugin *plugin = cls;
1447 struct Session *session;
1448 const struct TCP_NAT_ProbeMessage *tcp_nat_probe;
1451 struct IPv4TcpAddress *t4;
1452 struct IPv6TcpAddress *t6;
1453 const struct sockaddr_in *s4;
1454 const struct sockaddr_in6 *s6;
1457 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp", "received NAT probe\n");
1459 /* We have received a TCP NAT probe, meaning we (hopefully) initiated
1460 * a connection to this peer by running gnunet-nat-client. This peer
1461 * received the punch message and now wants us to use the new connection
1462 * as the default for that peer. Do so and then send a WELCOME message
1463 * so we can really be connected!
1465 if (ntohs (message->size) != sizeof (struct TCP_NAT_ProbeMessage))
1467 GNUNET_break_op (0);
1468 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1472 tcp_nat_probe = (const struct TCP_NAT_ProbeMessage *) message;
1474 memcmp (&tcp_nat_probe->clientIdentity, plugin->env->my_identity,
1475 sizeof (struct GNUNET_PeerIdentity)))
1477 /* refuse connections from ourselves */
1478 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1483 GNUNET_CONTAINER_multihashmap_get (plugin->nat_wait_conns,
1485 clientIdentity.hashPubKey);
1486 if (session == NULL)
1489 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1490 "Did NOT find session for NAT probe!\n");
1492 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1496 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1497 "Found session for NAT probe!\n");
1499 GNUNET_assert (GNUNET_CONTAINER_multihashmap_remove
1500 (plugin->nat_wait_conns,
1501 &tcp_nat_probe->clientIdentity.hashPubKey,
1502 session) == GNUNET_YES);
1503 if (GNUNET_OK != GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
1506 GNUNET_free (session);
1507 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1511 GNUNET_SERVER_client_keep (client);
1512 session->client = client;
1513 session->last_activity = GNUNET_TIME_absolute_get ();
1514 session->inbound = GNUNET_NO;
1517 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1518 "Found address `%s' for incoming connection\n",
1519 GNUNET_a2s (vaddr, alen));
1521 switch (((const struct sockaddr *) vaddr)->sa_family)
1525 t4 = GNUNET_malloc (sizeof (struct IPv4TcpAddress));
1526 t4->t4_port = s4->sin_port;
1527 t4->ipv4_addr = s4->sin_addr.s_addr;
1528 session->connect_addr = t4;
1529 session->connect_alen = sizeof (struct IPv4TcpAddress);
1533 t6 = GNUNET_malloc (sizeof (struct IPv6TcpAddress));
1534 t6->t6_port = s6->sin6_port;
1535 memcpy (&t6->ipv6_addr, &s6->sin6_addr, sizeof (struct in6_addr));
1536 session->connect_addr = t6;
1537 session->connect_alen = sizeof (struct IPv6TcpAddress);
1540 GNUNET_break_op (0);
1542 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1543 "Bad address for incoming connection!\n");
1545 GNUNET_free (vaddr);
1546 GNUNET_SERVER_client_drop (client);
1547 GNUNET_free (session);
1548 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1551 GNUNET_free (vaddr);
1553 session->next = plugin->sessions;
1554 plugin->sessions = session;
1555 GNUNET_STATISTICS_update (plugin->env->stats,
1556 gettext_noop ("# TCP sessions active"), 1,
1558 process_pending_messages (session);
1559 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1564 * We've received a welcome from this peer via TCP. Possibly create a
1565 * fresh client record and send back our welcome.
1567 * @param cls closure
1568 * @param client identification of the client
1569 * @param message the actual message
1572 handle_tcp_welcome (void *cls, struct GNUNET_SERVER_Client *client,
1573 const struct GNUNET_MessageHeader *message)
1575 struct Plugin *plugin = cls;
1576 const struct WelcomeMessage *wm = (const struct WelcomeMessage *) message;
1577 struct Session *session;
1580 struct IPv4TcpAddress *t4;
1581 struct IPv6TcpAddress *t6;
1582 const struct sockaddr_in *s4;
1583 const struct sockaddr_in6 *s6;
1586 memcmp (&wm->clientIdentity, plugin->env->my_identity,
1587 sizeof (struct GNUNET_PeerIdentity)))
1589 /* refuse connections from ourselves */
1590 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1594 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1595 "Received %s message from `%4s'.\n", "WELCOME",
1596 GNUNET_i2s (&wm->clientIdentity));
1598 GNUNET_STATISTICS_update (plugin->env->stats,
1599 gettext_noop ("# TCP WELCOME messages received"), 1,
1601 session = find_session_by_client (plugin, client);
1603 if (session == NULL)
1606 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1607 "Received %s message from a `%4s', creating new session\n",
1608 "WELCOME", GNUNET_i2s (&wm->clientIdentity));
1610 GNUNET_SERVER_client_keep (client);
1611 session = create_session (plugin, &wm->clientIdentity, client, GNUNET_NO);
1612 session->inbound = GNUNET_YES;
1613 if (GNUNET_OK == GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
1616 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1617 "Found address `%s' for incoming connection\n",
1618 GNUNET_a2s (vaddr, alen));
1621 if (alen == sizeof (struct sockaddr_in))
1624 t4 = GNUNET_malloc (sizeof (struct IPv4TcpAddress));
1625 t4->t4_port = s4->sin_port;
1626 t4->ipv4_addr = s4->sin_addr.s_addr;
1627 session->connect_addr = t4;
1628 session->connect_alen = sizeof (struct IPv4TcpAddress);
1630 else if (alen == sizeof (struct sockaddr_in6))
1633 t6 = GNUNET_malloc (sizeof (struct IPv6TcpAddress));
1634 t6->t6_port = s6->sin6_port;
1635 memcpy (&t6->ipv6_addr, &s6->sin6_addr, sizeof (struct in6_addr));
1636 session->connect_addr = t6;
1637 session->connect_alen = sizeof (struct IPv6TcpAddress);
1640 struct GNUNET_ATS_Information ats;
1641 ats = plugin->env->get_address_type (plugin->env->cls, vaddr ,alen);
1642 session->ats_address_network_type = ats.value;
1644 GNUNET_free (vaddr);
1649 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1650 "Did not obtain TCP socket address for incoming connection\n");
1653 process_pending_messages (session);
1658 if (GNUNET_OK == GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
1660 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1661 "Found address `%s' (already have session)\n",
1662 GNUNET_a2s (vaddr, alen));
1663 GNUNET_free (vaddr);
1668 if (session->expecting_welcome != GNUNET_YES)
1670 GNUNET_break_op (0);
1671 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1674 session->last_activity = GNUNET_TIME_absolute_get ();
1675 session->expecting_welcome = GNUNET_NO;
1676 GNUNET_SERVER_client_set_timeout (client,
1677 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1678 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1683 * Task to signal the server that we can continue
1684 * receiving from the TCP client now.
1686 * @param cls the 'struct Session*'
1687 * @param tc task context (unused)
1690 delayed_done (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1692 struct Session *session = cls;
1693 struct GNUNET_TIME_Relative delay;
1694 struct GNUNET_ATS_Information ats;
1696 session->receive_delay_task = GNUNET_SCHEDULER_NO_TASK;
1698 session->plugin->env->receive (session->plugin->env->cls,
1699 &session->target, NULL, &ats, 0, session,
1701 if (delay.rel_value == 0)
1702 GNUNET_SERVER_receive_done (session->client, GNUNET_OK);
1704 session->receive_delay_task =
1705 GNUNET_SCHEDULER_add_delayed (delay, &delayed_done, session);
1710 * We've received data for this peer via TCP. Unbox,
1711 * compute latency and forward.
1713 * @param cls closure
1714 * @param client identification of the client
1715 * @param message the actual message
1718 handle_tcp_data (void *cls, struct GNUNET_SERVER_Client *client,
1719 const struct GNUNET_MessageHeader *message)
1721 struct Plugin *plugin = cls;
1722 struct Session *session;
1723 struct GNUNET_TIME_Relative delay;
1726 type = ntohs (message->type);
1727 if ((GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME == type) ||
1728 (GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE == type))
1730 /* We don't want to propagate WELCOME and NAT Probe messages up! */
1731 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1734 session = find_session_by_client (plugin, client);
1735 if ((NULL == session) || (GNUNET_YES == session->expecting_welcome))
1737 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1740 session->last_activity = GNUNET_TIME_absolute_get ();
1742 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1743 "Passing %u bytes of type %u from `%4s' to transport service.\n",
1744 (unsigned int) ntohs (message->size),
1745 (unsigned int) ntohs (message->type),
1746 GNUNET_i2s (&session->target));
1748 GNUNET_STATISTICS_update (plugin->env->stats,
1749 gettext_noop ("# bytes received via TCP"),
1750 ntohs (message->size), GNUNET_NO);
1751 struct GNUNET_ATS_Information distance[2];
1753 distance[0].type = htonl (GNUNET_ATS_QUALITY_NET_DISTANCE);
1754 distance[0].value = htonl (1);
1755 distance[1].type = htonl (GNUNET_ATS_NETWORK_TYPE);
1756 distance[1].value = session->ats_address_network_type;
1757 GNUNET_break (ntohl(session->ats_address_network_type) != GNUNET_ATS_NET_UNSPECIFIED);
1760 plugin->env->receive (plugin->env->cls, &session->target, message,
1761 (const struct GNUNET_ATS_Information *) &distance,
1764 session->inbound) ? NULL : session->connect_addr,
1766 session->inbound) ? 0 : session->connect_alen);
1767 if (delay.rel_value == 0)
1769 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1774 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1775 "Throttling receiving from `%s' for %llu ms\n",
1776 GNUNET_i2s (&session->target),
1777 (unsigned long long) delay.rel_value);
1779 GNUNET_SERVER_disable_receive_done_warning (client);
1780 session->receive_delay_task =
1781 GNUNET_SCHEDULER_add_delayed (delay, &delayed_done, session);
1787 * Functions with this signature are called whenever a peer
1788 * is disconnected on the network level.
1790 * @param cls closure
1791 * @param client identification of the client
1794 disconnect_notify (void *cls, struct GNUNET_SERVER_Client *client)
1796 struct Plugin *plugin = cls;
1797 struct Session *session;
1801 plugin->max_connections++;
1802 session = find_session_by_client (plugin, client);
1803 if (session == NULL)
1804 return; /* unknown, nothing to do */
1806 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1807 "Destroying session of `%4s' with %s due to network-level disconnect.\n",
1808 GNUNET_i2s (&session->target),
1809 (session->connect_addr !=
1810 NULL) ? tcp_address_to_string (session->plugin,
1811 session->connect_addr,
1812 session->connect_alen) :
1815 GNUNET_STATISTICS_update (session->plugin->env->stats,
1817 ("# network-level TCP disconnect events"), 1,
1819 disconnect_session (session);
1824 * We can now send a probe message, copy into buffer to really send.
1826 * @param cls closure, a struct TCPProbeContext
1827 * @param size max size to copy
1828 * @param buf buffer to copy message to
1829 * @return number of bytes copied into buf
1832 notify_send_probe (void *cls, size_t size, void *buf)
1834 struct TCPProbeContext *tcp_probe_ctx = cls;
1835 struct Plugin *plugin = tcp_probe_ctx->plugin;
1838 tcp_probe_ctx->transmit_handle = NULL;
1839 GNUNET_CONTAINER_DLL_remove (plugin->probe_head, plugin->probe_tail,
1843 GNUNET_CONNECTION_destroy (tcp_probe_ctx->sock, GNUNET_NO);
1844 GNUNET_free (tcp_probe_ctx);
1847 GNUNET_assert (size >= sizeof (tcp_probe_ctx->message));
1848 memcpy (buf, &tcp_probe_ctx->message, sizeof (tcp_probe_ctx->message));
1849 GNUNET_SERVER_connect_socket (tcp_probe_ctx->plugin->server,
1850 tcp_probe_ctx->sock);
1851 ret = sizeof (tcp_probe_ctx->message);
1852 GNUNET_free (tcp_probe_ctx);
1858 * Function called by the NAT subsystem suggesting another peer wants
1859 * to connect to us via connection reversal. Try to connect back to the
1862 * @param cls closure
1863 * @param addr address to try
1864 * @param addrlen number of bytes in addr
1867 try_connection_reversal (void *cls, const struct sockaddr *addr,
1870 struct Plugin *plugin = cls;
1871 struct GNUNET_CONNECTION_Handle *sock;
1872 struct TCPProbeContext *tcp_probe_ctx;
1875 * We have received an ICMP response, ostensibly from a peer
1876 * that wants to connect to us! Send a message to establish a connection.
1878 sock = GNUNET_CONNECTION_create_from_sockaddr (AF_INET, addr, addrlen);
1881 /* failed for some odd reason (out of sockets?); ignore attempt */
1885 /* FIXME: do we need to track these probe context objects so that
1886 * we can clean them up on plugin unload? */
1887 tcp_probe_ctx = GNUNET_malloc (sizeof (struct TCPProbeContext));
1888 tcp_probe_ctx->message.header.size =
1889 htons (sizeof (struct TCP_NAT_ProbeMessage));
1890 tcp_probe_ctx->message.header.type =
1891 htons (GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE);
1892 memcpy (&tcp_probe_ctx->message.clientIdentity, plugin->env->my_identity,
1893 sizeof (struct GNUNET_PeerIdentity));
1894 tcp_probe_ctx->plugin = plugin;
1895 tcp_probe_ctx->sock = sock;
1896 GNUNET_CONTAINER_DLL_insert (plugin->probe_head, plugin->probe_tail,
1898 tcp_probe_ctx->transmit_handle =
1899 GNUNET_CONNECTION_notify_transmit_ready (sock,
1900 ntohs (tcp_probe_ctx->
1901 message.header.size),
1902 GNUNET_TIME_UNIT_FOREVER_REL,
1910 * Entry point for the plugin.
1912 * @param cls closure, the 'struct GNUNET_TRANSPORT_PluginEnvironment*'
1913 * @return the 'struct GNUNET_TRANSPORT_PluginFunctions*' or NULL on error
1916 libgnunet_plugin_transport_tcp_init (void *cls)
1918 static const struct GNUNET_SERVER_MessageHandler my_handlers[] = {
1919 {&handle_tcp_welcome, NULL, GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME,
1920 sizeof (struct WelcomeMessage)},
1921 {&handle_tcp_nat_probe, NULL, GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE,
1922 sizeof (struct TCP_NAT_ProbeMessage)},
1923 {&handle_tcp_data, NULL, GNUNET_MESSAGE_TYPE_ALL, 0},
1926 struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
1927 struct GNUNET_TRANSPORT_PluginFunctions *api;
1928 struct Plugin *plugin;
1929 struct GNUNET_SERVICE_Context *service;
1930 unsigned long long aport;
1931 unsigned long long bport;
1932 unsigned long long max_connections;
1934 struct GNUNET_TIME_Relative idle_timeout;
1936 struct sockaddr **addrs;
1937 socklen_t *addrlens;
1940 GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-tcp",
1943 max_connections = 128;
1947 GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-tcp", "PORT",
1948 &bport)) || (bport > 65535) ||
1950 GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-tcp",
1951 "ADVERTISED-PORT", &aport)) &&
1954 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, "tcp",
1956 ("Require valid port number for service `%s' in configuration!\n"),
1966 service = GNUNET_SERVICE_start ("transport-tcp", env->cfg);
1967 if (service == NULL)
1969 GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, "tcp",
1970 _("Failed to start service.\n"));
1979 plugin = GNUNET_malloc (sizeof (struct Plugin));
1980 plugin->max_connections = max_connections;
1981 plugin->open_port = bport;
1982 plugin->adv_port = aport;
1984 plugin->lsock = NULL;
1985 if ((service != NULL) &&
1988 GNUNET_SERVICE_get_server_addresses ("transport-tcp", env->cfg, &addrs,
1992 GNUNET_NAT_register (env->cfg, GNUNET_YES, aport, (unsigned int) ret,
1993 (const struct sockaddr **) addrs, addrlens,
1994 &tcp_nat_port_map_callback,
1995 &try_connection_reversal, plugin);
1999 GNUNET_assert (addrs[ret] != NULL);
2000 GNUNET_free (addrs[ret]);
2002 GNUNET_free_non_null (addrs);
2003 GNUNET_free_non_null (addrlens);
2008 GNUNET_NAT_register (env->cfg, GNUNET_YES, 0, 0, NULL, NULL, NULL,
2009 &try_connection_reversal, plugin);
2011 api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
2013 api->send = &tcp_plugin_send;
2014 api->disconnect = &tcp_plugin_disconnect;
2015 api->address_pretty_printer = &tcp_plugin_address_pretty_printer;
2016 api->check_address = &tcp_plugin_check_address;
2017 api->address_to_string = &tcp_address_to_string;
2018 plugin->service = service;
2019 if (service != NULL)
2021 plugin->server = GNUNET_SERVICE_get_server (service);
2026 GNUNET_CONFIGURATION_get_value_time (env->cfg, "transport-tcp",
2027 "TIMEOUT", &idle_timeout))
2029 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, "tcp",
2030 _("Failed to find option %s in section %s!\n"),
2031 "TIMEOUT", "transport-tcp");
2032 if (plugin->nat != NULL)
2033 GNUNET_NAT_unregister (plugin->nat);
2034 GNUNET_free (plugin);
2039 GNUNET_SERVER_create_with_sockets (&plugin_tcp_access_check, plugin,
2040 NULL, idle_timeout, GNUNET_YES);
2042 plugin->handlers = GNUNET_malloc (sizeof (my_handlers));
2043 memcpy (plugin->handlers, my_handlers, sizeof (my_handlers));
2045 i < sizeof (my_handlers) / sizeof (struct GNUNET_SERVER_MessageHandler);
2047 plugin->handlers[i].callback_cls = plugin;
2048 GNUNET_SERVER_add_handlers (plugin->server, plugin->handlers);
2049 GNUNET_SERVER_disconnect_notify (plugin->server, &disconnect_notify, plugin);
2050 plugin->nat_wait_conns = GNUNET_CONTAINER_multihashmap_create (16);
2052 GNUNET_log_from (GNUNET_ERROR_TYPE_INFO, "tcp",
2053 _("TCP transport listening on port %llu\n"), bport);
2055 GNUNET_log_from (GNUNET_ERROR_TYPE_INFO, "tcp",
2057 ("TCP transport not listening on any port (client only)\n"));
2059 GNUNET_log_from (GNUNET_ERROR_TYPE_INFO, "tcp",
2061 ("TCP transport advertises itself as being on port %llu\n"),
2068 * Exit point from the plugin.
2071 libgnunet_plugin_transport_tcp_done (void *cls)
2073 struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
2074 struct Plugin *plugin = api->cls;
2075 struct Session *session;
2076 struct TCPProbeContext *tcp_probe;
2078 while (NULL != (session = plugin->sessions))
2079 disconnect_session (session);
2080 if (plugin->service != NULL)
2081 GNUNET_SERVICE_stop (plugin->service);
2083 GNUNET_SERVER_destroy (plugin->server);
2084 GNUNET_free (plugin->handlers);
2085 if (plugin->nat != NULL)
2086 GNUNET_NAT_unregister (plugin->nat);
2087 while (NULL != (tcp_probe = plugin->probe_head))
2089 GNUNET_CONTAINER_DLL_remove (plugin->probe_head, plugin->probe_tail,
2091 GNUNET_CONNECTION_destroy (tcp_probe->sock, GNUNET_NO);
2092 GNUNET_free (tcp_probe);
2094 GNUNET_CONTAINER_multihashmap_destroy (plugin->nat_wait_conns);
2095 GNUNET_free (plugin);
2100 /* end of plugin_transport_tcp.c */