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 * Session was idle, so disconnect it
870 * @param cls the `struct Session` of the idle session
871 * @param tc scheduler context
874 session_timeout (void *cls,
875 const struct GNUNET_SCHEDULER_TaskContext *tc)
877 struct Session *s = cls;
879 s->timeout_task = GNUNET_SCHEDULER_NO_TASK;
880 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
881 "Session %p was idle for %s, disconnecting\n",
883 GNUNET_STRINGS_relative_time_to_string (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
885 /* call session destroy function */
886 tcp_disconnect_session (s->plugin, s);
891 * Increment session timeout due to activity
893 * @param s session to increment timeout for
896 reschedule_session_timeout (struct Session *s)
898 GNUNET_assert (GNUNET_SCHEDULER_NO_TASK != s->timeout_task);
899 GNUNET_SCHEDULER_cancel (s->timeout_task);
900 s->timeout_task = GNUNET_SCHEDULER_add_delayed (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
903 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
904 "Timeout rescheduled for session %p set to %s\n",
906 GNUNET_STRINGS_relative_time_to_string (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
912 * Create a new session. Also queues a welcome message.
914 * @param plugin the plugin
915 * @param target peer to connect to
916 * @param client client to use, reference counter must have already been increased
917 * @param is_nat this a NAT session, we should wait for a client to
918 * connect to us from an address, then assign that to
920 * @return new session object
922 static struct Session *
923 create_session (struct Plugin *plugin,
924 const struct GNUNET_PeerIdentity *target,
925 struct GNUNET_SERVER_Client *client, int is_nat)
927 struct Session *session;
928 struct PendingMessage *pm;
929 struct WelcomeMessage welcome;
931 if (GNUNET_YES != is_nat)
932 GNUNET_assert (NULL != client);
934 GNUNET_assert (NULL == client);
936 LOG (GNUNET_ERROR_TYPE_DEBUG,
937 "Creating new session for peer `%4s'\n",
938 GNUNET_i2s (target));
939 session = GNUNET_new (struct Session);
940 session->last_activity = GNUNET_TIME_absolute_get ();
941 session->plugin = plugin;
942 session->is_nat = is_nat;
943 session->client = client;
944 session->target = *target;
945 session->expecting_welcome = GNUNET_YES;
946 session->ats_address_network_type = GNUNET_ATS_NET_UNSPECIFIED;
947 pm = GNUNET_malloc (sizeof (struct PendingMessage) +
948 sizeof (struct WelcomeMessage));
949 pm->msg = (const char *) &pm[1];
950 pm->message_size = sizeof (struct WelcomeMessage);
951 welcome.header.size = htons (sizeof (struct WelcomeMessage));
952 welcome.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME);
953 welcome.clientIdentity = *plugin->env->my_identity;
954 memcpy (&pm[1], &welcome, sizeof (welcome));
955 pm->timeout = GNUNET_TIME_UNIT_FOREVER_ABS;
956 GNUNET_STATISTICS_update (plugin->env->stats,
957 gettext_noop ("# bytes currently in TCP buffers"),
958 pm->message_size, GNUNET_NO);
959 GNUNET_CONTAINER_DLL_insert (session->pending_messages_head,
960 session->pending_messages_tail, pm);
961 if (GNUNET_YES != is_nat)
963 GNUNET_STATISTICS_update (plugin->env->stats,
964 gettext_noop ("# TCP sessions active"), 1,
967 session->timeout_task = GNUNET_SCHEDULER_add_delayed (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
975 * If we have pending messages, ask the server to
976 * transmit them (schedule the respective tasks, etc.)
978 * @param session for which session should we do this
981 process_pending_messages (struct Session *session);
985 * Function called to notify a client about the socket
986 * being ready to queue more data. "buf" will be
987 * NULL and "size" zero if the socket was closed for
988 * writing in the meantime.
991 * @param size number of bytes available in buf
992 * @param buf where the callee should write the message
993 * @return number of bytes written to buf
996 do_transmit (void *cls, size_t size, void *buf)
998 struct Session *session = cls;
999 struct GNUNET_PeerIdentity pid;
1000 struct Plugin *plugin;
1001 struct PendingMessage *pos;
1002 struct PendingMessage *hd;
1003 struct PendingMessage *tl;
1004 struct GNUNET_TIME_Absolute now;
1008 GNUNET_assert (NULL != session);
1009 session->transmit_handle = NULL;
1010 plugin = session->plugin;
1013 LOG (GNUNET_ERROR_TYPE_DEBUG,
1014 "Timeout trying to transmit to peer `%4s', discarding message queue.\n",
1015 GNUNET_i2s (&session->target));
1016 /* timeout; cancel all messages that have already expired */
1020 now = GNUNET_TIME_absolute_get ();
1021 while ((NULL != (pos = session->pending_messages_head)) &&
1022 (pos->timeout.abs_value_us <= now.abs_value_us))
1024 GNUNET_CONTAINER_DLL_remove (session->pending_messages_head,
1025 session->pending_messages_tail, pos);
1026 LOG (GNUNET_ERROR_TYPE_DEBUG,
1027 "Failed to transmit %u byte message to `%4s'.\n",
1028 pos->message_size, GNUNET_i2s (&session->target));
1029 ret += pos->message_size;
1030 GNUNET_CONTAINER_DLL_insert_after (hd, tl, tl, pos);
1032 /* do this call before callbacks (so that if callbacks destroy
1033 * session, they have a chance to cancel actions done by this
1035 process_pending_messages (session);
1036 pid = session->target;
1037 /* no do callbacks and do not use session again since
1038 * the callbacks may abort the session */
1039 while (NULL != (pos = hd))
1041 GNUNET_CONTAINER_DLL_remove (hd, tl, pos);
1042 if (pos->transmit_cont != NULL)
1043 pos->transmit_cont (pos->transmit_cont_cls, &pid, GNUNET_SYSERR, pos->message_size, 0);
1046 GNUNET_STATISTICS_update (plugin->env->stats,
1047 gettext_noop ("# bytes currently in TCP buffers"),
1048 -(int64_t) ret, GNUNET_NO);
1049 GNUNET_STATISTICS_update (plugin->env->stats,
1051 ("# bytes discarded by TCP (timeout)"), ret,
1055 /* copy all pending messages that would fit */
1060 while (NULL != (pos = session->pending_messages_head))
1062 if (ret + pos->message_size > size)
1064 GNUNET_CONTAINER_DLL_remove (session->pending_messages_head,
1065 session->pending_messages_tail, pos);
1066 GNUNET_assert (size >= pos->message_size);
1067 LOG (GNUNET_ERROR_TYPE_DEBUG,
1068 "Transmitting message of type %u\n",
1069 ntohs (((struct GNUNET_MessageHeader *) pos->msg)->type));
1070 /* FIXME: this memcpy can be up to 7% of our total runtime */
1071 memcpy (cbuf, pos->msg, pos->message_size);
1072 cbuf += pos->message_size;
1073 ret += pos->message_size;
1074 size -= pos->message_size;
1075 GNUNET_CONTAINER_DLL_insert_tail (hd, tl, pos);
1077 /* schedule 'continuation' before callbacks so that callbacks that
1078 * cancel everything don't cause us to use a session that no longer
1080 process_pending_messages (session);
1081 session->last_activity = GNUNET_TIME_absolute_get ();
1082 pid = session->target;
1083 /* we'll now call callbacks that may cancel the session; hence
1084 * we should not use 'session' after this point */
1085 while (NULL != (pos = hd))
1087 GNUNET_CONTAINER_DLL_remove (hd, tl, pos);
1088 if (pos->transmit_cont != NULL)
1089 pos->transmit_cont (pos->transmit_cont_cls, &pid, GNUNET_OK, pos->message_size, pos->message_size); /* FIXME: include TCP overhead */
1092 GNUNET_assert (hd == NULL);
1093 GNUNET_assert (tl == NULL);
1094 LOG (GNUNET_ERROR_TYPE_DEBUG, "Transmitting %u bytes\n",
1096 GNUNET_STATISTICS_update (plugin->env->stats,
1097 gettext_noop ("# bytes currently in TCP buffers"),
1098 -(int64_t) ret, GNUNET_NO);
1099 GNUNET_STATISTICS_update (plugin->env->stats,
1100 gettext_noop ("# bytes transmitted via TCP"), ret,
1107 * If we have pending messages, ask the server to
1108 * transmit them (schedule the respective tasks, etc.)
1110 * @param session for which session should we do this
1113 process_pending_messages (struct Session *session)
1115 struct PendingMessage *pm;
1117 GNUNET_assert (session->client != NULL);
1118 if (session->transmit_handle != NULL)
1120 if (NULL == (pm = session->pending_messages_head))
1123 session->transmit_handle =
1124 GNUNET_SERVER_notify_transmit_ready (session->client, pm->message_size,
1125 GNUNET_TIME_absolute_get_remaining
1126 (pm->timeout), &do_transmit,
1133 * Closure for #session_it().
1135 struct FindSessionContext
1138 * Session we are looking for.
1143 * Set to #GNUNET_OK if we found the session.
1150 * Function called to check if a session is in our maps.
1152 * @param cls the `struct FindSessionContext`
1153 * @param key peer identity
1154 * @param value session in the map
1155 * @return #GNUNET_YES to continue looking, #GNUNET_NO if we found the session
1158 session_it (void *cls,
1159 const struct GNUNET_PeerIdentity *key,
1162 struct FindSessionContext *res = cls;
1163 struct Session *session = value;
1165 if (res->s == session)
1167 res->res = GNUNET_OK;
1175 * Check that the given session is known to the plugin and
1176 * is in one of our maps.
1178 * @param plugin the plugin to check against
1179 * @param session the session to check
1180 * @return #GNUNET_OK if all is well, #GNUNET_SYSERR if the session is invalid
1183 find_session (struct Plugin *plugin,
1184 struct Session *session)
1186 struct FindSessionContext session_map_res;
1187 struct FindSessionContext nat_map_res;
1189 session_map_res.s = session;
1190 session_map_res.res = GNUNET_SYSERR;
1191 GNUNET_CONTAINER_multipeermap_iterate (plugin->sessionmap,
1192 &session_it, &session_map_res);
1193 if (GNUNET_SYSERR != session_map_res.res)
1195 nat_map_res.s = session;
1196 nat_map_res.res = GNUNET_SYSERR;
1197 GNUNET_CONTAINER_multipeermap_iterate (plugin->nat_wait_conns,
1198 &session_it, &nat_map_res);
1199 if (GNUNET_SYSERR != nat_map_res.res)
1202 return GNUNET_SYSERR;
1208 * Function that can be used by the transport service to transmit
1209 * a message using the plugin. Note that in the case of a
1210 * peer disconnecting, the continuation MUST be called
1211 * prior to the disconnect notification itself. This function
1212 * will be called with this peer's HELLO message to initiate
1213 * a fresh connection to another peer.
1215 * @param cls closure
1216 * @param session which session must be used
1217 * @param msgbuf the message to transmit
1218 * @param msgbuf_size number of bytes in 'msgbuf'
1219 * @param priority how important is the message (most plugins will
1220 * ignore message priority and just FIFO)
1221 * @param to how long to wait at most for the transmission (does not
1222 * require plugins to discard the message after the timeout,
1223 * just advisory for the desired delay; most plugins will ignore
1225 * @param cont continuation to call once the message has
1226 * been transmitted (or if the transport is ready
1227 * for the next transmission call; or if the
1228 * peer disconnected...); can be NULL
1229 * @param cont_cls closure for @a cont
1230 * @return number of bytes used (on the physical network, with overheads);
1231 * -1 on hard errors (i.e. address invalid); 0 is a legal value
1232 * and does NOT mean that the message was not transmitted (DV)
1235 tcp_plugin_send (void *cls,
1236 struct Session *session,
1237 const char *msgbuf, size_t msgbuf_size,
1238 unsigned int priority,
1239 struct GNUNET_TIME_Relative to,
1240 GNUNET_TRANSPORT_TransmitContinuation cont, void *cont_cls)
1242 struct Plugin * plugin = cls;
1243 struct PendingMessage *pm;
1246 if (GNUNET_SYSERR == find_session (plugin, session))
1248 LOG (GNUNET_ERROR_TYPE_ERROR,
1249 _("Trying to send with invalid session %p\n"));
1251 return GNUNET_SYSERR;
1254 /* create new message entry */
1255 pm = GNUNET_malloc (sizeof (struct PendingMessage) + msgbuf_size);
1256 pm->msg = (const char *) &pm[1];
1257 memcpy (&pm[1], msgbuf, msgbuf_size);
1258 pm->message_size = msgbuf_size;
1259 pm->timeout = GNUNET_TIME_relative_to_absolute (to);
1260 pm->transmit_cont = cont;
1261 pm->transmit_cont_cls = cont_cls;
1263 LOG (GNUNET_ERROR_TYPE_DEBUG,
1264 "Asked to transmit %u bytes to `%s', added message to list.\n",
1265 msgbuf_size, GNUNET_i2s (&session->target));
1268 GNUNET_CONTAINER_multipeermap_contains_value (plugin->sessionmap,
1272 GNUNET_assert (session->client != NULL);
1273 reschedule_session_timeout (session);
1274 GNUNET_SERVER_client_set_timeout (session->client,
1275 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1276 GNUNET_STATISTICS_update (plugin->env->stats,
1277 gettext_noop ("# bytes currently in TCP buffers"),
1278 msgbuf_size, GNUNET_NO);
1280 /* append pm to pending_messages list */
1281 GNUNET_CONTAINER_DLL_insert_tail (session->pending_messages_head,
1282 session->pending_messages_tail, pm);
1284 process_pending_messages (session);
1287 else if (GNUNET_YES == GNUNET_CONTAINER_multipeermap_contains_value(plugin->nat_wait_conns, &session->target, session))
1289 LOG (GNUNET_ERROR_TYPE_DEBUG,
1290 "This NAT WAIT session for peer `%s' is not yet ready!\n",
1291 GNUNET_i2s (&session->target));
1292 reschedule_session_timeout (session);
1293 GNUNET_STATISTICS_update (plugin->env->stats,
1294 gettext_noop ("# bytes currently in TCP buffers"),
1295 msgbuf_size, GNUNET_NO);
1297 /* append pm to pending_messages list */
1298 GNUNET_CONTAINER_DLL_insert_tail (session->pending_messages_head,
1299 session->pending_messages_tail, pm);
1304 LOG (GNUNET_ERROR_TYPE_ERROR,
1305 "Invalid session %p\n", session);
1307 cont (cont_cls, &session->target, GNUNET_SYSERR, pm->message_size, 0);
1310 return GNUNET_SYSERR; /* session does not exist here */
1316 * Closure for #session_lookup_it().
1321 * Address we are looking for.
1326 * Number of bytes in @e addr.
1331 * Where to store the session (if we found it).
1333 struct Session *result;
1338 * Look for a session by address.
1340 * @param cls the `struct SessionItCtx`
1342 * @param value a `struct Session`
1343 * @return #GNUNET_YES to continue looking, #GNUNET_NO if we found the session
1346 session_lookup_it (void *cls,
1347 const struct GNUNET_PeerIdentity *key,
1350 struct SessionItCtx * si_ctx = cls;
1351 struct Session * session = value;
1353 char * a1 = strdup (tcp_address_to_string(NULL, session->addr, session->addrlen));
1354 char * a2 = strdup (tcp_address_to_string(NULL, si_ctx->addr, si_ctx->addrlen));
1355 LOG (GNUNET_ERROR_TYPE_DEBUG,
1356 "Comparing: %s %u <-> %s %u\n",
1364 if (session->addrlen != si_ctx->addrlen)
1366 if (0 != memcmp (session->addr, si_ctx->addr, si_ctx->addrlen))
1369 a1 = strdup (tcp_address_to_string (NULL, session->addr, session->addrlen));
1370 a2 = strdup (tcp_address_to_string (NULL, si_ctx->addr, si_ctx->addrlen));
1371 LOG (GNUNET_ERROR_TYPE_DEBUG,
1372 "Comparing: %s %u <-> %s %u , OK!\n",
1380 /* Found existing session */
1381 si_ctx->result = session;
1387 * Task cleaning up a NAT connection attempt after timeout
1389 * @param cls the `struct Session`
1390 * @param tc scheduler context (unused)
1393 nat_connect_timeout (void *cls,
1394 const struct GNUNET_SCHEDULER_TaskContext *tc)
1396 struct Session *session = cls;
1398 session->nat_connection_timeout = GNUNET_SCHEDULER_NO_TASK;
1399 LOG (GNUNET_ERROR_TYPE_DEBUG,
1400 "NAT WAIT connection to `%4s' at `%s' could not be established, removing session\n",
1401 GNUNET_i2s (&session->target),
1402 tcp_address_to_string (NULL,
1403 session->addr, session->addrlen));
1404 tcp_disconnect_session (session->plugin,
1410 * Create a new session to transmit data to the target
1411 * This session will used to send data to this peer and the plugin will
1412 * notify us by calling the env->session_end function
1414 * @param cls closure
1415 * @param address the address to use
1416 * @return the session if the address is valid, NULL otherwise
1418 static struct Session *
1419 tcp_plugin_get_session (void *cls,
1420 const struct GNUNET_HELLO_Address *address)
1422 struct Plugin *plugin = cls;
1423 struct Session *session = NULL;
1427 struct GNUNET_CONNECTION_Handle *sa;
1428 struct sockaddr_in a4;
1429 struct sockaddr_in6 a6;
1430 const struct IPv4TcpAddress *t4;
1431 const struct IPv6TcpAddress *t6;
1432 struct GNUNET_ATS_Information ats;
1433 unsigned int is_natd = GNUNET_NO;
1436 addrlen = address->address_length;
1437 LOG (GNUNET_ERROR_TYPE_DEBUG,
1438 "Trying to get session for `%s' address of peer `%s'\n",
1439 tcp_address_to_string(NULL, address->address, address->address_length),
1440 GNUNET_i2s (&address->peer));
1442 /* look for existing session */
1444 GNUNET_CONTAINER_multipeermap_contains (plugin->sessionmap,
1447 struct SessionItCtx si_ctx;
1449 si_ctx.addr = (void *) address->address;
1450 si_ctx.addrlen = address->address_length;
1452 si_ctx.result = NULL;
1454 GNUNET_CONTAINER_multipeermap_get_multiple (plugin->sessionmap,
1456 &session_lookup_it, &si_ctx);
1457 if (si_ctx.result != NULL)
1459 session = si_ctx.result;
1460 LOG (GNUNET_ERROR_TYPE_DEBUG,
1461 "Found existing session for `%s' address `%s' session %p\n",
1462 GNUNET_i2s (&address->peer),
1463 tcp_address_to_string(NULL, address->address, address->address_length),
1467 LOG (GNUNET_ERROR_TYPE_DEBUG,
1468 "Existing sessions did not match address `%s' or peer `%s'\n",
1469 tcp_address_to_string(NULL, address->address, address->address_length),
1470 GNUNET_i2s (&address->peer));
1473 if (addrlen == sizeof (struct IPv6TcpAddress))
1475 GNUNET_assert (NULL != address->address); /* make static analysis happy */
1476 t6 = address->address;
1478 memset (&a6, 0, sizeof (a6));
1479 #if HAVE_SOCKADDR_IN_SIN_LEN
1480 a6.sin6_len = sizeof (a6);
1482 a6.sin6_family = AF_INET6;
1483 a6.sin6_port = t6->t6_port;
1484 if (t6->t6_port == 0)
1485 is_natd = GNUNET_YES;
1486 memcpy (&a6.sin6_addr, &t6->ipv6_addr, sizeof (struct in6_addr));
1490 else if (addrlen == sizeof (struct IPv4TcpAddress))
1492 GNUNET_assert (NULL != address->address); /* make static analysis happy */
1493 t4 = address->address;
1495 memset (&a4, 0, sizeof (a4));
1496 #if HAVE_SOCKADDR_IN_SIN_LEN
1497 a4.sin_len = sizeof (a4);
1499 a4.sin_family = AF_INET;
1500 a4.sin_port = t4->t4_port;
1501 if (t4->t4_port == 0)
1502 is_natd = GNUNET_YES;
1503 a4.sin_addr.s_addr = t4->ipv4_addr;
1509 GNUNET_STATISTICS_update (plugin->env->stats,
1511 ("# requests to create session with invalid address"),
1516 ats = plugin->env->get_address_type (plugin->env->cls, sb, sbs);
1518 if ((is_natd == GNUNET_YES) && (addrlen == sizeof (struct IPv6TcpAddress)))
1520 /* NAT client only works with IPv4 addresses */
1524 if (plugin->cur_connections >= plugin->max_connections)
1530 if ((is_natd == GNUNET_YES) &&
1532 GNUNET_CONTAINER_multipeermap_contains (plugin->nat_wait_conns,
1535 /* Only do one NAT punch attempt per peer identity */
1539 if ((is_natd == GNUNET_YES) && (NULL != plugin->nat) &&
1541 GNUNET_CONTAINER_multipeermap_contains (plugin->nat_wait_conns,
1544 LOG (GNUNET_ERROR_TYPE_DEBUG,
1545 "Found valid IPv4 NAT address (creating session)!\n") ;
1546 session = create_session (plugin,
1550 session->addrlen = 0;
1551 session->addr = NULL;
1552 session->ats_address_network_type = (enum GNUNET_ATS_Network_Type) ntohl (ats.value)
1554 GNUNET_break (session->ats_address_network_type != GNUNET_ATS_NET_UNSPECIFIED);
1555 session->nat_connection_timeout = GNUNET_SCHEDULER_add_delayed (NAT_TIMEOUT,
1556 &nat_connect_timeout,
1558 GNUNET_assert (session != NULL);
1559 GNUNET_assert (GNUNET_OK ==
1560 GNUNET_CONTAINER_multipeermap_put (plugin->nat_wait_conns,
1563 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
1565 LOG (GNUNET_ERROR_TYPE_DEBUG,
1566 "Created NAT WAIT connection to `%4s' at `%s'\n",
1567 GNUNET_i2s (&session->target), GNUNET_a2s (sb, sbs));
1569 if (GNUNET_OK == GNUNET_NAT_run_client (plugin->nat, &a4))
1573 LOG (GNUNET_ERROR_TYPE_DEBUG,
1574 "Running NAT client for `%4s' at `%s' failed\n",
1575 GNUNET_i2s (&session->target), GNUNET_a2s (sb, sbs));
1576 tcp_disconnect_session (plugin, session);
1581 /* create new outbound session */
1582 GNUNET_assert (plugin->cur_connections <= plugin->max_connections);
1583 sa = GNUNET_CONNECTION_create_from_sockaddr (af, sb, sbs);
1586 LOG (GNUNET_ERROR_TYPE_DEBUG,
1587 "Failed to create connection to `%4s' at `%s'\n",
1588 GNUNET_i2s (&address->peer), GNUNET_a2s (sb, sbs));
1591 plugin->cur_connections++;
1592 if (plugin->cur_connections == plugin->max_connections)
1593 GNUNET_SERVER_suspend (plugin->server); /* Maximum number of connections rechead */
1595 LOG (GNUNET_ERROR_TYPE_DEBUG,
1596 "Asked to transmit to `%4s', creating fresh session using address `%s'.\n",
1597 GNUNET_i2s (&address->peer),
1598 GNUNET_a2s (sb, sbs));
1600 session = create_session (plugin,
1602 GNUNET_SERVER_connect_socket (plugin->server, sa),
1604 session->addr = GNUNET_malloc (addrlen);
1605 memcpy (session->addr, address->address, addrlen);
1606 session->addrlen = addrlen;
1607 session->ats_address_network_type = (enum GNUNET_ATS_Network_Type) ntohl (ats.value);
1608 GNUNET_break (session->ats_address_network_type != GNUNET_ATS_NET_UNSPECIFIED);
1609 GNUNET_SERVER_client_set_user_context (session->client, session);
1610 GNUNET_CONTAINER_multipeermap_put (plugin->sessionmap,
1613 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
1614 LOG (GNUNET_ERROR_TYPE_DEBUG,
1615 "Creating new session for `%s' address `%s' session %p\n",
1616 GNUNET_i2s (&address->peer),
1617 tcp_address_to_string(NULL, address->address, address->address_length),
1619 /* Send TCP Welcome */
1620 process_pending_messages (session);
1627 session_disconnect_it (void *cls,
1628 const struct GNUNET_PeerIdentity *key,
1631 struct Plugin *plugin = cls;
1632 struct Session *session = value;
1634 GNUNET_STATISTICS_update (session->plugin->env->stats,
1636 ("# transport-service disconnect requests for TCP"),
1638 tcp_disconnect_session (plugin,
1645 * Function that can be called to force a disconnect from the
1646 * specified neighbour. This should also cancel all previously
1647 * scheduled transmissions. Obviously the transmission may have been
1648 * partially completed already, which is OK. The plugin is supposed
1649 * to close the connection (if applicable) and no longer call the
1650 * transmit continuation(s).
1652 * Finally, plugin MUST NOT call the services's receive function to
1653 * notify the service that the connection to the specified target was
1654 * closed after a getting this call.
1656 * @param cls closure
1657 * @param target peer for which the last transmission is
1661 tcp_plugin_disconnect (void *cls,
1662 const struct GNUNET_PeerIdentity *target)
1664 struct Plugin *plugin = cls;
1666 LOG (GNUNET_ERROR_TYPE_DEBUG,
1667 "Disconnecting peer `%4s'\n",
1668 GNUNET_i2s (target));
1669 GNUNET_CONTAINER_multipeermap_get_multiple (plugin->sessionmap, target,
1670 &session_disconnect_it, plugin);
1671 GNUNET_CONTAINER_multipeermap_get_multiple (plugin->nat_wait_conns, target,
1672 &session_disconnect_it, plugin);
1677 * Running pretty printers: head
1679 static struct PrettyPrinterContext *ppc_dll_head;
1682 * Running pretty printers: tail
1684 static struct PrettyPrinterContext *ppc_dll_tail;
1687 * Context for address to string conversion.
1689 struct PrettyPrinterContext
1694 struct PrettyPrinterContext *next;
1699 struct PrettyPrinterContext *prev;
1704 GNUNET_SCHEDULER_TaskIdentifier timeout_task;
1709 struct GNUNET_RESOLVER_RequestHandle *resolver_handle;
1712 * Function to call with the result.
1714 GNUNET_TRANSPORT_AddressStringCallback asc;
1717 * Clsoure for 'asc'.
1722 * Port to add after the IP address.
1739 ppc_cancel_task (void *cls,
1740 const struct GNUNET_SCHEDULER_TaskContext *tc)
1743 struct PrettyPrinterContext *ppc = cls;
1744 struct PrettyPrinterContext *cur;
1746 for (cur = ppc_dll_head; (NULL != cur); cur = cur->next)
1752 // GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Cancel request %p, %u pending\n", ppc, count);
1753 ppc->timeout_task = GNUNET_SCHEDULER_NO_TASK;
1754 if (NULL != ppc->resolver_handle)
1756 GNUNET_RESOLVER_request_cancel (ppc->resolver_handle);
1757 ppc->resolver_handle = NULL;
1759 GNUNET_CONTAINER_DLL_remove (ppc_dll_head, ppc_dll_tail, ppc);
1765 * Append our port and forward the result.
1767 * @param cls the 'struct PrettyPrinterContext*'
1768 * @param hostname hostname part of the address
1771 append_port (void *cls, const char *hostname)
1773 struct PrettyPrinterContext *ppc = cls;
1774 struct PrettyPrinterContext *cur;
1778 for (cur = ppc_dll_head; (NULL != cur); cur = cur->next)
1783 //GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Callback request %p == %s, %u pending\n", ppc, hostname, count);
1784 if (hostname == NULL)
1786 ppc->asc (ppc->asc_cls, NULL);
1787 GNUNET_CONTAINER_DLL_remove (ppc_dll_head, ppc_dll_tail, ppc);
1788 GNUNET_SCHEDULER_cancel (ppc->timeout_task);
1789 ppc->timeout_task = GNUNET_SCHEDULER_NO_TASK;
1790 ppc->resolver_handle = NULL;
1791 //GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Done request %p, %u pending\n", ppc, count);
1795 for (cur = ppc_dll_head; (NULL != cur); cur = cur->next)
1802 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Invalid callback for PPC %p \n", ppc);
1806 if (GNUNET_YES == ppc->ipv6)
1807 GNUNET_asprintf (&ret, "%s.%u.[%s]:%d", PLUGIN_NAME, ppc->options, hostname, ppc->port);
1809 GNUNET_asprintf (&ret, "%s.%u.%s:%d", PLUGIN_NAME, ppc->options, hostname, ppc->port);
1810 ppc->asc (ppc->asc_cls, ret);
1816 * Convert the transports address to a nice, human-readable
1819 * @param cls closure
1820 * @param type name of the transport that generated the address
1821 * @param addr one of the addresses of the host, NULL for the last address
1822 * the specific address format depends on the transport
1823 * @param addrlen length of the address
1824 * @param numeric should (IP) addresses be displayed in numeric form?
1825 * @param timeout after how long should we give up?
1826 * @param asc function to call on each string
1827 * @param asc_cls closure for asc
1830 tcp_plugin_address_pretty_printer (void *cls, const char *type,
1831 const void *addr, size_t addrlen,
1833 struct GNUNET_TIME_Relative timeout,
1834 GNUNET_TRANSPORT_AddressStringCallback asc,
1837 struct PrettyPrinterContext *ppc;
1840 struct sockaddr_in a4;
1841 struct sockaddr_in6 a6;
1842 const struct IPv4TcpAddress *t4;
1843 const struct IPv6TcpAddress *t6;
1847 if (addrlen == sizeof (struct IPv6TcpAddress))
1850 memset (&a6, 0, sizeof (a6));
1851 a6.sin6_family = AF_INET6;
1852 a6.sin6_port = t6->t6_port;
1853 memcpy (&a6.sin6_addr, &t6->ipv6_addr, sizeof (struct in6_addr));
1854 port = ntohs (t6->t6_port);
1855 options = ntohl (t6->options);
1859 else if (addrlen == sizeof (struct IPv4TcpAddress))
1862 memset (&a4, 0, sizeof (a4));
1863 a4.sin_family = AF_INET;
1864 a4.sin_port = t4->t4_port;
1865 a4.sin_addr.s_addr = t4->ipv4_addr;
1866 port = ntohs (t4->t4_port);
1867 options = ntohl (t4->options);
1871 else if (0 == addrlen)
1873 asc (asc_cls, TRANSPORT_SESSION_INBOUND_STRING);
1874 asc (asc_cls, NULL);
1879 /* invalid address */
1880 GNUNET_break_op (0);
1881 asc (asc_cls, NULL);
1884 ppc = GNUNET_malloc (sizeof (struct PrettyPrinterContext));
1885 if (addrlen == sizeof (struct IPv6TcpAddress))
1886 ppc->ipv6 = GNUNET_YES;
1888 ppc->ipv6 = GNUNET_NO;
1890 ppc->asc_cls = asc_cls;
1892 ppc->options = options;
1893 ppc->timeout_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply(timeout, 2),
1894 &ppc_cancel_task, ppc);
1895 ppc->resolver_handle = GNUNET_RESOLVER_hostname_get (sb, sbs, !numeric,
1898 if (NULL != ppc->resolver_handle)
1900 //GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Adding request %p\n", ppc);
1901 GNUNET_CONTAINER_DLL_insert (ppc_dll_head, ppc_dll_tail, ppc);
1912 * Check if the given port is plausible (must be either our listen
1913 * port or our advertised port), or any port if we are behind NAT
1914 * and do not have a port open. If it is neither, we return
1917 * @param plugin global variables
1918 * @param in_port port number to check
1919 * @return #GNUNET_OK if port is either open_port or adv_port
1922 check_port (struct Plugin *plugin, uint16_t in_port)
1924 if ((in_port == plugin->adv_port) || (in_port == plugin->open_port))
1926 return GNUNET_SYSERR;
1931 * Function that will be called to check if a binary address for this
1932 * plugin is well-formed and corresponds to an address for THIS peer
1933 * (as per our configuration). Naturally, if absolutely necessary,
1934 * plugins can be a bit conservative in their answer, but in general
1935 * plugins should make sure that the address does not redirect
1936 * traffic to a 3rd party that might try to man-in-the-middle our
1939 * @param cls closure, our 'struct Plugin*'
1940 * @param addr pointer to the address
1941 * @param addrlen length of addr
1942 * @return #GNUNET_OK if this is a plausible address for this peer
1943 * and transport, #GNUNET_SYSERR if not
1946 tcp_plugin_check_address (void *cls, const void *addr, size_t addrlen)
1948 struct Plugin *plugin = cls;
1949 struct IPv4TcpAddress *v4;
1950 struct IPv6TcpAddress *v6;
1952 if ((addrlen != sizeof (struct IPv4TcpAddress)) &&
1953 (addrlen != sizeof (struct IPv6TcpAddress)))
1957 return GNUNET_SYSERR;
1960 if (addrlen == sizeof (struct IPv4TcpAddress))
1962 v4 = (struct IPv4TcpAddress *) addr;
1963 if (0 != memcmp (&v4->options, &myoptions, sizeof (myoptions)))
1966 return GNUNET_SYSERR;
1968 if (GNUNET_OK != check_port (plugin, ntohs (v4->t4_port)))
1969 return GNUNET_SYSERR;
1971 GNUNET_NAT_test_address (plugin->nat, &v4->ipv4_addr,
1972 sizeof (struct in_addr)))
1973 return GNUNET_SYSERR;
1977 v6 = (struct IPv6TcpAddress *) addr;
1978 if (IN6_IS_ADDR_LINKLOCAL (&v6->ipv6_addr))
1980 GNUNET_break_op (0);
1981 return GNUNET_SYSERR;
1983 if (0 != memcmp (&v6->options, &myoptions, sizeof (myoptions)))
1986 return GNUNET_SYSERR;
1988 if (GNUNET_OK != check_port (plugin, ntohs (v6->t6_port)))
1989 return GNUNET_SYSERR;
1991 GNUNET_NAT_test_address (plugin->nat, &v6->ipv6_addr,
1992 sizeof (struct in6_addr)))
1993 return GNUNET_SYSERR;
2000 * We've received a nat probe from this peer via TCP. Finish
2001 * creating the client session and resume sending of queued
2004 * @param cls closure
2005 * @param client identification of the client
2006 * @param message the actual message
2009 handle_tcp_nat_probe (void *cls,
2010 struct GNUNET_SERVER_Client *client,
2011 const struct GNUNET_MessageHeader *message)
2013 struct Plugin *plugin = cls;
2014 struct Session *session;
2015 const struct TCP_NAT_ProbeMessage *tcp_nat_probe;
2018 struct IPv4TcpAddress *t4;
2019 struct IPv6TcpAddress *t6;
2020 const struct sockaddr_in *s4;
2021 const struct sockaddr_in6 *s6;
2023 LOG (GNUNET_ERROR_TYPE_DEBUG,
2024 "Received NAT probe\n");
2025 /* We have received a TCP NAT probe, meaning we (hopefully) initiated
2026 * a connection to this peer by running gnunet-nat-client. This peer
2027 * received the punch message and now wants us to use the new connection
2028 * as the default for that peer. Do so and then send a WELCOME message
2029 * so we can really be connected!
2031 if (ntohs (message->size) != sizeof (struct TCP_NAT_ProbeMessage))
2033 GNUNET_break_op (0);
2034 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2038 tcp_nat_probe = (const struct TCP_NAT_ProbeMessage *) message;
2040 memcmp (&tcp_nat_probe->clientIdentity, plugin->env->my_identity,
2041 sizeof (struct GNUNET_PeerIdentity)))
2043 /* refuse connections from ourselves */
2044 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2049 GNUNET_CONTAINER_multipeermap_get (plugin->nat_wait_conns,
2050 &tcp_nat_probe->clientIdentity);
2051 if (session == NULL)
2053 LOG (GNUNET_ERROR_TYPE_DEBUG,
2054 "Did NOT find session for NAT probe!\n");
2055 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2058 LOG (GNUNET_ERROR_TYPE_DEBUG,
2059 "Found session for NAT probe!\n");
2061 if (session->nat_connection_timeout != GNUNET_SCHEDULER_NO_TASK)
2063 GNUNET_SCHEDULER_cancel (session->nat_connection_timeout);
2064 session->nat_connection_timeout = GNUNET_SCHEDULER_NO_TASK;
2067 if (GNUNET_OK != GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
2070 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2071 tcp_disconnect_session (plugin, session);
2074 GNUNET_assert (GNUNET_CONTAINER_multipeermap_remove
2075 (plugin->nat_wait_conns,
2076 &tcp_nat_probe->clientIdentity,
2077 session) == GNUNET_YES);
2078 GNUNET_SERVER_client_set_user_context (client, session);
2079 GNUNET_CONTAINER_multipeermap_put (plugin->sessionmap,
2080 &session->target, session,
2081 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2082 session->last_activity = GNUNET_TIME_absolute_get ();
2083 session->inbound = GNUNET_NO;
2084 LOG (GNUNET_ERROR_TYPE_DEBUG,
2085 "Found address `%s' for incoming connection\n",
2086 GNUNET_a2s (vaddr, alen));
2087 switch (((const struct sockaddr *) vaddr)->sa_family)
2091 t4 = GNUNET_new (struct IPv4TcpAddress);
2093 t4->t4_port = s4->sin_port;
2094 t4->ipv4_addr = s4->sin_addr.s_addr;
2096 session->addrlen = sizeof (struct IPv4TcpAddress);
2100 t6 = GNUNET_new (struct IPv6TcpAddress);
2102 t6->t6_port = s6->sin6_port;
2103 memcpy (&t6->ipv6_addr, &s6->sin6_addr, sizeof (struct in6_addr));
2105 session->addrlen = sizeof (struct IPv6TcpAddress);
2108 GNUNET_break_op (0);
2109 LOG (GNUNET_ERROR_TYPE_DEBUG,
2110 "Bad address for incoming connection!\n");
2111 GNUNET_free (vaddr);
2112 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2113 tcp_disconnect_session (plugin, session);
2116 GNUNET_free (vaddr);
2117 GNUNET_break (NULL == session->client);
2118 GNUNET_SERVER_client_keep (client);
2119 session->client = client;
2120 GNUNET_STATISTICS_update (plugin->env->stats,
2121 gettext_noop ("# TCP sessions active"), 1,
2123 process_pending_messages (session);
2124 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2129 * We've received a welcome from this peer via TCP. Possibly create a
2130 * fresh client record and send back our welcome.
2132 * @param cls closure
2133 * @param client identification of the client
2134 * @param message the actual message
2137 handle_tcp_welcome (void *cls, struct GNUNET_SERVER_Client *client,
2138 const struct GNUNET_MessageHeader *message)
2140 struct Plugin *plugin = cls;
2141 const struct WelcomeMessage *wm = (const struct WelcomeMessage *) message;
2142 struct Session *session;
2145 struct IPv4TcpAddress *t4;
2146 struct IPv6TcpAddress *t6;
2147 const struct sockaddr_in *s4;
2148 const struct sockaddr_in6 *s6;
2149 struct GNUNET_ATS_Information ats;
2152 memcmp (&wm->clientIdentity, plugin->env->my_identity,
2153 sizeof (struct GNUNET_PeerIdentity)))
2155 /* refuse connections from ourselves */
2156 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2157 if (GNUNET_OK == GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
2159 LOG (GNUNET_ERROR_TYPE_WARNING,
2160 "Received %s message from my own identity `%4s' on address `%s'\n",
2161 "WELCOME", GNUNET_i2s (&wm->clientIdentity), GNUNET_a2s (vaddr, alen));
2162 GNUNET_free (vaddr);
2164 GNUNET_break_op (0);
2167 LOG (GNUNET_ERROR_TYPE_DEBUG,
2168 "Received %s message from `%4s' %p\n", "WELCOME",
2169 GNUNET_i2s (&wm->clientIdentity), client);
2170 GNUNET_STATISTICS_update (plugin->env->stats,
2171 gettext_noop ("# TCP WELCOME messages received"), 1,
2173 session = lookup_session_by_client (plugin, client);
2174 if (session != NULL)
2176 if (GNUNET_OK == GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
2178 LOG (GNUNET_ERROR_TYPE_DEBUG,
2179 "Found existing session %p for peer `%s'\n",
2181 GNUNET_a2s (vaddr, alen));
2182 GNUNET_free (vaddr);
2187 GNUNET_SERVER_client_keep (client);
2188 if (plugin->service != NULL) /* Otherwise value is incremented in tcp_access_check */
2189 plugin->cur_connections++;
2190 if (plugin->cur_connections == plugin->max_connections)
2191 GNUNET_SERVER_suspend (plugin->server); /* Maximum number of connections rechead */
2193 session = create_session (plugin, &wm->clientIdentity, client, GNUNET_NO);
2194 session->inbound = GNUNET_YES;
2195 if (GNUNET_OK == GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
2197 if (alen == sizeof (struct sockaddr_in))
2200 t4 = GNUNET_new (struct IPv4TcpAddress);
2201 t4->options = htonl (0);
2202 t4->t4_port = s4->sin_port;
2203 t4->ipv4_addr = s4->sin_addr.s_addr;
2205 session->addrlen = sizeof (struct IPv4TcpAddress);
2207 else if (alen == sizeof (struct sockaddr_in6))
2210 t6 = GNUNET_new (struct IPv6TcpAddress);
2211 t6->options = htonl (0);
2212 t6->t6_port = s6->sin6_port;
2213 memcpy (&t6->ipv6_addr, &s6->sin6_addr, sizeof (struct in6_addr));
2215 session->addrlen = sizeof (struct IPv6TcpAddress);
2218 ats = plugin->env->get_address_type (plugin->env->cls, vaddr ,alen);
2219 session->ats_address_network_type = (enum GNUNET_ATS_Network_Type) ntohl (ats.value);
2220 LOG (GNUNET_ERROR_TYPE_DEBUG,
2221 "Creating new session %p for peer `%s'\n",
2223 GNUNET_a2s (vaddr, alen));
2224 GNUNET_free (vaddr);
2225 GNUNET_SERVER_client_set_user_context (session->client, session);
2226 GNUNET_CONTAINER_multipeermap_put (plugin->sessionmap,
2229 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2233 LOG (GNUNET_ERROR_TYPE_DEBUG,
2234 "Did not obtain TCP socket address for incoming connection\n");
2239 if (session->expecting_welcome != GNUNET_YES)
2241 GNUNET_break_op (0);
2242 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2246 session->last_activity = GNUNET_TIME_absolute_get ();
2247 session->expecting_welcome = GNUNET_NO;
2249 /* Notify transport and ATS about new session */
2250 if (GNUNET_YES == session->inbound)
2252 plugin->env->session_start (NULL, &wm->clientIdentity, PLUGIN_NAME,
2253 (GNUNET_YES == session->inbound) ? NULL : session->addr,
2254 (GNUNET_YES == session->inbound) ? 0 : session->addrlen,
2258 process_pending_messages (session);
2260 GNUNET_SERVER_client_set_timeout (client,
2261 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
2262 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2267 * Task to signal the server that we can continue
2268 * receiving from the TCP client now.
2270 * @param cls the 'struct Session*'
2271 * @param tc task context (unused)
2274 delayed_done (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2276 struct Session *session = cls;
2278 session->receive_delay_task = GNUNET_SCHEDULER_NO_TASK;
2279 reschedule_session_timeout (session);
2281 GNUNET_SERVER_receive_done (session->client, GNUNET_OK);
2286 * We've received data for this peer via TCP. Unbox,
2287 * compute latency and forward.
2289 * @param cls closure
2290 * @param client identification of the client
2291 * @param message the actual message
2294 handle_tcp_data (void *cls, struct GNUNET_SERVER_Client *client,
2295 const struct GNUNET_MessageHeader *message)
2297 struct Plugin *plugin = cls;
2298 struct Session *session;
2299 struct GNUNET_TIME_Relative delay;
2302 type = ntohs (message->type);
2303 if ((GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME == type) ||
2304 (GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE == type))
2306 /* We don't want to propagate WELCOME and NAT Probe messages up! */
2307 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2310 session = lookup_session_by_client (plugin, client);
2311 if (NULL == session)
2313 /* No inbound session found */
2317 GNUNET_SERVER_client_get_address (client, &vaddr, &alen);
2318 LOG (GNUNET_ERROR_TYPE_ERROR,
2319 "Received unexpected %u bytes of type %u from `%s'\n",
2320 (unsigned int) ntohs (message->size),
2321 (unsigned int) ntohs (message->type),
2322 GNUNET_a2s(vaddr, alen));
2323 GNUNET_break_op (0);
2324 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2325 GNUNET_free_non_null(vaddr);
2328 else if (GNUNET_YES == session->expecting_welcome)
2330 /* Session is expecting WELCOME message */
2334 GNUNET_SERVER_client_get_address (client, &vaddr, &alen);
2335 LOG (GNUNET_ERROR_TYPE_ERROR,
2336 "Received unexpected %u bytes of type %u from `%s'\n",
2337 (unsigned int) ntohs (message->size),
2338 (unsigned int) ntohs (message->type),
2339 GNUNET_a2s(vaddr, alen));
2340 GNUNET_break_op (0);
2341 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2342 GNUNET_free_non_null(vaddr);
2346 session->last_activity = GNUNET_TIME_absolute_get ();
2347 LOG (GNUNET_ERROR_TYPE_DEBUG,
2348 "Passing %u bytes of type %u from `%4s' to transport service.\n",
2349 (unsigned int) ntohs (message->size),
2350 (unsigned int) ntohs (message->type),
2351 GNUNET_i2s (&session->target));
2353 GNUNET_STATISTICS_update (plugin->env->stats,
2354 gettext_noop ("# bytes received via TCP"),
2355 ntohs (message->size), GNUNET_NO);
2356 struct GNUNET_ATS_Information distance;
2358 distance.type = htonl (GNUNET_ATS_NETWORK_TYPE);
2359 distance.value = htonl ((uint32_t) session->ats_address_network_type);
2360 GNUNET_break (session->ats_address_network_type != GNUNET_ATS_NET_UNSPECIFIED);
2362 GNUNET_assert (GNUNET_CONTAINER_multipeermap_contains_value (plugin->sessionmap,
2366 delay = plugin->env->receive (plugin->env->cls,
2370 (GNUNET_YES == session->inbound) ? NULL : session->addr,
2371 (GNUNET_YES == session->inbound) ? 0 : session->addrlen);
2372 plugin->env->update_address_metrics (plugin->env->cls,
2374 (GNUNET_YES == session->inbound) ? NULL : session->addr,
2375 (GNUNET_YES == session->inbound) ? 0 : session->addrlen,
2376 session, &distance, 1);
2377 reschedule_session_timeout (session);
2378 if (0 == delay.rel_value_us)
2380 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2384 LOG (GNUNET_ERROR_TYPE_DEBUG,
2385 "Throttling receiving from `%s' for %s\n",
2386 GNUNET_i2s (&session->target),
2387 GNUNET_STRINGS_relative_time_to_string (delay, GNUNET_YES));
2388 GNUNET_SERVER_disable_receive_done_warning (client);
2389 session->receive_delay_task =
2390 GNUNET_SCHEDULER_add_delayed (delay, &delayed_done, session);
2396 * Functions with this signature are called whenever a peer
2397 * is disconnected on the network level.
2399 * @param cls closure
2400 * @param client identification of the client
2403 disconnect_notify (void *cls, struct GNUNET_SERVER_Client *client)
2405 struct Plugin *plugin = cls;
2406 struct Session *session;
2410 session = lookup_session_by_client (plugin, client);
2411 if (session == NULL)
2412 return; /* unknown, nothing to do */
2413 LOG (GNUNET_ERROR_TYPE_DEBUG,
2414 "Destroying session of `%4s' with %s due to network-level disconnect.\n",
2415 GNUNET_i2s (&session->target),
2417 NULL) ? tcp_address_to_string (session->plugin,
2422 if (plugin->cur_connections == plugin->max_connections)
2423 GNUNET_SERVER_resume (plugin->server); /* Resume server */
2425 if (plugin->cur_connections < 1)
2428 plugin->cur_connections--;
2430 GNUNET_STATISTICS_update (session->plugin->env->stats,
2432 ("# network-level TCP disconnect events"), 1,
2434 tcp_disconnect_session (plugin, session);
2439 * We can now send a probe message, copy into buffer to really send.
2441 * @param cls closure, a struct TCPProbeContext
2442 * @param size max size to copy
2443 * @param buf buffer to copy message to
2444 * @return number of bytes copied into buf
2447 notify_send_probe (void *cls, size_t size, void *buf)
2449 struct TCPProbeContext *tcp_probe_ctx = cls;
2450 struct Plugin *plugin = tcp_probe_ctx->plugin;
2453 tcp_probe_ctx->transmit_handle = NULL;
2454 GNUNET_CONTAINER_DLL_remove (plugin->probe_head, plugin->probe_tail,
2458 GNUNET_CONNECTION_destroy (tcp_probe_ctx->sock);
2459 GNUNET_free (tcp_probe_ctx);
2462 GNUNET_assert (size >= sizeof (tcp_probe_ctx->message));
2463 memcpy (buf, &tcp_probe_ctx->message, sizeof (tcp_probe_ctx->message));
2464 GNUNET_SERVER_connect_socket (tcp_probe_ctx->plugin->server,
2465 tcp_probe_ctx->sock);
2466 ret = sizeof (tcp_probe_ctx->message);
2467 GNUNET_free (tcp_probe_ctx);
2473 * Function called by the NAT subsystem suggesting another peer wants
2474 * to connect to us via connection reversal. Try to connect back to the
2477 * @param cls closure
2478 * @param addr address to try
2479 * @param addrlen number of bytes in @a addr
2482 try_connection_reversal (void *cls, const struct sockaddr *addr,
2485 struct Plugin *plugin = cls;
2486 struct GNUNET_CONNECTION_Handle *sock;
2487 struct TCPProbeContext *tcp_probe_ctx;
2490 * We have received an ICMP response, ostensibly from a peer
2491 * that wants to connect to us! Send a message to establish a connection.
2493 sock = GNUNET_CONNECTION_create_from_sockaddr (AF_INET, addr, addrlen);
2496 /* failed for some odd reason (out of sockets?); ignore attempt */
2500 /* FIXME: do we need to track these probe context objects so that
2501 * we can clean them up on plugin unload? */
2502 tcp_probe_ctx = GNUNET_malloc (sizeof (struct TCPProbeContext));
2503 tcp_probe_ctx->message.header.size =
2504 htons (sizeof (struct TCP_NAT_ProbeMessage));
2505 tcp_probe_ctx->message.header.type =
2506 htons (GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE);
2507 memcpy (&tcp_probe_ctx->message.clientIdentity, plugin->env->my_identity,
2508 sizeof (struct GNUNET_PeerIdentity));
2509 tcp_probe_ctx->plugin = plugin;
2510 tcp_probe_ctx->sock = sock;
2511 GNUNET_CONTAINER_DLL_insert (plugin->probe_head, plugin->probe_tail,
2513 tcp_probe_ctx->transmit_handle =
2514 GNUNET_CONNECTION_notify_transmit_ready (sock,
2515 ntohs (tcp_probe_ctx->
2516 message.header.size),
2517 GNUNET_TIME_UNIT_FOREVER_REL,
2525 * Function obtain the network type for a session
2527 * @param cls closure ('struct Plugin*')
2528 * @param session the session
2529 * @return the network type in HBO or #GNUNET_SYSERR
2531 static enum GNUNET_ATS_Network_Type
2532 tcp_get_network (void *cls,
2533 struct Session *session)
2535 GNUNET_assert (NULL != session);
2536 return session->ats_address_network_type;
2541 * Entry point for the plugin.
2543 * @param cls closure, the 'struct GNUNET_TRANSPORT_PluginEnvironment*'
2544 * @return the 'struct GNUNET_TRANSPORT_PluginFunctions*' or NULL on error
2547 libgnunet_plugin_transport_tcp_init (void *cls)
2549 static const struct GNUNET_SERVER_MessageHandler my_handlers[] = {
2550 {&handle_tcp_welcome, NULL, GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME,
2551 sizeof (struct WelcomeMessage)},
2552 {&handle_tcp_nat_probe, NULL, GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE,
2553 sizeof (struct TCP_NAT_ProbeMessage)},
2554 {&handle_tcp_data, NULL, GNUNET_MESSAGE_TYPE_ALL, 0},
2557 struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
2558 struct GNUNET_TRANSPORT_PluginFunctions *api;
2559 struct Plugin *plugin;
2560 struct GNUNET_SERVICE_Context *service;
2561 unsigned long long aport;
2562 unsigned long long bport;
2563 unsigned long long max_connections;
2565 struct GNUNET_TIME_Relative idle_timeout;
2568 struct sockaddr **addrs;
2569 socklen_t *addrlens;
2572 if (NULL == env->receive)
2574 /* run in 'stub' mode (i.e. as part of gnunet-peerinfo), don't fully
2575 initialze the plugin or the API */
2576 api = GNUNET_new (struct GNUNET_TRANSPORT_PluginFunctions);
2578 api->address_pretty_printer = &tcp_plugin_address_pretty_printer;
2579 api->address_to_string = &tcp_address_to_string;
2580 api->string_to_address = &tcp_string_to_address;
2584 GNUNET_assert (NULL != env->cfg);
2586 GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-tcp",
2589 max_connections = 128;
2593 GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-tcp", "PORT",
2594 &bport)) || (bport > 65535) ||
2596 GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-tcp",
2597 "ADVERTISED-PORT", &aport)) &&
2600 LOG (GNUNET_ERROR_TYPE_ERROR,
2601 _("Require valid port number for service `%s' in configuration!\n"),
2611 service = GNUNET_SERVICE_start ("transport-tcp", env->cfg, GNUNET_SERVICE_OPTION_NONE);
2612 if (service == NULL)
2614 LOG (GNUNET_ERROR_TYPE_WARNING,
2615 _("Failed to start service.\n"));
2622 /* Initialize my flags */
2625 plugin = GNUNET_new (struct Plugin);
2626 plugin->sessionmap = GNUNET_CONTAINER_multipeermap_create (max_connections, GNUNET_YES);
2627 plugin->max_connections = max_connections;
2628 plugin->cur_connections = 0;
2629 plugin->open_port = bport;
2630 plugin->adv_port = aport;
2632 plugin->lsock = NULL;
2633 if ((service != NULL) &&
2636 GNUNET_SERVICE_get_server_addresses ("transport-tcp", env->cfg, &addrs,
2639 for (ret = ret_s-1; ret >= 0; ret--)
2640 LOG (GNUNET_ERROR_TYPE_INFO,
2641 "Binding to address `%s'\n",
2642 GNUNET_a2s (addrs[ret], addrlens[ret]));
2644 GNUNET_NAT_register (env->cfg, GNUNET_YES, aport, (unsigned int) ret_s,
2645 (const struct sockaddr **) addrs, addrlens,
2646 &tcp_nat_port_map_callback,
2647 &try_connection_reversal, plugin);
2648 for (ret = ret_s -1; ret >= 0; ret--)
2650 GNUNET_assert (addrs[ret] != NULL);
2651 GNUNET_free (addrs[ret]);
2653 GNUNET_free_non_null (addrs);
2654 GNUNET_free_non_null (addrlens);
2658 plugin->nat = GNUNET_NAT_register (plugin->env->cfg,
2659 GNUNET_YES, 0, 0, NULL, NULL, NULL,
2660 &try_connection_reversal, plugin);
2662 api = GNUNET_new (struct GNUNET_TRANSPORT_PluginFunctions);
2664 api->send = &tcp_plugin_send;
2665 api->get_session = &tcp_plugin_get_session;
2667 api->disconnect_session = &tcp_disconnect_session;
2668 api->disconnect_peer = &tcp_plugin_disconnect;
2669 api->address_pretty_printer = &tcp_plugin_address_pretty_printer;
2670 api->check_address = &tcp_plugin_check_address;
2671 api->address_to_string = &tcp_address_to_string;
2672 api->string_to_address = &tcp_string_to_address;
2673 api->get_network = &tcp_get_network;
2674 plugin->service = service;
2675 if (NULL != service)
2677 plugin->server = GNUNET_SERVICE_get_server (service);
2682 GNUNET_CONFIGURATION_get_value_time (env->cfg, "transport-tcp",
2683 "TIMEOUT", &idle_timeout))
2685 GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
2686 "transport-tcp", "TIMEOUT");
2687 if (plugin->nat != NULL)
2688 GNUNET_NAT_unregister (plugin->nat);
2689 GNUNET_free (plugin);
2694 GNUNET_SERVER_create_with_sockets (&plugin_tcp_access_check, plugin,
2695 NULL, idle_timeout, GNUNET_YES);
2697 plugin->handlers = GNUNET_malloc (sizeof (my_handlers));
2698 memcpy (plugin->handlers, my_handlers, sizeof (my_handlers));
2700 i < sizeof (my_handlers) / sizeof (struct GNUNET_SERVER_MessageHandler);
2702 plugin->handlers[i].callback_cls = plugin;
2704 GNUNET_SERVER_add_handlers (plugin->server, plugin->handlers);
2705 GNUNET_SERVER_disconnect_notify (plugin->server, &disconnect_notify, plugin);
2706 plugin->nat_wait_conns = GNUNET_CONTAINER_multipeermap_create (16, GNUNET_YES);
2708 LOG (GNUNET_ERROR_TYPE_INFO,
2709 _("TCP transport listening on port %llu\n"), bport);
2711 LOG (GNUNET_ERROR_TYPE_INFO,
2712 _("TCP transport not listening on any port (client only)\n"));
2714 LOG (GNUNET_ERROR_TYPE_INFO,
2715 _("TCP transport advertises itself as being on port %llu\n"),
2717 /* Initially set connections to 0 */
2718 GNUNET_assert (NULL != plugin->env->stats);
2719 GNUNET_STATISTICS_set (plugin->env->stats,
2720 gettext_noop ("# TCP sessions active"), 0,
2727 * Exit point from the plugin.
2730 libgnunet_plugin_transport_tcp_done (void *cls)
2732 struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
2733 struct Plugin *plugin = api->cls;
2734 struct TCPProbeContext *tcp_probe;
2735 struct PrettyPrinterContext *cur;
2736 struct PrettyPrinterContext *next;
2743 LOG (GNUNET_ERROR_TYPE_DEBUG,
2744 "Shutting down TCP plugin\n");
2746 /* Removing leftover sessions */
2747 GNUNET_CONTAINER_multipeermap_iterate (plugin->sessionmap,
2748 &session_disconnect_it, plugin);
2749 /* Removing leftover NAT sessions */
2750 GNUNET_CONTAINER_multipeermap_iterate (plugin->nat_wait_conns,
2751 &session_disconnect_it, plugin);
2753 next = ppc_dll_head;
2754 for (cur = next; NULL != cur; cur = next)
2757 GNUNET_CONTAINER_DLL_remove (ppc_dll_head, ppc_dll_tail, cur);
2758 if (NULL != cur->resolver_handle)
2759 GNUNET_RESOLVER_request_cancel (cur->resolver_handle);
2760 GNUNET_SCHEDULER_cancel (cur->timeout_task);
2765 if (plugin->service != NULL)
2766 GNUNET_SERVICE_stop (plugin->service);
2768 GNUNET_SERVER_destroy (plugin->server);
2769 GNUNET_free (plugin->handlers);
2770 if (plugin->nat != NULL)
2771 GNUNET_NAT_unregister (plugin->nat);
2772 while (NULL != (tcp_probe = plugin->probe_head))
2774 GNUNET_CONTAINER_DLL_remove (plugin->probe_head, plugin->probe_tail,
2776 GNUNET_CONNECTION_destroy (tcp_probe->sock);
2777 GNUNET_free (tcp_probe);
2779 GNUNET_CONTAINER_multipeermap_destroy (plugin->nat_wait_conns);
2780 GNUNET_CONTAINER_multipeermap_destroy (plugin->sessionmap);
2781 GNUNET_free (plugin);
2786 /* end of plugin_transport_tcp.c */