2 This file is part of GNUnet
3 (C) 2002--2013 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)
51 GNUNET_NETWORK_STRUCT_BEGIN
56 static uint32_t myoptions;
59 * Initial handshake message for a session.
64 * Type is GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME.
66 struct GNUNET_MessageHeader header;
69 * Identity of the node connecting (TCP client)
71 struct GNUNET_PeerIdentity clientIdentity;
77 * Basically a WELCOME message, but with the purpose
78 * of giving the waiting peer a client handle to use
80 struct TCP_NAT_ProbeMessage
83 * Type is GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE.
85 struct GNUNET_MessageHeader header;
88 * Identity of the sender of the message.
90 struct GNUNET_PeerIdentity clientIdentity;
93 GNUNET_NETWORK_STRUCT_END
96 * Context for sending a NAT probe via TCP.
98 struct TCPProbeContext
102 * Active probes are kept in a DLL.
104 struct TCPProbeContext *next;
107 * Active probes are kept in a DLL.
109 struct TCPProbeContext *prev;
114 struct GNUNET_CONNECTION_Handle *sock;
117 * Message to be sent.
119 struct TCP_NAT_ProbeMessage message;
122 * Handle to the transmission.
124 struct GNUNET_CONNECTION_TransmitHandle *transmit_handle;
127 * Transport plugin handle.
129 struct Plugin *plugin;
133 GNUNET_NETWORK_STRUCT_BEGIN
136 * Network format for IPv4 addresses.
138 struct IPv4TcpAddress
141 * Optional options and flags for this address
146 * IPv4 address, in network byte order.
148 uint32_t ipv4_addr GNUNET_PACKED;
151 * Port number, in network byte order.
153 uint16_t t4_port GNUNET_PACKED;
159 * Network format for IPv6 addresses.
161 struct IPv6TcpAddress
164 * Optional flags for this address
171 struct in6_addr ipv6_addr GNUNET_PACKED;
174 * Port number, in network byte order.
176 uint16_t t6_port GNUNET_PACKED;
179 GNUNET_NETWORK_STRUCT_END
182 * Encapsulation of all of the state of the plugin.
188 * Information kept for each message that is yet to
191 struct PendingMessage
195 * This is a doubly-linked list.
197 struct PendingMessage *next;
200 * This is a doubly-linked list.
202 struct PendingMessage *prev;
205 * The pending message
210 * Continuation function to call once the message
211 * has been sent. Can be NULL if there is no
212 * continuation to call.
214 GNUNET_TRANSPORT_TransmitContinuation transmit_cont;
217 * Closure for transmit_cont.
219 void *transmit_cont_cls;
222 * Timeout value for the pending message.
224 struct GNUNET_TIME_Absolute timeout;
227 * So that the gnunet-service-transport can group messages together,
228 * these pending messages need to accept a message buffer and size
229 * instead of just a GNUNET_MessageHeader.
237 * Session handle for TCP connections.
242 * To whom are we talking to (set to our identity
243 * if we are still waiting for the welcome message)
245 struct GNUNET_PeerIdentity target;
250 struct SessionHeader header;
253 * Pointer to the global plugin struct.
255 struct Plugin *plugin;
258 * The client (used to identify this connection)
260 struct GNUNET_SERVER_Client *client;
263 * Task cleaning up a NAT client connection establishment attempt;
265 GNUNET_SCHEDULER_TaskIdentifier nat_connection_timeout;
268 * Messages currently pending for transmission
269 * to this peer, if any.
271 struct PendingMessage *pending_messages_head;
274 * Messages currently pending for transmission
275 * to this peer, if any.
277 struct PendingMessage *pending_messages_tail;
280 * Handle for pending transmission request.
282 struct GNUNET_SERVER_TransmitHandle *transmit_handle;
285 * ID of task used to delay receiving more to throttle sender.
287 GNUNET_SCHEDULER_TaskIdentifier receive_delay_task;
290 * Session timeout task
292 GNUNET_SCHEDULER_TaskIdentifier timeout_task;
295 * Address of the other peer (either based on our 'connect'
296 * call or on our 'accept' call).
298 * struct IPv4TcpAddress or struct IPv6TcpAddress
308 * Last activity on this connection. Used to select preferred
311 struct GNUNET_TIME_Absolute last_activity;
314 * Are we still expecting the welcome message? (#GNUNET_YES/#GNUNET_NO)
316 int expecting_welcome;
319 * Was this a connection that was inbound (we accepted)? (#GNUNET_YES/#GNUNET_NO)
324 * Was this session created using NAT traversal?
329 * ATS network type in NBO
331 enum GNUNET_ATS_Network_Type ats_address_network_type;
336 * Encapsulation of all of the state of the plugin.
343 struct GNUNET_TRANSPORT_PluginEnvironment *env;
348 struct GNUNET_CONNECTION_Handle *lsock;
351 * Our handle to the NAT module.
353 struct GNUNET_NAT_Handle *nat;
356 * Map from peer identities to sessions for the given peer.
358 struct GNUNET_CONTAINER_MultiPeerMap *sessionmap;
361 * Handle to the network service.
363 struct GNUNET_SERVICE_Context *service;
366 * Handle to the server for this service.
368 struct GNUNET_SERVER_Handle *server;
371 * Copy of the handler array where the closures are
372 * set to this struct's instance.
374 struct GNUNET_SERVER_MessageHandler *handlers;
377 * Map of peers we have tried to contact behind a NAT
379 struct GNUNET_CONTAINER_MultiPeerMap *nat_wait_conns;
382 * List of active TCP probes.
384 struct TCPProbeContext *probe_head;
387 * List of active TCP probes.
389 struct TCPProbeContext *probe_tail;
392 * Handle for (DYN)DNS lookup of our external IP.
394 struct GNUNET_RESOLVER_RequestHandle *ext_dns;
397 * How many more TCP sessions are we allowed to open right now?
399 unsigned long long max_connections;
402 * How many more TCP sessions do we have right now?
404 unsigned long long cur_connections;
407 * ID of task used to update our addresses when one expires.
409 GNUNET_SCHEDULER_TaskIdentifier address_update_task;
412 * Port that we are actually listening on.
417 * Port that the user said we would have visible to the
426 * Function called for a quick conversion of the binary address to
427 * a numeric address. Note that the caller must not free the
428 * address and that the next call to this function is allowed
429 * to override the address again.
431 * @param cls closure ('struct Plugin*')
432 * @param addr binary address
433 * @param addrlen length of the address
434 * @return string representing the same address
437 tcp_address_to_string (void *cls,
443 * Function to check if an inbound connection is acceptable.
444 * Mostly used to limit the total number of open connections
447 * @param cls the `struct Plugin`
448 * @param ucred credentials, if available, otherwise NULL
449 * @param addr address
450 * @param addrlen length of address
451 * @return #GNUNET_YES to allow, #GNUNET_NO to deny, #GNUNET_SYSERR
452 * for unknown address family (will be denied).
455 plugin_tcp_access_check (void *cls,
456 const struct GNUNET_CONNECTION_Credentials *ucred,
457 const struct sockaddr *addr, socklen_t addrlen)
459 struct Plugin *plugin = cls;
460 LOG (GNUNET_ERROR_TYPE_DEBUG,
461 "Accepting new incoming TCP connection from `%s'\n",
462 GNUNET_a2s (addr, addrlen));
463 if (plugin->cur_connections >= plugin->max_connections)
465 plugin->cur_connections ++;
471 * Our external IP address/port mapping has changed.
473 * @param cls closure, the 'struct Plugin'
474 * @param add_remove #GNUNET_YES to mean the new public IP address, #GNUNET_NO to mean
475 * the previous (now invalid) one
476 * @param addr either the previous or the new public IP address
477 * @param addrlen actual lenght of the address
480 tcp_nat_port_map_callback (void *cls, int add_remove,
481 const struct sockaddr *addr,
484 struct Plugin *plugin = cls;
485 struct IPv4TcpAddress t4;
486 struct IPv6TcpAddress t6;
490 LOG (GNUNET_ERROR_TYPE_INFO,
491 "NAT notification to %s address `%s'\n",
492 (GNUNET_YES == add_remove) ? "add" : "remove",
493 GNUNET_a2s (addr, addrlen));
494 /* convert 'addr' to our internal format */
495 switch (addr->sa_family)
498 GNUNET_assert (addrlen == sizeof (struct sockaddr_in));
499 memset (&t4,0, sizeof (t4));
500 t4.options = htonl (myoptions);
501 t4.ipv4_addr = ((struct sockaddr_in *) addr)->sin_addr.s_addr;
502 t4.t4_port = ((struct sockaddr_in *) addr)->sin_port;
507 GNUNET_assert (addrlen == sizeof (struct sockaddr_in6));
508 memset (&t6, 0, sizeof (t6));
509 memcpy (&t6.ipv6_addr, &((struct sockaddr_in6 *) addr)->sin6_addr,
510 sizeof (struct in6_addr));
511 t6.options = htonl (myoptions);
512 t6.t6_port = ((struct sockaddr_in6 *) addr)->sin6_port;
520 /* modify our published address list */
521 plugin->env->notify_address (plugin->env->cls, add_remove, arg, args, "tcp");
526 * Function called for a quick conversion of the binary address to
527 * a numeric address. Note that the caller must not free the
528 * address and that the next call to this function is allowed
529 * to override the address again.
531 * @param cls closure (`struct Plugin*`)
532 * @param addr binary address
533 * @param addrlen length of the address
534 * @return string representing the same address
537 tcp_address_to_string (void *cls, const void *addr, size_t addrlen)
539 static char rbuf[INET6_ADDRSTRLEN + 12];
540 char buf[INET6_ADDRSTRLEN];
544 const struct IPv4TcpAddress *t4;
545 const struct IPv6TcpAddress *t6;
552 case sizeof (struct IPv6TcpAddress):
555 port = ntohs (t6->t6_port);
556 options = ntohl (t6->options);
557 memcpy (&a6, &t6->ipv6_addr, sizeof (a6));
560 case sizeof (struct IPv4TcpAddress):
563 port = ntohs (t4->t4_port);
564 options = ntohl (t4->options);
565 memcpy (&a4, &t4->ipv4_addr, sizeof (a4));
570 GNUNET_snprintf (rbuf, sizeof (rbuf), "%s",
571 TRANSPORT_SESSION_INBOUND_STRING);
575 LOG (GNUNET_ERROR_TYPE_WARNING,
576 _("Unexpected address length: %u bytes\n"),
577 (unsigned int) addrlen);
580 if (NULL == inet_ntop (af, sb, buf, INET6_ADDRSTRLEN))
582 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "inet_ntop");
585 GNUNET_snprintf (rbuf,
599 * Function called to convert a string address to
602 * @param cls closure (`struct Plugin*`)
603 * @param addr string address
604 * @param addrlen length of the address
605 * @param buf location to store the buffer
606 * @param added location to store the number of bytes in the buffer.
607 * If the function returns #GNUNET_SYSERR, its contents are undefined.
608 * @return #GNUNET_OK on success, #GNUNET_SYSERR on failure
611 tcp_string_to_address (void *cls,
614 void **buf, size_t *added)
616 struct sockaddr_storage socket_address;
622 /* Format tcp.options.address:port */
626 if ((NULL == addr) || (addrlen == 0))
629 return GNUNET_SYSERR;
631 if ('\0' != addr[addrlen - 1])
634 return GNUNET_SYSERR;
636 if (strlen (addr) != addrlen - 1)
639 return GNUNET_SYSERR;
641 plugin = GNUNET_strdup (addr);
642 optionstr = strchr (plugin, '.');
643 if (NULL == optionstr)
646 GNUNET_free (plugin);
647 return GNUNET_SYSERR;
651 options = atol (optionstr);
652 address = strchr (optionstr, '.');
656 GNUNET_free (plugin);
657 return GNUNET_SYSERR;
663 GNUNET_STRINGS_to_address_ip (address, strlen (address),
667 GNUNET_free (plugin);
668 return GNUNET_SYSERR;
671 GNUNET_free (plugin);
672 switch (socket_address.ss_family)
676 struct IPv4TcpAddress *t4;
677 struct sockaddr_in *in4 = (struct sockaddr_in *) &socket_address;
678 t4 = GNUNET_new (struct IPv4TcpAddress);
679 t4->options = htonl (options);
680 t4->ipv4_addr = in4->sin_addr.s_addr;
681 t4->t4_port = in4->sin_port;
683 *added = sizeof (struct IPv4TcpAddress);
688 struct IPv6TcpAddress *t6;
689 struct sockaddr_in6 *in6 = (struct sockaddr_in6 *) &socket_address;
690 t6 = GNUNET_new (struct IPv6TcpAddress);
691 t6->options = htonl (options);
692 t6->ipv6_addr = in6->sin6_addr;
693 t6->t6_port = in6->sin6_port;
695 *added = sizeof (struct IPv6TcpAddress);
699 return GNUNET_SYSERR;
705 * Closure for #session_lookup_by_client_it().
707 struct SessionClientCtx
710 * Client we are looking for.
712 const struct GNUNET_SERVER_Client *client;
715 * Session that was found.
722 session_lookup_by_client_it (void *cls,
723 const struct GNUNET_PeerIdentity *key,
726 struct SessionClientCtx *sc_ctx = cls;
727 struct Session *s = value;
729 if (s->client == sc_ctx->client)
739 * Find the session handle for the given client.
740 * Currently uses both the hashmap and the client
741 * context, as the client context is new and the
742 * logic still needs to be tested.
744 * @param plugin the plugin
745 * @param client which client to find the session handle for
746 * @return NULL if no matching session exists
748 static struct Session *
749 lookup_session_by_client (struct Plugin *plugin,
750 struct GNUNET_SERVER_Client *client)
753 struct SessionClientCtx sc_ctx;
755 ret = GNUNET_SERVER_client_get_user_context (client, struct Session);
756 sc_ctx.client = client;
758 GNUNET_CONTAINER_multipeermap_iterate (plugin->sessionmap,
759 &session_lookup_by_client_it, &sc_ctx);
760 /* check both methods yield the same result */
761 GNUNET_break (ret == sc_ctx.ret);
767 * Functions with this signature are called whenever we need
768 * to close a session due to a disconnect or failure to
769 * establish a connection.
771 * @param cls the `struct Plugin`
772 * @param session session to close down
773 * @return #GNUNET_OK on success
776 tcp_disconnect_session (void *cls,
777 struct Session *session)
779 struct Plugin *plugin = cls;
780 struct PendingMessage *pm;
782 LOG (GNUNET_ERROR_TYPE_DEBUG,
783 "Disconnecting session of peer `%s' address `%s'\n",
784 GNUNET_i2s (&session->target),
785 tcp_address_to_string (NULL, session->addr, session->addrlen));
787 if (GNUNET_SCHEDULER_NO_TASK != session->timeout_task)
789 GNUNET_SCHEDULER_cancel (session->timeout_task);
790 session->timeout_task = GNUNET_SCHEDULER_NO_TASK;
794 GNUNET_CONTAINER_multipeermap_remove (plugin->sessionmap,
798 GNUNET_STATISTICS_update (session->plugin->env->stats,
799 gettext_noop ("# TCP sessions active"), -1,
804 GNUNET_assert (GNUNET_YES ==
805 GNUNET_CONTAINER_multipeermap_remove (plugin->nat_wait_conns,
809 GNUNET_SERVER_client_set_user_context (session->client,
813 if (NULL != session->transmit_handle)
815 GNUNET_SERVER_notify_transmit_ready_cancel (session->transmit_handle);
816 session->transmit_handle = NULL;
818 session->plugin->env->session_end (session->plugin->env->cls,
819 &session->target, session);
821 if (GNUNET_SCHEDULER_NO_TASK != session->nat_connection_timeout)
823 GNUNET_SCHEDULER_cancel (session->nat_connection_timeout);
824 session->nat_connection_timeout = GNUNET_SCHEDULER_NO_TASK;
827 while (NULL != (pm = session->pending_messages_head))
829 LOG (GNUNET_ERROR_TYPE_DEBUG,
831 NULL ? "Could not deliver message to `%4s'.\n" :
832 "Could not deliver message to `%4s', notifying.\n",
833 GNUNET_i2s (&session->target));
834 GNUNET_STATISTICS_update (session->plugin->env->stats,
835 gettext_noop ("# bytes currently in TCP buffers"),
836 -(int64_t) pm->message_size, GNUNET_NO);
837 GNUNET_STATISTICS_update (session->plugin->env->stats,
839 ("# bytes discarded by TCP (disconnect)"),
840 pm->message_size, GNUNET_NO);
841 GNUNET_CONTAINER_DLL_remove (session->pending_messages_head,
842 session->pending_messages_tail, pm);
843 if (NULL != pm->transmit_cont)
844 pm->transmit_cont (pm->transmit_cont_cls, &session->target,
845 GNUNET_SYSERR, pm->message_size, 0);
848 if (session->receive_delay_task != GNUNET_SCHEDULER_NO_TASK)
850 GNUNET_SCHEDULER_cancel (session->receive_delay_task);
851 if (NULL != session->client)
852 GNUNET_SERVER_receive_done (session->client, GNUNET_SYSERR);
854 if (NULL != session->client)
856 GNUNET_SERVER_client_disconnect (session->client);
857 GNUNET_SERVER_client_drop (session->client);
858 session->client = NULL;
860 GNUNET_free_non_null (session->addr);
861 GNUNET_assert (NULL == session->transmit_handle);
862 GNUNET_free (session);
868 * Function that is called to get the keepalive factor.
869 * GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT is divided by this number to
870 * calculate the interval between keepalive packets.
872 * @param cls closure with the `struct Plugin`
873 * @return keepalive factor
876 tcp_query_keepalive_factor (void *cls)
883 * Session was idle, so disconnect it
885 * @param cls the `struct Session` of the idle session
886 * @param tc scheduler context
889 session_timeout (void *cls,
890 const struct GNUNET_SCHEDULER_TaskContext *tc)
892 struct Session *s = cls;
894 s->timeout_task = GNUNET_SCHEDULER_NO_TASK;
895 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
896 "Session %p was idle for %s, disconnecting\n",
898 GNUNET_STRINGS_relative_time_to_string (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
900 /* call session destroy function */
901 tcp_disconnect_session (s->plugin, s);
906 * Increment session timeout due to activity
908 * @param s session to increment timeout for
911 reschedule_session_timeout (struct Session *s)
913 GNUNET_assert (GNUNET_SCHEDULER_NO_TASK != s->timeout_task);
914 GNUNET_SCHEDULER_cancel (s->timeout_task);
915 s->timeout_task = GNUNET_SCHEDULER_add_delayed (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
918 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
919 "Timeout rescheduled for session %p set to %s\n",
921 GNUNET_STRINGS_relative_time_to_string (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
927 * Create a new session. Also queues a welcome message.
929 * @param plugin the plugin
930 * @param target peer to connect to
931 * @param client client to use, reference counter must have already been increased
932 * @param is_nat this a NAT session, we should wait for a client to
933 * connect to us from an address, then assign that to
935 * @return new session object
937 static struct Session *
938 create_session (struct Plugin *plugin,
939 const struct GNUNET_PeerIdentity *target,
940 struct GNUNET_SERVER_Client *client, int is_nat)
942 struct Session *session;
943 struct PendingMessage *pm;
944 struct WelcomeMessage welcome;
946 if (GNUNET_YES != is_nat)
947 GNUNET_assert (NULL != client);
949 GNUNET_assert (NULL == client);
951 LOG (GNUNET_ERROR_TYPE_DEBUG,
952 "Creating new session for peer `%4s'\n",
953 GNUNET_i2s (target));
954 session = GNUNET_new (struct Session);
955 session->last_activity = GNUNET_TIME_absolute_get ();
956 session->plugin = plugin;
957 session->is_nat = is_nat;
958 session->client = client;
959 session->target = *target;
960 session->expecting_welcome = GNUNET_YES;
961 session->ats_address_network_type = GNUNET_ATS_NET_UNSPECIFIED;
962 pm = GNUNET_malloc (sizeof (struct PendingMessage) +
963 sizeof (struct WelcomeMessage));
964 pm->msg = (const char *) &pm[1];
965 pm->message_size = sizeof (struct WelcomeMessage);
966 welcome.header.size = htons (sizeof (struct WelcomeMessage));
967 welcome.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME);
968 welcome.clientIdentity = *plugin->env->my_identity;
969 memcpy (&pm[1], &welcome, sizeof (welcome));
970 pm->timeout = GNUNET_TIME_UNIT_FOREVER_ABS;
971 GNUNET_STATISTICS_update (plugin->env->stats,
972 gettext_noop ("# bytes currently in TCP buffers"),
973 pm->message_size, GNUNET_NO);
974 GNUNET_CONTAINER_DLL_insert (session->pending_messages_head,
975 session->pending_messages_tail, pm);
976 if (GNUNET_YES != is_nat)
978 GNUNET_STATISTICS_update (plugin->env->stats,
979 gettext_noop ("# TCP sessions active"), 1,
982 session->timeout_task = GNUNET_SCHEDULER_add_delayed (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
990 * If we have pending messages, ask the server to
991 * transmit them (schedule the respective tasks, etc.)
993 * @param session for which session should we do this
996 process_pending_messages (struct Session *session);
1000 * Function called to notify a client about the socket
1001 * being ready to queue more data. "buf" will be
1002 * NULL and "size" zero if the socket was closed for
1003 * writing in the meantime.
1005 * @param cls closure
1006 * @param size number of bytes available in buf
1007 * @param buf where the callee should write the message
1008 * @return number of bytes written to buf
1011 do_transmit (void *cls, size_t size, void *buf)
1013 struct Session *session = cls;
1014 struct GNUNET_PeerIdentity pid;
1015 struct Plugin *plugin;
1016 struct PendingMessage *pos;
1017 struct PendingMessage *hd;
1018 struct PendingMessage *tl;
1019 struct GNUNET_TIME_Absolute now;
1023 GNUNET_assert (NULL != session);
1024 session->transmit_handle = NULL;
1025 plugin = session->plugin;
1028 LOG (GNUNET_ERROR_TYPE_DEBUG,
1029 "Timeout trying to transmit to peer `%4s', discarding message queue.\n",
1030 GNUNET_i2s (&session->target));
1031 /* timeout; cancel all messages that have already expired */
1035 now = GNUNET_TIME_absolute_get ();
1036 while ((NULL != (pos = session->pending_messages_head)) &&
1037 (pos->timeout.abs_value_us <= now.abs_value_us))
1039 GNUNET_CONTAINER_DLL_remove (session->pending_messages_head,
1040 session->pending_messages_tail, pos);
1041 LOG (GNUNET_ERROR_TYPE_DEBUG,
1042 "Failed to transmit %u byte message to `%4s'.\n",
1043 pos->message_size, GNUNET_i2s (&session->target));
1044 ret += pos->message_size;
1045 GNUNET_CONTAINER_DLL_insert_after (hd, tl, tl, pos);
1047 /* do this call before callbacks (so that if callbacks destroy
1048 * session, they have a chance to cancel actions done by this
1050 process_pending_messages (session);
1051 pid = session->target;
1052 /* no do callbacks and do not use session again since
1053 * the callbacks may abort the session */
1054 while (NULL != (pos = hd))
1056 GNUNET_CONTAINER_DLL_remove (hd, tl, pos);
1057 if (pos->transmit_cont != NULL)
1058 pos->transmit_cont (pos->transmit_cont_cls, &pid, GNUNET_SYSERR, pos->message_size, 0);
1061 GNUNET_STATISTICS_update (plugin->env->stats,
1062 gettext_noop ("# bytes currently in TCP buffers"),
1063 -(int64_t) ret, GNUNET_NO);
1064 GNUNET_STATISTICS_update (plugin->env->stats,
1066 ("# bytes discarded by TCP (timeout)"), ret,
1070 /* copy all pending messages that would fit */
1075 while (NULL != (pos = session->pending_messages_head))
1077 if (ret + pos->message_size > size)
1079 GNUNET_CONTAINER_DLL_remove (session->pending_messages_head,
1080 session->pending_messages_tail, pos);
1081 GNUNET_assert (size >= pos->message_size);
1082 LOG (GNUNET_ERROR_TYPE_DEBUG,
1083 "Transmitting message of type %u\n",
1084 ntohs (((struct GNUNET_MessageHeader *) pos->msg)->type));
1085 /* FIXME: this memcpy can be up to 7% of our total runtime */
1086 memcpy (cbuf, pos->msg, pos->message_size);
1087 cbuf += pos->message_size;
1088 ret += pos->message_size;
1089 size -= pos->message_size;
1090 GNUNET_CONTAINER_DLL_insert_tail (hd, tl, pos);
1092 /* schedule 'continuation' before callbacks so that callbacks that
1093 * cancel everything don't cause us to use a session that no longer
1095 process_pending_messages (session);
1096 session->last_activity = GNUNET_TIME_absolute_get ();
1097 pid = session->target;
1098 /* we'll now call callbacks that may cancel the session; hence
1099 * we should not use 'session' after this point */
1100 while (NULL != (pos = hd))
1102 GNUNET_CONTAINER_DLL_remove (hd, tl, pos);
1103 if (pos->transmit_cont != NULL)
1104 pos->transmit_cont (pos->transmit_cont_cls, &pid, GNUNET_OK, pos->message_size, pos->message_size); /* FIXME: include TCP overhead */
1107 GNUNET_assert (hd == NULL);
1108 GNUNET_assert (tl == NULL);
1109 LOG (GNUNET_ERROR_TYPE_DEBUG, "Transmitting %u bytes\n",
1111 GNUNET_STATISTICS_update (plugin->env->stats,
1112 gettext_noop ("# bytes currently in TCP buffers"),
1113 -(int64_t) ret, GNUNET_NO);
1114 GNUNET_STATISTICS_update (plugin->env->stats,
1115 gettext_noop ("# bytes transmitted via TCP"), ret,
1122 * If we have pending messages, ask the server to
1123 * transmit them (schedule the respective tasks, etc.)
1125 * @param session for which session should we do this
1128 process_pending_messages (struct Session *session)
1130 struct PendingMessage *pm;
1132 GNUNET_assert (session->client != NULL);
1133 if (session->transmit_handle != NULL)
1135 if (NULL == (pm = session->pending_messages_head))
1138 session->transmit_handle =
1139 GNUNET_SERVER_notify_transmit_ready (session->client, pm->message_size,
1140 GNUNET_TIME_absolute_get_remaining
1141 (pm->timeout), &do_transmit,
1148 * Closure for #session_it().
1150 struct FindSessionContext
1153 * Session we are looking for.
1158 * Set to #GNUNET_OK if we found the session.
1165 * Function called to check if a session is in our maps.
1167 * @param cls the `struct FindSessionContext`
1168 * @param key peer identity
1169 * @param value session in the map
1170 * @return #GNUNET_YES to continue looking, #GNUNET_NO if we found the session
1173 session_it (void *cls,
1174 const struct GNUNET_PeerIdentity *key,
1177 struct FindSessionContext *res = cls;
1178 struct Session *session = value;
1180 if (res->s == session)
1182 res->res = GNUNET_OK;
1190 * Check that the given session is known to the plugin and
1191 * is in one of our maps.
1193 * @param plugin the plugin to check against
1194 * @param session the session to check
1195 * @return #GNUNET_OK if all is well, #GNUNET_SYSERR if the session is invalid
1198 find_session (struct Plugin *plugin,
1199 struct Session *session)
1201 struct FindSessionContext session_map_res;
1202 struct FindSessionContext nat_map_res;
1204 session_map_res.s = session;
1205 session_map_res.res = GNUNET_SYSERR;
1206 GNUNET_CONTAINER_multipeermap_iterate (plugin->sessionmap,
1207 &session_it, &session_map_res);
1208 if (GNUNET_SYSERR != session_map_res.res)
1210 nat_map_res.s = session;
1211 nat_map_res.res = GNUNET_SYSERR;
1212 GNUNET_CONTAINER_multipeermap_iterate (plugin->nat_wait_conns,
1213 &session_it, &nat_map_res);
1214 if (GNUNET_SYSERR != nat_map_res.res)
1217 return GNUNET_SYSERR;
1223 * Function that can be used by the transport service to transmit
1224 * a message using the plugin. Note that in the case of a
1225 * peer disconnecting, the continuation MUST be called
1226 * prior to the disconnect notification itself. This function
1227 * will be called with this peer's HELLO message to initiate
1228 * a fresh connection to another peer.
1230 * @param cls closure
1231 * @param session which session must be used
1232 * @param msgbuf the message to transmit
1233 * @param msgbuf_size number of bytes in 'msgbuf'
1234 * @param priority how important is the message (most plugins will
1235 * ignore message priority and just FIFO)
1236 * @param to how long to wait at most for the transmission (does not
1237 * require plugins to discard the message after the timeout,
1238 * just advisory for the desired delay; most plugins will ignore
1240 * @param cont continuation to call once the message has
1241 * been transmitted (or if the transport is ready
1242 * for the next transmission call; or if the
1243 * peer disconnected...); can be NULL
1244 * @param cont_cls closure for @a cont
1245 * @return number of bytes used (on the physical network, with overheads);
1246 * -1 on hard errors (i.e. address invalid); 0 is a legal value
1247 * and does NOT mean that the message was not transmitted (DV)
1250 tcp_plugin_send (void *cls,
1251 struct Session *session,
1252 const char *msgbuf, size_t msgbuf_size,
1253 unsigned int priority,
1254 struct GNUNET_TIME_Relative to,
1255 GNUNET_TRANSPORT_TransmitContinuation cont, void *cont_cls)
1257 struct Plugin * plugin = cls;
1258 struct PendingMessage *pm;
1261 if (GNUNET_SYSERR == find_session (plugin, session))
1263 LOG (GNUNET_ERROR_TYPE_ERROR,
1264 _("Trying to send with invalid session %p\n"));
1266 return GNUNET_SYSERR;
1269 /* create new message entry */
1270 pm = GNUNET_malloc (sizeof (struct PendingMessage) + msgbuf_size);
1271 pm->msg = (const char *) &pm[1];
1272 memcpy (&pm[1], msgbuf, msgbuf_size);
1273 pm->message_size = msgbuf_size;
1274 pm->timeout = GNUNET_TIME_relative_to_absolute (to);
1275 pm->transmit_cont = cont;
1276 pm->transmit_cont_cls = cont_cls;
1278 LOG (GNUNET_ERROR_TYPE_DEBUG,
1279 "Asked to transmit %u bytes to `%s', added message to list.\n",
1280 msgbuf_size, GNUNET_i2s (&session->target));
1283 GNUNET_CONTAINER_multipeermap_contains_value (plugin->sessionmap,
1287 GNUNET_assert (session->client != NULL);
1288 reschedule_session_timeout (session);
1289 GNUNET_SERVER_client_set_timeout (session->client,
1290 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1291 GNUNET_STATISTICS_update (plugin->env->stats,
1292 gettext_noop ("# bytes currently in TCP buffers"),
1293 msgbuf_size, GNUNET_NO);
1295 /* append pm to pending_messages list */
1296 GNUNET_CONTAINER_DLL_insert_tail (session->pending_messages_head,
1297 session->pending_messages_tail, pm);
1299 process_pending_messages (session);
1302 else if (GNUNET_YES == GNUNET_CONTAINER_multipeermap_contains_value(plugin->nat_wait_conns, &session->target, session))
1304 LOG (GNUNET_ERROR_TYPE_DEBUG,
1305 "This NAT WAIT session for peer `%s' is not yet ready!\n",
1306 GNUNET_i2s (&session->target));
1307 reschedule_session_timeout (session);
1308 GNUNET_STATISTICS_update (plugin->env->stats,
1309 gettext_noop ("# bytes currently in TCP buffers"),
1310 msgbuf_size, GNUNET_NO);
1312 /* append pm to pending_messages list */
1313 GNUNET_CONTAINER_DLL_insert_tail (session->pending_messages_head,
1314 session->pending_messages_tail, pm);
1319 LOG (GNUNET_ERROR_TYPE_ERROR,
1320 "Invalid session %p\n", session);
1322 cont (cont_cls, &session->target, GNUNET_SYSERR, pm->message_size, 0);
1325 return GNUNET_SYSERR; /* session does not exist here */
1331 * Closure for #session_lookup_it().
1336 * Address we are looking for.
1341 * Number of bytes in @e addr.
1346 * Where to store the session (if we found it).
1348 struct Session *result;
1353 * Look for a session by address.
1355 * @param cls the `struct SessionItCtx`
1357 * @param value a `struct Session`
1358 * @return #GNUNET_YES to continue looking, #GNUNET_NO if we found the session
1361 session_lookup_it (void *cls,
1362 const struct GNUNET_PeerIdentity *key,
1365 struct SessionItCtx * si_ctx = cls;
1366 struct Session * session = value;
1368 char * a1 = strdup (tcp_address_to_string(NULL, session->addr, session->addrlen));
1369 char * a2 = strdup (tcp_address_to_string(NULL, si_ctx->addr, si_ctx->addrlen));
1370 LOG (GNUNET_ERROR_TYPE_DEBUG,
1371 "Comparing: %s %u <-> %s %u\n",
1379 if (session->addrlen != si_ctx->addrlen)
1381 if (0 != memcmp (session->addr, si_ctx->addr, si_ctx->addrlen))
1384 a1 = strdup (tcp_address_to_string (NULL, session->addr, session->addrlen));
1385 a2 = strdup (tcp_address_to_string (NULL, si_ctx->addr, si_ctx->addrlen));
1386 LOG (GNUNET_ERROR_TYPE_DEBUG,
1387 "Comparing: %s %u <-> %s %u , OK!\n",
1395 /* Found existing session */
1396 si_ctx->result = session;
1402 * Task cleaning up a NAT connection attempt after timeout
1404 * @param cls the `struct Session`
1405 * @param tc scheduler context (unused)
1408 nat_connect_timeout (void *cls,
1409 const struct GNUNET_SCHEDULER_TaskContext *tc)
1411 struct Session *session = cls;
1413 session->nat_connection_timeout = GNUNET_SCHEDULER_NO_TASK;
1414 LOG (GNUNET_ERROR_TYPE_DEBUG,
1415 "NAT WAIT connection to `%4s' at `%s' could not be established, removing session\n",
1416 GNUNET_i2s (&session->target),
1417 tcp_address_to_string (NULL,
1418 session->addr, session->addrlen));
1419 tcp_disconnect_session (session->plugin,
1424 tcp_plugin_update_session_timeout (void *cls,
1425 const struct GNUNET_PeerIdentity *peer,
1426 struct Session *session)
1433 * Create a new session to transmit data to the target
1434 * This session will used to send data to this peer and the plugin will
1435 * notify us by calling the env->session_end function
1437 * @param cls closure
1438 * @param address the address to use
1439 * @return the session if the address is valid, NULL otherwise
1441 static struct Session *
1442 tcp_plugin_get_session (void *cls,
1443 const struct GNUNET_HELLO_Address *address)
1445 struct Plugin *plugin = cls;
1446 struct Session *session = NULL;
1450 struct GNUNET_CONNECTION_Handle *sa;
1451 struct sockaddr_in a4;
1452 struct sockaddr_in6 a6;
1453 const struct IPv4TcpAddress *t4;
1454 const struct IPv6TcpAddress *t6;
1455 struct GNUNET_ATS_Information ats;
1456 unsigned int is_natd = GNUNET_NO;
1459 addrlen = address->address_length;
1460 LOG (GNUNET_ERROR_TYPE_DEBUG,
1461 "Trying to get session for `%s' address of peer `%s'\n",
1462 tcp_address_to_string(NULL, address->address, address->address_length),
1463 GNUNET_i2s (&address->peer));
1465 /* look for existing session */
1467 GNUNET_CONTAINER_multipeermap_contains (plugin->sessionmap,
1470 struct SessionItCtx si_ctx;
1472 si_ctx.addr = (void *) address->address;
1473 si_ctx.addrlen = address->address_length;
1475 si_ctx.result = NULL;
1477 GNUNET_CONTAINER_multipeermap_get_multiple (plugin->sessionmap,
1479 &session_lookup_it, &si_ctx);
1480 if (si_ctx.result != NULL)
1482 session = si_ctx.result;
1483 LOG (GNUNET_ERROR_TYPE_DEBUG,
1484 "Found existing session for `%s' address `%s' session %p\n",
1485 GNUNET_i2s (&address->peer),
1486 tcp_address_to_string(NULL, address->address, address->address_length),
1490 LOG (GNUNET_ERROR_TYPE_DEBUG,
1491 "Existing sessions did not match address `%s' or peer `%s'\n",
1492 tcp_address_to_string(NULL, address->address, address->address_length),
1493 GNUNET_i2s (&address->peer));
1496 if (addrlen == sizeof (struct IPv6TcpAddress))
1498 GNUNET_assert (NULL != address->address); /* make static analysis happy */
1499 t6 = address->address;
1501 memset (&a6, 0, sizeof (a6));
1502 #if HAVE_SOCKADDR_IN_SIN_LEN
1503 a6.sin6_len = sizeof (a6);
1505 a6.sin6_family = AF_INET6;
1506 a6.sin6_port = t6->t6_port;
1507 if (t6->t6_port == 0)
1508 is_natd = GNUNET_YES;
1509 memcpy (&a6.sin6_addr, &t6->ipv6_addr, sizeof (struct in6_addr));
1513 else if (addrlen == sizeof (struct IPv4TcpAddress))
1515 GNUNET_assert (NULL != address->address); /* make static analysis happy */
1516 t4 = address->address;
1518 memset (&a4, 0, sizeof (a4));
1519 #if HAVE_SOCKADDR_IN_SIN_LEN
1520 a4.sin_len = sizeof (a4);
1522 a4.sin_family = AF_INET;
1523 a4.sin_port = t4->t4_port;
1524 if (t4->t4_port == 0)
1525 is_natd = GNUNET_YES;
1526 a4.sin_addr.s_addr = t4->ipv4_addr;
1532 GNUNET_STATISTICS_update (plugin->env->stats,
1534 ("# requests to create session with invalid address"),
1539 ats = plugin->env->get_address_type (plugin->env->cls, sb, sbs);
1541 if ((is_natd == GNUNET_YES) && (addrlen == sizeof (struct IPv6TcpAddress)))
1543 /* NAT client only works with IPv4 addresses */
1547 if (plugin->cur_connections >= plugin->max_connections)
1553 if ((is_natd == GNUNET_YES) &&
1555 GNUNET_CONTAINER_multipeermap_contains (plugin->nat_wait_conns,
1558 /* Only do one NAT punch attempt per peer identity */
1562 if ((is_natd == GNUNET_YES) && (NULL != plugin->nat) &&
1564 GNUNET_CONTAINER_multipeermap_contains (plugin->nat_wait_conns,
1567 LOG (GNUNET_ERROR_TYPE_DEBUG,
1568 "Found valid IPv4 NAT address (creating session)!\n") ;
1569 session = create_session (plugin,
1573 session->addrlen = 0;
1574 session->addr = NULL;
1575 session->ats_address_network_type = (enum GNUNET_ATS_Network_Type) ntohl (ats.value)
1577 GNUNET_break (session->ats_address_network_type != GNUNET_ATS_NET_UNSPECIFIED);
1578 session->nat_connection_timeout = GNUNET_SCHEDULER_add_delayed (NAT_TIMEOUT,
1579 &nat_connect_timeout,
1581 GNUNET_assert (session != NULL);
1582 GNUNET_assert (GNUNET_OK ==
1583 GNUNET_CONTAINER_multipeermap_put (plugin->nat_wait_conns,
1586 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
1588 LOG (GNUNET_ERROR_TYPE_DEBUG,
1589 "Created NAT WAIT connection to `%4s' at `%s'\n",
1590 GNUNET_i2s (&session->target), GNUNET_a2s (sb, sbs));
1592 if (GNUNET_OK == GNUNET_NAT_run_client (plugin->nat, &a4))
1596 LOG (GNUNET_ERROR_TYPE_DEBUG,
1597 "Running NAT client for `%4s' at `%s' failed\n",
1598 GNUNET_i2s (&session->target), GNUNET_a2s (sb, sbs));
1599 tcp_disconnect_session (plugin, session);
1604 /* create new outbound session */
1605 GNUNET_assert (plugin->cur_connections <= plugin->max_connections);
1606 sa = GNUNET_CONNECTION_create_from_sockaddr (af, sb, sbs);
1609 LOG (GNUNET_ERROR_TYPE_DEBUG,
1610 "Failed to create connection to `%4s' at `%s'\n",
1611 GNUNET_i2s (&address->peer), GNUNET_a2s (sb, sbs));
1614 plugin->cur_connections++;
1615 if (plugin->cur_connections == plugin->max_connections)
1616 GNUNET_SERVER_suspend (plugin->server); /* Maximum number of connections rechead */
1618 LOG (GNUNET_ERROR_TYPE_DEBUG,
1619 "Asked to transmit to `%4s', creating fresh session using address `%s'.\n",
1620 GNUNET_i2s (&address->peer),
1621 GNUNET_a2s (sb, sbs));
1623 session = create_session (plugin,
1625 GNUNET_SERVER_connect_socket (plugin->server, sa),
1627 session->addr = GNUNET_malloc (addrlen);
1628 memcpy (session->addr, address->address, addrlen);
1629 session->addrlen = addrlen;
1630 session->ats_address_network_type = (enum GNUNET_ATS_Network_Type) ntohl (ats.value);
1631 GNUNET_break (session->ats_address_network_type != GNUNET_ATS_NET_UNSPECIFIED);
1632 GNUNET_SERVER_client_set_user_context (session->client, session);
1633 GNUNET_CONTAINER_multipeermap_put (plugin->sessionmap,
1636 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
1637 LOG (GNUNET_ERROR_TYPE_DEBUG,
1638 "Creating new session for `%s' address `%s' session %p\n",
1639 GNUNET_i2s (&address->peer),
1640 tcp_address_to_string(NULL, address->address, address->address_length),
1642 /* Send TCP Welcome */
1643 process_pending_messages (session);
1650 session_disconnect_it (void *cls,
1651 const struct GNUNET_PeerIdentity *key,
1654 struct Plugin *plugin = cls;
1655 struct Session *session = value;
1657 GNUNET_STATISTICS_update (session->plugin->env->stats,
1659 ("# transport-service disconnect requests for TCP"),
1661 tcp_disconnect_session (plugin,
1668 * Function that can be called to force a disconnect from the
1669 * specified neighbour. This should also cancel all previously
1670 * scheduled transmissions. Obviously the transmission may have been
1671 * partially completed already, which is OK. The plugin is supposed
1672 * to close the connection (if applicable) and no longer call the
1673 * transmit continuation(s).
1675 * Finally, plugin MUST NOT call the services's receive function to
1676 * notify the service that the connection to the specified target was
1677 * closed after a getting this call.
1679 * @param cls closure
1680 * @param target peer for which the last transmission is
1684 tcp_plugin_disconnect (void *cls,
1685 const struct GNUNET_PeerIdentity *target)
1687 struct Plugin *plugin = cls;
1689 LOG (GNUNET_ERROR_TYPE_DEBUG,
1690 "Disconnecting peer `%4s'\n",
1691 GNUNET_i2s (target));
1692 GNUNET_CONTAINER_multipeermap_get_multiple (plugin->sessionmap, target,
1693 &session_disconnect_it, plugin);
1694 GNUNET_CONTAINER_multipeermap_get_multiple (plugin->nat_wait_conns, target,
1695 &session_disconnect_it, plugin);
1700 * Running pretty printers: head
1702 static struct PrettyPrinterContext *ppc_dll_head;
1705 * Running pretty printers: tail
1707 static struct PrettyPrinterContext *ppc_dll_tail;
1710 * Context for address to string conversion.
1712 struct PrettyPrinterContext
1717 struct PrettyPrinterContext *next;
1722 struct PrettyPrinterContext *prev;
1727 GNUNET_SCHEDULER_TaskIdentifier timeout_task;
1732 struct GNUNET_RESOLVER_RequestHandle *resolver_handle;
1735 * Function to call with the result.
1737 GNUNET_TRANSPORT_AddressStringCallback asc;
1740 * Clsoure for 'asc'.
1745 * Port to add after the IP address.
1762 ppc_cancel_task (void *cls,
1763 const struct GNUNET_SCHEDULER_TaskContext *tc)
1766 struct PrettyPrinterContext *ppc = cls;
1767 struct PrettyPrinterContext *cur;
1769 for (cur = ppc_dll_head; (NULL != cur); cur = cur->next)
1775 // GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Cancel request %p, %u pending\n", ppc, count);
1776 ppc->timeout_task = GNUNET_SCHEDULER_NO_TASK;
1777 if (NULL != ppc->resolver_handle)
1779 GNUNET_RESOLVER_request_cancel (ppc->resolver_handle);
1780 ppc->resolver_handle = NULL;
1782 GNUNET_CONTAINER_DLL_remove (ppc_dll_head, ppc_dll_tail, ppc);
1788 * Append our port and forward the result.
1790 * @param cls the 'struct PrettyPrinterContext*'
1791 * @param hostname hostname part of the address
1794 append_port (void *cls, const char *hostname)
1796 struct PrettyPrinterContext *ppc = cls;
1797 struct PrettyPrinterContext *cur;
1801 for (cur = ppc_dll_head; (NULL != cur); cur = cur->next)
1806 //GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Callback request %p == %s, %u pending\n", ppc, hostname, count);
1807 if (hostname == NULL)
1809 ppc->asc (ppc->asc_cls, NULL);
1810 GNUNET_CONTAINER_DLL_remove (ppc_dll_head, ppc_dll_tail, ppc);
1811 GNUNET_SCHEDULER_cancel (ppc->timeout_task);
1812 ppc->timeout_task = GNUNET_SCHEDULER_NO_TASK;
1813 ppc->resolver_handle = NULL;
1814 //GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Done request %p, %u pending\n", ppc, count);
1818 for (cur = ppc_dll_head; (NULL != cur); cur = cur->next)
1825 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Invalid callback for PPC %p \n", ppc);
1829 if (GNUNET_YES == ppc->ipv6)
1830 GNUNET_asprintf (&ret, "%s.%u.[%s]:%d", PLUGIN_NAME, ppc->options, hostname, ppc->port);
1832 GNUNET_asprintf (&ret, "%s.%u.%s:%d", PLUGIN_NAME, ppc->options, hostname, ppc->port);
1833 ppc->asc (ppc->asc_cls, ret);
1839 * Convert the transports address to a nice, human-readable
1842 * @param cls closure
1843 * @param type name of the transport that generated the address
1844 * @param addr one of the addresses of the host, NULL for the last address
1845 * the specific address format depends on the transport
1846 * @param addrlen length of the address
1847 * @param numeric should (IP) addresses be displayed in numeric form?
1848 * @param timeout after how long should we give up?
1849 * @param asc function to call on each string
1850 * @param asc_cls closure for asc
1853 tcp_plugin_address_pretty_printer (void *cls, const char *type,
1854 const void *addr, size_t addrlen,
1856 struct GNUNET_TIME_Relative timeout,
1857 GNUNET_TRANSPORT_AddressStringCallback asc,
1860 struct PrettyPrinterContext *ppc;
1863 struct sockaddr_in a4;
1864 struct sockaddr_in6 a6;
1865 const struct IPv4TcpAddress *t4;
1866 const struct IPv6TcpAddress *t6;
1870 if (addrlen == sizeof (struct IPv6TcpAddress))
1873 memset (&a6, 0, sizeof (a6));
1874 a6.sin6_family = AF_INET6;
1875 a6.sin6_port = t6->t6_port;
1876 memcpy (&a6.sin6_addr, &t6->ipv6_addr, sizeof (struct in6_addr));
1877 port = ntohs (t6->t6_port);
1878 options = ntohl (t6->options);
1882 else if (addrlen == sizeof (struct IPv4TcpAddress))
1885 memset (&a4, 0, sizeof (a4));
1886 a4.sin_family = AF_INET;
1887 a4.sin_port = t4->t4_port;
1888 a4.sin_addr.s_addr = t4->ipv4_addr;
1889 port = ntohs (t4->t4_port);
1890 options = ntohl (t4->options);
1894 else if (0 == addrlen)
1896 asc (asc_cls, TRANSPORT_SESSION_INBOUND_STRING);
1897 asc (asc_cls, NULL);
1902 /* invalid address */
1903 GNUNET_break_op (0);
1904 asc (asc_cls, NULL);
1907 ppc = GNUNET_malloc (sizeof (struct PrettyPrinterContext));
1908 if (addrlen == sizeof (struct IPv6TcpAddress))
1909 ppc->ipv6 = GNUNET_YES;
1911 ppc->ipv6 = GNUNET_NO;
1913 ppc->asc_cls = asc_cls;
1915 ppc->options = options;
1916 ppc->timeout_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply(timeout, 2),
1917 &ppc_cancel_task, ppc);
1918 ppc->resolver_handle = GNUNET_RESOLVER_hostname_get (sb, sbs, !numeric,
1921 if (NULL != ppc->resolver_handle)
1923 //GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Adding request %p\n", ppc);
1924 GNUNET_CONTAINER_DLL_insert (ppc_dll_head, ppc_dll_tail, ppc);
1935 * Check if the given port is plausible (must be either our listen
1936 * port or our advertised port), or any port if we are behind NAT
1937 * and do not have a port open. If it is neither, we return
1940 * @param plugin global variables
1941 * @param in_port port number to check
1942 * @return #GNUNET_OK if port is either open_port or adv_port
1945 check_port (struct Plugin *plugin, uint16_t in_port)
1947 if ((in_port == plugin->adv_port) || (in_port == plugin->open_port))
1949 return GNUNET_SYSERR;
1954 * Function that will be called to check if a binary address for this
1955 * plugin is well-formed and corresponds to an address for THIS peer
1956 * (as per our configuration). Naturally, if absolutely necessary,
1957 * plugins can be a bit conservative in their answer, but in general
1958 * plugins should make sure that the address does not redirect
1959 * traffic to a 3rd party that might try to man-in-the-middle our
1962 * @param cls closure, our 'struct Plugin*'
1963 * @param addr pointer to the address
1964 * @param addrlen length of addr
1965 * @return #GNUNET_OK if this is a plausible address for this peer
1966 * and transport, #GNUNET_SYSERR if not
1969 tcp_plugin_check_address (void *cls, const void *addr, size_t addrlen)
1971 struct Plugin *plugin = cls;
1972 struct IPv4TcpAddress *v4;
1973 struct IPv6TcpAddress *v6;
1975 if ((addrlen != sizeof (struct IPv4TcpAddress)) &&
1976 (addrlen != sizeof (struct IPv6TcpAddress)))
1980 return GNUNET_SYSERR;
1983 if (addrlen == sizeof (struct IPv4TcpAddress))
1985 v4 = (struct IPv4TcpAddress *) addr;
1986 if (0 != memcmp (&v4->options, &myoptions, sizeof (myoptions)))
1989 return GNUNET_SYSERR;
1991 if (GNUNET_OK != check_port (plugin, ntohs (v4->t4_port)))
1992 return GNUNET_SYSERR;
1994 GNUNET_NAT_test_address (plugin->nat, &v4->ipv4_addr,
1995 sizeof (struct in_addr)))
1996 return GNUNET_SYSERR;
2000 v6 = (struct IPv6TcpAddress *) addr;
2001 if (IN6_IS_ADDR_LINKLOCAL (&v6->ipv6_addr))
2003 GNUNET_break_op (0);
2004 return GNUNET_SYSERR;
2006 if (0 != memcmp (&v6->options, &myoptions, sizeof (myoptions)))
2009 return GNUNET_SYSERR;
2011 if (GNUNET_OK != check_port (plugin, ntohs (v6->t6_port)))
2012 return GNUNET_SYSERR;
2014 GNUNET_NAT_test_address (plugin->nat, &v6->ipv6_addr,
2015 sizeof (struct in6_addr)))
2016 return GNUNET_SYSERR;
2023 * We've received a nat probe from this peer via TCP. Finish
2024 * creating the client session and resume sending of queued
2027 * @param cls closure
2028 * @param client identification of the client
2029 * @param message the actual message
2032 handle_tcp_nat_probe (void *cls,
2033 struct GNUNET_SERVER_Client *client,
2034 const struct GNUNET_MessageHeader *message)
2036 struct Plugin *plugin = cls;
2037 struct Session *session;
2038 const struct TCP_NAT_ProbeMessage *tcp_nat_probe;
2041 struct IPv4TcpAddress *t4;
2042 struct IPv6TcpAddress *t6;
2043 const struct sockaddr_in *s4;
2044 const struct sockaddr_in6 *s6;
2046 LOG (GNUNET_ERROR_TYPE_DEBUG,
2047 "Received NAT probe\n");
2048 /* We have received a TCP NAT probe, meaning we (hopefully) initiated
2049 * a connection to this peer by running gnunet-nat-client. This peer
2050 * received the punch message and now wants us to use the new connection
2051 * as the default for that peer. Do so and then send a WELCOME message
2052 * so we can really be connected!
2054 if (ntohs (message->size) != sizeof (struct TCP_NAT_ProbeMessage))
2056 GNUNET_break_op (0);
2057 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2061 tcp_nat_probe = (const struct TCP_NAT_ProbeMessage *) message;
2063 memcmp (&tcp_nat_probe->clientIdentity, plugin->env->my_identity,
2064 sizeof (struct GNUNET_PeerIdentity)))
2066 /* refuse connections from ourselves */
2067 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2072 GNUNET_CONTAINER_multipeermap_get (plugin->nat_wait_conns,
2073 &tcp_nat_probe->clientIdentity);
2074 if (session == NULL)
2076 LOG (GNUNET_ERROR_TYPE_DEBUG,
2077 "Did NOT find session for NAT probe!\n");
2078 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2081 LOG (GNUNET_ERROR_TYPE_DEBUG,
2082 "Found session for NAT probe!\n");
2084 if (session->nat_connection_timeout != GNUNET_SCHEDULER_NO_TASK)
2086 GNUNET_SCHEDULER_cancel (session->nat_connection_timeout);
2087 session->nat_connection_timeout = GNUNET_SCHEDULER_NO_TASK;
2090 if (GNUNET_OK != GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
2093 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2094 tcp_disconnect_session (plugin, session);
2097 GNUNET_assert (GNUNET_CONTAINER_multipeermap_remove
2098 (plugin->nat_wait_conns,
2099 &tcp_nat_probe->clientIdentity,
2100 session) == GNUNET_YES);
2101 GNUNET_SERVER_client_set_user_context (client, session);
2102 GNUNET_CONTAINER_multipeermap_put (plugin->sessionmap,
2103 &session->target, session,
2104 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2105 session->last_activity = GNUNET_TIME_absolute_get ();
2106 session->inbound = GNUNET_NO;
2107 LOG (GNUNET_ERROR_TYPE_DEBUG,
2108 "Found address `%s' for incoming connection\n",
2109 GNUNET_a2s (vaddr, alen));
2110 switch (((const struct sockaddr *) vaddr)->sa_family)
2114 t4 = GNUNET_new (struct IPv4TcpAddress);
2116 t4->t4_port = s4->sin_port;
2117 t4->ipv4_addr = s4->sin_addr.s_addr;
2119 session->addrlen = sizeof (struct IPv4TcpAddress);
2123 t6 = GNUNET_new (struct IPv6TcpAddress);
2125 t6->t6_port = s6->sin6_port;
2126 memcpy (&t6->ipv6_addr, &s6->sin6_addr, sizeof (struct in6_addr));
2128 session->addrlen = sizeof (struct IPv6TcpAddress);
2131 GNUNET_break_op (0);
2132 LOG (GNUNET_ERROR_TYPE_DEBUG,
2133 "Bad address for incoming connection!\n");
2134 GNUNET_free (vaddr);
2135 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2136 tcp_disconnect_session (plugin, session);
2139 GNUNET_free (vaddr);
2140 GNUNET_break (NULL == session->client);
2141 GNUNET_SERVER_client_keep (client);
2142 session->client = client;
2143 GNUNET_STATISTICS_update (plugin->env->stats,
2144 gettext_noop ("# TCP sessions active"), 1,
2146 process_pending_messages (session);
2147 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2152 * We've received a welcome from this peer via TCP. Possibly create a
2153 * fresh client record and send back our welcome.
2155 * @param cls closure
2156 * @param client identification of the client
2157 * @param message the actual message
2160 handle_tcp_welcome (void *cls, struct GNUNET_SERVER_Client *client,
2161 const struct GNUNET_MessageHeader *message)
2163 struct Plugin *plugin = cls;
2164 const struct WelcomeMessage *wm = (const struct WelcomeMessage *) message;
2165 struct Session *session;
2168 struct IPv4TcpAddress *t4;
2169 struct IPv6TcpAddress *t6;
2170 const struct sockaddr_in *s4;
2171 const struct sockaddr_in6 *s6;
2172 struct GNUNET_ATS_Information ats;
2175 memcmp (&wm->clientIdentity, plugin->env->my_identity,
2176 sizeof (struct GNUNET_PeerIdentity)))
2178 /* refuse connections from ourselves */
2179 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2180 if (GNUNET_OK == GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
2182 LOG (GNUNET_ERROR_TYPE_WARNING,
2183 "Received %s message from my own identity `%4s' on address `%s'\n",
2184 "WELCOME", GNUNET_i2s (&wm->clientIdentity), GNUNET_a2s (vaddr, alen));
2185 GNUNET_free (vaddr);
2187 GNUNET_break_op (0);
2190 LOG (GNUNET_ERROR_TYPE_DEBUG,
2191 "Received %s message from `%4s' %p\n", "WELCOME",
2192 GNUNET_i2s (&wm->clientIdentity), client);
2193 GNUNET_STATISTICS_update (plugin->env->stats,
2194 gettext_noop ("# TCP WELCOME messages received"), 1,
2196 session = lookup_session_by_client (plugin, client);
2197 if (session != NULL)
2199 if (GNUNET_OK == GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
2201 LOG (GNUNET_ERROR_TYPE_DEBUG,
2202 "Found existing session %p for peer `%s'\n",
2204 GNUNET_a2s (vaddr, alen));
2205 GNUNET_free (vaddr);
2210 GNUNET_SERVER_client_keep (client);
2211 if (plugin->service != NULL) /* Otherwise value is incremented in tcp_access_check */
2212 plugin->cur_connections++;
2213 if (plugin->cur_connections == plugin->max_connections)
2214 GNUNET_SERVER_suspend (plugin->server); /* Maximum number of connections rechead */
2216 session = create_session (plugin, &wm->clientIdentity, client, GNUNET_NO);
2217 session->inbound = GNUNET_YES;
2218 if (GNUNET_OK == GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
2220 if (alen == sizeof (struct sockaddr_in))
2223 t4 = GNUNET_new (struct IPv4TcpAddress);
2224 t4->options = htonl (0);
2225 t4->t4_port = s4->sin_port;
2226 t4->ipv4_addr = s4->sin_addr.s_addr;
2228 session->addrlen = sizeof (struct IPv4TcpAddress);
2230 else if (alen == sizeof (struct sockaddr_in6))
2233 t6 = GNUNET_new (struct IPv6TcpAddress);
2234 t6->options = htonl (0);
2235 t6->t6_port = s6->sin6_port;
2236 memcpy (&t6->ipv6_addr, &s6->sin6_addr, sizeof (struct in6_addr));
2238 session->addrlen = sizeof (struct IPv6TcpAddress);
2241 ats = plugin->env->get_address_type (plugin->env->cls, vaddr ,alen);
2242 session->ats_address_network_type = (enum GNUNET_ATS_Network_Type) ntohl (ats.value);
2243 LOG (GNUNET_ERROR_TYPE_DEBUG,
2244 "Creating new session %p for peer `%s'\n",
2246 GNUNET_a2s (vaddr, alen));
2247 GNUNET_free (vaddr);
2248 GNUNET_SERVER_client_set_user_context (session->client, session);
2249 GNUNET_CONTAINER_multipeermap_put (plugin->sessionmap,
2252 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2256 LOG (GNUNET_ERROR_TYPE_DEBUG,
2257 "Did not obtain TCP socket address for incoming connection\n");
2262 if (session->expecting_welcome != GNUNET_YES)
2264 GNUNET_break_op (0);
2265 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2269 session->last_activity = GNUNET_TIME_absolute_get ();
2270 session->expecting_welcome = GNUNET_NO;
2272 /* Notify transport and ATS about new session */
2273 if (GNUNET_YES == session->inbound)
2275 plugin->env->session_start (NULL, &wm->clientIdentity, PLUGIN_NAME,
2276 (GNUNET_YES == session->inbound) ? NULL : session->addr,
2277 (GNUNET_YES == session->inbound) ? 0 : session->addrlen,
2281 process_pending_messages (session);
2283 GNUNET_SERVER_client_set_timeout (client,
2284 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
2285 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2290 * Task to signal the server that we can continue
2291 * receiving from the TCP client now.
2293 * @param cls the 'struct Session*'
2294 * @param tc task context (unused)
2297 delayed_done (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2299 struct Session *session = cls;
2301 session->receive_delay_task = GNUNET_SCHEDULER_NO_TASK;
2302 reschedule_session_timeout (session);
2304 GNUNET_SERVER_receive_done (session->client, GNUNET_OK);
2309 * We've received data for this peer via TCP. Unbox,
2310 * compute latency and forward.
2312 * @param cls closure
2313 * @param client identification of the client
2314 * @param message the actual message
2317 handle_tcp_data (void *cls, struct GNUNET_SERVER_Client *client,
2318 const struct GNUNET_MessageHeader *message)
2320 struct Plugin *plugin = cls;
2321 struct Session *session;
2322 struct GNUNET_TIME_Relative delay;
2325 type = ntohs (message->type);
2326 if ((GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME == type) ||
2327 (GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE == type))
2329 /* We don't want to propagate WELCOME and NAT Probe messages up! */
2330 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2333 session = lookup_session_by_client (plugin, client);
2334 if (NULL == session)
2336 /* No inbound session found */
2340 GNUNET_SERVER_client_get_address (client, &vaddr, &alen);
2341 LOG (GNUNET_ERROR_TYPE_ERROR,
2342 "Received unexpected %u bytes of type %u from `%s'\n",
2343 (unsigned int) ntohs (message->size),
2344 (unsigned int) ntohs (message->type),
2345 GNUNET_a2s(vaddr, alen));
2346 GNUNET_break_op (0);
2347 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2348 GNUNET_free_non_null(vaddr);
2351 else if (GNUNET_YES == session->expecting_welcome)
2353 /* Session is expecting WELCOME message */
2357 GNUNET_SERVER_client_get_address (client, &vaddr, &alen);
2358 LOG (GNUNET_ERROR_TYPE_ERROR,
2359 "Received unexpected %u bytes of type %u from `%s'\n",
2360 (unsigned int) ntohs (message->size),
2361 (unsigned int) ntohs (message->type),
2362 GNUNET_a2s(vaddr, alen));
2363 GNUNET_break_op (0);
2364 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2365 GNUNET_free_non_null(vaddr);
2369 session->last_activity = GNUNET_TIME_absolute_get ();
2370 LOG (GNUNET_ERROR_TYPE_DEBUG,
2371 "Passing %u bytes of type %u from `%4s' to transport service.\n",
2372 (unsigned int) ntohs (message->size),
2373 (unsigned int) ntohs (message->type),
2374 GNUNET_i2s (&session->target));
2376 GNUNET_STATISTICS_update (plugin->env->stats,
2377 gettext_noop ("# bytes received via TCP"),
2378 ntohs (message->size), GNUNET_NO);
2379 struct GNUNET_ATS_Information distance;
2381 distance.type = htonl (GNUNET_ATS_NETWORK_TYPE);
2382 distance.value = htonl ((uint32_t) session->ats_address_network_type);
2383 GNUNET_break (session->ats_address_network_type != GNUNET_ATS_NET_UNSPECIFIED);
2385 GNUNET_assert (GNUNET_CONTAINER_multipeermap_contains_value (plugin->sessionmap,
2389 delay = plugin->env->receive (plugin->env->cls,
2393 (GNUNET_YES == session->inbound) ? NULL : session->addr,
2394 (GNUNET_YES == session->inbound) ? 0 : session->addrlen);
2395 plugin->env->update_address_metrics (plugin->env->cls,
2397 (GNUNET_YES == session->inbound) ? NULL : session->addr,
2398 (GNUNET_YES == session->inbound) ? 0 : session->addrlen,
2399 session, &distance, 1);
2400 reschedule_session_timeout (session);
2401 if (0 == delay.rel_value_us)
2403 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2407 LOG (GNUNET_ERROR_TYPE_DEBUG,
2408 "Throttling receiving from `%s' for %s\n",
2409 GNUNET_i2s (&session->target),
2410 GNUNET_STRINGS_relative_time_to_string (delay, GNUNET_YES));
2411 GNUNET_SERVER_disable_receive_done_warning (client);
2412 session->receive_delay_task =
2413 GNUNET_SCHEDULER_add_delayed (delay, &delayed_done, session);
2419 * Functions with this signature are called whenever a peer
2420 * is disconnected on the network level.
2422 * @param cls closure
2423 * @param client identification of the client
2426 disconnect_notify (void *cls, struct GNUNET_SERVER_Client *client)
2428 struct Plugin *plugin = cls;
2429 struct Session *session;
2433 session = lookup_session_by_client (plugin, client);
2434 if (session == NULL)
2435 return; /* unknown, nothing to do */
2436 LOG (GNUNET_ERROR_TYPE_DEBUG,
2437 "Destroying session of `%4s' with %s due to network-level disconnect.\n",
2438 GNUNET_i2s (&session->target),
2440 NULL) ? tcp_address_to_string (session->plugin,
2445 if (plugin->cur_connections == plugin->max_connections)
2446 GNUNET_SERVER_resume (plugin->server); /* Resume server */
2448 if (plugin->cur_connections < 1)
2451 plugin->cur_connections--;
2453 GNUNET_STATISTICS_update (session->plugin->env->stats,
2455 ("# network-level TCP disconnect events"), 1,
2457 tcp_disconnect_session (plugin, session);
2462 * We can now send a probe message, copy into buffer to really send.
2464 * @param cls closure, a struct TCPProbeContext
2465 * @param size max size to copy
2466 * @param buf buffer to copy message to
2467 * @return number of bytes copied into buf
2470 notify_send_probe (void *cls, size_t size, void *buf)
2472 struct TCPProbeContext *tcp_probe_ctx = cls;
2473 struct Plugin *plugin = tcp_probe_ctx->plugin;
2476 tcp_probe_ctx->transmit_handle = NULL;
2477 GNUNET_CONTAINER_DLL_remove (plugin->probe_head, plugin->probe_tail,
2481 GNUNET_CONNECTION_destroy (tcp_probe_ctx->sock);
2482 GNUNET_free (tcp_probe_ctx);
2485 GNUNET_assert (size >= sizeof (tcp_probe_ctx->message));
2486 memcpy (buf, &tcp_probe_ctx->message, sizeof (tcp_probe_ctx->message));
2487 GNUNET_SERVER_connect_socket (tcp_probe_ctx->plugin->server,
2488 tcp_probe_ctx->sock);
2489 ret = sizeof (tcp_probe_ctx->message);
2490 GNUNET_free (tcp_probe_ctx);
2496 * Function called by the NAT subsystem suggesting another peer wants
2497 * to connect to us via connection reversal. Try to connect back to the
2500 * @param cls closure
2501 * @param addr address to try
2502 * @param addrlen number of bytes in @a addr
2505 try_connection_reversal (void *cls, const struct sockaddr *addr,
2508 struct Plugin *plugin = cls;
2509 struct GNUNET_CONNECTION_Handle *sock;
2510 struct TCPProbeContext *tcp_probe_ctx;
2513 * We have received an ICMP response, ostensibly from a peer
2514 * that wants to connect to us! Send a message to establish a connection.
2516 sock = GNUNET_CONNECTION_create_from_sockaddr (AF_INET, addr, addrlen);
2519 /* failed for some odd reason (out of sockets?); ignore attempt */
2523 /* FIXME: do we need to track these probe context objects so that
2524 * we can clean them up on plugin unload? */
2525 tcp_probe_ctx = GNUNET_malloc (sizeof (struct TCPProbeContext));
2526 tcp_probe_ctx->message.header.size =
2527 htons (sizeof (struct TCP_NAT_ProbeMessage));
2528 tcp_probe_ctx->message.header.type =
2529 htons (GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE);
2530 memcpy (&tcp_probe_ctx->message.clientIdentity, plugin->env->my_identity,
2531 sizeof (struct GNUNET_PeerIdentity));
2532 tcp_probe_ctx->plugin = plugin;
2533 tcp_probe_ctx->sock = sock;
2534 GNUNET_CONTAINER_DLL_insert (plugin->probe_head, plugin->probe_tail,
2536 tcp_probe_ctx->transmit_handle =
2537 GNUNET_CONNECTION_notify_transmit_ready (sock,
2538 ntohs (tcp_probe_ctx->
2539 message.header.size),
2540 GNUNET_TIME_UNIT_FOREVER_REL,
2548 * Function obtain the network type for a session
2550 * @param cls closure ('struct Plugin*')
2551 * @param session the session
2552 * @return the network type in HBO or #GNUNET_SYSERR
2554 static enum GNUNET_ATS_Network_Type
2555 tcp_get_network (void *cls,
2556 struct Session *session)
2558 GNUNET_assert (NULL != session);
2559 return session->ats_address_network_type;
2564 * Entry point for the plugin.
2566 * @param cls closure, the 'struct GNUNET_TRANSPORT_PluginEnvironment*'
2567 * @return the 'struct GNUNET_TRANSPORT_PluginFunctions*' or NULL on error
2570 libgnunet_plugin_transport_tcp_init (void *cls)
2572 static const struct GNUNET_SERVER_MessageHandler my_handlers[] = {
2573 {&handle_tcp_welcome, NULL, GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME,
2574 sizeof (struct WelcomeMessage)},
2575 {&handle_tcp_nat_probe, NULL, GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE,
2576 sizeof (struct TCP_NAT_ProbeMessage)},
2577 {&handle_tcp_data, NULL, GNUNET_MESSAGE_TYPE_ALL, 0},
2580 struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
2581 struct GNUNET_TRANSPORT_PluginFunctions *api;
2582 struct Plugin *plugin;
2583 struct GNUNET_SERVICE_Context *service;
2584 unsigned long long aport;
2585 unsigned long long bport;
2586 unsigned long long max_connections;
2588 struct GNUNET_TIME_Relative idle_timeout;
2591 struct sockaddr **addrs;
2592 socklen_t *addrlens;
2595 if (NULL == env->receive)
2597 /* run in 'stub' mode (i.e. as part of gnunet-peerinfo), don't fully
2598 initialze the plugin or the API */
2599 api = GNUNET_new (struct GNUNET_TRANSPORT_PluginFunctions);
2601 api->address_pretty_printer = &tcp_plugin_address_pretty_printer;
2602 api->address_to_string = &tcp_address_to_string;
2603 api->string_to_address = &tcp_string_to_address;
2607 GNUNET_assert (NULL != env->cfg);
2609 GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-tcp",
2612 max_connections = 128;
2616 GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-tcp", "PORT",
2617 &bport)) || (bport > 65535) ||
2619 GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-tcp",
2620 "ADVERTISED-PORT", &aport)) &&
2623 LOG (GNUNET_ERROR_TYPE_ERROR,
2624 _("Require valid port number for service `%s' in configuration!\n"),
2634 service = GNUNET_SERVICE_start ("transport-tcp", env->cfg, GNUNET_SERVICE_OPTION_NONE);
2635 if (service == NULL)
2637 LOG (GNUNET_ERROR_TYPE_WARNING,
2638 _("Failed to start service.\n"));
2645 /* Initialize my flags */
2648 plugin = GNUNET_new (struct Plugin);
2649 plugin->sessionmap = GNUNET_CONTAINER_multipeermap_create (max_connections, GNUNET_YES);
2650 plugin->max_connections = max_connections;
2651 plugin->cur_connections = 0;
2652 plugin->open_port = bport;
2653 plugin->adv_port = aport;
2655 plugin->lsock = NULL;
2656 if ((service != NULL) &&
2659 GNUNET_SERVICE_get_server_addresses ("transport-tcp", env->cfg, &addrs,
2662 for (ret = ret_s-1; ret >= 0; ret--)
2663 LOG (GNUNET_ERROR_TYPE_INFO,
2664 "Binding to address `%s'\n",
2665 GNUNET_a2s (addrs[ret], addrlens[ret]));
2667 GNUNET_NAT_register (env->cfg, GNUNET_YES, aport, (unsigned int) ret_s,
2668 (const struct sockaddr **) addrs, addrlens,
2669 &tcp_nat_port_map_callback,
2670 &try_connection_reversal, plugin);
2671 for (ret = ret_s -1; ret >= 0; ret--)
2673 GNUNET_assert (addrs[ret] != NULL);
2674 GNUNET_free (addrs[ret]);
2676 GNUNET_free_non_null (addrs);
2677 GNUNET_free_non_null (addrlens);
2681 plugin->nat = GNUNET_NAT_register (plugin->env->cfg,
2682 GNUNET_YES, 0, 0, NULL, NULL, NULL,
2683 &try_connection_reversal, plugin);
2685 api = GNUNET_new (struct GNUNET_TRANSPORT_PluginFunctions);
2687 api->send = &tcp_plugin_send;
2688 api->get_session = &tcp_plugin_get_session;
2690 api->disconnect_session = &tcp_disconnect_session;
2691 api->query_keepalive_factor = &tcp_query_keepalive_factor;
2692 api->disconnect_peer = &tcp_plugin_disconnect;
2693 api->address_pretty_printer = &tcp_plugin_address_pretty_printer;
2694 api->check_address = &tcp_plugin_check_address;
2695 api->address_to_string = &tcp_address_to_string;
2696 api->string_to_address = &tcp_string_to_address;
2697 api->get_network = &tcp_get_network;
2698 api->update_session_timeout = &tcp_plugin_update_session_timeout;
2699 plugin->service = service;
2700 if (NULL != service)
2702 plugin->server = GNUNET_SERVICE_get_server (service);
2707 GNUNET_CONFIGURATION_get_value_time (env->cfg, "transport-tcp",
2708 "TIMEOUT", &idle_timeout))
2710 GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
2711 "transport-tcp", "TIMEOUT");
2712 if (plugin->nat != NULL)
2713 GNUNET_NAT_unregister (plugin->nat);
2714 GNUNET_free (plugin);
2719 GNUNET_SERVER_create_with_sockets (&plugin_tcp_access_check, plugin,
2720 NULL, idle_timeout, GNUNET_YES);
2722 plugin->handlers = GNUNET_malloc (sizeof (my_handlers));
2723 memcpy (plugin->handlers, my_handlers, sizeof (my_handlers));
2725 i < sizeof (my_handlers) / sizeof (struct GNUNET_SERVER_MessageHandler);
2727 plugin->handlers[i].callback_cls = plugin;
2729 GNUNET_SERVER_add_handlers (plugin->server, plugin->handlers);
2730 GNUNET_SERVER_disconnect_notify (plugin->server, &disconnect_notify, plugin);
2731 plugin->nat_wait_conns = GNUNET_CONTAINER_multipeermap_create (16, GNUNET_YES);
2733 LOG (GNUNET_ERROR_TYPE_INFO,
2734 _("TCP transport listening on port %llu\n"), bport);
2736 LOG (GNUNET_ERROR_TYPE_INFO,
2737 _("TCP transport not listening on any port (client only)\n"));
2739 LOG (GNUNET_ERROR_TYPE_INFO,
2740 _("TCP transport advertises itself as being on port %llu\n"),
2742 /* Initially set connections to 0 */
2743 GNUNET_assert (NULL != plugin->env->stats);
2744 GNUNET_STATISTICS_set (plugin->env->stats,
2745 gettext_noop ("# TCP sessions active"), 0,
2752 * Exit point from the plugin.
2755 libgnunet_plugin_transport_tcp_done (void *cls)
2757 struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
2758 struct Plugin *plugin = api->cls;
2759 struct TCPProbeContext *tcp_probe;
2760 struct PrettyPrinterContext *cur;
2761 struct PrettyPrinterContext *next;
2768 LOG (GNUNET_ERROR_TYPE_DEBUG,
2769 "Shutting down TCP plugin\n");
2771 /* Removing leftover sessions */
2772 GNUNET_CONTAINER_multipeermap_iterate (plugin->sessionmap,
2773 &session_disconnect_it, plugin);
2774 /* Removing leftover NAT sessions */
2775 GNUNET_CONTAINER_multipeermap_iterate (plugin->nat_wait_conns,
2776 &session_disconnect_it, plugin);
2778 next = ppc_dll_head;
2779 for (cur = next; NULL != cur; cur = next)
2782 GNUNET_CONTAINER_DLL_remove (ppc_dll_head, ppc_dll_tail, cur);
2783 if (NULL != cur->resolver_handle)
2784 GNUNET_RESOLVER_request_cancel (cur->resolver_handle);
2785 GNUNET_SCHEDULER_cancel (cur->timeout_task);
2790 if (plugin->service != NULL)
2791 GNUNET_SERVICE_stop (plugin->service);
2793 GNUNET_SERVER_destroy (plugin->server);
2794 GNUNET_free (plugin->handlers);
2795 if (plugin->nat != NULL)
2796 GNUNET_NAT_unregister (plugin->nat);
2797 while (NULL != (tcp_probe = plugin->probe_head))
2799 GNUNET_CONTAINER_DLL_remove (plugin->probe_head, plugin->probe_tail,
2801 GNUNET_CONNECTION_destroy (tcp_probe->sock);
2802 GNUNET_free (tcp_probe);
2804 GNUNET_CONTAINER_multipeermap_destroy (plugin->nat_wait_conns);
2805 GNUNET_CONTAINER_multipeermap_destroy (plugin->sessionmap);
2806 GNUNET_free (plugin);
2811 /* end of plugin_transport_tcp.c */