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,
842 GNUNET_STATISTICS_update (session->plugin->env->stats,
843 gettext_noop ("# TCP sessions active"), -1, GNUNET_NO);
847 GNUNET_assert(GNUNET_YES ==
848 GNUNET_CONTAINER_multipeermap_remove (plugin->nat_wait_conns,
852 if (NULL != session->client)
853 GNUNET_SERVER_client_set_user_context (session->client,
857 if (NULL != session->transmit_handle)
859 GNUNET_SERVER_notify_transmit_ready_cancel (session->transmit_handle);
860 session->transmit_handle = NULL;
862 plugin->env->unregister_quota_notification (plugin->env->cls,
866 session->plugin->env->session_end (session->plugin->env->cls,
870 if (GNUNET_SCHEDULER_NO_TASK != session->nat_connection_timeout)
872 GNUNET_SCHEDULER_cancel (session->nat_connection_timeout);
873 session->nat_connection_timeout = GNUNET_SCHEDULER_NO_TASK;
876 while (NULL != (pm = session->pending_messages_head))
878 LOG (GNUNET_ERROR_TYPE_DEBUG,
879 (NULL != pm->transmit_cont)
880 ? "Could not deliver message to `%4s'.\n"
881 : "Could not deliver message to `%4s', notifying.\n",
882 GNUNET_i2s (&session->target));
883 GNUNET_STATISTICS_update (session->plugin->env->stats,
884 gettext_noop ("# bytes currently in TCP buffers"),
885 -(int64_t) pm->message_size, GNUNET_NO);
886 GNUNET_STATISTICS_update (session->plugin->env->stats,
887 gettext_noop ("# bytes discarded by TCP (disconnect)"),
890 GNUNET_CONTAINER_DLL_remove (session->pending_messages_head,
891 session->pending_messages_tail,
893 GNUNET_assert (0 < session->msgs_in_queue);
894 session->msgs_in_queue--;
895 GNUNET_assert (pm->message_size <= session->bytes_in_queue);
896 session->bytes_in_queue -= pm->message_size;
897 if (NULL != pm->transmit_cont)
898 pm->transmit_cont (pm->transmit_cont_cls,
905 GNUNET_assert (0 == session->msgs_in_queue);
906 GNUNET_assert (0 == session->bytes_in_queue);
907 notify_session_monitor (session->plugin,
909 GNUNET_TRANSPORT_SS_UP);
911 if (session->receive_delay_task != GNUNET_SCHEDULER_NO_TASK )
913 GNUNET_SCHEDULER_cancel (session->receive_delay_task);
914 if (NULL != session->client)
915 GNUNET_SERVER_receive_done (session->client, GNUNET_SYSERR);
917 if (NULL != session->client)
919 GNUNET_SERVER_client_disconnect (session->client);
920 GNUNET_SERVER_client_drop (session->client);
921 session->client = NULL;
923 GNUNET_HELLO_address_free (session->address);
924 GNUNET_assert(NULL == session->transmit_handle);
925 GNUNET_free(session);
931 * Function that is called to get the keepalive factor.
932 * #GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT is divided by this number to
933 * calculate the interval between keepalive packets.
935 * @param cls closure with the `struct Plugin`
936 * @return keepalive factor
939 tcp_query_keepalive_factor (void *cls)
946 * Session was idle, so disconnect it
948 * @param cls the `struct Session` of the idle session
949 * @param tc scheduler context
952 session_timeout (void *cls,
953 const struct GNUNET_SCHEDULER_TaskContext *tc)
955 struct Session *s = cls;
956 struct GNUNET_TIME_Relative left;
958 s->timeout_task = GNUNET_SCHEDULER_NO_TASK;
959 left = GNUNET_TIME_absolute_get_remaining (s->timeout);
960 if (0 != left.rel_value_us)
962 /* not actually our turn yet, but let's at least update
963 the monitor, it may think we're about to die ... */
964 notify_session_monitor (s->plugin,
966 GNUNET_TRANSPORT_SS_UP);
967 s->timeout_task = GNUNET_SCHEDULER_add_delayed (left,
972 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
973 "Session %p was idle for %s, disconnecting\n",
975 GNUNET_STRINGS_relative_time_to_string (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
977 /* call session destroy function */
978 tcp_disconnect_session (s->plugin, s);
983 * Increment session timeout due to activity
985 * @param s session to increment timeout for
988 reschedule_session_timeout (struct Session *s)
990 GNUNET_assert(GNUNET_SCHEDULER_NO_TASK != s->timeout_task);
991 s->timeout = GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
996 * Create a new session. Also queues a welcome message.
998 * @param plugin the plugin
999 * @param address the address to create the session for
1000 * @param client client to use, reference counter must have already been increased
1001 * @param is_nat this a NAT session, we should wait for a client to
1002 * connect to us from an address, then assign that to
1004 * @return new session object
1006 static struct Session *
1007 create_session (struct Plugin *plugin,
1008 const struct GNUNET_HELLO_Address *address,
1009 struct GNUNET_SERVER_Client *client,
1012 struct Session *session;
1013 struct PendingMessage *pm;
1014 struct WelcomeMessage welcome;
1016 if (GNUNET_YES != is_nat)
1017 GNUNET_assert(NULL != client);
1019 GNUNET_assert(NULL == client);
1021 LOG (GNUNET_ERROR_TYPE_DEBUG,
1022 "Creating new session for peer `%4s'\n",
1023 GNUNET_i2s (&address->peer));
1024 session = GNUNET_new (struct Session);
1025 session->last_activity = GNUNET_TIME_absolute_get ();
1026 session->plugin = plugin;
1027 session->is_nat = is_nat;
1028 session->client = client;
1029 session->address = GNUNET_HELLO_address_copy (address);
1030 session->target = address->peer;
1031 session->expecting_welcome = GNUNET_YES;
1032 session->ats_address_network_type = GNUNET_ATS_NET_UNSPECIFIED;
1033 pm = GNUNET_malloc (sizeof (struct PendingMessage) +
1034 sizeof (struct WelcomeMessage));
1035 pm->msg = (const char *) &pm[1];
1036 pm->message_size = sizeof(struct WelcomeMessage);
1037 welcome.header.size = htons (sizeof(struct WelcomeMessage));
1038 welcome.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME);
1039 welcome.clientIdentity = *plugin->env->my_identity;
1040 memcpy (&pm[1], &welcome, sizeof(welcome));
1041 pm->timeout = GNUNET_TIME_UNIT_FOREVER_ABS;
1042 GNUNET_STATISTICS_update (plugin->env->stats,
1043 gettext_noop ("# bytes currently in TCP buffers"), pm->message_size,
1045 GNUNET_CONTAINER_DLL_insert (session->pending_messages_head,
1046 session->pending_messages_tail,
1048 session->msgs_in_queue++;
1049 session->bytes_in_queue += pm->message_size;
1050 session->timeout = GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1051 session->timeout_task = GNUNET_SCHEDULER_add_delayed (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
1054 if (GNUNET_YES != is_nat)
1056 GNUNET_STATISTICS_update (plugin->env->stats,
1057 gettext_noop ("# TCP sessions active"),
1060 notify_session_monitor (session->plugin,
1062 GNUNET_TRANSPORT_SS_UP);
1066 notify_session_monitor (session->plugin,
1068 GNUNET_TRANSPORT_SS_HANDSHAKE);
1070 plugin->env->register_quota_notification (plugin->env->cls,
1079 * If we have pending messages, ask the server to
1080 * transmit them (schedule the respective tasks, etc.)
1082 * @param session for which session should we do this
1085 process_pending_messages (struct Session *session);
1089 * Function called to notify a client about the socket
1090 * being ready to queue more data. "buf" will be
1091 * NULL and "size" zero if the socket was closed for
1092 * writing in the meantime.
1094 * @param cls closure
1095 * @param size number of bytes available in @a buf
1096 * @param buf where the callee should write the message
1097 * @return number of bytes written to @a buf
1100 do_transmit (void *cls, size_t size, void *buf)
1102 struct Session *session = cls;
1103 struct GNUNET_PeerIdentity pid;
1104 struct Plugin *plugin;
1105 struct PendingMessage *pos;
1106 struct PendingMessage *hd;
1107 struct PendingMessage *tl;
1108 struct GNUNET_TIME_Absolute now;
1112 session->transmit_handle = NULL;
1113 plugin = session->plugin;
1116 LOG (GNUNET_ERROR_TYPE_DEBUG,
1117 "Timeout trying to transmit to peer `%4s', discarding message queue.\n",
1118 GNUNET_i2s (&session->target));
1119 /* timeout; cancel all messages that have already expired */
1123 now = GNUNET_TIME_absolute_get ();
1124 while ((NULL != (pos = session->pending_messages_head))
1125 && (pos->timeout.abs_value_us <= now.abs_value_us))
1127 GNUNET_CONTAINER_DLL_remove (session->pending_messages_head,
1128 session->pending_messages_tail,
1130 GNUNET_assert (0 < session->msgs_in_queue);
1131 session->msgs_in_queue--;
1132 GNUNET_assert (pos->message_size <= session->bytes_in_queue);
1133 session->bytes_in_queue -= pos->message_size;
1134 LOG (GNUNET_ERROR_TYPE_DEBUG,
1135 "Failed to transmit %u byte message to `%4s'.\n",
1137 GNUNET_i2s (&session->target));
1138 ret += pos->message_size;
1139 GNUNET_CONTAINER_DLL_insert_after (hd, tl, tl, pos);
1141 /* do this call before callbacks (so that if callbacks destroy
1142 * session, they have a chance to cancel actions done by this
1144 process_pending_messages (session);
1145 pid = session->target;
1146 /* no do callbacks and do not use session again since
1147 * the callbacks may abort the session */
1148 while (NULL != (pos = hd))
1150 GNUNET_CONTAINER_DLL_remove (hd, tl, pos);
1151 if (pos->transmit_cont != NULL)
1152 pos->transmit_cont (pos->transmit_cont_cls,
1155 pos->message_size, 0);
1158 GNUNET_STATISTICS_update (plugin->env->stats,
1159 gettext_noop ("# bytes currently in TCP buffers"), -(int64_t) ret,
1161 GNUNET_STATISTICS_update (plugin->env->stats,
1162 gettext_noop ("# bytes discarded by TCP (timeout)"),
1166 notify_session_monitor (session->plugin,
1168 GNUNET_TRANSPORT_SS_UP);
1171 /* copy all pending messages that would fit */
1176 while (NULL != (pos = session->pending_messages_head))
1178 if (ret + pos->message_size > size)
1180 GNUNET_CONTAINER_DLL_remove (session->pending_messages_head,
1181 session->pending_messages_tail,
1183 GNUNET_assert (0 < session->msgs_in_queue);
1184 session->msgs_in_queue--;
1185 GNUNET_assert (pos->message_size <= session->bytes_in_queue);
1186 session->bytes_in_queue -= pos->message_size;
1187 GNUNET_assert(size >= pos->message_size);
1188 LOG(GNUNET_ERROR_TYPE_DEBUG,
1189 "Transmitting message of type %u size %u\n",
1190 ntohs (((struct GNUNET_MessageHeader * ) pos->msg)->type),
1192 /* FIXME: this memcpy can be up to 7% of our total runtime */
1193 memcpy (cbuf, pos->msg, pos->message_size);
1194 cbuf += pos->message_size;
1195 ret += pos->message_size;
1196 size -= pos->message_size;
1197 GNUNET_CONTAINER_DLL_insert_tail (hd, tl, pos);
1199 notify_session_monitor (session->plugin,
1201 GNUNET_TRANSPORT_SS_UP);
1202 /* schedule 'continuation' before callbacks so that callbacks that
1203 * cancel everything don't cause us to use a session that no longer
1205 process_pending_messages (session);
1206 session->last_activity = GNUNET_TIME_absolute_get ();
1207 pid = session->target;
1208 /* we'll now call callbacks that may cancel the session; hence
1209 * we should not use 'session' after this point */
1210 while (NULL != (pos = hd))
1212 GNUNET_CONTAINER_DLL_remove (hd, tl, pos);
1213 if (pos->transmit_cont != NULL)
1214 pos->transmit_cont (pos->transmit_cont_cls,
1218 pos->message_size); /* FIXME: include TCP overhead */
1221 GNUNET_assert(hd == NULL);
1222 GNUNET_assert(tl == NULL);
1223 LOG(GNUNET_ERROR_TYPE_DEBUG, "Transmitting %u bytes\n", ret);
1224 GNUNET_STATISTICS_update (plugin->env->stats,
1225 gettext_noop ("# bytes currently in TCP buffers"), -(int64_t) ret,
1227 GNUNET_STATISTICS_update (plugin->env->stats,
1228 gettext_noop ("# bytes transmitted via TCP"), ret, GNUNET_NO);
1234 * If we have pending messages, ask the server to
1235 * transmit them (schedule the respective tasks, etc.)
1237 * @param session for which session should we do this
1240 process_pending_messages (struct Session *session)
1242 struct PendingMessage *pm;
1244 GNUNET_assert(NULL != session->client);
1245 if (NULL != session->transmit_handle)
1247 if (NULL == (pm = session->pending_messages_head))
1250 session->transmit_handle = GNUNET_SERVER_notify_transmit_ready (
1251 session->client, pm->message_size,
1252 GNUNET_TIME_absolute_get_remaining (pm->timeout), &do_transmit, session);
1257 * Closure for #session_it().
1259 struct FindSessionContext
1262 * Session we are looking for.
1267 * Set to #GNUNET_OK if we found the session.
1274 * Function called to check if a session is in our maps.
1276 * @param cls the `struct FindSessionContext`
1277 * @param key peer identity
1278 * @param value session in the map
1279 * @return #GNUNET_YES to continue looking, #GNUNET_NO if we found the session
1282 session_it (void *cls, const struct GNUNET_PeerIdentity *key, void *value)
1284 struct FindSessionContext *res = cls;
1285 struct Session *session = value;
1287 if (res->s == session)
1289 res->res = GNUNET_OK;
1297 * Check that the given session is known to the plugin and
1298 * is in one of our maps.
1300 * @param plugin the plugin to check against
1301 * @param session the session to check
1302 * @return #GNUNET_OK if all is well, #GNUNET_SYSERR if the session is invalid
1305 find_session (struct Plugin *plugin, struct Session *session)
1307 struct FindSessionContext session_map_res;
1308 struct FindSessionContext nat_map_res;
1310 session_map_res.s = session;
1311 session_map_res.res = GNUNET_SYSERR;
1312 GNUNET_CONTAINER_multipeermap_iterate (plugin->sessionmap, &session_it,
1314 if (GNUNET_SYSERR != session_map_res.res)
1316 nat_map_res.s = session;
1317 nat_map_res.res = GNUNET_SYSERR;
1318 GNUNET_CONTAINER_multipeermap_iterate (plugin->nat_wait_conns, &session_it,
1320 if (GNUNET_SYSERR != nat_map_res.res)
1323 return GNUNET_SYSERR;
1329 * Function that can be used by the transport service to transmit
1330 * a message using the plugin. Note that in the case of a
1331 * peer disconnecting, the continuation MUST be called
1332 * prior to the disconnect notification itself. This function
1333 * will be called with this peer's HELLO message to initiate
1334 * a fresh connection to another peer.
1336 * @param cls closure
1337 * @param session which session must be used
1338 * @param msgbuf the message to transmit
1339 * @param msgbuf_size number of bytes in 'msgbuf'
1340 * @param priority how important is the message (most plugins will
1341 * ignore message priority and just FIFO)
1342 * @param to how long to wait at most for the transmission (does not
1343 * require plugins to discard the message after the timeout,
1344 * just advisory for the desired delay; most plugins will ignore
1346 * @param cont continuation to call once the message has
1347 * been transmitted (or if the transport is ready
1348 * for the next transmission call; or if the
1349 * peer disconnected...); can be NULL
1350 * @param cont_cls closure for @a cont
1351 * @return number of bytes used (on the physical network, with overheads);
1352 * -1 on hard errors (i.e. address invalid); 0 is a legal value
1353 * and does NOT mean that the message was not transmitted (DV)
1356 tcp_plugin_send (void *cls,
1357 struct Session *session,
1360 unsigned int priority,
1361 struct GNUNET_TIME_Relative to,
1362 GNUNET_TRANSPORT_TransmitContinuation cont,
1365 struct Plugin * plugin = cls;
1366 struct PendingMessage *pm;
1369 if (GNUNET_SYSERR == find_session (plugin, session))
1371 LOG(GNUNET_ERROR_TYPE_ERROR, _("Trying to send with invalid session %p\n"));
1373 return GNUNET_SYSERR;
1376 /* create new message entry */
1377 pm = GNUNET_malloc (sizeof (struct PendingMessage) + msgbuf_size);
1378 pm->msg = (const char *) &pm[1];
1379 memcpy (&pm[1], msgbuf, msgbuf_size);
1380 pm->message_size = msgbuf_size;
1381 pm->timeout = GNUNET_TIME_relative_to_absolute (to);
1382 pm->transmit_cont = cont;
1383 pm->transmit_cont_cls = cont_cls;
1385 LOG(GNUNET_ERROR_TYPE_DEBUG,
1386 "Asked to transmit %u bytes to `%s', added message to list.\n",
1387 msgbuf_size, GNUNET_i2s (&session->target));
1390 GNUNET_CONTAINER_multipeermap_contains_value (plugin->sessionmap,
1394 GNUNET_assert (NULL != session->client);
1395 GNUNET_SERVER_client_set_timeout (session->client,
1396 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1397 GNUNET_STATISTICS_update (plugin->env->stats,
1398 gettext_noop ("# bytes currently in TCP buffers"), msgbuf_size,
1401 /* append pm to pending_messages list */
1402 GNUNET_CONTAINER_DLL_insert_tail (session->pending_messages_head,
1403 session->pending_messages_tail,
1405 notify_session_monitor (session->plugin,
1407 GNUNET_TRANSPORT_SS_UP);
1408 session->msgs_in_queue++;
1409 session->bytes_in_queue += pm->message_size;
1410 process_pending_messages (session);
1413 else if (GNUNET_YES ==
1414 GNUNET_CONTAINER_multipeermap_contains_value (plugin->nat_wait_conns,
1418 LOG (GNUNET_ERROR_TYPE_DEBUG,
1419 "This NAT WAIT session for peer `%s' is not yet ready!\n",
1420 GNUNET_i2s (&session->target));
1421 GNUNET_STATISTICS_update (plugin->env->stats,
1422 gettext_noop ("# bytes currently in TCP buffers"), msgbuf_size,
1424 /* append pm to pending_messages list */
1425 GNUNET_CONTAINER_DLL_insert_tail (session->pending_messages_head,
1426 session->pending_messages_tail,
1428 session->msgs_in_queue++;
1429 session->bytes_in_queue += pm->message_size;
1430 notify_session_monitor (session->plugin,
1432 GNUNET_TRANSPORT_SS_HANDSHAKE);
1437 LOG(GNUNET_ERROR_TYPE_ERROR,
1438 "Invalid session %p\n",
1448 return GNUNET_SYSERR; /* session does not exist here */
1453 * Closure for #session_lookup_it().
1458 * Address we are looking for.
1460 const struct GNUNET_HELLO_Address *address;
1463 * Where to store the session (if we found it).
1465 struct Session *result;
1471 * Look for a session by address.
1473 * @param cls the `struct SessionItCtx`
1475 * @param value a `struct Session`
1476 * @return #GNUNET_YES to continue looking, #GNUNET_NO if we found the session
1479 session_lookup_it (void *cls,
1480 const struct GNUNET_PeerIdentity *key,
1483 struct SessionItCtx * si_ctx = cls;
1484 struct Session * session = value;
1486 if (0 != GNUNET_HELLO_address_cmp (si_ctx->address, session->address))
1488 /* Found existing session */
1489 si_ctx->result = session;
1495 * Task cleaning up a NAT connection attempt after timeout
1497 * @param cls the `struct Session`
1498 * @param tc scheduler context (unused)
1501 nat_connect_timeout (void *cls,
1502 const struct GNUNET_SCHEDULER_TaskContext *tc)
1504 struct Session *session = cls;
1506 session->nat_connection_timeout = GNUNET_SCHEDULER_NO_TASK;
1507 LOG(GNUNET_ERROR_TYPE_DEBUG,
1508 "NAT WAIT connection to `%4s' at `%s' could not be established, removing session\n",
1509 GNUNET_i2s (&session->target),
1510 tcp_address_to_string (NULL, session->address->address, session->address->address_length));
1511 tcp_disconnect_session (session->plugin, session);
1516 tcp_plugin_update_session_timeout (void *cls,
1517 const struct GNUNET_PeerIdentity *peer,
1518 struct Session *session)
1520 struct Plugin *plugin = cls;
1522 if (GNUNET_SYSERR == find_session (plugin, session))
1524 reschedule_session_timeout (session);
1528 * Task to signal the server that we can continue
1529 * receiving from the TCP client now.
1531 * @param cls the `struct Session*`
1532 * @param tc task context (unused)
1535 delayed_done (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1537 struct Session *session = cls;
1539 session->receive_delay_task = GNUNET_SCHEDULER_NO_TASK;
1540 reschedule_session_timeout (session);
1542 GNUNET_SERVER_receive_done (session->client, GNUNET_OK);
1547 tcp_plugin_update_inbound_delay (void *cls,
1548 const struct GNUNET_PeerIdentity *peer,
1549 struct Session *session,
1550 struct GNUNET_TIME_Relative delay)
1552 if (GNUNET_SCHEDULER_NO_TASK == session->receive_delay_task)
1555 LOG(GNUNET_ERROR_TYPE_DEBUG,
1556 "New inbound delay %llu us\n",delay.rel_value_us);
1558 GNUNET_SCHEDULER_cancel (session->receive_delay_task);
1559 session->receive_delay_task = GNUNET_SCHEDULER_add_delayed (delay,
1560 &delayed_done, session);
1565 * Create a new session to transmit data to the target
1566 * This session will used to send data to this peer and the plugin will
1567 * notify us by calling the env->session_end function
1569 * @param cls closure
1570 * @param address the address to use
1571 * @return the session if the address is valid, NULL otherwise
1573 static struct Session *
1574 tcp_plugin_get_session (void *cls,
1575 const struct GNUNET_HELLO_Address *address)
1577 struct Plugin *plugin = cls;
1578 struct Session *session = NULL;
1582 struct GNUNET_CONNECTION_Handle *sa;
1583 struct sockaddr_in a4;
1584 struct sockaddr_in6 a6;
1585 const struct IPv4TcpAddress *t4;
1586 const struct IPv6TcpAddress *t6;
1587 struct GNUNET_ATS_Information ats;
1588 unsigned int is_natd = GNUNET_NO;
1591 addrlen = address->address_length;
1592 LOG(GNUNET_ERROR_TYPE_DEBUG,
1593 "Trying to get session for `%s' address of peer `%s'\n",
1594 tcp_address_to_string(NULL, address->address, address->address_length),
1595 GNUNET_i2s (&address->peer));
1597 if (GNUNET_HELLO_address_check_option(address, GNUNET_HELLO_ADDRESS_INFO_INBOUND))
1603 /* look for existing session */
1604 if (GNUNET_YES == GNUNET_CONTAINER_multipeermap_contains (plugin->sessionmap,
1607 struct SessionItCtx si_ctx;
1609 si_ctx.address = address;
1610 si_ctx.result = NULL;
1612 GNUNET_CONTAINER_multipeermap_get_multiple (plugin->sessionmap,
1613 &address->peer, &session_lookup_it, &si_ctx);
1614 if (si_ctx.result != NULL )
1616 session = si_ctx.result;
1617 LOG(GNUNET_ERROR_TYPE_DEBUG,
1618 "Found existing session for `%s' address `%s' session %p\n",
1619 GNUNET_i2s (&address->peer),
1620 tcp_address_to_string(NULL, address->address, address->address_length),
1624 LOG(GNUNET_ERROR_TYPE_DEBUG,
1625 "Existing sessions did not match address `%s' or peer `%s'\n",
1626 tcp_address_to_string(NULL, address->address, address->address_length),
1627 GNUNET_i2s (&address->peer));
1630 if (addrlen == sizeof(struct IPv6TcpAddress))
1632 GNUNET_assert(NULL != address->address); /* make static analysis happy */
1633 t6 = address->address;
1635 memset (&a6, 0, sizeof(a6));
1636 #if HAVE_SOCKADDR_IN_SIN_LEN
1637 a6.sin6_len = sizeof (a6);
1639 a6.sin6_family = AF_INET6;
1640 a6.sin6_port = t6->t6_port;
1641 if (t6->t6_port == 0)
1642 is_natd = GNUNET_YES;
1643 memcpy (&a6.sin6_addr, &t6->ipv6_addr, sizeof(struct in6_addr));
1647 else if (addrlen == sizeof(struct IPv4TcpAddress))
1649 GNUNET_assert(NULL != address->address); /* make static analysis happy */
1650 t4 = address->address;
1652 memset (&a4, 0, sizeof(a4));
1653 #if HAVE_SOCKADDR_IN_SIN_LEN
1654 a4.sin_len = sizeof (a4);
1656 a4.sin_family = AF_INET;
1657 a4.sin_port = t4->t4_port;
1658 if (t4->t4_port == 0)
1659 is_natd = GNUNET_YES;
1660 a4.sin_addr.s_addr = t4->ipv4_addr;
1666 GNUNET_STATISTICS_update (plugin->env->stats, gettext_noop
1667 ("# requests to create session with invalid address"), 1, GNUNET_NO);
1671 ats = plugin->env->get_address_type (plugin->env->cls, sb, sbs);
1673 if ((is_natd == GNUNET_YES) && (addrlen == sizeof(struct IPv6TcpAddress)))
1675 /* NAT client only works with IPv4 addresses */
1679 if (plugin->cur_connections >= plugin->max_connections)
1685 if ((is_natd == GNUNET_YES)
1687 == GNUNET_CONTAINER_multipeermap_contains (plugin->nat_wait_conns,
1690 /* Only do one NAT punch attempt per peer identity */
1694 if ((is_natd == GNUNET_YES) && (NULL != plugin->nat) &&
1695 (GNUNET_NO == GNUNET_CONTAINER_multipeermap_contains (plugin->nat_wait_conns,
1698 LOG (GNUNET_ERROR_TYPE_DEBUG,
1699 "Found valid IPv4 NAT address (creating session)!\n");
1700 session = create_session (plugin, address, NULL, GNUNET_YES);
1701 session->ats_address_network_type = (enum GNUNET_ATS_Network_Type) ntohl (
1704 session->ats_address_network_type != GNUNET_ATS_NET_UNSPECIFIED);
1705 session->nat_connection_timeout = GNUNET_SCHEDULER_add_delayed (NAT_TIMEOUT,
1706 &nat_connect_timeout, session);
1707 GNUNET_assert(session != NULL);
1708 GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_multipeermap_put (plugin->nat_wait_conns,
1709 &session->target, session, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
1711 LOG(GNUNET_ERROR_TYPE_DEBUG,
1712 "Created NAT WAIT connection to `%4s' at `%s'\n",
1713 GNUNET_i2s (&session->target), GNUNET_a2s (sb, sbs));
1715 if (GNUNET_OK == GNUNET_NAT_run_client (plugin->nat, &a4))
1719 LOG(GNUNET_ERROR_TYPE_DEBUG,
1720 "Running NAT client for `%4s' at `%s' failed\n",
1721 GNUNET_i2s (&session->target), GNUNET_a2s (sb, sbs));
1722 tcp_disconnect_session (plugin, session);
1727 /* create new outbound session */
1728 GNUNET_assert(plugin->cur_connections <= plugin->max_connections);
1729 sa = GNUNET_CONNECTION_create_from_sockaddr (af, sb, sbs);
1732 LOG(GNUNET_ERROR_TYPE_DEBUG,
1733 "Failed to create connection to `%4s' at `%s'\n",
1734 GNUNET_i2s (&address->peer), GNUNET_a2s (sb, sbs));
1737 plugin->cur_connections++;
1738 if (plugin->cur_connections == plugin->max_connections)
1739 GNUNET_SERVER_suspend (plugin->server); /* Maximum number of connections rechead */
1741 LOG(GNUNET_ERROR_TYPE_DEBUG,
1742 "Asked to transmit to `%4s', creating fresh session using address `%s'.\n",
1743 GNUNET_i2s (&address->peer), GNUNET_a2s (sb, sbs));
1745 session = create_session (plugin, address,
1746 GNUNET_SERVER_connect_socket (plugin->server, sa), GNUNET_NO);
1747 session->ats_address_network_type = (enum GNUNET_ATS_Network_Type) ntohl (
1749 GNUNET_break(session->ats_address_network_type != GNUNET_ATS_NET_UNSPECIFIED);
1750 GNUNET_SERVER_client_set_user_context(session->client, session);
1751 GNUNET_CONTAINER_multipeermap_put (plugin->sessionmap, &session->target,
1752 session, GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
1753 LOG(GNUNET_ERROR_TYPE_DEBUG,
1754 "Creating new session for `%s' address `%s' session %p\n",
1755 GNUNET_i2s (&address->peer),
1756 tcp_address_to_string(NULL, address->address, address->address_length),
1758 /* Send TCP Welcome */
1759 process_pending_messages (session);
1766 session_disconnect_it (void *cls,
1767 const struct GNUNET_PeerIdentity *key,
1770 struct Plugin *plugin = cls;
1771 struct Session *session = value;
1773 GNUNET_STATISTICS_update (session->plugin->env->stats, gettext_noop
1774 ("# transport-service disconnect requests for TCP"), 1, GNUNET_NO);
1775 tcp_disconnect_session (plugin, session);
1781 * Function that can be called to force a disconnect from the
1782 * specified neighbour. This should also cancel all previously
1783 * scheduled transmissions. Obviously the transmission may have been
1784 * partially completed already, which is OK. The plugin is supposed
1785 * to close the connection (if applicable) and no longer call the
1786 * transmit continuation(s).
1788 * Finally, plugin MUST NOT call the services's receive function to
1789 * notify the service that the connection to the specified target was
1790 * closed after a getting this call.
1792 * @param cls closure
1793 * @param target peer for which the last transmission is
1797 tcp_plugin_disconnect (void *cls,
1798 const struct GNUNET_PeerIdentity *target)
1800 struct Plugin *plugin = cls;
1802 LOG(GNUNET_ERROR_TYPE_DEBUG,
1803 "Disconnecting peer `%4s'\n",
1804 GNUNET_i2s (target));
1805 GNUNET_CONTAINER_multipeermap_get_multiple (plugin->sessionmap,
1807 &session_disconnect_it,
1809 GNUNET_CONTAINER_multipeermap_get_multiple (plugin->nat_wait_conns,
1811 &session_disconnect_it,
1817 * Running pretty printers: head
1819 static struct PrettyPrinterContext *ppc_dll_head;
1822 * Running pretty printers: tail
1824 static struct PrettyPrinterContext *ppc_dll_tail;
1827 * Context for address to string conversion, closure
1828 * for #append_port().
1830 struct PrettyPrinterContext
1835 struct PrettyPrinterContext *next;
1840 struct PrettyPrinterContext *prev;
1845 GNUNET_SCHEDULER_TaskIdentifier timeout_task;
1850 struct GNUNET_RESOLVER_RequestHandle *resolver_handle;
1853 * Function to call with the result.
1855 GNUNET_TRANSPORT_AddressStringCallback asc;
1858 * Clsoure for @e asc.
1863 * Port to add after the IP address.
1880 * Append our port and forward the result.
1882 * @param cls the `struct PrettyPrinterContext *`
1883 * @param hostname hostname part of the address
1886 append_port (void *cls,
1887 const char *hostname)
1889 struct PrettyPrinterContext *ppc = cls;
1892 if (NULL == hostname)
1894 /* Final call, done */
1895 ppc->resolver_handle = NULL;
1896 GNUNET_CONTAINER_DLL_remove (ppc_dll_head,
1899 ppc->asc (ppc->asc_cls,
1905 if (GNUNET_YES == ppc->ipv6)
1906 GNUNET_asprintf (&ret,
1913 GNUNET_asprintf (&ret,
1919 ppc->asc (ppc->asc_cls,
1927 * Convert the transports address to a nice, human-readable
1930 * @param cls closure
1931 * @param type name of the transport that generated the address
1932 * @param addr one of the addresses of the host, NULL for the last address
1933 * the specific address format depends on the transport
1934 * @param addrlen length of the @a addr
1935 * @param numeric should (IP) addresses be displayed in numeric form?
1936 * @param timeout after how long should we give up?
1937 * @param asc function to call on each string
1938 * @param asc_cls closure for @a asc
1941 tcp_plugin_address_pretty_printer (void *cls,
1946 struct GNUNET_TIME_Relative timeout,
1947 GNUNET_TRANSPORT_AddressStringCallback asc,
1950 struct PrettyPrinterContext *ppc;
1953 struct sockaddr_in a4;
1954 struct sockaddr_in6 a6;
1955 const struct IPv4TcpAddress *t4;
1956 const struct IPv6TcpAddress *t6;
1960 if (sizeof(struct IPv6TcpAddress) == addrlen)
1963 memset (&a6, 0, sizeof(a6));
1964 a6.sin6_family = AF_INET6;
1965 a6.sin6_port = t6->t6_port;
1966 memcpy (&a6.sin6_addr, &t6->ipv6_addr, sizeof(struct in6_addr));
1967 port = ntohs (t6->t6_port);
1968 options = ntohl (t6->options);
1972 else if (sizeof(struct IPv4TcpAddress) == addrlen)
1975 memset (&a4, 0, sizeof(a4));
1976 a4.sin_family = AF_INET;
1977 a4.sin_port = t4->t4_port;
1978 a4.sin_addr.s_addr = t4->ipv4_addr;
1979 port = ntohs (t4->t4_port);
1980 options = ntohl (t4->options);
1986 /* invalid address */
1987 asc (asc_cls, NULL, GNUNET_SYSERR);
1988 asc (asc_cls, NULL, GNUNET_OK);
1991 ppc = GNUNET_new (struct PrettyPrinterContext);
1992 if (addrlen == sizeof(struct IPv6TcpAddress))
1993 ppc->ipv6 = GNUNET_YES;
1995 ppc->ipv6 = GNUNET_NO;
1997 ppc->asc_cls = asc_cls;
1999 ppc->options = options;
2000 ppc->resolver_handle = GNUNET_RESOLVER_hostname_get (sb,
2005 if (NULL == ppc->resolver_handle)
2011 GNUNET_CONTAINER_DLL_insert (ppc_dll_head,
2018 * Check if the given port is plausible (must be either our listen
2019 * port or our advertised port), or any port if we are behind NAT
2020 * and do not have a port open. If it is neither, we return
2023 * @param plugin global variables
2024 * @param in_port port number to check
2025 * @return #GNUNET_OK if port is either open_port or adv_port
2028 check_port (struct Plugin *plugin, uint16_t in_port)
2030 if ((in_port == plugin->adv_port) || (in_port == plugin->open_port))
2032 return GNUNET_SYSERR;
2036 * Function that will be called to check if a binary address for this
2037 * plugin is well-formed and corresponds to an address for THIS peer
2038 * (as per our configuration). Naturally, if absolutely necessary,
2039 * plugins can be a bit conservative in their answer, but in general
2040 * plugins should make sure that the address does not redirect
2041 * traffic to a 3rd party that might try to man-in-the-middle our
2044 * @param cls closure, our `struct Plugin *`
2045 * @param addr pointer to the address
2046 * @param addrlen length of addr
2047 * @return #GNUNET_OK if this is a plausible address for this peer
2048 * and transport, #GNUNET_SYSERR if not
2051 tcp_plugin_check_address (void *cls, const void *addr, size_t addrlen)
2053 struct Plugin *plugin = cls;
2054 struct IPv4TcpAddress *v4;
2055 struct IPv6TcpAddress *v6;
2057 if ((addrlen != sizeof(struct IPv4TcpAddress))
2058 && (addrlen != sizeof(struct IPv6TcpAddress)))
2061 return GNUNET_SYSERR;
2064 if (addrlen == sizeof(struct IPv4TcpAddress))
2066 v4 = (struct IPv4TcpAddress *) addr;
2067 if (0 != memcmp (&v4->options,
2072 return GNUNET_SYSERR;
2074 if (GNUNET_OK != check_port (plugin, ntohs (v4->t4_port)))
2075 return GNUNET_SYSERR;
2077 != GNUNET_NAT_test_address (plugin->nat, &v4->ipv4_addr,
2078 sizeof(struct in_addr)))
2079 return GNUNET_SYSERR;
2083 v6 = (struct IPv6TcpAddress *) addr;
2084 if (IN6_IS_ADDR_LINKLOCAL (&v6->ipv6_addr))
2087 return GNUNET_SYSERR;
2089 if (0 != memcmp (&v6->options,
2094 return GNUNET_SYSERR;
2096 if (GNUNET_OK != check_port (plugin, ntohs (v6->t6_port)))
2097 return GNUNET_SYSERR;
2099 != GNUNET_NAT_test_address (plugin->nat, &v6->ipv6_addr,
2100 sizeof(struct in6_addr)))
2101 return GNUNET_SYSERR;
2107 * We've received a nat probe from this peer via TCP. Finish
2108 * creating the client session and resume sending of queued
2111 * @param cls closure
2112 * @param client identification of the client
2113 * @param message the actual message
2116 handle_tcp_nat_probe (void *cls,
2117 struct GNUNET_SERVER_Client *client,
2118 const struct GNUNET_MessageHeader *message)
2120 struct Plugin *plugin = cls;
2121 struct Session *session;
2122 const struct TCP_NAT_ProbeMessage *tcp_nat_probe;
2125 struct IPv4TcpAddress *t4;
2126 struct IPv6TcpAddress *t6;
2127 const struct sockaddr_in *s4;
2128 const struct sockaddr_in6 *s6;
2130 LOG(GNUNET_ERROR_TYPE_DEBUG, "Received NAT probe\n");
2131 /* We have received a TCP NAT probe, meaning we (hopefully) initiated
2132 * a connection to this peer by running gnunet-nat-client. This peer
2133 * received the punch message and now wants us to use the new connection
2134 * as the default for that peer. Do so and then send a WELCOME message
2135 * so we can really be connected!
2137 if (ntohs (message->size) != sizeof(struct TCP_NAT_ProbeMessage))
2140 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2144 tcp_nat_probe = (const struct TCP_NAT_ProbeMessage *) message;
2145 if (0 == memcmp (&tcp_nat_probe->clientIdentity, plugin->env->my_identity,
2146 sizeof(struct GNUNET_PeerIdentity)))
2148 /* refuse connections from ourselves */
2149 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2153 session = GNUNET_CONTAINER_multipeermap_get (plugin->nat_wait_conns,
2154 &tcp_nat_probe->clientIdentity);
2155 if (session == NULL )
2157 LOG(GNUNET_ERROR_TYPE_DEBUG, "Did NOT find session for NAT probe!\n");
2158 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2161 LOG(GNUNET_ERROR_TYPE_DEBUG, "Found session for NAT probe!\n");
2163 if (session->nat_connection_timeout != GNUNET_SCHEDULER_NO_TASK )
2165 GNUNET_SCHEDULER_cancel (session->nat_connection_timeout);
2166 session->nat_connection_timeout = GNUNET_SCHEDULER_NO_TASK;
2169 if (GNUNET_OK != GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
2172 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2173 tcp_disconnect_session (plugin, session);
2177 GNUNET_CONTAINER_multipeermap_remove (plugin->nat_wait_conns, &tcp_nat_probe->clientIdentity, session) == GNUNET_YES);
2178 GNUNET_SERVER_client_set_user_context(client, session);
2179 GNUNET_CONTAINER_multipeermap_put (plugin->sessionmap, &session->target,
2180 session, GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2181 session->last_activity = GNUNET_TIME_absolute_get ();
2182 LOG(GNUNET_ERROR_TYPE_DEBUG, "Found address `%s' for incoming connection\n",
2183 GNUNET_a2s (vaddr, alen));
2184 switch (((const struct sockaddr *) vaddr)->sa_family)
2188 t4 = GNUNET_new (struct IPv4TcpAddress);
2189 t4->options = htonl(0);
2190 t4->t4_port = s4->sin_port;
2191 t4->ipv4_addr = s4->sin_addr.s_addr;
2192 session->address = GNUNET_HELLO_address_allocate (
2193 &tcp_nat_probe->clientIdentity, PLUGIN_NAME, &t4,
2194 sizeof(struct IPv4TcpAddress),
2195 GNUNET_HELLO_ADDRESS_INFO_NONE);
2199 t6 = GNUNET_new (struct IPv6TcpAddress);
2200 t6->options = htonl(0);
2201 t6->t6_port = s6->sin6_port;
2202 memcpy (&t6->ipv6_addr, &s6->sin6_addr, sizeof(struct in6_addr));
2203 session->address = GNUNET_HELLO_address_allocate (
2204 &tcp_nat_probe->clientIdentity,
2205 PLUGIN_NAME, &t6, sizeof(struct IPv6TcpAddress),
2206 GNUNET_HELLO_ADDRESS_INFO_NONE);
2210 LOG(GNUNET_ERROR_TYPE_DEBUG, "Bad address for incoming connection!\n");
2212 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2213 tcp_disconnect_session (plugin, session);
2217 GNUNET_break(NULL == session->client);
2218 GNUNET_SERVER_client_keep (client);
2219 session->client = client;
2220 GNUNET_STATISTICS_update (plugin->env->stats,
2221 gettext_noop ("# TCP sessions active"), 1, GNUNET_NO);
2222 process_pending_messages (session);
2223 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2227 * We've received a welcome from this peer via TCP. Possibly create a
2228 * fresh client record and send back our welcome.
2230 * @param cls closure
2231 * @param client identification of the client
2232 * @param message the actual message
2235 handle_tcp_welcome (void *cls,
2236 struct GNUNET_SERVER_Client *client,
2237 const struct GNUNET_MessageHeader *message)
2239 struct Plugin *plugin = cls;
2240 const struct WelcomeMessage *wm = (const struct WelcomeMessage *) message;
2241 struct GNUNET_HELLO_Address *address;
2242 struct Session *session;
2245 struct IPv4TcpAddress t4;
2246 struct IPv6TcpAddress t6;
2247 const struct sockaddr_in *s4;
2248 const struct sockaddr_in6 *s6;
2249 struct GNUNET_ATS_Information ats;
2252 if (0 == memcmp (&wm->clientIdentity, plugin->env->my_identity,
2253 sizeof(struct GNUNET_PeerIdentity)))
2255 /* refuse connections from ourselves */
2256 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2257 if (GNUNET_OK == GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
2259 LOG(GNUNET_ERROR_TYPE_INFO,
2260 "Received %s message from my own identity `%4s' on address `%s'\n",
2261 "WELCOME", GNUNET_i2s (&wm->clientIdentity),
2262 GNUNET_a2s (vaddr, alen));
2268 LOG(GNUNET_ERROR_TYPE_DEBUG, "Received %s message from `%4s' %p\n", "WELCOME",
2269 GNUNET_i2s (&wm->clientIdentity), client);
2270 GNUNET_STATISTICS_update (plugin->env->stats,
2271 gettext_noop ("# TCP WELCOME messages received"), 1, GNUNET_NO);
2272 session = lookup_session_by_client (plugin, client);
2273 if (NULL != session)
2275 if (GNUNET_OK == GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
2277 LOG(GNUNET_ERROR_TYPE_DEBUG, "Found existing session %p for peer `%s'\n",
2278 session, GNUNET_a2s (vaddr, alen));
2284 GNUNET_SERVER_client_keep (client);
2285 if (NULL != plugin->service) /* Otherwise value is incremented in tcp_access_check */
2286 plugin->cur_connections++;
2287 if (plugin->cur_connections == plugin->max_connections)
2288 GNUNET_SERVER_suspend (plugin->server); /* Maximum number of connections rechead */
2290 if (GNUNET_OK == GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
2292 if (alen == sizeof(struct sockaddr_in))
2295 memset (&t4, '\0', sizeof (t4));
2296 t4.options = htonl (0);
2297 t4.t4_port = s4->sin_port;
2298 t4.ipv4_addr = s4->sin_addr.s_addr;
2299 address = GNUNET_HELLO_address_allocate (&wm->clientIdentity,
2300 PLUGIN_NAME, &t4, sizeof(t4),
2301 GNUNET_HELLO_ADDRESS_INFO_INBOUND);
2303 else if (alen == sizeof(struct sockaddr_in6))
2306 memset (&t6, '\0', sizeof (t6));
2307 t6.options = htonl (0);
2308 t6.t6_port = s6->sin6_port;
2309 memcpy (&t6.ipv6_addr, &s6->sin6_addr, sizeof(struct in6_addr));
2310 address = GNUNET_HELLO_address_allocate (&wm->clientIdentity,
2311 PLUGIN_NAME, &t6, sizeof (t6),
2312 GNUNET_HELLO_ADDRESS_INFO_INBOUND);
2317 GNUNET_free_non_null (vaddr);
2320 session = create_session (plugin, address, client, GNUNET_NO);
2321 GNUNET_HELLO_address_free (address);
2322 ats = plugin->env->get_address_type (plugin->env->cls, vaddr, alen);
2323 session->ats_address_network_type = (enum GNUNET_ATS_Network_Type) ntohl (
2325 LOG(GNUNET_ERROR_TYPE_DEBUG, "Creating new%s session %p for peer `%s' client %p \n",
2326 GNUNET_HELLO_address_check_option (session->address,
2327 GNUNET_HELLO_ADDRESS_INFO_INBOUND) ? " inbound" : "", session,
2328 tcp_address_to_string(NULL, (void *) session->address->address,
2329 session->address->address_length),
2332 GNUNET_SERVER_client_set_user_context(session->client, session);
2333 GNUNET_CONTAINER_multipeermap_put (plugin->sessionmap, &session->target,
2334 session, GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2336 /* Notify transport and ATS about new session */
2337 plugin->env->session_start (NULL, session->address, session, &ats, 1);
2341 LOG(GNUNET_ERROR_TYPE_DEBUG,
2342 "Did not obtain TCP socket address for incoming connection\n");
2348 if (session->expecting_welcome != GNUNET_YES)
2351 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2355 session->last_activity = GNUNET_TIME_absolute_get ();
2356 session->expecting_welcome = GNUNET_NO;
2358 process_pending_messages (session);
2359 GNUNET_SERVER_client_set_timeout (client,
2360 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
2361 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2366 * We've received data for this peer via TCP. Unbox,
2367 * compute latency and forward.
2369 * @param cls closure
2370 * @param client identification of the client
2371 * @param message the actual message
2374 handle_tcp_data (void *cls,
2375 struct GNUNET_SERVER_Client *client,
2376 const struct GNUNET_MessageHeader *message)
2378 struct Plugin *plugin = cls;
2379 struct Session *session;
2380 struct GNUNET_TIME_Relative delay;
2383 type = ntohs (message->type);
2384 if ((GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME == type)
2385 || (GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE == type))
2387 /* We don't want to propagate WELCOME and NAT Probe messages up! */
2388 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2391 session = lookup_session_by_client (plugin, client);
2392 if (NULL == session)
2394 /* No inbound session found */
2398 GNUNET_SERVER_client_get_address (client, &vaddr, &alen);
2399 LOG(GNUNET_ERROR_TYPE_ERROR,
2400 "Received unexpected %u bytes of type %u from `%s'\n",
2401 (unsigned int ) ntohs (message->size),
2402 (unsigned int ) ntohs (message->type), GNUNET_a2s (vaddr, alen));
2404 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2405 GNUNET_free_non_null(vaddr);
2408 else if (GNUNET_YES == session->expecting_welcome)
2410 /* Session is expecting WELCOME message */
2414 GNUNET_SERVER_client_get_address (client, &vaddr, &alen);
2415 LOG(GNUNET_ERROR_TYPE_ERROR,
2416 "Received unexpected %u bytes of type %u from `%s'\n",
2417 (unsigned int ) ntohs (message->size),
2418 (unsigned int ) ntohs (message->type), GNUNET_a2s (vaddr, alen));
2420 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2421 GNUNET_free_non_null(vaddr);
2425 session->last_activity = GNUNET_TIME_absolute_get ();
2426 LOG(GNUNET_ERROR_TYPE_DEBUG,
2427 "Passing %u bytes of type %u from `%4s' to transport service.\n",
2428 (unsigned int ) ntohs (message->size),
2429 (unsigned int ) ntohs (message->type), GNUNET_i2s (&session->target));
2431 GNUNET_STATISTICS_update (plugin->env->stats,
2432 gettext_noop ("# bytes received via TCP"), ntohs (message->size),
2434 struct GNUNET_ATS_Information distance;
2436 distance.type = htonl (GNUNET_ATS_NETWORK_TYPE);
2437 distance.value = htonl ((uint32_t) session->ats_address_network_type);
2438 GNUNET_break(session->ats_address_network_type != GNUNET_ATS_NET_UNSPECIFIED);
2440 GNUNET_assert(GNUNET_CONTAINER_multipeermap_contains_value (plugin->sessionmap,
2444 delay = plugin->env->receive (plugin->env->cls,
2448 plugin->env->update_address_metrics (plugin->env->cls,
2452 reschedule_session_timeout (session);
2453 if (0 == delay.rel_value_us)
2455 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2459 LOG(GNUNET_ERROR_TYPE_DEBUG,
2460 "Throttling receiving from `%s' for %s\n",
2461 GNUNET_i2s (&session->target),
2462 GNUNET_STRINGS_relative_time_to_string (delay, GNUNET_YES));
2463 GNUNET_SERVER_disable_receive_done_warning (client);
2464 session->receive_delay_task = GNUNET_SCHEDULER_add_delayed (delay,
2465 &delayed_done, session);
2471 * Functions with this signature are called whenever a peer
2472 * is disconnected on the network level.
2474 * @param cls closure
2475 * @param client identification of the client
2478 disconnect_notify (void *cls, struct GNUNET_SERVER_Client *client)
2480 struct Plugin *plugin = cls;
2481 struct Session *session;
2485 session = lookup_session_by_client (plugin, client);
2486 if (NULL == session)
2487 return; /* unknown, nothing to do */
2488 LOG (GNUNET_ERROR_TYPE_DEBUG,
2489 "Destroying session of `%4s' with %s due to network-level disconnect.\n",
2490 GNUNET_i2s (&session->target),
2491 tcp_address_to_string (session->plugin, session->address->address,
2492 session->address->address_length));
2494 if (plugin->cur_connections == plugin->max_connections)
2495 GNUNET_SERVER_resume (plugin->server); /* Resume server */
2497 if (plugin->cur_connections < 1)
2500 plugin->cur_connections--;
2502 GNUNET_STATISTICS_update (session->plugin->env->stats, gettext_noop
2503 ("# network-level TCP disconnect events"),
2506 tcp_disconnect_session (plugin, session);
2511 * We can now send a probe message, copy into buffer to really send.
2513 * @param cls closure, a struct TCPProbeContext
2514 * @param size max size to copy
2515 * @param buf buffer to copy message to
2516 * @return number of bytes copied into @a buf
2519 notify_send_probe (void *cls,
2523 struct TCPProbeContext *tcp_probe_ctx = cls;
2524 struct Plugin *plugin = tcp_probe_ctx->plugin;
2527 tcp_probe_ctx->transmit_handle = NULL;
2528 GNUNET_CONTAINER_DLL_remove (plugin->probe_head,
2533 GNUNET_CONNECTION_destroy (tcp_probe_ctx->sock);
2534 GNUNET_free(tcp_probe_ctx);
2537 GNUNET_assert(size >= sizeof(tcp_probe_ctx->message));
2538 memcpy (buf, &tcp_probe_ctx->message, sizeof(tcp_probe_ctx->message));
2539 GNUNET_SERVER_connect_socket (tcp_probe_ctx->plugin->server,
2540 tcp_probe_ctx->sock);
2541 ret = sizeof(tcp_probe_ctx->message);
2542 GNUNET_free(tcp_probe_ctx);
2548 * Function called by the NAT subsystem suggesting another peer wants
2549 * to connect to us via connection reversal. Try to connect back to the
2552 * @param cls closure
2553 * @param addr address to try
2554 * @param addrlen number of bytes in @a addr
2557 try_connection_reversal (void *cls,
2558 const struct sockaddr *addr,
2561 struct Plugin *plugin = cls;
2562 struct GNUNET_CONNECTION_Handle *sock;
2563 struct TCPProbeContext *tcp_probe_ctx;
2566 * We have received an ICMP response, ostensibly from a peer
2567 * that wants to connect to us! Send a message to establish a connection.
2569 sock = GNUNET_CONNECTION_create_from_sockaddr (AF_INET, addr, addrlen);
2572 /* failed for some odd reason (out of sockets?); ignore attempt */
2576 tcp_probe_ctx = GNUNET_new (struct TCPProbeContext);
2577 tcp_probe_ctx->message.header.size = htons (
2578 sizeof(struct TCP_NAT_ProbeMessage));
2579 tcp_probe_ctx->message.header.type = htons (
2580 GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE);
2581 memcpy (&tcp_probe_ctx->message.clientIdentity, plugin->env->my_identity,
2582 sizeof(struct GNUNET_PeerIdentity));
2583 tcp_probe_ctx->plugin = plugin;
2584 tcp_probe_ctx->sock = sock;
2585 GNUNET_CONTAINER_DLL_insert (plugin->probe_head,
2588 tcp_probe_ctx->transmit_handle = GNUNET_CONNECTION_notify_transmit_ready (
2589 sock, ntohs (tcp_probe_ctx->message.header.size),
2590 GNUNET_TIME_UNIT_FOREVER_REL, ¬ify_send_probe, tcp_probe_ctx);
2596 * Function obtain the network type for a session
2598 * @param cls closure ('struct Plugin*')
2599 * @param session the session
2600 * @return the network type in HBO or #GNUNET_SYSERR
2602 static enum GNUNET_ATS_Network_Type
2603 tcp_get_network (void *cls,
2604 struct Session *session)
2606 struct Plugin * plugin = cls;
2608 GNUNET_assert (NULL != plugin);
2609 GNUNET_assert (NULL != session);
2610 if (GNUNET_SYSERR == find_session (plugin,session))
2611 return GNUNET_ATS_NET_UNSPECIFIED;
2612 return session->ats_address_network_type;
2617 * Return information about the given session to the
2620 * @param cls the `struct Plugin` with the monitor callback (`sic`)
2621 * @param peer peer we send information about
2622 * @param value our `struct Session` to send information about
2623 * @return #GNUNET_OK (continue to iterate)
2626 send_session_info_iter (void *cls,
2627 const struct GNUNET_PeerIdentity *peer,
2630 struct Plugin *plugin = cls;
2631 struct Session *session = value;
2633 notify_session_monitor (plugin,
2635 GNUNET_TRANSPORT_SS_UP);
2641 * Begin monitoring sessions of a plugin. There can only
2642 * be one active monitor per plugin (i.e. if there are
2643 * multiple monitors, the transport service needs to
2644 * multiplex the generated events over all of them).
2646 * @param cls closure of the plugin
2647 * @param sic callback to invoke, NULL to disable monitor;
2648 * plugin will being by iterating over all active
2649 * sessions immediately and then enter monitor mode
2650 * @param sic_cls closure for @a sic
2653 tcp_plugin_setup_monitor (void *cls,
2654 GNUNET_TRANSPORT_SessionInfoCallback sic,
2657 struct Plugin *plugin = cls;
2660 plugin->sic_cls = sic_cls;
2663 GNUNET_CONTAINER_multipeermap_iterate (plugin->sessionmap,
2664 &send_session_info_iter,
2666 /* signal end of first iteration */
2667 sic (sic_cls, NULL, NULL);
2673 * Entry point for the plugin.
2675 * @param cls closure, the 'struct GNUNET_TRANSPORT_PluginEnvironment*'
2676 * @return the 'struct GNUNET_TRANSPORT_PluginFunctions*' or NULL on error
2679 libgnunet_plugin_transport_tcp_init (void *cls)
2681 static const struct GNUNET_SERVER_MessageHandler my_handlers[] = {
2682 { &handle_tcp_welcome, NULL,
2683 GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME, sizeof(struct WelcomeMessage) },
2684 { &handle_tcp_nat_probe, NULL,
2685 GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE, sizeof(struct TCP_NAT_ProbeMessage) },
2686 { &handle_tcp_data, NULL,
2687 GNUNET_MESSAGE_TYPE_ALL, 0 },
2688 { NULL, NULL, 0, 0 }
2690 struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
2691 struct GNUNET_TRANSPORT_PluginFunctions *api;
2692 struct Plugin *plugin;
2693 struct GNUNET_SERVICE_Context *service;
2694 unsigned long long aport;
2695 unsigned long long bport;
2696 unsigned long long max_connections;
2698 struct GNUNET_TIME_Relative idle_timeout;
2701 struct sockaddr **addrs;
2702 socklen_t *addrlens;
2704 if (NULL == env->receive)
2706 /* run in 'stub' mode (i.e. as part of gnunet-peerinfo), don't fully
2707 initialze the plugin or the API */
2708 api = GNUNET_new (struct GNUNET_TRANSPORT_PluginFunctions);
2710 api->address_pretty_printer = &tcp_plugin_address_pretty_printer;
2711 api->address_to_string = &tcp_address_to_string;
2712 api->string_to_address = &tcp_string_to_address;
2716 GNUNET_assert (NULL != env->cfg);
2718 GNUNET_CONFIGURATION_get_value_number (env->cfg,
2722 max_connections = 128;
2726 != GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-tcp",
2727 "PORT", &bport)) || (bport > 65535)
2729 == GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-tcp",
2730 "ADVERTISED-PORT", &aport)) && (aport > 65535)))
2732 LOG(GNUNET_ERROR_TYPE_ERROR,
2733 _("Require valid port number for service `%s' in configuration!\n"),
2743 service = GNUNET_SERVICE_start ("transport-tcp",
2745 GNUNET_SERVICE_OPTION_NONE);
2746 if (service == NULL)
2748 LOG (GNUNET_ERROR_TYPE_WARNING,
2749 _("Failed to start service.\n"));
2756 plugin = GNUNET_new (struct Plugin);
2757 plugin->sessionmap = GNUNET_CONTAINER_multipeermap_create (max_connections,
2759 plugin->max_connections = max_connections;
2760 plugin->open_port = bport;
2761 plugin->adv_port = aport;
2763 if ( (service != NULL) &&
2766 GNUNET_SERVICE_get_server_addresses ("transport-tcp",
2771 for (ret = ret_s-1; ret >= 0; ret--)
2772 LOG (GNUNET_ERROR_TYPE_INFO,
2773 "Binding to address `%s'\n",
2774 GNUNET_a2s (addrs[ret], addrlens[ret]));
2776 = GNUNET_NAT_register (env->cfg,
2779 (unsigned int) ret_s,
2780 (const struct sockaddr **) addrs, addrlens,
2781 &tcp_nat_port_map_callback,
2782 &try_connection_reversal,
2784 for (ret = ret_s -1; ret >= 0; ret--)
2785 GNUNET_free (addrs[ret]);
2786 GNUNET_free_non_null (addrs);
2787 GNUNET_free_non_null (addrlens);
2791 plugin->nat = GNUNET_NAT_register (plugin->env->cfg,
2792 GNUNET_YES, 0, 0, NULL, NULL, NULL,
2793 &try_connection_reversal, plugin);
2795 api = GNUNET_new (struct GNUNET_TRANSPORT_PluginFunctions);
2797 api->send = &tcp_plugin_send;
2798 api->get_session = &tcp_plugin_get_session;
2799 api->disconnect_session = &tcp_disconnect_session;
2800 api->query_keepalive_factor = &tcp_query_keepalive_factor;
2801 api->disconnect_peer = &tcp_plugin_disconnect;
2802 api->address_pretty_printer = &tcp_plugin_address_pretty_printer;
2803 api->check_address = &tcp_plugin_check_address;
2804 api->address_to_string = &tcp_address_to_string;
2805 api->string_to_address = &tcp_string_to_address;
2806 api->get_network = &tcp_get_network;
2807 api->update_session_timeout = &tcp_plugin_update_session_timeout;
2808 api->update_inbound_delay = &tcp_plugin_update_inbound_delay;
2809 api->setup_monitor = &tcp_plugin_setup_monitor;
2810 plugin->service = service;
2811 if (NULL != service)
2813 plugin->server = GNUNET_SERVICE_get_server (service);
2818 GNUNET_CONFIGURATION_get_value_time (env->cfg,
2823 GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
2826 if (NULL != plugin->nat)
2827 GNUNET_NAT_unregister (plugin->nat);
2828 GNUNET_free(plugin);
2833 = GNUNET_SERVER_create_with_sockets (&plugin_tcp_access_check,
2835 idle_timeout, GNUNET_YES);
2837 plugin->handlers = GNUNET_malloc (sizeof (my_handlers));
2838 memcpy (plugin->handlers, my_handlers, sizeof(my_handlers));
2839 for (i = 0;i < sizeof(my_handlers) / sizeof(struct GNUNET_SERVER_MessageHandler);i++)
2840 plugin->handlers[i].callback_cls = plugin;
2842 GNUNET_SERVER_add_handlers (plugin->server, plugin->handlers);
2843 GNUNET_SERVER_disconnect_notify (plugin->server, &disconnect_notify, plugin);
2844 plugin->nat_wait_conns = GNUNET_CONTAINER_multipeermap_create (16,
2847 LOG (GNUNET_ERROR_TYPE_INFO,
2848 _("TCP transport listening on port %llu\n"),
2851 LOG (GNUNET_ERROR_TYPE_INFO,
2852 _("TCP transport not listening on any port (client only)\n"));
2853 if ( (aport != bport) &&
2855 LOG (GNUNET_ERROR_TYPE_INFO,
2856 _("TCP transport advertises itself as being on port %llu\n"),
2858 /* Initially set connections to 0 */
2859 GNUNET_assert(NULL != plugin->env->stats);
2860 GNUNET_STATISTICS_set (plugin->env->stats,
2861 gettext_noop ("# TCP sessions active"), 0, GNUNET_NO);
2867 * Exit point from the plugin.
2869 * @param cls the `struct GNUNET_TRANSPORT_PluginFunctions`
2873 libgnunet_plugin_transport_tcp_done (void *cls)
2875 struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
2876 struct Plugin *plugin = api->cls;
2877 struct TCPProbeContext *tcp_probe;
2878 struct PrettyPrinterContext *cur;
2879 struct PrettyPrinterContext *next;
2886 LOG (GNUNET_ERROR_TYPE_DEBUG,
2887 "Shutting down TCP plugin\n");
2889 /* Removing leftover sessions */
2890 GNUNET_CONTAINER_multipeermap_iterate (plugin->sessionmap,
2891 &session_disconnect_it,
2893 /* Removing leftover NAT sessions */
2894 GNUNET_CONTAINER_multipeermap_iterate (plugin->nat_wait_conns,
2895 &session_disconnect_it,
2898 next = ppc_dll_head;
2899 for (cur = next; NULL != cur; cur = next)
2903 GNUNET_CONTAINER_DLL_remove (ppc_dll_head,
2906 GNUNET_RESOLVER_request_cancel (cur->resolver_handle);
2910 if (NULL != plugin->service)
2911 GNUNET_SERVICE_stop (plugin->service);
2913 GNUNET_SERVER_destroy (plugin->server);
2914 GNUNET_free(plugin->handlers);
2915 if (NULL != plugin->nat)
2916 GNUNET_NAT_unregister (plugin->nat);
2917 while (NULL != (tcp_probe = plugin->probe_head))
2919 GNUNET_CONTAINER_DLL_remove (plugin->probe_head,
2922 GNUNET_CONNECTION_destroy (tcp_probe->sock);
2923 GNUNET_free(tcp_probe);
2925 GNUNET_CONTAINER_multipeermap_destroy (plugin->nat_wait_conns);
2926 GNUNET_CONTAINER_multipeermap_destroy (plugin->sessionmap);
2927 GNUNET_free(plugin);
2932 /* end of plugin_transport_tcp.c */