2 This file is part of GNUnet
3 (C) 2002--2014 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_util_lib.h"
29 #include "gnunet_nat_lib.h"
30 #include "gnunet_protocols.h"
31 #include "gnunet_resolver_service.h"
32 #include "gnunet_signatures.h"
33 #include "gnunet_statistics_service.h"
34 #include "gnunet_transport_service.h"
35 #include "gnunet_transport_plugin.h"
36 #include "transport.h"
38 #define LOG(kind,...) GNUNET_log_from (kind, "transport-tcp",__VA_ARGS__)
40 #define PLUGIN_NAME "tcp"
42 #define EXTRA_CHECKS ALLOW_EXTRA_CHECKS
45 * How long until we give up on establishing an NAT connection?
48 #define NAT_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 10)
50 GNUNET_NETWORK_STRUCT_BEGIN
54 * Initial handshake message for a session.
59 * Type is #GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME.
61 struct GNUNET_MessageHeader header;
64 * Identity of the node connecting (TCP client)
66 struct GNUNET_PeerIdentity clientIdentity;
71 * Basically a WELCOME message, but with the purpose
72 * of giving the waiting peer a client handle to use
74 struct TCP_NAT_ProbeMessage
77 * Type is #GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE.
79 struct GNUNET_MessageHeader header;
82 * Identity of the sender of the message.
84 struct GNUNET_PeerIdentity clientIdentity;
87 GNUNET_NETWORK_STRUCT_END
90 * Context for sending a NAT probe via TCP.
92 struct TCPProbeContext
96 * Active probes are kept in a DLL.
98 struct TCPProbeContext *next;
101 * Active probes are kept in a DLL.
103 struct TCPProbeContext *prev;
108 struct GNUNET_CONNECTION_Handle *sock;
111 * Message to be sent.
113 struct TCP_NAT_ProbeMessage message;
116 * Handle to the transmission.
118 struct GNUNET_CONNECTION_TransmitHandle *transmit_handle;
121 * Transport plugin handle.
123 struct Plugin *plugin;
126 GNUNET_NETWORK_STRUCT_BEGIN
129 * Network format for IPv4 addresses.
131 struct IPv4TcpAddress
134 * Optional options and flags for this address
139 * IPv4 address, in network byte order.
141 uint32_t ipv4_addr GNUNET_PACKED;
144 * Port number, in network byte order.
146 uint16_t t4_port GNUNET_PACKED;
151 * Network format for IPv6 addresses.
153 struct IPv6TcpAddress
156 * Optional flags for this address
163 struct in6_addr ipv6_addr GNUNET_PACKED;
166 * Port number, in network byte order.
168 uint16_t t6_port GNUNET_PACKED;
171 GNUNET_NETWORK_STRUCT_END
174 * Encapsulation of all of the state of the plugin.
179 * Information kept for each message that is yet to
182 struct PendingMessage
186 * This is a doubly-linked list.
188 struct PendingMessage *next;
191 * This is a doubly-linked list.
193 struct PendingMessage *prev;
196 * The pending message
201 * Continuation function to call once the message
202 * has been sent. Can be NULL if there is no
203 * continuation to call.
205 GNUNET_TRANSPORT_TransmitContinuation transmit_cont;
208 * Closure for transmit_cont.
210 void *transmit_cont_cls;
213 * Timeout value for the pending message.
215 struct GNUNET_TIME_Absolute timeout;
218 * So that the gnunet-service-transport can group messages together,
219 * these pending messages need to accept a message buffer and size
220 * instead of just a GNUNET_MessageHeader.
227 * Session handle for TCP connections.
232 * To whom are we talking to (set to our identity
233 * if we are still waiting for the welcome message)
235 struct GNUNET_PeerIdentity target;
240 struct SessionHeader header;
243 * Pointer to the global plugin struct.
245 struct Plugin *plugin;
248 * The client (used to identify this connection)
250 struct GNUNET_SERVER_Client *client;
253 * Task cleaning up a NAT client connection establishment attempt;
255 GNUNET_SCHEDULER_TaskIdentifier nat_connection_timeout;
258 * Messages currently pending for transmission
259 * to this peer, if any.
261 struct PendingMessage *pending_messages_head;
264 * Messages currently pending for transmission
265 * to this peer, if any.
267 struct PendingMessage *pending_messages_tail;
270 * Handle for pending transmission request.
272 struct GNUNET_SERVER_TransmitHandle *transmit_handle;
275 * Address of the other peer.
277 struct GNUNET_HELLO_Address *address;
280 * ID of task used to delay receiving more to throttle sender.
282 GNUNET_SCHEDULER_TaskIdentifier receive_delay_task;
285 * Session timeout task
287 GNUNET_SCHEDULER_TaskIdentifier timeout_task;
290 * When will this session time out?
292 struct GNUNET_TIME_Absolute timeout;
295 * Last activity on this connection. Used to select preferred
298 struct GNUNET_TIME_Absolute last_activity;
301 * Number of bytes waiting for transmission to this peer.
303 unsigned long long bytes_in_queue;
306 * Number of messages waiting for transmission to this peer.
308 unsigned int msgs_in_queue;
311 * Are we still expecting the welcome message? (#GNUNET_YES/#GNUNET_NO)
313 int expecting_welcome;
316 * Was this session created using NAT traversal?
321 * ATS network type in NBO
323 enum GNUNET_ATS_Network_Type ats_address_network_type;
327 * Encapsulation of all of the state of the plugin.
334 struct GNUNET_TRANSPORT_PluginEnvironment *env;
339 struct GNUNET_CONNECTION_Handle *lsock;
342 * Our handle to the NAT module.
344 struct GNUNET_NAT_Handle *nat;
347 * Map from peer identities to sessions for the given peer.
349 struct GNUNET_CONTAINER_MultiPeerMap *sessionmap;
352 * Handle to the network service.
354 struct GNUNET_SERVICE_Context *service;
357 * Handle to the server for this service.
359 struct GNUNET_SERVER_Handle *server;
362 * Copy of the handler array where the closures are
363 * set to this struct's instance.
365 struct GNUNET_SERVER_MessageHandler *handlers;
368 * Map of peers we have tried to contact behind a NAT
370 struct GNUNET_CONTAINER_MultiPeerMap *nat_wait_conns;
373 * List of active TCP probes.
375 struct TCPProbeContext *probe_head;
378 * List of active TCP probes.
380 struct TCPProbeContext *probe_tail;
383 * Handle for (DYN)DNS lookup of our external IP.
385 struct GNUNET_RESOLVER_RequestHandle *ext_dns;
388 * Function to call about session status changes.
390 GNUNET_TRANSPORT_SessionInfoCallback sic;
393 * Closure for @e sic.
398 * How many more TCP sessions are we allowed to open right now?
400 unsigned long long max_connections;
403 * How many more TCP sessions do we have right now?
405 unsigned long long cur_connections;
408 * ID of task used to update our addresses when one expires.
410 GNUNET_SCHEDULER_TaskIdentifier address_update_task;
418 * Port that we are actually listening on.
423 * Port that the user said we would have visible to the
432 * If a session monitor is attached, notify it about the new
435 * @param plugin our plugin
436 * @param session session that changed state
437 * @param state new state of the session
440 notify_session_monitor (struct Plugin *plugin,
441 struct Session *session,
442 enum GNUNET_TRANSPORT_SessionState state)
444 struct GNUNET_TRANSPORT_SessionInfo info;
446 if (NULL == plugin->sic)
448 memset (&info, 0, sizeof (info));
450 info.is_inbound = GNUNET_SYSERR; /* hard to say */
451 info.num_msg_pending = session->msgs_in_queue;
452 info.num_bytes_pending = session->bytes_in_queue;
453 /* info.receive_delay remains zero as this is not supported by UDP
454 (cannot selectively not receive from 'some' peer while continuing
455 to receive from others) */
456 info.session_timeout = session->timeout;
457 info.address = session->address;
458 plugin->sic (plugin->sic_cls,
465 * Function called for a quick conversion of the binary address to
466 * a numeric address. Note that the caller must not free the
467 * address and that the next call to this function is allowed
468 * to override the address again.
470 * @param cls closure ('struct Plugin*')
471 * @param addr binary address
472 * @param addrlen length of the address
473 * @return string representing the same address
476 tcp_address_to_string (void *cls,
482 * Function to check if an inbound connection is acceptable.
483 * Mostly used to limit the total number of open connections
486 * @param cls the `struct Plugin`
487 * @param ucred credentials, if available, otherwise NULL
488 * @param addr address
489 * @param addrlen length of address
490 * @return #GNUNET_YES to allow, #GNUNET_NO to deny, #GNUNET_SYSERR
491 * for unknown address family (will be denied).
494 plugin_tcp_access_check (void *cls,
495 const struct GNUNET_CONNECTION_Credentials *ucred,
496 const struct sockaddr *addr,
499 struct Plugin *plugin = cls;
500 LOG(GNUNET_ERROR_TYPE_DEBUG,
501 "Accepting new incoming TCP connection from `%s'\n",
502 GNUNET_a2s (addr, addrlen));
503 if (plugin->cur_connections >= plugin->max_connections)
505 plugin->cur_connections++;
511 * Our external IP address/port mapping has changed.
513 * @param cls closure, the `struct Plugin`
514 * @param add_remove #GNUNET_YES to mean the new public IP address, #GNUNET_NO to mean
515 * the previous (now invalid) one
516 * @param addr either the previous or the new public IP address
517 * @param addrlen actual length of @a addr
520 tcp_nat_port_map_callback (void *cls,
522 const struct sockaddr *addr,
525 struct Plugin *plugin = cls;
526 struct GNUNET_HELLO_Address *address;
527 struct IPv4TcpAddress t4;
528 struct IPv6TcpAddress t6;
532 LOG(GNUNET_ERROR_TYPE_INFO, "NAT notification to %s address `%s'\n",
533 (GNUNET_YES == add_remove) ? "add" : "remove",
534 GNUNET_a2s (addr, addrlen));
535 /* convert 'addr' to our internal format */
536 switch (addr->sa_family)
539 GNUNET_assert(addrlen == sizeof(struct sockaddr_in));
540 memset (&t4, 0, sizeof(t4));
541 t4.options = htonl (plugin->myoptions);
542 t4.ipv4_addr = ((struct sockaddr_in *) addr)->sin_addr.s_addr;
543 t4.t4_port = ((struct sockaddr_in *) addr)->sin_port;
548 GNUNET_assert(addrlen == sizeof(struct sockaddr_in6));
549 memset (&t6, 0, sizeof(t6));
550 memcpy (&t6.ipv6_addr, &((struct sockaddr_in6 *) addr)->sin6_addr,
551 sizeof(struct in6_addr));
552 t6.options = htonl (plugin->myoptions);
553 t6.t6_port = ((struct sockaddr_in6 *) addr)->sin6_port;
561 /* modify our published address list */
562 GNUNET_assert ((args == sizeof (struct IPv4TcpAddress)) ||
563 (args == sizeof (struct IPv6TcpAddress)));
564 address = GNUNET_HELLO_address_allocate (plugin->env->my_identity,
565 PLUGIN_NAME, arg, args, GNUNET_HELLO_ADDRESS_INFO_NONE);
566 plugin->env->notify_address (plugin->env->cls, add_remove, address);
567 GNUNET_HELLO_address_free(address);
572 * Function called for a quick conversion of the binary address to
573 * a numeric address. Note that the caller must not free the
574 * address and that the next call to this function is allowed
575 * to override the address again.
577 * @param cls closure (`struct Plugin*`)
578 * @param addr binary address
579 * @param addrlen length of @a addr
580 * @return string representing the same address
583 tcp_address_to_string (void *cls,
587 static char rbuf[INET6_ADDRSTRLEN + 12];
588 char buf[INET6_ADDRSTRLEN];
592 const struct IPv4TcpAddress *t4;
593 const struct IPv6TcpAddress *t6;
600 case sizeof(struct IPv6TcpAddress):
603 port = ntohs (t6->t6_port);
604 options = ntohl (t6->options);
605 memcpy (&a6, &t6->ipv6_addr, sizeof(a6));
608 case sizeof(struct IPv4TcpAddress):
611 port = ntohs (t4->t4_port);
612 options = ntohl (t4->options);
613 memcpy (&a4, &t4->ipv4_addr, sizeof(a4));
617 LOG (GNUNET_ERROR_TYPE_WARNING,
618 _("Unexpected address length: %u bytes\n"),
619 (unsigned int ) addrlen);
622 if (NULL == inet_ntop (af, sb, buf, INET6_ADDRSTRLEN))
624 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING,
628 GNUNET_snprintf (rbuf, sizeof(rbuf),
629 (af == AF_INET6) ? "%s.%u.[%s]:%u" : "%s.%u.%s:%u",
639 * Function called to convert a string address to
642 * @param cls closure (`struct Plugin*`)
643 * @param addr string address
644 * @param addrlen length of the address
645 * @param buf location to store the buffer
646 * @param added location to store the number of bytes in the buffer.
647 * If the function returns #GNUNET_SYSERR, its contents are undefined.
648 * @return #GNUNET_OK on success, #GNUNET_SYSERR on failure
651 tcp_string_to_address (void *cls,
657 struct sockaddr_storage socket_address;
663 /* Format tcp.options.address:port */
667 if ((NULL == addr) || (addrlen == 0))
670 return GNUNET_SYSERR;
672 if ('\0' != addr[addrlen - 1])
675 return GNUNET_SYSERR;
677 if (strlen (addr) != addrlen - 1)
680 return GNUNET_SYSERR;
682 plugin = GNUNET_strdup (addr);
683 optionstr = strchr (plugin, '.');
684 if (NULL == optionstr)
688 return GNUNET_SYSERR;
692 options = atol (optionstr);
693 address = strchr (optionstr, '.');
698 return GNUNET_SYSERR;
704 != GNUNET_STRINGS_to_address_ip (address, strlen (address),
709 return GNUNET_SYSERR;
713 switch (socket_address.ss_family)
717 struct IPv4TcpAddress *t4;
718 struct sockaddr_in *in4 = (struct sockaddr_in *) &socket_address;
719 t4 = GNUNET_new (struct IPv4TcpAddress);
720 t4->options = htonl (options);
721 t4->ipv4_addr = in4->sin_addr.s_addr;
722 t4->t4_port = in4->sin_port;
724 *added = sizeof(struct IPv4TcpAddress);
729 struct IPv6TcpAddress *t6;
730 struct sockaddr_in6 *in6 = (struct sockaddr_in6 *) &socket_address;
731 t6 = GNUNET_new (struct IPv6TcpAddress);
732 t6->options = htonl (options);
733 t6->ipv6_addr = in6->sin6_addr;
734 t6->t6_port = in6->sin6_port;
736 *added = sizeof(struct IPv6TcpAddress);
740 return GNUNET_SYSERR;
746 * Closure for #session_lookup_by_client_it().
748 struct SessionClientCtx
751 * Client we are looking for.
753 const struct GNUNET_SERVER_Client *client;
756 * Session that was found.
763 session_lookup_by_client_it (void *cls,
764 const struct GNUNET_PeerIdentity *key,
767 struct SessionClientCtx *sc_ctx = cls;
768 struct Session *s = value;
770 if (s->client == sc_ctx->client)
780 * Find the session handle for the given client.
781 * Currently uses both the hashmap and the client
782 * context, as the client context is new and the
783 * logic still needs to be tested.
785 * @param plugin the plugin
786 * @param client which client to find the session handle for
787 * @return NULL if no matching session exists
789 static struct Session *
790 lookup_session_by_client (struct Plugin *plugin,
791 struct GNUNET_SERVER_Client *client)
794 struct SessionClientCtx sc_ctx;
796 ret = GNUNET_SERVER_client_get_user_context (client, struct Session);
797 sc_ctx.client = client;
799 GNUNET_CONTAINER_multipeermap_iterate (plugin->sessionmap,
800 &session_lookup_by_client_it, &sc_ctx);
801 /* check both methods yield the same result */
802 GNUNET_break(ret == sc_ctx.ret);
808 * Functions with this signature are called whenever we need
809 * to close a session due to a disconnect or failure to
810 * establish a connection.
812 * @param cls the `struct Plugin`
813 * @param session session to close down
814 * @return #GNUNET_OK on success
817 tcp_disconnect_session (void *cls,
818 struct Session *session)
820 struct Plugin *plugin = cls;
821 struct PendingMessage *pm;
823 LOG(GNUNET_ERROR_TYPE_DEBUG,
824 "Disconnecting session of peer `%s' address `%s'\n",
825 GNUNET_i2s (&session->target),
826 tcp_address_to_string (NULL,
827 session->address->address,
828 session->address->address_length));
830 if (GNUNET_SCHEDULER_NO_TASK != session->timeout_task)
832 GNUNET_SCHEDULER_cancel (session->timeout_task);
833 session->timeout_task = GNUNET_SCHEDULER_NO_TASK;
834 session->timeout = GNUNET_TIME_UNIT_ZERO_ABS;
838 == GNUNET_CONTAINER_multipeermap_remove (plugin->sessionmap,
839 &session->target, session))
841 GNUNET_STATISTICS_update (session->plugin->env->stats,
842 gettext_noop ("# TCP sessions active"), -1, GNUNET_NO);
846 GNUNET_assert(GNUNET_YES ==
847 GNUNET_CONTAINER_multipeermap_remove (plugin->nat_wait_conns,
851 if (NULL != session->client)
852 GNUNET_SERVER_client_set_user_context (session->client,
856 if (NULL != session->transmit_handle)
858 GNUNET_SERVER_notify_transmit_ready_cancel (session->transmit_handle);
859 session->transmit_handle = NULL;
861 plugin->env->unregister_quota_notification (plugin->env->cls,
862 &session->target, PLUGIN_NAME, session);
863 session->plugin->env->session_end (session->plugin->env->cls,
864 session->address, session);
866 if (GNUNET_SCHEDULER_NO_TASK != session->nat_connection_timeout)
868 GNUNET_SCHEDULER_cancel (session->nat_connection_timeout);
869 session->nat_connection_timeout = GNUNET_SCHEDULER_NO_TASK;
872 while (NULL != (pm = session->pending_messages_head))
874 LOG (GNUNET_ERROR_TYPE_DEBUG,
875 (NULL != pm->transmit_cont)
876 ? "Could not deliver message to `%4s'.\n"
877 : "Could not deliver message to `%4s', notifying.\n",
878 GNUNET_i2s (&session->target));
879 GNUNET_STATISTICS_update (session->plugin->env->stats,
880 gettext_noop ("# bytes currently in TCP buffers"),
881 -(int64_t) pm->message_size, GNUNET_NO);
882 GNUNET_STATISTICS_update (session->plugin->env->stats,
883 gettext_noop ("# bytes discarded by TCP (disconnect)"),
886 GNUNET_CONTAINER_DLL_remove (session->pending_messages_head,
887 session->pending_messages_tail,
889 GNUNET_assert (0 < session->msgs_in_queue);
890 session->msgs_in_queue--;
891 GNUNET_assert (pm->message_size <= session->bytes_in_queue);
892 session->bytes_in_queue -= pm->message_size;
893 if (NULL != pm->transmit_cont)
894 pm->transmit_cont (pm->transmit_cont_cls,
901 if (session->receive_delay_task != GNUNET_SCHEDULER_NO_TASK )
903 GNUNET_SCHEDULER_cancel (session->receive_delay_task);
904 if (NULL != session->client)
905 GNUNET_SERVER_receive_done (session->client, GNUNET_SYSERR);
907 if (NULL != session->client)
909 GNUNET_SERVER_client_disconnect (session->client);
910 GNUNET_SERVER_client_drop (session->client);
911 session->client = NULL;
913 GNUNET_HELLO_address_free (session->address);
914 GNUNET_assert(NULL == session->transmit_handle);
915 GNUNET_free(session);
921 * Function that is called to get the keepalive factor.
922 * #GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT is divided by this number to
923 * calculate the interval between keepalive packets.
925 * @param cls closure with the `struct Plugin`
926 * @return keepalive factor
929 tcp_query_keepalive_factor (void *cls)
936 * Session was idle, so disconnect it
938 * @param cls the `struct Session` of the idle session
939 * @param tc scheduler context
942 session_timeout (void *cls,
943 const struct GNUNET_SCHEDULER_TaskContext *tc)
945 struct Session *s = cls;
946 struct GNUNET_TIME_Relative left;
948 s->timeout_task = GNUNET_SCHEDULER_NO_TASK;
949 left = GNUNET_TIME_absolute_get_remaining (s->timeout);
950 if (0 != left.rel_value_us)
952 /* not actually our turn yet, but let's at least update
953 the monitor, it may think we're about to die ... */
954 notify_session_monitor (s->plugin,
956 GNUNET_TRANSPORT_SS_UP);
957 s->timeout_task = GNUNET_SCHEDULER_add_delayed (left,
962 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
963 "Session %p was idle for %s, disconnecting\n",
965 GNUNET_STRINGS_relative_time_to_string (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
967 /* call session destroy function */
968 tcp_disconnect_session (s->plugin, s);
973 * Increment session timeout due to activity
975 * @param s session to increment timeout for
978 reschedule_session_timeout (struct Session *s)
980 GNUNET_assert(GNUNET_SCHEDULER_NO_TASK != s->timeout_task);
981 s->timeout = GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
986 * Create a new session. Also queues a welcome message.
988 * @param plugin the plugin
989 * @param address the address to create the session for
990 * @param client client to use, reference counter must have already been increased
991 * @param is_nat this a NAT session, we should wait for a client to
992 * connect to us from an address, then assign that to
994 * @return new session object
996 static struct Session *
997 create_session (struct Plugin *plugin,
998 const struct GNUNET_HELLO_Address *address,
999 struct GNUNET_SERVER_Client *client,
1002 struct Session *session;
1003 struct PendingMessage *pm;
1004 struct WelcomeMessage welcome;
1006 if (GNUNET_YES != is_nat)
1007 GNUNET_assert(NULL != client);
1009 GNUNET_assert(NULL == client);
1011 LOG(GNUNET_ERROR_TYPE_DEBUG,
1012 "Creating new session for peer `%4s'\n",
1013 GNUNET_i2s (&address->peer));
1014 session = GNUNET_new (struct Session);
1015 session->last_activity = GNUNET_TIME_absolute_get ();
1016 session->plugin = plugin;
1017 session->is_nat = is_nat;
1018 session->client = client;
1019 session->address = GNUNET_HELLO_address_copy (address);
1020 session->target = address->peer;
1021 session->expecting_welcome = GNUNET_YES;
1022 session->ats_address_network_type = GNUNET_ATS_NET_UNSPECIFIED;
1023 pm = GNUNET_malloc (sizeof (struct PendingMessage) +
1024 sizeof (struct WelcomeMessage));
1025 pm->msg = (const char *) &pm[1];
1026 pm->message_size = sizeof(struct WelcomeMessage);
1027 welcome.header.size = htons (sizeof(struct WelcomeMessage));
1028 welcome.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME);
1029 welcome.clientIdentity = *plugin->env->my_identity;
1030 memcpy (&pm[1], &welcome, sizeof(welcome));
1031 pm->timeout = GNUNET_TIME_UNIT_FOREVER_ABS;
1032 GNUNET_STATISTICS_update (plugin->env->stats,
1033 gettext_noop ("# bytes currently in TCP buffers"), pm->message_size,
1035 GNUNET_CONTAINER_DLL_insert (session->pending_messages_head,
1036 session->pending_messages_tail,
1038 session->msgs_in_queue++;
1039 session->bytes_in_queue += pm->message_size;
1040 if (GNUNET_YES != is_nat)
1042 GNUNET_STATISTICS_update (plugin->env->stats,
1043 gettext_noop ("# TCP sessions active"), 1, GNUNET_NO);
1045 plugin->env->register_quota_notification (plugin->env->cls,
1046 &address->peer, PLUGIN_NAME, session);
1047 session->timeout = GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1048 session->timeout_task = GNUNET_SCHEDULER_add_delayed (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
1056 * If we have pending messages, ask the server to
1057 * transmit them (schedule the respective tasks, etc.)
1059 * @param session for which session should we do this
1062 process_pending_messages (struct Session *session);
1066 * Function called to notify a client about the socket
1067 * being ready to queue more data. "buf" will be
1068 * NULL and "size" zero if the socket was closed for
1069 * writing in the meantime.
1071 * @param cls closure
1072 * @param size number of bytes available in @a buf
1073 * @param buf where the callee should write the message
1074 * @return number of bytes written to @a buf
1077 do_transmit (void *cls, size_t size, void *buf)
1079 struct Session *session = cls;
1080 struct GNUNET_PeerIdentity pid;
1081 struct Plugin *plugin;
1082 struct PendingMessage *pos;
1083 struct PendingMessage *hd;
1084 struct PendingMessage *tl;
1085 struct GNUNET_TIME_Absolute now;
1089 session->transmit_handle = NULL;
1090 plugin = session->plugin;
1093 LOG (GNUNET_ERROR_TYPE_DEBUG,
1094 "Timeout trying to transmit to peer `%4s', discarding message queue.\n",
1095 GNUNET_i2s (&session->target));
1096 /* timeout; cancel all messages that have already expired */
1100 now = GNUNET_TIME_absolute_get ();
1101 while ((NULL != (pos = session->pending_messages_head))
1102 && (pos->timeout.abs_value_us <= now.abs_value_us))
1104 GNUNET_CONTAINER_DLL_remove (session->pending_messages_head,
1105 session->pending_messages_tail,
1107 GNUNET_assert (0 < session->msgs_in_queue);
1108 session->msgs_in_queue--;
1109 GNUNET_assert (pos->message_size <= session->bytes_in_queue);
1110 session->bytes_in_queue -= pos->message_size;
1111 LOG (GNUNET_ERROR_TYPE_DEBUG,
1112 "Failed to transmit %u byte message to `%4s'.\n",
1114 GNUNET_i2s (&session->target));
1115 ret += pos->message_size;
1116 GNUNET_CONTAINER_DLL_insert_after (hd, tl, tl, pos);
1118 /* do this call before callbacks (so that if callbacks destroy
1119 * session, they have a chance to cancel actions done by this
1121 process_pending_messages (session);
1122 pid = session->target;
1123 /* no do callbacks and do not use session again since
1124 * the callbacks may abort the session */
1125 while (NULL != (pos = hd))
1127 GNUNET_CONTAINER_DLL_remove (hd, tl, pos);
1128 if (pos->transmit_cont != NULL)
1129 pos->transmit_cont (pos->transmit_cont_cls,
1132 pos->message_size, 0);
1135 GNUNET_STATISTICS_update (plugin->env->stats,
1136 gettext_noop ("# bytes currently in TCP buffers"), -(int64_t) ret,
1138 GNUNET_STATISTICS_update (plugin->env->stats, gettext_noop
1139 ("# bytes discarded by TCP (timeout)"), ret, GNUNET_NO);
1142 /* copy all pending messages that would fit */
1147 while (NULL != (pos = session->pending_messages_head))
1149 if (ret + pos->message_size > size)
1151 GNUNET_CONTAINER_DLL_remove (session->pending_messages_head,
1152 session->pending_messages_tail,
1154 GNUNET_assert (0 < session->msgs_in_queue);
1155 session->msgs_in_queue--;
1156 GNUNET_assert (pos->message_size <= session->bytes_in_queue);
1157 session->bytes_in_queue -= pos->message_size;
1158 GNUNET_assert(size >= pos->message_size);
1159 LOG(GNUNET_ERROR_TYPE_DEBUG,
1160 "Transmitting message of type %u size %u\n",
1161 ntohs (((struct GNUNET_MessageHeader * ) pos->msg)->type),
1163 /* FIXME: this memcpy can be up to 7% of our total runtime */
1164 memcpy (cbuf, pos->msg, pos->message_size);
1165 cbuf += pos->message_size;
1166 ret += pos->message_size;
1167 size -= pos->message_size;
1168 GNUNET_CONTAINER_DLL_insert_tail (hd, tl, pos);
1170 /* schedule 'continuation' before callbacks so that callbacks that
1171 * cancel everything don't cause us to use a session that no longer
1173 process_pending_messages (session);
1174 session->last_activity = GNUNET_TIME_absolute_get ();
1175 pid = session->target;
1176 /* we'll now call callbacks that may cancel the session; hence
1177 * we should not use 'session' after this point */
1178 while (NULL != (pos = hd))
1180 GNUNET_CONTAINER_DLL_remove (hd, tl, pos);
1181 if (pos->transmit_cont != NULL)
1182 pos->transmit_cont (pos->transmit_cont_cls,
1186 pos->message_size); /* FIXME: include TCP overhead */
1189 GNUNET_assert(hd == NULL);
1190 GNUNET_assert(tl == NULL);
1191 LOG(GNUNET_ERROR_TYPE_DEBUG, "Transmitting %u bytes\n", ret);
1192 GNUNET_STATISTICS_update (plugin->env->stats,
1193 gettext_noop ("# bytes currently in TCP buffers"), -(int64_t) ret,
1195 GNUNET_STATISTICS_update (plugin->env->stats,
1196 gettext_noop ("# bytes transmitted via TCP"), ret, GNUNET_NO);
1202 * If we have pending messages, ask the server to
1203 * transmit them (schedule the respective tasks, etc.)
1205 * @param session for which session should we do this
1208 process_pending_messages (struct Session *session)
1210 struct PendingMessage *pm;
1212 GNUNET_assert(NULL != session->client);
1213 if (NULL != session->transmit_handle)
1215 if (NULL == (pm = session->pending_messages_head))
1218 session->transmit_handle = GNUNET_SERVER_notify_transmit_ready (
1219 session->client, pm->message_size,
1220 GNUNET_TIME_absolute_get_remaining (pm->timeout), &do_transmit, session);
1225 * Closure for #session_it().
1227 struct FindSessionContext
1230 * Session we are looking for.
1235 * Set to #GNUNET_OK if we found the session.
1242 * Function called to check if a session is in our maps.
1244 * @param cls the `struct FindSessionContext`
1245 * @param key peer identity
1246 * @param value session in the map
1247 * @return #GNUNET_YES to continue looking, #GNUNET_NO if we found the session
1250 session_it (void *cls, const struct GNUNET_PeerIdentity *key, void *value)
1252 struct FindSessionContext *res = cls;
1253 struct Session *session = value;
1255 if (res->s == session)
1257 res->res = GNUNET_OK;
1264 * Check that the given session is known to the plugin and
1265 * is in one of our maps.
1267 * @param plugin the plugin to check against
1268 * @param session the session to check
1269 * @return #GNUNET_OK if all is well, #GNUNET_SYSERR if the session is invalid
1272 find_session (struct Plugin *plugin, struct Session *session)
1274 struct FindSessionContext session_map_res;
1275 struct FindSessionContext nat_map_res;
1277 session_map_res.s = session;
1278 session_map_res.res = GNUNET_SYSERR;
1279 GNUNET_CONTAINER_multipeermap_iterate (plugin->sessionmap, &session_it,
1281 if (GNUNET_SYSERR != session_map_res.res)
1283 nat_map_res.s = session;
1284 nat_map_res.res = GNUNET_SYSERR;
1285 GNUNET_CONTAINER_multipeermap_iterate (plugin->nat_wait_conns, &session_it,
1287 if (GNUNET_SYSERR != nat_map_res.res)
1290 return GNUNET_SYSERR;
1296 * Function that can be used by the transport service to transmit
1297 * a message using the plugin. Note that in the case of a
1298 * peer disconnecting, the continuation MUST be called
1299 * prior to the disconnect notification itself. This function
1300 * will be called with this peer's HELLO message to initiate
1301 * a fresh connection to another peer.
1303 * @param cls closure
1304 * @param session which session must be used
1305 * @param msgbuf the message to transmit
1306 * @param msgbuf_size number of bytes in 'msgbuf'
1307 * @param priority how important is the message (most plugins will
1308 * ignore message priority and just FIFO)
1309 * @param to how long to wait at most for the transmission (does not
1310 * require plugins to discard the message after the timeout,
1311 * just advisory for the desired delay; most plugins will ignore
1313 * @param cont continuation to call once the message has
1314 * been transmitted (or if the transport is ready
1315 * for the next transmission call; or if the
1316 * peer disconnected...); can be NULL
1317 * @param cont_cls closure for @a cont
1318 * @return number of bytes used (on the physical network, with overheads);
1319 * -1 on hard errors (i.e. address invalid); 0 is a legal value
1320 * and does NOT mean that the message was not transmitted (DV)
1323 tcp_plugin_send (void *cls, struct Session *session, const char *msgbuf,
1324 size_t msgbuf_size, unsigned int priority, struct GNUNET_TIME_Relative to,
1325 GNUNET_TRANSPORT_TransmitContinuation cont, void *cont_cls)
1327 struct Plugin * plugin = cls;
1328 struct PendingMessage *pm;
1331 if (GNUNET_SYSERR == find_session (plugin, session))
1333 LOG(GNUNET_ERROR_TYPE_ERROR, _("Trying to send with invalid session %p\n"));
1335 return GNUNET_SYSERR;
1338 /* create new message entry */
1339 pm = GNUNET_malloc (sizeof (struct PendingMessage) + msgbuf_size);
1340 pm->msg = (const char *) &pm[1];
1341 memcpy (&pm[1], msgbuf, msgbuf_size);
1342 pm->message_size = msgbuf_size;
1343 pm->timeout = GNUNET_TIME_relative_to_absolute (to);
1344 pm->transmit_cont = cont;
1345 pm->transmit_cont_cls = cont_cls;
1347 LOG(GNUNET_ERROR_TYPE_DEBUG,
1348 "Asked to transmit %u bytes to `%s', added message to list.\n",
1349 msgbuf_size, GNUNET_i2s (&session->target));
1352 GNUNET_CONTAINER_multipeermap_contains_value (plugin->sessionmap,
1356 GNUNET_assert (NULL != session->client);
1357 GNUNET_SERVER_client_set_timeout (session->client,
1358 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1359 GNUNET_STATISTICS_update (plugin->env->stats,
1360 gettext_noop ("# bytes currently in TCP buffers"), msgbuf_size,
1363 /* append pm to pending_messages list */
1364 GNUNET_CONTAINER_DLL_insert_tail (session->pending_messages_head,
1365 session->pending_messages_tail,
1367 session->msgs_in_queue++;
1368 session->bytes_in_queue += pm->message_size;
1369 process_pending_messages (session);
1373 == GNUNET_CONTAINER_multipeermap_contains_value (plugin->nat_wait_conns,
1374 &session->target, session))
1376 LOG(GNUNET_ERROR_TYPE_DEBUG,
1377 "This NAT WAIT session for peer `%s' is not yet ready!\n",
1378 GNUNET_i2s (&session->target));
1379 GNUNET_STATISTICS_update (plugin->env->stats,
1380 gettext_noop ("# bytes currently in TCP buffers"), msgbuf_size,
1383 /* append pm to pending_messages list */
1384 GNUNET_CONTAINER_DLL_insert_tail (session->pending_messages_head,
1385 session->pending_messages_tail,
1387 session->msgs_in_queue++;
1388 session->bytes_in_queue += pm->message_size;
1393 LOG(GNUNET_ERROR_TYPE_ERROR,
1394 "Invalid session %p\n", session);
1403 return GNUNET_SYSERR; /* session does not exist here */
1408 * Closure for #session_lookup_it().
1413 * Address we are looking for.
1415 const struct GNUNET_HELLO_Address *address;
1418 * Where to store the session (if we found it).
1420 struct Session *result;
1426 * Look for a session by address.
1428 * @param cls the `struct SessionItCtx`
1430 * @param value a `struct Session`
1431 * @return #GNUNET_YES to continue looking, #GNUNET_NO if we found the session
1434 session_lookup_it (void *cls,
1435 const struct GNUNET_PeerIdentity *key,
1438 struct SessionItCtx * si_ctx = cls;
1439 struct Session * session = value;
1441 if (0 != GNUNET_HELLO_address_cmp (si_ctx->address, session->address))
1443 /* Found existing session */
1444 si_ctx->result = session;
1449 * Task cleaning up a NAT connection attempt after timeout
1451 * @param cls the `struct Session`
1452 * @param tc scheduler context (unused)
1455 nat_connect_timeout (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1457 struct Session *session = cls;
1459 session->nat_connection_timeout = GNUNET_SCHEDULER_NO_TASK;
1460 LOG(GNUNET_ERROR_TYPE_DEBUG,
1461 "NAT WAIT connection to `%4s' at `%s' could not be established, removing session\n",
1462 GNUNET_i2s (&session->target),
1463 tcp_address_to_string (NULL, session->address->address, session->address->address_length));
1464 tcp_disconnect_session (session->plugin, session);
1468 tcp_plugin_update_session_timeout (void *cls,
1469 const struct GNUNET_PeerIdentity *peer, struct Session *session)
1471 struct Plugin *plugin = cls;
1473 if (GNUNET_SYSERR == find_session (plugin, session))
1475 reschedule_session_timeout (session);
1479 * Task to signal the server that we can continue
1480 * receiving from the TCP client now.
1482 * @param cls the `struct Session*`
1483 * @param tc task context (unused)
1486 delayed_done (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1488 struct Session *session = cls;
1490 session->receive_delay_task = GNUNET_SCHEDULER_NO_TASK;
1491 reschedule_session_timeout (session);
1493 GNUNET_SERVER_receive_done (session->client, GNUNET_OK);
1496 static void tcp_plugin_update_inbound_delay (void *cls,
1497 const struct GNUNET_PeerIdentity *peer,
1498 struct Session *session,
1499 struct GNUNET_TIME_Relative delay)
1501 if (GNUNET_SCHEDULER_NO_TASK == session->receive_delay_task)
1504 LOG(GNUNET_ERROR_TYPE_DEBUG,
1505 "New inbound delay %llu us\n",delay.rel_value_us);
1507 GNUNET_SCHEDULER_cancel (session->receive_delay_task);
1508 session->receive_delay_task = GNUNET_SCHEDULER_add_delayed (delay,
1509 &delayed_done, session);
1514 * Create a new session to transmit data to the target
1515 * This session will used to send data to this peer and the plugin will
1516 * notify us by calling the env->session_end function
1518 * @param cls closure
1519 * @param address the address to use
1520 * @return the session if the address is valid, NULL otherwise
1522 static struct Session *
1523 tcp_plugin_get_session (void *cls, const struct GNUNET_HELLO_Address *address)
1525 struct Plugin *plugin = cls;
1526 struct Session *session = NULL;
1530 struct GNUNET_CONNECTION_Handle *sa;
1531 struct sockaddr_in a4;
1532 struct sockaddr_in6 a6;
1533 const struct IPv4TcpAddress *t4;
1534 const struct IPv6TcpAddress *t6;
1535 struct GNUNET_ATS_Information ats;
1536 unsigned int is_natd = GNUNET_NO;
1539 addrlen = address->address_length;
1540 LOG(GNUNET_ERROR_TYPE_DEBUG,
1541 "Trying to get session for `%s' address of peer `%s'\n",
1542 tcp_address_to_string(NULL, address->address, address->address_length),
1543 GNUNET_i2s (&address->peer));
1545 if (GNUNET_HELLO_address_check_option(address, GNUNET_HELLO_ADDRESS_INFO_INBOUND))
1551 /* look for existing session */
1552 if (GNUNET_YES == GNUNET_CONTAINER_multipeermap_contains (plugin->sessionmap,
1555 struct SessionItCtx si_ctx;
1557 si_ctx.address = address;
1558 si_ctx.result = NULL;
1560 GNUNET_CONTAINER_multipeermap_get_multiple (plugin->sessionmap,
1561 &address->peer, &session_lookup_it, &si_ctx);
1562 if (si_ctx.result != NULL )
1564 session = si_ctx.result;
1565 LOG(GNUNET_ERROR_TYPE_DEBUG,
1566 "Found existing session for `%s' address `%s' session %p\n",
1567 GNUNET_i2s (&address->peer),
1568 tcp_address_to_string(NULL, address->address, address->address_length),
1572 LOG(GNUNET_ERROR_TYPE_DEBUG,
1573 "Existing sessions did not match address `%s' or peer `%s'\n",
1574 tcp_address_to_string(NULL, address->address, address->address_length),
1575 GNUNET_i2s (&address->peer));
1578 if (addrlen == sizeof(struct IPv6TcpAddress))
1580 GNUNET_assert(NULL != address->address); /* make static analysis happy */
1581 t6 = address->address;
1583 memset (&a6, 0, sizeof(a6));
1584 #if HAVE_SOCKADDR_IN_SIN_LEN
1585 a6.sin6_len = sizeof (a6);
1587 a6.sin6_family = AF_INET6;
1588 a6.sin6_port = t6->t6_port;
1589 if (t6->t6_port == 0)
1590 is_natd = GNUNET_YES;
1591 memcpy (&a6.sin6_addr, &t6->ipv6_addr, sizeof(struct in6_addr));
1595 else if (addrlen == sizeof(struct IPv4TcpAddress))
1597 GNUNET_assert(NULL != address->address); /* make static analysis happy */
1598 t4 = address->address;
1600 memset (&a4, 0, sizeof(a4));
1601 #if HAVE_SOCKADDR_IN_SIN_LEN
1602 a4.sin_len = sizeof (a4);
1604 a4.sin_family = AF_INET;
1605 a4.sin_port = t4->t4_port;
1606 if (t4->t4_port == 0)
1607 is_natd = GNUNET_YES;
1608 a4.sin_addr.s_addr = t4->ipv4_addr;
1614 GNUNET_STATISTICS_update (plugin->env->stats, gettext_noop
1615 ("# requests to create session with invalid address"), 1, GNUNET_NO);
1619 ats = plugin->env->get_address_type (plugin->env->cls, sb, sbs);
1621 if ((is_natd == GNUNET_YES) && (addrlen == sizeof(struct IPv6TcpAddress)))
1623 /* NAT client only works with IPv4 addresses */
1627 if (plugin->cur_connections >= plugin->max_connections)
1633 if ((is_natd == GNUNET_YES)
1635 == GNUNET_CONTAINER_multipeermap_contains (plugin->nat_wait_conns,
1638 /* Only do one NAT punch attempt per peer identity */
1642 if ((is_natd == GNUNET_YES) && (NULL != plugin->nat) &&
1643 (GNUNET_NO == GNUNET_CONTAINER_multipeermap_contains (plugin->nat_wait_conns,
1646 LOG (GNUNET_ERROR_TYPE_DEBUG,
1647 "Found valid IPv4 NAT address (creating session)!\n");
1648 session = create_session (plugin, address, NULL, GNUNET_YES);
1649 session->ats_address_network_type = (enum GNUNET_ATS_Network_Type) ntohl (
1652 session->ats_address_network_type != GNUNET_ATS_NET_UNSPECIFIED);
1653 session->nat_connection_timeout = GNUNET_SCHEDULER_add_delayed (NAT_TIMEOUT,
1654 &nat_connect_timeout, session);
1655 GNUNET_assert(session != NULL);
1656 GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_multipeermap_put (plugin->nat_wait_conns,
1657 &session->target, session, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
1659 LOG(GNUNET_ERROR_TYPE_DEBUG,
1660 "Created NAT WAIT connection to `%4s' at `%s'\n",
1661 GNUNET_i2s (&session->target), GNUNET_a2s (sb, sbs));
1663 if (GNUNET_OK == GNUNET_NAT_run_client (plugin->nat, &a4))
1667 LOG(GNUNET_ERROR_TYPE_DEBUG,
1668 "Running NAT client for `%4s' at `%s' failed\n",
1669 GNUNET_i2s (&session->target), GNUNET_a2s (sb, sbs));
1670 tcp_disconnect_session (plugin, session);
1675 /* create new outbound session */
1676 GNUNET_assert(plugin->cur_connections <= plugin->max_connections);
1677 sa = GNUNET_CONNECTION_create_from_sockaddr (af, sb, sbs);
1680 LOG(GNUNET_ERROR_TYPE_DEBUG,
1681 "Failed to create connection to `%4s' at `%s'\n",
1682 GNUNET_i2s (&address->peer), GNUNET_a2s (sb, sbs));
1685 plugin->cur_connections++;
1686 if (plugin->cur_connections == plugin->max_connections)
1687 GNUNET_SERVER_suspend (plugin->server); /* Maximum number of connections rechead */
1689 LOG(GNUNET_ERROR_TYPE_DEBUG,
1690 "Asked to transmit to `%4s', creating fresh session using address `%s'.\n",
1691 GNUNET_i2s (&address->peer), GNUNET_a2s (sb, sbs));
1693 session = create_session (plugin, address,
1694 GNUNET_SERVER_connect_socket (plugin->server, sa), GNUNET_NO);
1695 session->ats_address_network_type = (enum GNUNET_ATS_Network_Type) ntohl (
1697 GNUNET_break(session->ats_address_network_type != GNUNET_ATS_NET_UNSPECIFIED);
1698 GNUNET_SERVER_client_set_user_context(session->client, session);
1699 GNUNET_CONTAINER_multipeermap_put (plugin->sessionmap, &session->target,
1700 session, GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
1701 LOG(GNUNET_ERROR_TYPE_DEBUG,
1702 "Creating new session for `%s' address `%s' session %p\n",
1703 GNUNET_i2s (&address->peer),
1704 tcp_address_to_string(NULL, address->address, address->address_length),
1706 /* Send TCP Welcome */
1707 process_pending_messages (session);
1713 session_disconnect_it (void *cls, const struct GNUNET_PeerIdentity *key,
1716 struct Plugin *plugin = cls;
1717 struct Session *session = value;
1719 GNUNET_STATISTICS_update (session->plugin->env->stats, gettext_noop
1720 ("# transport-service disconnect requests for TCP"), 1, GNUNET_NO);
1721 tcp_disconnect_session (plugin, session);
1726 * Function that can be called to force a disconnect from the
1727 * specified neighbour. This should also cancel all previously
1728 * scheduled transmissions. Obviously the transmission may have been
1729 * partially completed already, which is OK. The plugin is supposed
1730 * to close the connection (if applicable) and no longer call the
1731 * transmit continuation(s).
1733 * Finally, plugin MUST NOT call the services's receive function to
1734 * notify the service that the connection to the specified target was
1735 * closed after a getting this call.
1737 * @param cls closure
1738 * @param target peer for which the last transmission is
1742 tcp_plugin_disconnect (void *cls, const struct GNUNET_PeerIdentity *target)
1744 struct Plugin *plugin = cls;
1746 LOG(GNUNET_ERROR_TYPE_DEBUG,
1747 "Disconnecting peer `%4s'\n",
1748 GNUNET_i2s (target));
1749 GNUNET_CONTAINER_multipeermap_get_multiple (plugin->sessionmap, target,
1750 &session_disconnect_it, plugin);
1751 GNUNET_CONTAINER_multipeermap_get_multiple (plugin->nat_wait_conns, target,
1752 &session_disconnect_it, plugin);
1756 * Running pretty printers: head
1758 static struct PrettyPrinterContext *ppc_dll_head;
1761 * Running pretty printers: tail
1763 static struct PrettyPrinterContext *ppc_dll_tail;
1766 * Context for address to string conversion, closure
1767 * for #append_port().
1769 struct PrettyPrinterContext
1774 struct PrettyPrinterContext *next;
1779 struct PrettyPrinterContext *prev;
1784 GNUNET_SCHEDULER_TaskIdentifier timeout_task;
1789 struct GNUNET_RESOLVER_RequestHandle *resolver_handle;
1792 * Function to call with the result.
1794 GNUNET_TRANSPORT_AddressStringCallback asc;
1797 * Clsoure for @e asc.
1802 * Port to add after the IP address.
1819 * Append our port and forward the result.
1821 * @param cls the `struct PrettyPrinterContext *`
1822 * @param hostname hostname part of the address
1825 append_port (void *cls,
1826 const char *hostname)
1828 struct PrettyPrinterContext *ppc = cls;
1831 if (NULL == hostname)
1833 /* Final call, done */
1834 ppc->resolver_handle = NULL;
1835 GNUNET_CONTAINER_DLL_remove (ppc_dll_head,
1838 ppc->asc (ppc->asc_cls,
1844 if (GNUNET_YES == ppc->ipv6)
1845 GNUNET_asprintf (&ret,
1852 GNUNET_asprintf (&ret,
1858 ppc->asc (ppc->asc_cls,
1866 * Convert the transports address to a nice, human-readable
1869 * @param cls closure
1870 * @param type name of the transport that generated the address
1871 * @param addr one of the addresses of the host, NULL for the last address
1872 * the specific address format depends on the transport
1873 * @param addrlen length of the @a addr
1874 * @param numeric should (IP) addresses be displayed in numeric form?
1875 * @param timeout after how long should we give up?
1876 * @param asc function to call on each string
1877 * @param asc_cls closure for @a asc
1880 tcp_plugin_address_pretty_printer (void *cls,
1885 struct GNUNET_TIME_Relative timeout,
1886 GNUNET_TRANSPORT_AddressStringCallback asc,
1889 struct PrettyPrinterContext *ppc;
1892 struct sockaddr_in a4;
1893 struct sockaddr_in6 a6;
1894 const struct IPv4TcpAddress *t4;
1895 const struct IPv6TcpAddress *t6;
1899 if (sizeof(struct IPv6TcpAddress) == addrlen)
1902 memset (&a6, 0, sizeof(a6));
1903 a6.sin6_family = AF_INET6;
1904 a6.sin6_port = t6->t6_port;
1905 memcpy (&a6.sin6_addr, &t6->ipv6_addr, sizeof(struct in6_addr));
1906 port = ntohs (t6->t6_port);
1907 options = ntohl (t6->options);
1911 else if (sizeof(struct IPv4TcpAddress) == addrlen)
1914 memset (&a4, 0, sizeof(a4));
1915 a4.sin_family = AF_INET;
1916 a4.sin_port = t4->t4_port;
1917 a4.sin_addr.s_addr = t4->ipv4_addr;
1918 port = ntohs (t4->t4_port);
1919 options = ntohl (t4->options);
1925 /* invalid address */
1926 asc (asc_cls, NULL, GNUNET_SYSERR);
1927 asc (asc_cls, NULL, GNUNET_OK);
1930 ppc = GNUNET_new (struct PrettyPrinterContext);
1931 if (addrlen == sizeof(struct IPv6TcpAddress))
1932 ppc->ipv6 = GNUNET_YES;
1934 ppc->ipv6 = GNUNET_NO;
1936 ppc->asc_cls = asc_cls;
1938 ppc->options = options;
1939 ppc->resolver_handle = GNUNET_RESOLVER_hostname_get (sb,
1944 if (NULL == ppc->resolver_handle)
1950 GNUNET_CONTAINER_DLL_insert (ppc_dll_head,
1957 * Check if the given port is plausible (must be either our listen
1958 * port or our advertised port), or any port if we are behind NAT
1959 * and do not have a port open. If it is neither, we return
1962 * @param plugin global variables
1963 * @param in_port port number to check
1964 * @return #GNUNET_OK if port is either open_port or adv_port
1967 check_port (struct Plugin *plugin, uint16_t in_port)
1969 if ((in_port == plugin->adv_port) || (in_port == plugin->open_port))
1971 return GNUNET_SYSERR;
1975 * Function that will be called to check if a binary address for this
1976 * plugin is well-formed and corresponds to an address for THIS peer
1977 * (as per our configuration). Naturally, if absolutely necessary,
1978 * plugins can be a bit conservative in their answer, but in general
1979 * plugins should make sure that the address does not redirect
1980 * traffic to a 3rd party that might try to man-in-the-middle our
1983 * @param cls closure, our `struct Plugin *`
1984 * @param addr pointer to the address
1985 * @param addrlen length of addr
1986 * @return #GNUNET_OK if this is a plausible address for this peer
1987 * and transport, #GNUNET_SYSERR if not
1990 tcp_plugin_check_address (void *cls, const void *addr, size_t addrlen)
1992 struct Plugin *plugin = cls;
1993 struct IPv4TcpAddress *v4;
1994 struct IPv6TcpAddress *v6;
1996 if ((addrlen != sizeof(struct IPv4TcpAddress))
1997 && (addrlen != sizeof(struct IPv6TcpAddress)))
2000 return GNUNET_SYSERR;
2003 if (addrlen == sizeof(struct IPv4TcpAddress))
2005 v4 = (struct IPv4TcpAddress *) addr;
2006 if (0 != memcmp (&v4->options,
2011 return GNUNET_SYSERR;
2013 if (GNUNET_OK != check_port (plugin, ntohs (v4->t4_port)))
2014 return GNUNET_SYSERR;
2016 != GNUNET_NAT_test_address (plugin->nat, &v4->ipv4_addr,
2017 sizeof(struct in_addr)))
2018 return GNUNET_SYSERR;
2022 v6 = (struct IPv6TcpAddress *) addr;
2023 if (IN6_IS_ADDR_LINKLOCAL (&v6->ipv6_addr))
2026 return GNUNET_SYSERR;
2028 if (0 != memcmp (&v6->options,
2033 return GNUNET_SYSERR;
2035 if (GNUNET_OK != check_port (plugin, ntohs (v6->t6_port)))
2036 return GNUNET_SYSERR;
2038 != GNUNET_NAT_test_address (plugin->nat, &v6->ipv6_addr,
2039 sizeof(struct in6_addr)))
2040 return GNUNET_SYSERR;
2046 * We've received a nat probe from this peer via TCP. Finish
2047 * creating the client session and resume sending of queued
2050 * @param cls closure
2051 * @param client identification of the client
2052 * @param message the actual message
2055 handle_tcp_nat_probe (void *cls, struct GNUNET_SERVER_Client *client,
2056 const struct GNUNET_MessageHeader *message)
2058 struct Plugin *plugin = cls;
2059 struct Session *session;
2060 const struct TCP_NAT_ProbeMessage *tcp_nat_probe;
2063 struct IPv4TcpAddress *t4;
2064 struct IPv6TcpAddress *t6;
2065 const struct sockaddr_in *s4;
2066 const struct sockaddr_in6 *s6;
2068 LOG(GNUNET_ERROR_TYPE_DEBUG, "Received NAT probe\n");
2069 /* We have received a TCP NAT probe, meaning we (hopefully) initiated
2070 * a connection to this peer by running gnunet-nat-client. This peer
2071 * received the punch message and now wants us to use the new connection
2072 * as the default for that peer. Do so and then send a WELCOME message
2073 * so we can really be connected!
2075 if (ntohs (message->size) != sizeof(struct TCP_NAT_ProbeMessage))
2078 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2082 tcp_nat_probe = (const struct TCP_NAT_ProbeMessage *) message;
2083 if (0 == memcmp (&tcp_nat_probe->clientIdentity, plugin->env->my_identity,
2084 sizeof(struct GNUNET_PeerIdentity)))
2086 /* refuse connections from ourselves */
2087 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2091 session = GNUNET_CONTAINER_multipeermap_get (plugin->nat_wait_conns,
2092 &tcp_nat_probe->clientIdentity);
2093 if (session == NULL )
2095 LOG(GNUNET_ERROR_TYPE_DEBUG, "Did NOT find session for NAT probe!\n");
2096 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2099 LOG(GNUNET_ERROR_TYPE_DEBUG, "Found session for NAT probe!\n");
2101 if (session->nat_connection_timeout != GNUNET_SCHEDULER_NO_TASK )
2103 GNUNET_SCHEDULER_cancel (session->nat_connection_timeout);
2104 session->nat_connection_timeout = GNUNET_SCHEDULER_NO_TASK;
2107 if (GNUNET_OK != GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
2110 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2111 tcp_disconnect_session (plugin, session);
2115 GNUNET_CONTAINER_multipeermap_remove (plugin->nat_wait_conns, &tcp_nat_probe->clientIdentity, session) == GNUNET_YES);
2116 GNUNET_SERVER_client_set_user_context(client, session);
2117 GNUNET_CONTAINER_multipeermap_put (plugin->sessionmap, &session->target,
2118 session, GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2119 session->last_activity = GNUNET_TIME_absolute_get ();
2120 LOG(GNUNET_ERROR_TYPE_DEBUG, "Found address `%s' for incoming connection\n",
2121 GNUNET_a2s (vaddr, alen));
2122 switch (((const struct sockaddr *) vaddr)->sa_family)
2126 t4 = GNUNET_new (struct IPv4TcpAddress);
2127 t4->options = htonl(0);
2128 t4->t4_port = s4->sin_port;
2129 t4->ipv4_addr = s4->sin_addr.s_addr;
2130 session->address = GNUNET_HELLO_address_allocate (
2131 &tcp_nat_probe->clientIdentity, PLUGIN_NAME, &t4,
2132 sizeof(struct IPv4TcpAddress),
2133 GNUNET_HELLO_ADDRESS_INFO_NONE);
2137 t6 = GNUNET_new (struct IPv6TcpAddress);
2138 t6->options = htonl(0);
2139 t6->t6_port = s6->sin6_port;
2140 memcpy (&t6->ipv6_addr, &s6->sin6_addr, sizeof(struct in6_addr));
2141 session->address = GNUNET_HELLO_address_allocate (
2142 &tcp_nat_probe->clientIdentity,
2143 PLUGIN_NAME, &t6, sizeof(struct IPv6TcpAddress),
2144 GNUNET_HELLO_ADDRESS_INFO_NONE);
2148 LOG(GNUNET_ERROR_TYPE_DEBUG, "Bad address for incoming connection!\n");
2150 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2151 tcp_disconnect_session (plugin, session);
2155 GNUNET_break(NULL == session->client);
2156 GNUNET_SERVER_client_keep (client);
2157 session->client = client;
2158 GNUNET_STATISTICS_update (plugin->env->stats,
2159 gettext_noop ("# TCP sessions active"), 1, GNUNET_NO);
2160 process_pending_messages (session);
2161 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2165 * We've received a welcome from this peer via TCP. Possibly create a
2166 * fresh client record and send back our welcome.
2168 * @param cls closure
2169 * @param client identification of the client
2170 * @param message the actual message
2173 handle_tcp_welcome (void *cls, struct GNUNET_SERVER_Client *client,
2174 const struct GNUNET_MessageHeader *message)
2176 struct Plugin *plugin = cls;
2177 const struct WelcomeMessage *wm = (const struct WelcomeMessage *) message;
2178 struct GNUNET_HELLO_Address *address;
2179 struct Session *session;
2182 struct IPv4TcpAddress t4;
2183 struct IPv6TcpAddress t6;
2184 const struct sockaddr_in *s4;
2185 const struct sockaddr_in6 *s6;
2186 struct GNUNET_ATS_Information ats;
2189 if (0 == memcmp (&wm->clientIdentity, plugin->env->my_identity,
2190 sizeof(struct GNUNET_PeerIdentity)))
2192 /* refuse connections from ourselves */
2193 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2194 if (GNUNET_OK == GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
2196 LOG(GNUNET_ERROR_TYPE_INFO,
2197 "Received %s message from my own identity `%4s' on address `%s'\n",
2198 "WELCOME", GNUNET_i2s (&wm->clientIdentity),
2199 GNUNET_a2s (vaddr, alen));
2205 LOG(GNUNET_ERROR_TYPE_DEBUG, "Received %s message from `%4s' %p\n", "WELCOME",
2206 GNUNET_i2s (&wm->clientIdentity), client);
2207 GNUNET_STATISTICS_update (plugin->env->stats,
2208 gettext_noop ("# TCP WELCOME messages received"), 1, GNUNET_NO);
2209 session = lookup_session_by_client (plugin, client);
2210 if (NULL != session)
2212 if (GNUNET_OK == GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
2214 LOG(GNUNET_ERROR_TYPE_DEBUG, "Found existing session %p for peer `%s'\n",
2215 session, GNUNET_a2s (vaddr, alen));
2221 GNUNET_SERVER_client_keep (client);
2222 if (NULL != plugin->service) /* Otherwise value is incremented in tcp_access_check */
2223 plugin->cur_connections++;
2224 if (plugin->cur_connections == plugin->max_connections)
2225 GNUNET_SERVER_suspend (plugin->server); /* Maximum number of connections rechead */
2227 if (GNUNET_OK == GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
2229 if (alen == sizeof(struct sockaddr_in))
2232 memset (&t4, '\0', sizeof (t4));
2233 t4.options = htonl (0);
2234 t4.t4_port = s4->sin_port;
2235 t4.ipv4_addr = s4->sin_addr.s_addr;
2236 address = GNUNET_HELLO_address_allocate (&wm->clientIdentity,
2237 PLUGIN_NAME, &t4, sizeof(t4),
2238 GNUNET_HELLO_ADDRESS_INFO_INBOUND);
2240 else if (alen == sizeof(struct sockaddr_in6))
2243 memset (&t6, '\0', sizeof (t6));
2244 t6.options = htonl (0);
2245 t6.t6_port = s6->sin6_port;
2246 memcpy (&t6.ipv6_addr, &s6->sin6_addr, sizeof(struct in6_addr));
2247 address = GNUNET_HELLO_address_allocate (&wm->clientIdentity,
2248 PLUGIN_NAME, &t6, sizeof (t6),
2249 GNUNET_HELLO_ADDRESS_INFO_INBOUND);
2254 GNUNET_free_non_null (vaddr);
2257 session = create_session (plugin, address, client, GNUNET_NO);
2258 GNUNET_HELLO_address_free (address);
2259 ats = plugin->env->get_address_type (plugin->env->cls, vaddr, alen);
2260 session->ats_address_network_type = (enum GNUNET_ATS_Network_Type) ntohl (
2262 LOG(GNUNET_ERROR_TYPE_DEBUG, "Creating new%s session %p for peer `%s' client %p \n",
2263 GNUNET_HELLO_address_check_option (session->address,
2264 GNUNET_HELLO_ADDRESS_INFO_INBOUND) ? " inbound" : "", session,
2265 tcp_address_to_string(NULL, (void *) session->address->address,
2266 session->address->address_length),
2269 GNUNET_SERVER_client_set_user_context(session->client, session);
2270 GNUNET_CONTAINER_multipeermap_put (plugin->sessionmap, &session->target,
2271 session, GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2273 /* Notify transport and ATS about new session */
2274 plugin->env->session_start (NULL, session->address, session, &ats, 1);
2278 LOG(GNUNET_ERROR_TYPE_DEBUG,
2279 "Did not obtain TCP socket address for incoming connection\n");
2285 if (session->expecting_welcome != GNUNET_YES)
2288 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2292 session->last_activity = GNUNET_TIME_absolute_get ();
2293 session->expecting_welcome = GNUNET_NO;
2295 process_pending_messages (session);
2296 GNUNET_SERVER_client_set_timeout (client,
2297 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
2298 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2303 * We've received data for this peer via TCP. Unbox,
2304 * compute latency and forward.
2306 * @param cls closure
2307 * @param client identification of the client
2308 * @param message the actual message
2311 handle_tcp_data (void *cls, struct GNUNET_SERVER_Client *client,
2312 const struct GNUNET_MessageHeader *message)
2314 struct Plugin *plugin = cls;
2315 struct Session *session;
2316 struct GNUNET_TIME_Relative delay;
2319 type = ntohs (message->type);
2320 if ((GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME == type)
2321 || (GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE == type))
2323 /* We don't want to propagate WELCOME and NAT Probe messages up! */
2324 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2327 session = lookup_session_by_client (plugin, client);
2328 if (NULL == session)
2330 /* No inbound session found */
2334 GNUNET_SERVER_client_get_address (client, &vaddr, &alen);
2335 LOG(GNUNET_ERROR_TYPE_ERROR,
2336 "Received unexpected %u bytes of type %u from `%s'\n",
2337 (unsigned int ) ntohs (message->size),
2338 (unsigned int ) ntohs (message->type), GNUNET_a2s (vaddr, alen));
2340 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2341 GNUNET_free_non_null(vaddr);
2344 else if (GNUNET_YES == session->expecting_welcome)
2346 /* Session is expecting WELCOME message */
2350 GNUNET_SERVER_client_get_address (client, &vaddr, &alen);
2351 LOG(GNUNET_ERROR_TYPE_ERROR,
2352 "Received unexpected %u bytes of type %u from `%s'\n",
2353 (unsigned int ) ntohs (message->size),
2354 (unsigned int ) ntohs (message->type), GNUNET_a2s (vaddr, alen));
2356 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2357 GNUNET_free_non_null(vaddr);
2361 session->last_activity = GNUNET_TIME_absolute_get ();
2362 LOG(GNUNET_ERROR_TYPE_DEBUG,
2363 "Passing %u bytes of type %u from `%4s' to transport service.\n",
2364 (unsigned int ) ntohs (message->size),
2365 (unsigned int ) ntohs (message->type), GNUNET_i2s (&session->target));
2367 GNUNET_STATISTICS_update (plugin->env->stats,
2368 gettext_noop ("# bytes received via TCP"), ntohs (message->size),
2370 struct GNUNET_ATS_Information distance;
2372 distance.type = htonl (GNUNET_ATS_NETWORK_TYPE);
2373 distance.value = htonl ((uint32_t) session->ats_address_network_type);
2374 GNUNET_break(session->ats_address_network_type != GNUNET_ATS_NET_UNSPECIFIED);
2377 GNUNET_CONTAINER_multipeermap_contains_value (plugin->sessionmap,
2378 &session->target, session));
2380 delay = plugin->env->receive (plugin->env->cls, session->address, session, message);
2381 plugin->env->update_address_metrics (plugin->env->cls, session->address,
2382 session, &distance, 1);
2383 reschedule_session_timeout (session);
2384 if (0 == delay.rel_value_us)
2386 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2390 LOG(GNUNET_ERROR_TYPE_DEBUG,
2391 "Throttling receiving from `%s' for %s\n",
2392 GNUNET_i2s (&session->target),
2393 GNUNET_STRINGS_relative_time_to_string (delay, GNUNET_YES));
2394 GNUNET_SERVER_disable_receive_done_warning (client);
2395 session->receive_delay_task = GNUNET_SCHEDULER_add_delayed (delay,
2396 &delayed_done, session);
2401 * Functions with this signature are called whenever a peer
2402 * is disconnected on the network level.
2404 * @param cls closure
2405 * @param client identification of the client
2408 disconnect_notify (void *cls, struct GNUNET_SERVER_Client *client)
2410 struct Plugin *plugin = cls;
2411 struct Session *session;
2415 session = lookup_session_by_client (plugin, client);
2416 if (NULL == session)
2417 return; /* unknown, nothing to do */
2418 LOG(GNUNET_ERROR_TYPE_DEBUG,
2419 "Destroying session of `%4s' with %s due to network-level disconnect.\n",
2420 GNUNET_i2s (&session->target),
2421 tcp_address_to_string (session->plugin, session->address->address,
2422 session->address->address_length));
2424 if (plugin->cur_connections == plugin->max_connections)
2425 GNUNET_SERVER_resume (plugin->server); /* Resume server */
2427 if (plugin->cur_connections < 1)
2430 plugin->cur_connections--;
2432 GNUNET_STATISTICS_update (session->plugin->env->stats, gettext_noop
2433 ("# network-level TCP disconnect events"), 1, GNUNET_NO);
2434 tcp_disconnect_session (plugin, session);
2438 * We can now send a probe message, copy into buffer to really send.
2440 * @param cls closure, a struct TCPProbeContext
2441 * @param size max size to copy
2442 * @param buf buffer to copy message to
2443 * @return number of bytes copied into @a buf
2446 notify_send_probe (void *cls,
2450 struct TCPProbeContext *tcp_probe_ctx = cls;
2451 struct Plugin *plugin = tcp_probe_ctx->plugin;
2454 tcp_probe_ctx->transmit_handle = NULL;
2455 GNUNET_CONTAINER_DLL_remove (plugin->probe_head,
2460 GNUNET_CONNECTION_destroy (tcp_probe_ctx->sock);
2461 GNUNET_free(tcp_probe_ctx);
2464 GNUNET_assert(size >= sizeof(tcp_probe_ctx->message));
2465 memcpy (buf, &tcp_probe_ctx->message, sizeof(tcp_probe_ctx->message));
2466 GNUNET_SERVER_connect_socket (tcp_probe_ctx->plugin->server,
2467 tcp_probe_ctx->sock);
2468 ret = sizeof(tcp_probe_ctx->message);
2469 GNUNET_free(tcp_probe_ctx);
2475 * Function called by the NAT subsystem suggesting another peer wants
2476 * to connect to us via connection reversal. Try to connect back to the
2479 * @param cls closure
2480 * @param addr address to try
2481 * @param addrlen number of bytes in @a addr
2484 try_connection_reversal (void *cls,
2485 const struct sockaddr *addr,
2488 struct Plugin *plugin = cls;
2489 struct GNUNET_CONNECTION_Handle *sock;
2490 struct TCPProbeContext *tcp_probe_ctx;
2493 * We have received an ICMP response, ostensibly from a peer
2494 * that wants to connect to us! Send a message to establish a connection.
2496 sock = GNUNET_CONNECTION_create_from_sockaddr (AF_INET, addr, addrlen);
2499 /* failed for some odd reason (out of sockets?); ignore attempt */
2503 tcp_probe_ctx = GNUNET_new (struct TCPProbeContext);
2504 tcp_probe_ctx->message.header.size = htons (
2505 sizeof(struct TCP_NAT_ProbeMessage));
2506 tcp_probe_ctx->message.header.type = htons (
2507 GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE);
2508 memcpy (&tcp_probe_ctx->message.clientIdentity, plugin->env->my_identity,
2509 sizeof(struct GNUNET_PeerIdentity));
2510 tcp_probe_ctx->plugin = plugin;
2511 tcp_probe_ctx->sock = sock;
2512 GNUNET_CONTAINER_DLL_insert (plugin->probe_head,
2515 tcp_probe_ctx->transmit_handle = GNUNET_CONNECTION_notify_transmit_ready (
2516 sock, ntohs (tcp_probe_ctx->message.header.size),
2517 GNUNET_TIME_UNIT_FOREVER_REL, ¬ify_send_probe, tcp_probe_ctx);
2523 * Function obtain the network type for a session
2525 * @param cls closure ('struct Plugin*')
2526 * @param session the session
2527 * @return the network type in HBO or #GNUNET_SYSERR
2529 static enum GNUNET_ATS_Network_Type
2530 tcp_get_network (void *cls,
2531 struct Session *session)
2533 struct Plugin * plugin = cls;
2535 GNUNET_assert (NULL != plugin);
2536 GNUNET_assert (NULL != session);
2537 if (GNUNET_SYSERR == find_session (plugin,session))
2538 return GNUNET_ATS_NET_UNSPECIFIED;
2539 return session->ats_address_network_type;
2544 * Return information about the given session to the
2547 * @param cls the `struct Plugin` with the monitor callback (`sic`)
2548 * @param peer peer we send information about
2549 * @param value our `struct Session` to send information about
2550 * @return #GNUNET_OK (continue to iterate)
2553 send_session_info_iter (void *cls,
2554 const struct GNUNET_PeerIdentity *peer,
2557 struct Plugin *plugin = cls;
2558 struct Session *session = value;
2560 notify_session_monitor (plugin,
2562 GNUNET_TRANSPORT_SS_UP);
2568 * Begin monitoring sessions of a plugin. There can only
2569 * be one active monitor per plugin (i.e. if there are
2570 * multiple monitors, the transport service needs to
2571 * multiplex the generated events over all of them).
2573 * @param cls closure of the plugin
2574 * @param sic callback to invoke, NULL to disable monitor;
2575 * plugin will being by iterating over all active
2576 * sessions immediately and then enter monitor mode
2577 * @param sic_cls closure for @a sic
2580 tcp_plugin_setup_monitor (void *cls,
2581 GNUNET_TRANSPORT_SessionInfoCallback sic,
2584 struct Plugin *plugin = cls;
2587 plugin->sic_cls = sic_cls;
2590 GNUNET_CONTAINER_multipeermap_iterate (plugin->sessionmap,
2591 &send_session_info_iter,
2593 /* signal end of first iteration */
2594 sic (sic_cls, NULL, NULL);
2600 * Entry point for the plugin.
2602 * @param cls closure, the 'struct GNUNET_TRANSPORT_PluginEnvironment*'
2603 * @return the 'struct GNUNET_TRANSPORT_PluginFunctions*' or NULL on error
2606 libgnunet_plugin_transport_tcp_init (void *cls)
2608 static const struct GNUNET_SERVER_MessageHandler my_handlers[] = {
2609 { &handle_tcp_welcome, NULL,
2610 GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME, sizeof(struct WelcomeMessage) },
2611 { &handle_tcp_nat_probe, NULL,
2612 GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE, sizeof(struct TCP_NAT_ProbeMessage) },
2613 { &handle_tcp_data, NULL,
2614 GNUNET_MESSAGE_TYPE_ALL, 0 },
2615 { NULL, NULL, 0, 0 }
2617 struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
2618 struct GNUNET_TRANSPORT_PluginFunctions *api;
2619 struct Plugin *plugin;
2620 struct GNUNET_SERVICE_Context *service;
2621 unsigned long long aport;
2622 unsigned long long bport;
2623 unsigned long long max_connections;
2625 struct GNUNET_TIME_Relative idle_timeout;
2628 struct sockaddr **addrs;
2629 socklen_t *addrlens;
2631 if (NULL == env->receive)
2633 /* run in 'stub' mode (i.e. as part of gnunet-peerinfo), don't fully
2634 initialze the plugin or the API */
2635 api = GNUNET_new (struct GNUNET_TRANSPORT_PluginFunctions);
2637 api->address_pretty_printer = &tcp_plugin_address_pretty_printer;
2638 api->address_to_string = &tcp_address_to_string;
2639 api->string_to_address = &tcp_string_to_address;
2643 GNUNET_assert (NULL != env->cfg);
2645 GNUNET_CONFIGURATION_get_value_number (env->cfg,
2649 max_connections = 128;
2653 != GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-tcp",
2654 "PORT", &bport)) || (bport > 65535)
2656 == GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-tcp",
2657 "ADVERTISED-PORT", &aport)) && (aport > 65535)))
2659 LOG(GNUNET_ERROR_TYPE_ERROR,
2660 _("Require valid port number for service `%s' in configuration!\n"),
2670 service = GNUNET_SERVICE_start ("transport-tcp",
2672 GNUNET_SERVICE_OPTION_NONE);
2673 if (service == NULL)
2675 LOG (GNUNET_ERROR_TYPE_WARNING,
2676 _("Failed to start service.\n"));
2683 plugin = GNUNET_new (struct Plugin);
2684 plugin->sessionmap = GNUNET_CONTAINER_multipeermap_create (max_connections,
2686 plugin->max_connections = max_connections;
2687 plugin->open_port = bport;
2688 plugin->adv_port = aport;
2690 if ( (service != NULL) &&
2693 GNUNET_SERVICE_get_server_addresses ("transport-tcp",
2698 for (ret = ret_s-1; ret >= 0; ret--)
2699 LOG (GNUNET_ERROR_TYPE_INFO,
2700 "Binding to address `%s'\n",
2701 GNUNET_a2s (addrs[ret], addrlens[ret]));
2703 = GNUNET_NAT_register (env->cfg,
2706 (unsigned int) ret_s,
2707 (const struct sockaddr **) addrs, addrlens,
2708 &tcp_nat_port_map_callback,
2709 &try_connection_reversal,
2711 for (ret = ret_s -1; ret >= 0; ret--)
2712 GNUNET_free (addrs[ret]);
2713 GNUNET_free_non_null (addrs);
2714 GNUNET_free_non_null (addrlens);
2718 plugin->nat = GNUNET_NAT_register (plugin->env->cfg,
2719 GNUNET_YES, 0, 0, NULL, NULL, NULL,
2720 &try_connection_reversal, plugin);
2722 api = GNUNET_new (struct GNUNET_TRANSPORT_PluginFunctions);
2724 api->send = &tcp_plugin_send;
2725 api->get_session = &tcp_plugin_get_session;
2726 api->disconnect_session = &tcp_disconnect_session;
2727 api->query_keepalive_factor = &tcp_query_keepalive_factor;
2728 api->disconnect_peer = &tcp_plugin_disconnect;
2729 api->address_pretty_printer = &tcp_plugin_address_pretty_printer;
2730 api->check_address = &tcp_plugin_check_address;
2731 api->address_to_string = &tcp_address_to_string;
2732 api->string_to_address = &tcp_string_to_address;
2733 api->get_network = &tcp_get_network;
2734 api->update_session_timeout = &tcp_plugin_update_session_timeout;
2735 api->update_inbound_delay = &tcp_plugin_update_inbound_delay;
2736 api->setup_monitor = &tcp_plugin_setup_monitor;
2737 plugin->service = service;
2738 if (NULL != service)
2740 plugin->server = GNUNET_SERVICE_get_server (service);
2745 GNUNET_CONFIGURATION_get_value_time (env->cfg,
2750 GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
2753 if (NULL != plugin->nat)
2754 GNUNET_NAT_unregister (plugin->nat);
2755 GNUNET_free(plugin);
2760 = GNUNET_SERVER_create_with_sockets (&plugin_tcp_access_check,
2762 idle_timeout, GNUNET_YES);
2764 plugin->handlers = GNUNET_malloc (sizeof (my_handlers));
2765 memcpy (plugin->handlers, my_handlers, sizeof(my_handlers));
2766 for (i = 0;i < sizeof(my_handlers) / sizeof(struct GNUNET_SERVER_MessageHandler);i++)
2767 plugin->handlers[i].callback_cls = plugin;
2769 GNUNET_SERVER_add_handlers (plugin->server, plugin->handlers);
2770 GNUNET_SERVER_disconnect_notify (plugin->server, &disconnect_notify, plugin);
2771 plugin->nat_wait_conns = GNUNET_CONTAINER_multipeermap_create (16,
2774 LOG (GNUNET_ERROR_TYPE_INFO,
2775 _("TCP transport listening on port %llu\n"),
2778 LOG (GNUNET_ERROR_TYPE_INFO,
2779 _("TCP transport not listening on any port (client only)\n"));
2780 if ( (aport != bport) &&
2782 LOG (GNUNET_ERROR_TYPE_INFO,
2783 _("TCP transport advertises itself as being on port %llu\n"),
2785 /* Initially set connections to 0 */
2786 GNUNET_assert(NULL != plugin->env->stats);
2787 GNUNET_STATISTICS_set (plugin->env->stats,
2788 gettext_noop ("# TCP sessions active"), 0, GNUNET_NO);
2794 * Exit point from the plugin.
2796 * @param cls the `struct GNUNET_TRANSPORT_PluginFunctions`
2800 libgnunet_plugin_transport_tcp_done (void *cls)
2802 struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
2803 struct Plugin *plugin = api->cls;
2804 struct TCPProbeContext *tcp_probe;
2805 struct PrettyPrinterContext *cur;
2806 struct PrettyPrinterContext *next;
2813 LOG (GNUNET_ERROR_TYPE_DEBUG,
2814 "Shutting down TCP plugin\n");
2816 /* Removing leftover sessions */
2817 GNUNET_CONTAINER_multipeermap_iterate (plugin->sessionmap,
2818 &session_disconnect_it,
2820 /* Removing leftover NAT sessions */
2821 GNUNET_CONTAINER_multipeermap_iterate (plugin->nat_wait_conns,
2822 &session_disconnect_it,
2825 next = ppc_dll_head;
2826 for (cur = next; NULL != cur; cur = next)
2830 GNUNET_CONTAINER_DLL_remove (ppc_dll_head,
2833 GNUNET_RESOLVER_request_cancel (cur->resolver_handle);
2837 if (NULL != plugin->service)
2838 GNUNET_SERVICE_stop (plugin->service);
2840 GNUNET_SERVER_destroy (plugin->server);
2841 GNUNET_free(plugin->handlers);
2842 if (NULL != plugin->nat)
2843 GNUNET_NAT_unregister (plugin->nat);
2844 while (NULL != (tcp_probe = plugin->probe_head))
2846 GNUNET_CONTAINER_DLL_remove (plugin->probe_head,
2849 GNUNET_CONNECTION_destroy (tcp_probe->sock);
2850 GNUNET_free(tcp_probe);
2852 GNUNET_CONTAINER_multipeermap_destroy (plugin->nat_wait_conns);
2853 GNUNET_CONTAINER_multipeermap_destroy (plugin->sessionmap);
2854 GNUNET_free(plugin);
2859 /* end of plugin_transport_tcp.c */