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)
50 GNUNET_NETWORK_STRUCT_BEGIN
55 static uint32_t myoptions;
58 * Initial handshake message for a session.
63 * Type is #GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME.
65 struct GNUNET_MessageHeader header;
68 * Identity of the node connecting (TCP client)
70 struct GNUNET_PeerIdentity clientIdentity;
75 * Basically a WELCOME message, but with the purpose
76 * of giving the waiting peer a client handle to use
78 struct TCP_NAT_ProbeMessage
81 * Type is #GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE.
83 struct GNUNET_MessageHeader header;
86 * Identity of the sender of the message.
88 struct GNUNET_PeerIdentity clientIdentity;
91 GNUNET_NETWORK_STRUCT_END
94 * Context for sending a NAT probe via TCP.
96 struct TCPProbeContext
100 * Active probes are kept in a DLL.
102 struct TCPProbeContext *next;
105 * Active probes are kept in a DLL.
107 struct TCPProbeContext *prev;
112 struct GNUNET_CONNECTION_Handle *sock;
115 * Message to be sent.
117 struct TCP_NAT_ProbeMessage message;
120 * Handle to the transmission.
122 struct GNUNET_CONNECTION_TransmitHandle *transmit_handle;
125 * Transport plugin handle.
127 struct Plugin *plugin;
130 GNUNET_NETWORK_STRUCT_BEGIN
133 * Network format for IPv4 addresses.
135 struct IPv4TcpAddress
138 * Optional options and flags for this address
143 * IPv4 address, in network byte order.
145 uint32_t ipv4_addr GNUNET_PACKED;
148 * Port number, in network byte order.
150 uint16_t t4_port GNUNET_PACKED;
155 * Network format for IPv6 addresses.
157 struct IPv6TcpAddress
160 * Optional flags for this address
167 struct in6_addr ipv6_addr GNUNET_PACKED;
170 * Port number, in network byte order.
172 uint16_t t6_port GNUNET_PACKED;
175 GNUNET_NETWORK_STRUCT_END
178 * Encapsulation of all of the state of the plugin.
183 * Information kept for each message that is yet to
186 struct PendingMessage
190 * This is a doubly-linked list.
192 struct PendingMessage *next;
195 * This is a doubly-linked list.
197 struct PendingMessage *prev;
200 * The pending message
205 * Continuation function to call once the message
206 * has been sent. Can be NULL if there is no
207 * continuation to call.
209 GNUNET_TRANSPORT_TransmitContinuation transmit_cont;
212 * Closure for transmit_cont.
214 void *transmit_cont_cls;
217 * Timeout value for the pending message.
219 struct GNUNET_TIME_Absolute timeout;
222 * So that the gnunet-service-transport can group messages together,
223 * these pending messages need to accept a message buffer and size
224 * instead of just a GNUNET_MessageHeader.
231 * Session handle for TCP connections.
236 * To whom are we talking to (set to our identity
237 * if we are still waiting for the welcome message)
239 struct GNUNET_PeerIdentity target;
244 struct SessionHeader header;
247 * Pointer to the global plugin struct.
249 struct Plugin *plugin;
252 * The client (used to identify this connection)
254 struct GNUNET_SERVER_Client *client;
257 * Task cleaning up a NAT client connection establishment attempt;
259 GNUNET_SCHEDULER_TaskIdentifier nat_connection_timeout;
262 * Messages currently pending for transmission
263 * to this peer, if any.
265 struct PendingMessage *pending_messages_head;
268 * Messages currently pending for transmission
269 * to this peer, if any.
271 struct PendingMessage *pending_messages_tail;
274 * Handle for pending transmission request.
276 struct GNUNET_SERVER_TransmitHandle *transmit_handle;
279 * ID of task used to delay receiving more to throttle sender.
281 GNUNET_SCHEDULER_TaskIdentifier receive_delay_task;
284 * Session timeout task
286 GNUNET_SCHEDULER_TaskIdentifier timeout_task;
288 struct GNUNET_HELLO_Address *address;
291 * Address of the other peer (either based on our 'connect'
292 * call or on our 'accept' call).
294 * struct IPv4TcpAddress or struct IPv6TcpAddress
302 * Last activity on this connection. Used to select preferred
305 struct GNUNET_TIME_Absolute last_activity;
308 * Are we still expecting the welcome message? (#GNUNET_YES/#GNUNET_NO)
310 int expecting_welcome;
313 * Was this session created using NAT traversal?
318 * ATS network type in NBO
320 enum GNUNET_ATS_Network_Type ats_address_network_type;
324 * Encapsulation of all of the state of the plugin.
331 struct GNUNET_TRANSPORT_PluginEnvironment *env;
336 struct GNUNET_CONNECTION_Handle *lsock;
339 * Our handle to the NAT module.
341 struct GNUNET_NAT_Handle *nat;
344 * Map from peer identities to sessions for the given peer.
346 struct GNUNET_CONTAINER_MultiPeerMap *sessionmap;
349 * Handle to the network service.
351 struct GNUNET_SERVICE_Context *service;
354 * Handle to the server for this service.
356 struct GNUNET_SERVER_Handle *server;
359 * Copy of the handler array where the closures are
360 * set to this struct's instance.
362 struct GNUNET_SERVER_MessageHandler *handlers;
365 * Map of peers we have tried to contact behind a NAT
367 struct GNUNET_CONTAINER_MultiPeerMap *nat_wait_conns;
370 * List of active TCP probes.
372 struct TCPProbeContext *probe_head;
375 * List of active TCP probes.
377 struct TCPProbeContext *probe_tail;
380 * Handle for (DYN)DNS lookup of our external IP.
382 struct GNUNET_RESOLVER_RequestHandle *ext_dns;
385 * How many more TCP sessions are we allowed to open right now?
387 unsigned long long max_connections;
390 * How many more TCP sessions do we have right now?
392 unsigned long long cur_connections;
395 * ID of task used to update our addresses when one expires.
397 GNUNET_SCHEDULER_TaskIdentifier address_update_task;
400 * Port that we are actually listening on.
405 * Port that the user said we would have visible to the
413 * Function called for a quick conversion of the binary address to
414 * a numeric address. Note that the caller must not free the
415 * address and that the next call to this function is allowed
416 * to override the address again.
418 * @param cls closure ('struct Plugin*')
419 * @param addr binary address
420 * @param addrlen length of the address
421 * @return string representing the same address
424 tcp_address_to_string (void *cls, const void *addr, size_t addrlen);
427 * Function to check if an inbound connection is acceptable.
428 * Mostly used to limit the total number of open connections
431 * @param cls the `struct Plugin`
432 * @param ucred credentials, if available, otherwise NULL
433 * @param addr address
434 * @param addrlen length of address
435 * @return #GNUNET_YES to allow, #GNUNET_NO to deny, #GNUNET_SYSERR
436 * for unknown address family (will be denied).
439 plugin_tcp_access_check (void *cls,
440 const struct GNUNET_CONNECTION_Credentials *ucred,
441 const struct sockaddr *addr, socklen_t addrlen)
443 struct Plugin *plugin = cls;
444 LOG(GNUNET_ERROR_TYPE_DEBUG,
445 "Accepting new incoming TCP connection from `%s'\n",
446 GNUNET_a2s (addr, addrlen));
447 if (plugin->cur_connections >= plugin->max_connections)
449 plugin->cur_connections++;
454 * Our external IP address/port mapping has changed.
456 * @param cls closure, the 'struct Plugin'
457 * @param add_remove #GNUNET_YES to mean the new public IP address, #GNUNET_NO to mean
458 * the previous (now invalid) one
459 * @param addr either the previous or the new public IP address
460 * @param addrlen actual lenght of the address
463 tcp_nat_port_map_callback (void *cls, int add_remove,
464 const struct sockaddr *addr, socklen_t addrlen)
466 struct Plugin *plugin = cls;
467 struct GNUNET_HELLO_Address *address;
468 struct IPv4TcpAddress t4;
469 struct IPv6TcpAddress t6;
473 LOG(GNUNET_ERROR_TYPE_INFO, "NAT notification to %s address `%s'\n",
474 (GNUNET_YES == add_remove) ? "add" : "remove",
475 GNUNET_a2s (addr, addrlen));
476 /* convert 'addr' to our internal format */
477 switch (addr->sa_family)
480 GNUNET_assert(addrlen == sizeof(struct sockaddr_in));
481 memset (&t4, 0, sizeof(t4));
482 t4.options = htonl (myoptions);
483 t4.ipv4_addr = ((struct sockaddr_in *) addr)->sin_addr.s_addr;
484 t4.t4_port = ((struct sockaddr_in *) addr)->sin_port;
489 GNUNET_assert(addrlen == sizeof(struct sockaddr_in6));
490 memset (&t6, 0, sizeof(t6));
491 memcpy (&t6.ipv6_addr, &((struct sockaddr_in6 *) addr)->sin6_addr,
492 sizeof(struct in6_addr));
493 t6.options = htonl (myoptions);
494 t6.t6_port = ((struct sockaddr_in6 *) addr)->sin6_port;
502 /* modify our published address list */
503 address = GNUNET_HELLO_address_allocate (plugin->env->my_identity,
504 PLUGIN_NAME, arg, args, GNUNET_HELLO_ADDRESS_INFO_NONE);
505 plugin->env->notify_address (plugin->env->cls, add_remove, address);
506 GNUNET_HELLO_address_free(address);
510 * Function called for a quick conversion of the binary address to
511 * a numeric address. Note that the caller must not free the
512 * address and that the next call to this function is allowed
513 * to override the address again.
515 * @param cls closure (`struct Plugin*`)
516 * @param addr binary address
517 * @param addrlen length of the address
518 * @return string representing the same address
521 tcp_address_to_string (void *cls, const void *addr, size_t addrlen)
523 static char rbuf[INET6_ADDRSTRLEN + 12];
524 char buf[INET6_ADDRSTRLEN];
528 const struct IPv4TcpAddress *t4;
529 const struct IPv6TcpAddress *t6;
536 case sizeof(struct IPv6TcpAddress):
539 port = ntohs (t6->t6_port);
540 options = ntohl (t6->options);
541 memcpy (&a6, &t6->ipv6_addr, sizeof(a6));
544 case sizeof(struct IPv4TcpAddress):
547 port = ntohs (t4->t4_port);
548 options = ntohl (t4->options);
549 memcpy (&a4, &t4->ipv4_addr, sizeof(a4));
554 GNUNET_snprintf (rbuf, sizeof(rbuf), "%s",
555 TRANSPORT_SESSION_INBOUND_STRING);
559 LOG(GNUNET_ERROR_TYPE_WARNING, _("Unexpected address length: %u bytes\n"),
560 (unsigned int ) addrlen);
563 if (NULL == inet_ntop (af, sb, buf, INET6_ADDRSTRLEN))
565 GNUNET_log_strerror(GNUNET_ERROR_TYPE_WARNING, "inet_ntop");
568 GNUNET_snprintf (rbuf, sizeof(rbuf),
569 (af == AF_INET6) ? "%s.%u.[%s]:%u" : "%s.%u.%s:%u", PLUGIN_NAME, options,
575 * Function called to convert a string address to
578 * @param cls closure (`struct Plugin*`)
579 * @param addr string address
580 * @param addrlen length of the address
581 * @param buf location to store the buffer
582 * @param added location to store the number of bytes in the buffer.
583 * If the function returns #GNUNET_SYSERR, its contents are undefined.
584 * @return #GNUNET_OK on success, #GNUNET_SYSERR on failure
587 tcp_string_to_address (void *cls, const char *addr, uint16_t addrlen,
588 void **buf, size_t *added)
590 struct sockaddr_storage socket_address;
596 /* Format tcp.options.address:port */
600 if ((NULL == addr) || (addrlen == 0))
603 return GNUNET_SYSERR;
605 if ('\0' != addr[addrlen - 1])
608 return GNUNET_SYSERR;
610 if (strlen (addr) != addrlen - 1)
613 return GNUNET_SYSERR;
615 plugin = GNUNET_strdup (addr);
616 optionstr = strchr (plugin, '.');
617 if (NULL == optionstr)
621 return GNUNET_SYSERR;
625 options = atol (optionstr);
626 address = strchr (optionstr, '.');
631 return GNUNET_SYSERR;
637 != GNUNET_STRINGS_to_address_ip (address, strlen (address),
642 return GNUNET_SYSERR;
646 switch (socket_address.ss_family)
650 struct IPv4TcpAddress *t4;
651 struct sockaddr_in *in4 = (struct sockaddr_in *) &socket_address;
652 t4 = GNUNET_new (struct IPv4TcpAddress);
653 t4->options = htonl (options);
654 t4->ipv4_addr = in4->sin_addr.s_addr;
655 t4->t4_port = in4->sin_port;
657 *added = sizeof(struct IPv4TcpAddress);
662 struct IPv6TcpAddress *t6;
663 struct sockaddr_in6 *in6 = (struct sockaddr_in6 *) &socket_address;
664 t6 = GNUNET_new (struct IPv6TcpAddress);
665 t6->options = htonl (options);
666 t6->ipv6_addr = in6->sin6_addr;
667 t6->t6_port = in6->sin6_port;
669 *added = sizeof(struct IPv6TcpAddress);
673 return GNUNET_SYSERR;
678 * Closure for #session_lookup_by_client_it().
680 struct SessionClientCtx
683 * Client we are looking for.
685 const struct GNUNET_SERVER_Client *client;
688 * Session that was found.
694 session_lookup_by_client_it (void *cls, const struct GNUNET_PeerIdentity *key,
697 struct SessionClientCtx *sc_ctx = cls;
698 struct Session *s = value;
700 if (s->client == sc_ctx->client)
709 * Find the session handle for the given client.
710 * Currently uses both the hashmap and the client
711 * context, as the client context is new and the
712 * logic still needs to be tested.
714 * @param plugin the plugin
715 * @param client which client to find the session handle for
716 * @return NULL if no matching session exists
718 static struct Session *
719 lookup_session_by_client (struct Plugin *plugin,
720 struct GNUNET_SERVER_Client *client)
723 struct SessionClientCtx sc_ctx;
725 ret = GNUNET_SERVER_client_get_user_context (client, struct Session);
726 sc_ctx.client = client;
728 GNUNET_CONTAINER_multipeermap_iterate (plugin->sessionmap,
729 &session_lookup_by_client_it, &sc_ctx);
730 /* check both methods yield the same result */
731 GNUNET_break(ret == sc_ctx.ret);
736 * Functions with this signature are called whenever we need
737 * to close a session due to a disconnect or failure to
738 * establish a connection.
740 * @param cls the `struct Plugin`
741 * @param session session to close down
742 * @return #GNUNET_OK on success
745 tcp_disconnect_session (void *cls, struct Session *session)
747 struct Plugin *plugin = cls;
748 struct PendingMessage *pm;
750 LOG(GNUNET_ERROR_TYPE_DEBUG,
751 "Disconnecting session of peer `%s' address `%s'\n",
752 GNUNET_i2s (&session->target),
753 tcp_address_to_string (NULL, session->address->address, session->address->address_length));
755 if (GNUNET_SCHEDULER_NO_TASK != session->timeout_task)
757 GNUNET_SCHEDULER_cancel (session->timeout_task);
758 session->timeout_task = GNUNET_SCHEDULER_NO_TASK;
762 == GNUNET_CONTAINER_multipeermap_remove (plugin->sessionmap,
763 &session->target, session))
765 GNUNET_STATISTICS_update (session->plugin->env->stats,
766 gettext_noop ("# TCP sessions active"), -1, GNUNET_NO);
771 GNUNET_YES == GNUNET_CONTAINER_multipeermap_remove (plugin->nat_wait_conns, &session->target, session));
773 if (NULL != session->client)
774 GNUNET_SERVER_client_set_user_context(session->client, (void *) NULL);
777 if (NULL != session->transmit_handle)
779 GNUNET_SERVER_notify_transmit_ready_cancel (session->transmit_handle);
780 session->transmit_handle = NULL;
782 session->plugin->env->session_end (session->plugin->env->cls,
783 &session->target, session);
785 if (GNUNET_SCHEDULER_NO_TASK != session->nat_connection_timeout)
787 GNUNET_SCHEDULER_cancel (session->nat_connection_timeout);
788 session->nat_connection_timeout = GNUNET_SCHEDULER_NO_TASK;
791 while (NULL != (pm = session->pending_messages_head))
793 LOG(GNUNET_ERROR_TYPE_DEBUG,
794 pm->transmit_cont != NULL ? "Could not deliver message to `%4s'.\n" : "Could not deliver message to `%4s', notifying.\n",
795 GNUNET_i2s (&session->target));
796 GNUNET_STATISTICS_update (session->plugin->env->stats,
797 gettext_noop ("# bytes currently in TCP buffers"),
798 -(int64_t) pm->message_size, GNUNET_NO);
799 GNUNET_STATISTICS_update (session->plugin->env->stats, gettext_noop
800 ("# bytes discarded by TCP (disconnect)"), pm->message_size, GNUNET_NO);
801 GNUNET_CONTAINER_DLL_remove(session->pending_messages_head,
802 session->pending_messages_tail, pm);
803 if (NULL != pm->transmit_cont)
804 pm->transmit_cont (pm->transmit_cont_cls, &session->target, GNUNET_SYSERR,
805 pm->message_size, 0);
808 if (session->receive_delay_task != GNUNET_SCHEDULER_NO_TASK )
810 GNUNET_SCHEDULER_cancel (session->receive_delay_task);
811 if (NULL != session->client)
812 GNUNET_SERVER_receive_done (session->client, GNUNET_SYSERR);
814 if (NULL != session->client)
816 GNUNET_SERVER_client_disconnect (session->client);
817 GNUNET_SERVER_client_drop (session->client);
818 session->client = NULL;
820 GNUNET_HELLO_address_free(session->address);
821 GNUNET_assert(NULL == session->transmit_handle);
822 GNUNET_free(session);
827 * Function that is called to get the keepalive factor.
828 * GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT is divided by this number to
829 * calculate the interval between keepalive packets.
831 * @param cls closure with the `struct Plugin`
832 * @return keepalive factor
835 tcp_query_keepalive_factor (void *cls)
841 * Session was idle, so disconnect it
843 * @param cls the `struct Session` of the idle session
844 * @param tc scheduler context
847 session_timeout (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
849 struct Session *s = cls;
851 s->timeout_task = GNUNET_SCHEDULER_NO_TASK;
852 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
853 "Session %p was idle for %s, disconnecting\n", s,
854 GNUNET_STRINGS_relative_time_to_string (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, GNUNET_YES));
855 /* call session destroy function */
856 tcp_disconnect_session (s->plugin, s);
860 * Increment session timeout due to activity
862 * @param s session to increment timeout for
865 reschedule_session_timeout (struct Session *s)
867 GNUNET_assert(GNUNET_SCHEDULER_NO_TASK != s->timeout_task);
868 GNUNET_SCHEDULER_cancel (s->timeout_task);
869 s->timeout_task = GNUNET_SCHEDULER_add_delayed (
870 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, &session_timeout, s);
871 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
872 "Timeout rescheduled for session %p set to %s\n", s,
873 GNUNET_STRINGS_relative_time_to_string (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, GNUNET_YES));
877 * Create a new session. Also queues a welcome message.
879 * @param plugin the plugin
880 * @param target peer to connect to
881 * @param client client to use, reference counter must have already been increased
882 * @param is_nat this a NAT session, we should wait for a client to
883 * connect to us from an address, then assign that to
885 * @return new session object
887 static struct Session *
888 create_session (struct Plugin *plugin, const struct GNUNET_PeerIdentity *target,
889 struct GNUNET_SERVER_Client *client, int is_nat)
891 struct Session *session;
892 struct PendingMessage *pm;
893 struct WelcomeMessage welcome;
895 if (GNUNET_YES != is_nat)
896 GNUNET_assert(NULL != client);
898 GNUNET_assert(NULL == client);
900 LOG(GNUNET_ERROR_TYPE_DEBUG, "Creating new session for peer `%4s'\n",
901 GNUNET_i2s (target));
902 session = GNUNET_new (struct Session);
903 session->last_activity = GNUNET_TIME_absolute_get ();
904 session->plugin = plugin;
905 session->is_nat = is_nat;
906 session->client = client;
907 session->target = *target;
908 session->expecting_welcome = GNUNET_YES;
909 session->ats_address_network_type = GNUNET_ATS_NET_UNSPECIFIED;
910 pm = GNUNET_malloc (sizeof (struct PendingMessage) +
911 sizeof (struct WelcomeMessage));
912 pm->msg = (const char *) &pm[1];
913 pm->message_size = sizeof(struct WelcomeMessage);
914 welcome.header.size = htons (sizeof(struct WelcomeMessage));
915 welcome.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME);
916 welcome.clientIdentity = *plugin->env->my_identity;
917 memcpy (&pm[1], &welcome, sizeof(welcome));
918 pm->timeout = GNUNET_TIME_UNIT_FOREVER_ABS;
919 GNUNET_STATISTICS_update (plugin->env->stats,
920 gettext_noop ("# bytes currently in TCP buffers"), pm->message_size,
922 GNUNET_CONTAINER_DLL_insert(session->pending_messages_head,
923 session->pending_messages_tail, pm);
924 if (GNUNET_YES != is_nat)
926 GNUNET_STATISTICS_update (plugin->env->stats,
927 gettext_noop ("# TCP sessions active"), 1, GNUNET_NO);
929 session->timeout_task = GNUNET_SCHEDULER_add_delayed (
930 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, &session_timeout, session);
935 * If we have pending messages, ask the server to
936 * transmit them (schedule the respective tasks, etc.)
938 * @param session for which session should we do this
941 process_pending_messages (struct Session *session);
944 * Function called to notify a client about the socket
945 * being ready to queue more data. "buf" will be
946 * NULL and "size" zero if the socket was closed for
947 * writing in the meantime.
950 * @param size number of bytes available in buf
951 * @param buf where the callee should write the message
952 * @return number of bytes written to buf
955 do_transmit (void *cls, size_t size, void *buf)
957 struct Session *session = cls;
958 struct GNUNET_PeerIdentity pid;
959 struct Plugin *plugin;
960 struct PendingMessage *pos;
961 struct PendingMessage *hd;
962 struct PendingMessage *tl;
963 struct GNUNET_TIME_Absolute now;
967 session->transmit_handle = NULL;
968 plugin = session->plugin;
971 LOG(GNUNET_ERROR_TYPE_DEBUG,
972 "Timeout trying to transmit to peer `%4s', discarding message queue.\n",
973 GNUNET_i2s (&session->target));
974 /* timeout; cancel all messages that have already expired */
978 now = GNUNET_TIME_absolute_get ();
979 while ((NULL != (pos = session->pending_messages_head))
980 && (pos->timeout.abs_value_us <= now.abs_value_us))
982 GNUNET_CONTAINER_DLL_remove(session->pending_messages_head,
983 session->pending_messages_tail, pos);
984 LOG(GNUNET_ERROR_TYPE_DEBUG,
985 "Failed to transmit %u byte message to `%4s'.\n", pos->message_size,
986 GNUNET_i2s (&session->target));
987 ret += pos->message_size;
988 GNUNET_CONTAINER_DLL_insert_after(hd, tl, tl, pos);
990 /* do this call before callbacks (so that if callbacks destroy
991 * session, they have a chance to cancel actions done by this
993 process_pending_messages (session);
994 pid = session->target;
995 /* no do callbacks and do not use session again since
996 * the callbacks may abort the session */
997 while (NULL != (pos = hd))
999 GNUNET_CONTAINER_DLL_remove(hd, tl, pos);
1000 if (pos->transmit_cont != NULL )
1001 pos->transmit_cont (pos->transmit_cont_cls, &pid, GNUNET_SYSERR,
1002 pos->message_size, 0);
1005 GNUNET_STATISTICS_update (plugin->env->stats,
1006 gettext_noop ("# bytes currently in TCP buffers"), -(int64_t) ret,
1008 GNUNET_STATISTICS_update (plugin->env->stats, gettext_noop
1009 ("# bytes discarded by TCP (timeout)"), ret, GNUNET_NO);
1012 /* copy all pending messages that would fit */
1017 while (NULL != (pos = session->pending_messages_head))
1019 if (ret + pos->message_size > size)
1021 GNUNET_CONTAINER_DLL_remove(session->pending_messages_head,
1022 session->pending_messages_tail, pos);
1023 GNUNET_assert(size >= pos->message_size);
1024 LOG(GNUNET_ERROR_TYPE_DEBUG, "Transmitting message of type %u\n",
1025 ntohs (((struct GNUNET_MessageHeader * ) pos->msg)->type));
1026 /* FIXME: this memcpy can be up to 7% of our total runtime */
1027 memcpy (cbuf, pos->msg, pos->message_size);
1028 cbuf += pos->message_size;
1029 ret += pos->message_size;
1030 size -= pos->message_size;
1031 GNUNET_CONTAINER_DLL_insert_tail(hd, tl, pos);
1033 /* schedule 'continuation' before callbacks so that callbacks that
1034 * cancel everything don't cause us to use a session that no longer
1036 process_pending_messages (session);
1037 session->last_activity = GNUNET_TIME_absolute_get ();
1038 pid = session->target;
1039 /* we'll now call callbacks that may cancel the session; hence
1040 * we should not use 'session' after this point */
1041 while (NULL != (pos = hd))
1043 GNUNET_CONTAINER_DLL_remove(hd, tl, pos);
1044 if (pos->transmit_cont != NULL )
1045 pos->transmit_cont (pos->transmit_cont_cls, &pid, GNUNET_OK,
1046 pos->message_size, pos->message_size); /* FIXME: include TCP overhead */
1049 GNUNET_assert(hd == NULL);
1050 GNUNET_assert(tl == NULL);
1051 LOG(GNUNET_ERROR_TYPE_DEBUG, "Transmitting %u bytes\n", ret);
1052 GNUNET_STATISTICS_update (plugin->env->stats,
1053 gettext_noop ("# bytes currently in TCP buffers"), -(int64_t) ret,
1055 GNUNET_STATISTICS_update (plugin->env->stats,
1056 gettext_noop ("# bytes transmitted via TCP"), ret, GNUNET_NO);
1061 * If we have pending messages, ask the server to
1062 * transmit them (schedule the respective tasks, etc.)
1064 * @param session for which session should we do this
1067 process_pending_messages (struct Session *session)
1069 struct PendingMessage *pm;
1071 GNUNET_assert(NULL != session->client);
1072 if (NULL != session->transmit_handle)
1074 if (NULL == (pm = session->pending_messages_head))
1077 session->transmit_handle = GNUNET_SERVER_notify_transmit_ready (
1078 session->client, pm->message_size,
1079 GNUNET_TIME_absolute_get_remaining (pm->timeout), &do_transmit, session);
1084 * Closure for #session_it().
1086 struct FindSessionContext
1089 * Session we are looking for.
1094 * Set to #GNUNET_OK if we found the session.
1100 * Function called to check if a session is in our maps.
1102 * @param cls the `struct FindSessionContext`
1103 * @param key peer identity
1104 * @param value session in the map
1105 * @return #GNUNET_YES to continue looking, #GNUNET_NO if we found the session
1108 session_it (void *cls, const struct GNUNET_PeerIdentity *key, void *value)
1110 struct FindSessionContext *res = cls;
1111 struct Session *session = value;
1113 if (res->s == session)
1115 res->res = GNUNET_OK;
1122 * Check that the given session is known to the plugin and
1123 * is in one of our maps.
1125 * @param plugin the plugin to check against
1126 * @param session the session to check
1127 * @return #GNUNET_OK if all is well, #GNUNET_SYSERR if the session is invalid
1130 find_session (struct Plugin *plugin, struct Session *session)
1132 struct FindSessionContext session_map_res;
1133 struct FindSessionContext nat_map_res;
1135 session_map_res.s = session;
1136 session_map_res.res = GNUNET_SYSERR;
1137 GNUNET_CONTAINER_multipeermap_iterate (plugin->sessionmap, &session_it,
1139 if (GNUNET_SYSERR != session_map_res.res)
1141 nat_map_res.s = session;
1142 nat_map_res.res = GNUNET_SYSERR;
1143 GNUNET_CONTAINER_multipeermap_iterate (plugin->nat_wait_conns, &session_it,
1145 if (GNUNET_SYSERR != nat_map_res.res)
1148 return GNUNET_SYSERR;
1153 * Function that can be used by the transport service to transmit
1154 * a message using the plugin. Note that in the case of a
1155 * peer disconnecting, the continuation MUST be called
1156 * prior to the disconnect notification itself. This function
1157 * will be called with this peer's HELLO message to initiate
1158 * a fresh connection to another peer.
1160 * @param cls closure
1161 * @param session which session must be used
1162 * @param msgbuf the message to transmit
1163 * @param msgbuf_size number of bytes in 'msgbuf'
1164 * @param priority how important is the message (most plugins will
1165 * ignore message priority and just FIFO)
1166 * @param to how long to wait at most for the transmission (does not
1167 * require plugins to discard the message after the timeout,
1168 * just advisory for the desired delay; most plugins will ignore
1170 * @param cont continuation to call once the message has
1171 * been transmitted (or if the transport is ready
1172 * for the next transmission call; or if the
1173 * peer disconnected...); can be NULL
1174 * @param cont_cls closure for @a cont
1175 * @return number of bytes used (on the physical network, with overheads);
1176 * -1 on hard errors (i.e. address invalid); 0 is a legal value
1177 * and does NOT mean that the message was not transmitted (DV)
1180 tcp_plugin_send (void *cls, struct Session *session, const char *msgbuf,
1181 size_t msgbuf_size, unsigned int priority, struct GNUNET_TIME_Relative to,
1182 GNUNET_TRANSPORT_TransmitContinuation cont, void *cont_cls)
1184 struct Plugin * plugin = cls;
1185 struct PendingMessage *pm;
1188 if (GNUNET_SYSERR == find_session (plugin, session))
1190 LOG(GNUNET_ERROR_TYPE_ERROR, _("Trying to send with invalid session %p\n"));
1192 return GNUNET_SYSERR;
1195 /* create new message entry */
1196 pm = GNUNET_malloc (sizeof (struct PendingMessage) + msgbuf_size);
1197 pm->msg = (const char *) &pm[1];
1198 memcpy (&pm[1], msgbuf, msgbuf_size);
1199 pm->message_size = msgbuf_size;
1200 pm->timeout = GNUNET_TIME_relative_to_absolute (to);
1201 pm->transmit_cont = cont;
1202 pm->transmit_cont_cls = cont_cls;
1204 LOG(GNUNET_ERROR_TYPE_DEBUG,
1205 "Asked to transmit %u bytes to `%s', added message to list.\n",
1206 msgbuf_size, GNUNET_i2s (&session->target));
1209 == GNUNET_CONTAINER_multipeermap_contains_value (plugin->sessionmap,
1210 &session->target, session))
1212 GNUNET_assert(NULL != session->client);
1213 GNUNET_SERVER_client_set_timeout (session->client,
1214 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1215 GNUNET_STATISTICS_update (plugin->env->stats,
1216 gettext_noop ("# bytes currently in TCP buffers"), msgbuf_size,
1219 /* append pm to pending_messages list */
1220 GNUNET_CONTAINER_DLL_insert_tail(session->pending_messages_head,
1221 session->pending_messages_tail, pm);
1223 process_pending_messages (session);
1227 == GNUNET_CONTAINER_multipeermap_contains_value (plugin->nat_wait_conns,
1228 &session->target, session))
1230 LOG(GNUNET_ERROR_TYPE_DEBUG,
1231 "This NAT WAIT session for peer `%s' is not yet ready!\n",
1232 GNUNET_i2s (&session->target));
1233 GNUNET_STATISTICS_update (plugin->env->stats,
1234 gettext_noop ("# bytes currently in TCP buffers"), msgbuf_size,
1237 /* append pm to pending_messages list */
1238 GNUNET_CONTAINER_DLL_insert_tail(session->pending_messages_head,
1239 session->pending_messages_tail, pm);
1244 LOG(GNUNET_ERROR_TYPE_ERROR, "Invalid session %p\n", session);
1246 cont (cont_cls, &session->target, GNUNET_SYSERR, pm->message_size, 0);
1249 return GNUNET_SYSERR; /* session does not exist here */
1254 * Closure for #session_lookup_it().
1259 * Address we are looking for.
1261 const struct GNUNET_HELLO_Address *address;
1264 * Where to store the session (if we found it).
1266 struct Session *result;
1271 * Look for a session by address.
1273 * @param cls the `struct SessionItCtx`
1275 * @param value a `struct Session`
1276 * @return #GNUNET_YES to continue looking, #GNUNET_NO if we found the session
1279 session_lookup_it (void *cls, const struct GNUNET_PeerIdentity *key,
1282 struct SessionItCtx * si_ctx = cls;
1283 struct Session * session = value;
1285 if (0 != GNUNET_HELLO_address_cmp (si_ctx->address, session->address))
1287 /* Found existing session */
1288 si_ctx->result = session;
1293 * Task cleaning up a NAT connection attempt after timeout
1295 * @param cls the `struct Session`
1296 * @param tc scheduler context (unused)
1299 nat_connect_timeout (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1301 struct Session *session = cls;
1303 session->nat_connection_timeout = GNUNET_SCHEDULER_NO_TASK;
1304 LOG(GNUNET_ERROR_TYPE_DEBUG,
1305 "NAT WAIT connection to `%4s' at `%s' could not be established, removing session\n",
1306 GNUNET_i2s (&session->target),
1307 tcp_address_to_string (NULL, session->address->address, session->address->address_length));
1308 tcp_disconnect_session (session->plugin, session);
1312 tcp_plugin_update_session_timeout (void *cls,
1313 const struct GNUNET_PeerIdentity *peer, struct Session *session)
1315 struct Plugin *plugin = cls;
1317 if (GNUNET_SYSERR == find_session (plugin, session))
1319 reschedule_session_timeout (session);
1323 * Create a new session to transmit data to the target
1324 * This session will used to send data to this peer and the plugin will
1325 * notify us by calling the env->session_end function
1327 * @param cls closure
1328 * @param address the address to use
1329 * @return the session if the address is valid, NULL otherwise
1331 static struct Session *
1332 tcp_plugin_get_session (void *cls, const struct GNUNET_HELLO_Address *address)
1334 struct Plugin *plugin = cls;
1335 struct Session *session = NULL;
1339 struct GNUNET_CONNECTION_Handle *sa;
1340 struct sockaddr_in a4;
1341 struct sockaddr_in6 a6;
1342 const struct IPv4TcpAddress *t4;
1343 const struct IPv6TcpAddress *t6;
1344 struct GNUNET_ATS_Information ats;
1345 unsigned int is_natd = GNUNET_NO;
1348 addrlen = address->address_length;
1349 LOG(GNUNET_ERROR_TYPE_DEBUG,
1350 "Trying to get session for `%s' address of peer `%s'\n",
1351 tcp_address_to_string(NULL, address->address, address->address_length),
1352 GNUNET_i2s (&address->peer));
1354 /* look for existing session */
1355 if (GNUNET_YES == GNUNET_CONTAINER_multipeermap_contains (plugin->sessionmap,
1358 struct SessionItCtx si_ctx;
1360 si_ctx.address = address;
1361 si_ctx.result = NULL;
1363 GNUNET_CONTAINER_multipeermap_get_multiple (plugin->sessionmap,
1364 &address->peer, &session_lookup_it, &si_ctx);
1365 if (si_ctx.result != NULL )
1367 session = si_ctx.result;
1368 LOG(GNUNET_ERROR_TYPE_DEBUG,
1369 "Found existing session for `%s' address `%s' session %p\n",
1370 GNUNET_i2s (&address->peer),
1371 tcp_address_to_string(NULL, address->address, address->address_length),
1375 LOG(GNUNET_ERROR_TYPE_DEBUG,
1376 "Existing sessions did not match address `%s' or peer `%s'\n",
1377 tcp_address_to_string(NULL, address->address, address->address_length),
1378 GNUNET_i2s (&address->peer));
1381 if (addrlen == sizeof(struct IPv6TcpAddress))
1383 GNUNET_assert(NULL != address->address); /* make static analysis happy */
1384 t6 = address->address;
1386 memset (&a6, 0, sizeof(a6));
1387 #if HAVE_SOCKADDR_IN_SIN_LEN
1388 a6.sin6_len = sizeof (a6);
1390 a6.sin6_family = AF_INET6;
1391 a6.sin6_port = t6->t6_port;
1392 if (t6->t6_port == 0)
1393 is_natd = GNUNET_YES;
1394 memcpy (&a6.sin6_addr, &t6->ipv6_addr, sizeof(struct in6_addr));
1398 else if (addrlen == sizeof(struct IPv4TcpAddress))
1400 GNUNET_assert(NULL != address->address); /* make static analysis happy */
1401 t4 = address->address;
1403 memset (&a4, 0, sizeof(a4));
1404 #if HAVE_SOCKADDR_IN_SIN_LEN
1405 a4.sin_len = sizeof (a4);
1407 a4.sin_family = AF_INET;
1408 a4.sin_port = t4->t4_port;
1409 if (t4->t4_port == 0)
1410 is_natd = GNUNET_YES;
1411 a4.sin_addr.s_addr = t4->ipv4_addr;
1417 GNUNET_STATISTICS_update (plugin->env->stats, gettext_noop
1418 ("# requests to create session with invalid address"), 1, GNUNET_NO);
1422 ats = plugin->env->get_address_type (plugin->env->cls, sb, sbs);
1424 if ((is_natd == GNUNET_YES) && (addrlen == sizeof(struct IPv6TcpAddress)))
1426 /* NAT client only works with IPv4 addresses */
1430 if (plugin->cur_connections >= plugin->max_connections)
1436 if ((is_natd == GNUNET_YES)
1438 == GNUNET_CONTAINER_multipeermap_contains (plugin->nat_wait_conns,
1441 /* Only do one NAT punch attempt per peer identity */
1445 if ((is_natd == GNUNET_YES) && (NULL != plugin->nat) &&
1446 (GNUNET_NO == GNUNET_CONTAINER_multipeermap_contains (plugin->nat_wait_conns,
1449 LOG (GNUNET_ERROR_TYPE_DEBUG,
1450 "Found valid IPv4 NAT address (creating session)!\n");
1451 session = create_session (plugin, &address->peer, NULL, GNUNET_YES);
1452 session->address = GNUNET_HELLO_address_copy (address);
1453 session->ats_address_network_type = (enum GNUNET_ATS_Network_Type) ntohl (
1456 session->ats_address_network_type != GNUNET_ATS_NET_UNSPECIFIED);
1457 session->nat_connection_timeout = GNUNET_SCHEDULER_add_delayed (NAT_TIMEOUT,
1458 &nat_connect_timeout, session);
1459 GNUNET_assert(session != NULL);
1461 GNUNET_OK == GNUNET_CONTAINER_multipeermap_put (plugin->nat_wait_conns, &session->target, session, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
1463 LOG(GNUNET_ERROR_TYPE_DEBUG,
1464 "Created NAT WAIT connection to `%4s' at `%s'\n",
1465 GNUNET_i2s (&session->target), GNUNET_a2s (sb, sbs));
1467 if (GNUNET_OK == GNUNET_NAT_run_client (plugin->nat, &a4))
1471 LOG(GNUNET_ERROR_TYPE_DEBUG,
1472 "Running NAT client for `%4s' at `%s' failed\n",
1473 GNUNET_i2s (&session->target), GNUNET_a2s (sb, sbs));
1474 tcp_disconnect_session (plugin, session);
1479 /* create new outbound session */
1480 GNUNET_assert(plugin->cur_connections <= plugin->max_connections);
1481 sa = GNUNET_CONNECTION_create_from_sockaddr (af, sb, sbs);
1484 LOG(GNUNET_ERROR_TYPE_DEBUG,
1485 "Failed to create connection to `%4s' at `%s'\n",
1486 GNUNET_i2s (&address->peer), GNUNET_a2s (sb, sbs));
1489 plugin->cur_connections++;
1490 if (plugin->cur_connections == plugin->max_connections)
1491 GNUNET_SERVER_suspend (plugin->server); /* Maximum number of connections rechead */
1493 LOG(GNUNET_ERROR_TYPE_DEBUG,
1494 "Asked to transmit to `%4s', creating fresh session using address `%s'.\n",
1495 GNUNET_i2s (&address->peer), GNUNET_a2s (sb, sbs));
1497 session = create_session (plugin, &address->peer,
1498 GNUNET_SERVER_connect_socket (plugin->server, sa), GNUNET_NO);
1499 session->address = GNUNET_HELLO_address_copy (address);
1500 session->ats_address_network_type = (enum GNUNET_ATS_Network_Type) ntohl (
1502 GNUNET_break(session->ats_address_network_type != GNUNET_ATS_NET_UNSPECIFIED);
1503 GNUNET_SERVER_client_set_user_context(session->client, session);
1504 GNUNET_CONTAINER_multipeermap_put (plugin->sessionmap, &session->target,
1505 session, GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
1506 LOG(GNUNET_ERROR_TYPE_DEBUG,
1507 "Creating new session for `%s' address `%s' session %p\n",
1508 GNUNET_i2s (&address->peer),
1509 tcp_address_to_string(NULL, address->address, address->address_length),
1511 /* Send TCP Welcome */
1512 process_pending_messages (session);
1518 session_disconnect_it (void *cls, const struct GNUNET_PeerIdentity *key,
1521 struct Plugin *plugin = cls;
1522 struct Session *session = value;
1524 GNUNET_STATISTICS_update (session->plugin->env->stats, gettext_noop
1525 ("# transport-service disconnect requests for TCP"), 1, GNUNET_NO);
1526 tcp_disconnect_session (plugin, session);
1531 * Function that can be called to force a disconnect from the
1532 * specified neighbour. This should also cancel all previously
1533 * scheduled transmissions. Obviously the transmission may have been
1534 * partially completed already, which is OK. The plugin is supposed
1535 * to close the connection (if applicable) and no longer call the
1536 * transmit continuation(s).
1538 * Finally, plugin MUST NOT call the services's receive function to
1539 * notify the service that the connection to the specified target was
1540 * closed after a getting this call.
1542 * @param cls closure
1543 * @param target peer for which the last transmission is
1547 tcp_plugin_disconnect (void *cls, const struct GNUNET_PeerIdentity *target)
1549 struct Plugin *plugin = cls;
1551 LOG(GNUNET_ERROR_TYPE_DEBUG, "Disconnecting peer `%4s'\n",
1552 GNUNET_i2s (target));
1553 GNUNET_CONTAINER_multipeermap_get_multiple (plugin->sessionmap, target,
1554 &session_disconnect_it, plugin);
1555 GNUNET_CONTAINER_multipeermap_get_multiple (plugin->nat_wait_conns, target,
1556 &session_disconnect_it, plugin);
1560 * Running pretty printers: head
1562 static struct PrettyPrinterContext *ppc_dll_head;
1565 * Running pretty printers: tail
1567 static struct PrettyPrinterContext *ppc_dll_tail;
1570 * Context for address to string conversion.
1572 struct PrettyPrinterContext
1577 struct PrettyPrinterContext *next;
1582 struct PrettyPrinterContext *prev;
1587 GNUNET_SCHEDULER_TaskIdentifier timeout_task;
1592 struct GNUNET_RESOLVER_RequestHandle *resolver_handle;
1595 * Function to call with the result.
1597 GNUNET_TRANSPORT_AddressStringCallback asc;
1600 * Clsoure for 'asc'.
1605 * Port to add after the IP address.
1621 ppc_cancel_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1623 struct PrettyPrinterContext *ppc = cls;
1625 ppc->timeout_task = GNUNET_SCHEDULER_NO_TASK;
1626 if (NULL != ppc->resolver_handle)
1628 GNUNET_RESOLVER_request_cancel (ppc->resolver_handle);
1629 ppc->resolver_handle = NULL;
1631 GNUNET_CONTAINER_DLL_remove(ppc_dll_head, ppc_dll_tail, ppc);
1636 * Append our port and forward the result.
1638 * @param cls the 'struct PrettyPrinterContext*'
1639 * @param hostname hostname part of the address
1642 append_port (void *cls, const char *hostname)
1644 struct PrettyPrinterContext *ppc = cls;
1645 struct PrettyPrinterContext *cur;
1648 if (NULL == hostname)
1650 ppc->asc (ppc->asc_cls, NULL );
1651 GNUNET_CONTAINER_DLL_remove(ppc_dll_head, ppc_dll_tail, ppc);
1652 GNUNET_SCHEDULER_cancel (ppc->timeout_task);
1653 ppc->timeout_task = GNUNET_SCHEDULER_NO_TASK;
1654 ppc->resolver_handle = NULL;
1658 for (cur = ppc_dll_head; (NULL != cur); cur = cur->next)
1667 if (GNUNET_YES == ppc->ipv6)
1668 GNUNET_asprintf (&ret, "%s.%u.[%s]:%d", PLUGIN_NAME, ppc->options, hostname,
1671 GNUNET_asprintf (&ret, "%s.%u.%s:%d", PLUGIN_NAME, ppc->options, hostname,
1673 ppc->asc (ppc->asc_cls, ret);
1678 * Convert the transports address to a nice, human-readable
1681 * @param cls closure
1682 * @param type name of the transport that generated the address
1683 * @param addr one of the addresses of the host, NULL for the last address
1684 * the specific address format depends on the transport
1685 * @param addrlen length of the address
1686 * @param numeric should (IP) addresses be displayed in numeric form?
1687 * @param timeout after how long should we give up?
1688 * @param asc function to call on each string
1689 * @param asc_cls closure for asc
1692 tcp_plugin_address_pretty_printer (void *cls, const char *type,
1693 const void *addr, size_t addrlen, int numeric,
1694 struct GNUNET_TIME_Relative timeout,
1695 GNUNET_TRANSPORT_AddressStringCallback asc, void *asc_cls)
1697 struct PrettyPrinterContext *ppc;
1700 struct sockaddr_in a4;
1701 struct sockaddr_in6 a6;
1702 const struct IPv4TcpAddress *t4;
1703 const struct IPv6TcpAddress *t6;
1707 if (addrlen == sizeof(struct IPv6TcpAddress))
1710 memset (&a6, 0, sizeof(a6));
1711 a6.sin6_family = AF_INET6;
1712 a6.sin6_port = t6->t6_port;
1713 memcpy (&a6.sin6_addr, &t6->ipv6_addr, sizeof(struct in6_addr));
1714 port = ntohs (t6->t6_port);
1715 options = ntohl (t6->options);
1719 else if (addrlen == sizeof(struct IPv4TcpAddress))
1722 memset (&a4, 0, sizeof(a4));
1723 a4.sin_family = AF_INET;
1724 a4.sin_port = t4->t4_port;
1725 a4.sin_addr.s_addr = t4->ipv4_addr;
1726 port = ntohs (t4->t4_port);
1727 options = ntohl (t4->options);
1731 else if (0 == addrlen)
1733 asc (asc_cls, TRANSPORT_SESSION_INBOUND_STRING);
1734 asc (asc_cls, NULL );
1739 /* invalid address */
1741 asc (asc_cls, NULL );
1744 ppc = GNUNET_new (struct PrettyPrinterContext);
1745 if (addrlen == sizeof(struct IPv6TcpAddress))
1746 ppc->ipv6 = GNUNET_YES;
1748 ppc->ipv6 = GNUNET_NO;
1750 ppc->asc_cls = asc_cls;
1752 ppc->options = options;
1753 ppc->timeout_task = GNUNET_SCHEDULER_add_delayed (
1754 GNUNET_TIME_relative_multiply (timeout, 2), &ppc_cancel_task, ppc);
1755 ppc->resolver_handle = GNUNET_RESOLVER_hostname_get (sb, sbs, !numeric,
1756 timeout, &append_port, ppc);
1757 if (NULL != ppc->resolver_handle)
1759 //GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Adding request %p\n", ppc);
1760 GNUNET_CONTAINER_DLL_insert(ppc_dll_head, ppc_dll_tail, ppc);
1770 * Check if the given port is plausible (must be either our listen
1771 * port or our advertised port), or any port if we are behind NAT
1772 * and do not have a port open. If it is neither, we return
1775 * @param plugin global variables
1776 * @param in_port port number to check
1777 * @return #GNUNET_OK if port is either open_port or adv_port
1780 check_port (struct Plugin *plugin, uint16_t in_port)
1782 if ((in_port == plugin->adv_port) || (in_port == plugin->open_port))
1784 return GNUNET_SYSERR;
1788 * Function that will be called to check if a binary address for this
1789 * plugin is well-formed and corresponds to an address for THIS peer
1790 * (as per our configuration). Naturally, if absolutely necessary,
1791 * plugins can be a bit conservative in their answer, but in general
1792 * plugins should make sure that the address does not redirect
1793 * traffic to a 3rd party that might try to man-in-the-middle our
1796 * @param cls closure, our `struct Plugin *`
1797 * @param addr pointer to the address
1798 * @param addrlen length of addr
1799 * @return #GNUNET_OK if this is a plausible address for this peer
1800 * and transport, #GNUNET_SYSERR if not
1803 tcp_plugin_check_address (void *cls, const void *addr, size_t addrlen)
1805 struct Plugin *plugin = cls;
1806 struct IPv4TcpAddress *v4;
1807 struct IPv6TcpAddress *v6;
1809 if ((addrlen != sizeof(struct IPv4TcpAddress))
1810 && (addrlen != sizeof(struct IPv6TcpAddress)))
1813 return GNUNET_SYSERR;
1816 if (addrlen == sizeof(struct IPv4TcpAddress))
1818 v4 = (struct IPv4TcpAddress *) addr;
1819 if (0 != memcmp (&v4->options, &myoptions, sizeof(myoptions)))
1822 return GNUNET_SYSERR;
1824 if (GNUNET_OK != check_port (plugin, ntohs (v4->t4_port)))
1825 return GNUNET_SYSERR;
1827 != GNUNET_NAT_test_address (plugin->nat, &v4->ipv4_addr,
1828 sizeof(struct in_addr)))
1829 return GNUNET_SYSERR;
1833 v6 = (struct IPv6TcpAddress *) addr;
1834 if (IN6_IS_ADDR_LINKLOCAL (&v6->ipv6_addr))
1837 return GNUNET_SYSERR;
1839 if (0 != memcmp (&v6->options, &myoptions, sizeof(myoptions)))
1842 return GNUNET_SYSERR;
1844 if (GNUNET_OK != check_port (plugin, ntohs (v6->t6_port)))
1845 return GNUNET_SYSERR;
1847 != GNUNET_NAT_test_address (plugin->nat, &v6->ipv6_addr,
1848 sizeof(struct in6_addr)))
1849 return GNUNET_SYSERR;
1855 * We've received a nat probe from this peer via TCP. Finish
1856 * creating the client session and resume sending of queued
1859 * @param cls closure
1860 * @param client identification of the client
1861 * @param message the actual message
1864 handle_tcp_nat_probe (void *cls, struct GNUNET_SERVER_Client *client,
1865 const struct GNUNET_MessageHeader *message)
1867 struct Plugin *plugin = cls;
1868 struct Session *session;
1869 const struct TCP_NAT_ProbeMessage *tcp_nat_probe;
1872 struct IPv4TcpAddress *t4;
1873 struct IPv6TcpAddress *t6;
1874 const struct sockaddr_in *s4;
1875 const struct sockaddr_in6 *s6;
1877 LOG(GNUNET_ERROR_TYPE_DEBUG, "Received NAT probe\n");
1878 /* We have received a TCP NAT probe, meaning we (hopefully) initiated
1879 * a connection to this peer by running gnunet-nat-client. This peer
1880 * received the punch message and now wants us to use the new connection
1881 * as the default for that peer. Do so and then send a WELCOME message
1882 * so we can really be connected!
1884 if (ntohs (message->size) != sizeof(struct TCP_NAT_ProbeMessage))
1887 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1891 tcp_nat_probe = (const struct TCP_NAT_ProbeMessage *) message;
1892 if (0 == memcmp (&tcp_nat_probe->clientIdentity, plugin->env->my_identity,
1893 sizeof(struct GNUNET_PeerIdentity)))
1895 /* refuse connections from ourselves */
1896 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1900 session = GNUNET_CONTAINER_multipeermap_get (plugin->nat_wait_conns,
1901 &tcp_nat_probe->clientIdentity);
1902 if (session == NULL )
1904 LOG(GNUNET_ERROR_TYPE_DEBUG, "Did NOT find session for NAT probe!\n");
1905 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1908 LOG(GNUNET_ERROR_TYPE_DEBUG, "Found session for NAT probe!\n");
1910 if (session->nat_connection_timeout != GNUNET_SCHEDULER_NO_TASK )
1912 GNUNET_SCHEDULER_cancel (session->nat_connection_timeout);
1913 session->nat_connection_timeout = GNUNET_SCHEDULER_NO_TASK;
1916 if (GNUNET_OK != GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
1919 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1920 tcp_disconnect_session (plugin, session);
1924 GNUNET_CONTAINER_multipeermap_remove (plugin->nat_wait_conns, &tcp_nat_probe->clientIdentity, session) == GNUNET_YES);
1925 GNUNET_SERVER_client_set_user_context(client, session);
1926 GNUNET_CONTAINER_multipeermap_put (plugin->sessionmap, &session->target,
1927 session, GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
1928 session->last_activity = GNUNET_TIME_absolute_get ();
1929 LOG(GNUNET_ERROR_TYPE_DEBUG, "Found address `%s' for incoming connection\n",
1930 GNUNET_a2s (vaddr, alen));
1931 switch (((const struct sockaddr *) vaddr)->sa_family)
1935 t4 = GNUNET_new (struct IPv4TcpAddress);
1937 t4->t4_port = s4->sin_port;
1938 t4->ipv4_addr = s4->sin_addr.s_addr;
1939 session->address = GNUNET_HELLO_address_allocate (
1940 &tcp_nat_probe->clientIdentity, PLUGIN_NAME, &t4,
1941 sizeof(struct IPv4TcpAddress), GNUNET_HELLO_ADDRESS_INFO_NONE);
1945 t6 = GNUNET_new (struct IPv6TcpAddress);
1947 t6->t6_port = s6->sin6_port;
1948 memcpy (&t6->ipv6_addr, &s6->sin6_addr, sizeof(struct in6_addr));
1949 session->address = GNUNET_HELLO_address_allocate (
1950 &tcp_nat_probe->clientIdentity, PLUGIN_NAME, &t6,
1951 sizeof(struct IPv6TcpAddress), GNUNET_HELLO_ADDRESS_INFO_NONE);
1955 LOG(GNUNET_ERROR_TYPE_DEBUG, "Bad address for incoming connection!\n");
1957 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1958 tcp_disconnect_session (plugin, session);
1962 GNUNET_break(NULL == session->client);
1963 GNUNET_SERVER_client_keep (client);
1964 session->client = client;
1965 GNUNET_STATISTICS_update (plugin->env->stats,
1966 gettext_noop ("# TCP sessions active"), 1, GNUNET_NO);
1967 process_pending_messages (session);
1968 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1972 * We've received a welcome from this peer via TCP. Possibly create a
1973 * fresh client record and send back our welcome.
1975 * @param cls closure
1976 * @param client identification of the client
1977 * @param message the actual message
1980 handle_tcp_welcome (void *cls, struct GNUNET_SERVER_Client *client,
1981 const struct GNUNET_MessageHeader *message)
1983 struct Plugin *plugin = cls;
1984 const struct WelcomeMessage *wm = (const struct WelcomeMessage *) message;
1985 struct Session *session;
1988 struct IPv4TcpAddress t4;
1989 struct IPv6TcpAddress t6;
1990 const struct sockaddr_in *s4;
1991 const struct sockaddr_in6 *s6;
1992 struct GNUNET_ATS_Information ats;
1994 if (0 == memcmp (&wm->clientIdentity, plugin->env->my_identity,
1995 sizeof(struct GNUNET_PeerIdentity)))
1997 /* refuse connections from ourselves */
1998 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1999 if (GNUNET_OK == GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
2001 LOG(GNUNET_ERROR_TYPE_WARNING,
2002 "Received %s message from my own identity `%4s' on address `%s'\n",
2003 "WELCOME", GNUNET_i2s (&wm->clientIdentity),
2004 GNUNET_a2s (vaddr, alen));
2010 LOG(GNUNET_ERROR_TYPE_DEBUG, "Received %s message from `%4s' %p\n", "WELCOME",
2011 GNUNET_i2s (&wm->clientIdentity), client);
2012 GNUNET_STATISTICS_update (plugin->env->stats,
2013 gettext_noop ("# TCP WELCOME messages received"), 1, GNUNET_NO);
2014 session = lookup_session_by_client (plugin, client);
2015 if (NULL != session)
2017 if (GNUNET_OK == GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
2019 LOG(GNUNET_ERROR_TYPE_DEBUG, "Found existing session %p for peer `%s'\n",
2020 session, GNUNET_a2s (vaddr, alen));
2026 GNUNET_SERVER_client_keep (client);
2027 if (NULL != plugin->service) /* Otherwise value is incremented in tcp_access_check */
2028 plugin->cur_connections++;
2029 if (plugin->cur_connections == plugin->max_connections)
2030 GNUNET_SERVER_suspend (plugin->server); /* Maximum number of connections rechead */
2032 session = create_session (plugin, &wm->clientIdentity, client, GNUNET_NO);
2033 if (GNUNET_OK == GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
2035 if (alen == sizeof(struct sockaddr_in))
2038 memset (&t4, '\0', sizeof (t4));
2039 t4.options = htonl (0);
2040 t4.t4_port = s4->sin_port;
2041 t4.ipv4_addr = s4->sin_addr.s_addr;
2042 session->address = GNUNET_HELLO_address_allocate (&wm->clientIdentity,
2043 PLUGIN_NAME, &t4, sizeof(struct IPv4TcpAddress),
2044 GNUNET_HELLO_ADDRESS_INFO_INBOUND);
2046 else if (alen == sizeof(struct sockaddr_in6))
2049 memset (&t6, '\0', sizeof (t6));
2050 t6.options = htonl (0);
2051 t6.t6_port = s6->sin6_port;
2052 memcpy (&t6.ipv6_addr, &s6->sin6_addr, sizeof(struct in6_addr));
2053 session->address = GNUNET_HELLO_address_allocate (&wm->clientIdentity,
2054 PLUGIN_NAME, &t6, sizeof(struct IPv6TcpAddress),
2055 GNUNET_HELLO_ADDRESS_INFO_INBOUND);
2058 ats = plugin->env->get_address_type (plugin->env->cls, vaddr, alen);
2059 session->ats_address_network_type = (enum GNUNET_ATS_Network_Type) ntohl (
2061 LOG(GNUNET_ERROR_TYPE_DEBUG, "Creating new session %p for peer `%s'\n",
2062 session, GNUNET_a2s (vaddr, alen));
2064 GNUNET_SERVER_client_set_user_context(session->client, session);
2065 GNUNET_CONTAINER_multipeermap_put (plugin->sessionmap, &session->target,
2066 session, GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2070 LOG(GNUNET_ERROR_TYPE_DEBUG,
2071 "Did not obtain TCP socket address for incoming connection\n");
2076 if (session->expecting_welcome != GNUNET_YES)
2079 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2083 session->last_activity = GNUNET_TIME_absolute_get ();
2084 session->expecting_welcome = GNUNET_NO;
2086 /* Notify transport and ATS about new session */
2087 plugin->env->session_start (NULL, session->address, session, &ats, 1);
2089 process_pending_messages (session);
2090 GNUNET_SERVER_client_set_timeout (client,
2091 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
2092 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2096 * Task to signal the server that we can continue
2097 * receiving from the TCP client now.
2099 * @param cls the `struct Session*`
2100 * @param tc task context (unused)
2103 delayed_done (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2105 struct Session *session = cls;
2107 session->receive_delay_task = GNUNET_SCHEDULER_NO_TASK;
2108 reschedule_session_timeout (session);
2110 GNUNET_SERVER_receive_done (session->client, GNUNET_OK);
2114 * We've received data for this peer via TCP. Unbox,
2115 * compute latency and forward.
2117 * @param cls closure
2118 * @param client identification of the client
2119 * @param message the actual message
2122 handle_tcp_data (void *cls, struct GNUNET_SERVER_Client *client,
2123 const struct GNUNET_MessageHeader *message)
2125 struct Plugin *plugin = cls;
2126 struct Session *session;
2127 struct GNUNET_TIME_Relative delay;
2130 type = ntohs (message->type);
2131 if ((GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME == type)
2132 || (GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE == type))
2134 /* We don't want to propagate WELCOME and NAT Probe messages up! */
2135 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2138 session = lookup_session_by_client (plugin, client);
2139 if (NULL == session)
2141 /* No inbound session found */
2145 GNUNET_SERVER_client_get_address (client, &vaddr, &alen);
2146 LOG(GNUNET_ERROR_TYPE_ERROR,
2147 "Received unexpected %u bytes of type %u from `%s'\n",
2148 (unsigned int ) ntohs (message->size),
2149 (unsigned int ) ntohs (message->type), GNUNET_a2s (vaddr, alen));
2151 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2152 GNUNET_free_non_null(vaddr);
2155 else if (GNUNET_YES == session->expecting_welcome)
2157 /* Session is expecting WELCOME message */
2161 GNUNET_SERVER_client_get_address (client, &vaddr, &alen);
2162 LOG(GNUNET_ERROR_TYPE_ERROR,
2163 "Received unexpected %u bytes of type %u from `%s'\n",
2164 (unsigned int ) ntohs (message->size),
2165 (unsigned int ) ntohs (message->type), GNUNET_a2s (vaddr, alen));
2167 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2168 GNUNET_free_non_null(vaddr);
2172 session->last_activity = GNUNET_TIME_absolute_get ();
2173 LOG(GNUNET_ERROR_TYPE_DEBUG,
2174 "Passing %u bytes of type %u from `%4s' to transport service.\n",
2175 (unsigned int ) ntohs (message->size),
2176 (unsigned int ) ntohs (message->type), GNUNET_i2s (&session->target));
2178 GNUNET_STATISTICS_update (plugin->env->stats,
2179 gettext_noop ("# bytes received via TCP"), ntohs (message->size),
2181 struct GNUNET_ATS_Information distance;
2183 distance.type = htonl (GNUNET_ATS_NETWORK_TYPE);
2184 distance.value = htonl ((uint32_t) session->ats_address_network_type);
2185 GNUNET_break(session->ats_address_network_type != GNUNET_ATS_NET_UNSPECIFIED);
2188 GNUNET_CONTAINER_multipeermap_contains_value (plugin->sessionmap,
2189 &session->target, session));
2191 delay = plugin->env->receive (plugin->env->cls, session->address, session, message);
2192 plugin->env->update_address_metrics (plugin->env->cls, session->address,
2193 session, &distance, 1);
2194 reschedule_session_timeout (session);
2195 if (0 == delay.rel_value_us)
2197 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2201 LOG(GNUNET_ERROR_TYPE_DEBUG, "Throttling receiving from `%s' for %s\n",
2202 GNUNET_i2s (&session->target),
2203 GNUNET_STRINGS_relative_time_to_string (delay, GNUNET_YES));
2204 GNUNET_SERVER_disable_receive_done_warning (client);
2205 session->receive_delay_task = GNUNET_SCHEDULER_add_delayed (delay,
2206 &delayed_done, session);
2211 * Functions with this signature are called whenever a peer
2212 * is disconnected on the network level.
2214 * @param cls closure
2215 * @param client identification of the client
2218 disconnect_notify (void *cls, struct GNUNET_SERVER_Client *client)
2220 struct Plugin *plugin = cls;
2221 struct Session *session;
2223 if (client == NULL )
2225 session = lookup_session_by_client (plugin, client);
2226 if (session == NULL )
2227 return; /* unknown, nothing to do */
2228 LOG(GNUNET_ERROR_TYPE_DEBUG,
2229 "Destroying session of `%4s' with %s due to network-level disconnect.\n",
2230 GNUNET_i2s (&session->target),
2231 tcp_address_to_string (session->plugin, session->address->address,
2232 session->address->address_length));
2234 if (plugin->cur_connections == plugin->max_connections)
2235 GNUNET_SERVER_resume (plugin->server); /* Resume server */
2237 if (plugin->cur_connections < 1)
2240 plugin->cur_connections--;
2242 GNUNET_STATISTICS_update (session->plugin->env->stats, gettext_noop
2243 ("# network-level TCP disconnect events"), 1, GNUNET_NO);
2244 tcp_disconnect_session (plugin, session);
2248 * We can now send a probe message, copy into buffer to really send.
2250 * @param cls closure, a struct TCPProbeContext
2251 * @param size max size to copy
2252 * @param buf buffer to copy message to
2253 * @return number of bytes copied into buf
2256 notify_send_probe (void *cls, size_t size, void *buf)
2258 struct TCPProbeContext *tcp_probe_ctx = cls;
2259 struct Plugin *plugin = tcp_probe_ctx->plugin;
2262 tcp_probe_ctx->transmit_handle = NULL;
2263 GNUNET_CONTAINER_DLL_remove(plugin->probe_head, plugin->probe_tail,
2267 GNUNET_CONNECTION_destroy (tcp_probe_ctx->sock);
2268 GNUNET_free(tcp_probe_ctx);
2271 GNUNET_assert(size >= sizeof(tcp_probe_ctx->message));
2272 memcpy (buf, &tcp_probe_ctx->message, sizeof(tcp_probe_ctx->message));
2273 GNUNET_SERVER_connect_socket (tcp_probe_ctx->plugin->server,
2274 tcp_probe_ctx->sock);
2275 ret = sizeof(tcp_probe_ctx->message);
2276 GNUNET_free(tcp_probe_ctx);
2281 * Function called by the NAT subsystem suggesting another peer wants
2282 * to connect to us via connection reversal. Try to connect back to the
2285 * @param cls closure
2286 * @param addr address to try
2287 * @param addrlen number of bytes in @a addr
2290 try_connection_reversal (void *cls, const struct sockaddr *addr,
2293 struct Plugin *plugin = cls;
2294 struct GNUNET_CONNECTION_Handle *sock;
2295 struct TCPProbeContext *tcp_probe_ctx;
2298 * We have received an ICMP response, ostensibly from a peer
2299 * that wants to connect to us! Send a message to establish a connection.
2301 sock = GNUNET_CONNECTION_create_from_sockaddr (AF_INET, addr, addrlen);
2304 /* failed for some odd reason (out of sockets?); ignore attempt */
2308 /* FIXME: do we need to track these probe context objects so that
2309 * we can clean them up on plugin unload? */
2310 tcp_probe_ctx = GNUNET_new (struct TCPProbeContext);
2311 tcp_probe_ctx->message.header.size = htons (
2312 sizeof(struct TCP_NAT_ProbeMessage));
2313 tcp_probe_ctx->message.header.type = htons (
2314 GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE);
2315 memcpy (&tcp_probe_ctx->message.clientIdentity, plugin->env->my_identity,
2316 sizeof(struct GNUNET_PeerIdentity));
2317 tcp_probe_ctx->plugin = plugin;
2318 tcp_probe_ctx->sock = sock;
2319 GNUNET_CONTAINER_DLL_insert(plugin->probe_head, plugin->probe_tail,
2321 tcp_probe_ctx->transmit_handle = GNUNET_CONNECTION_notify_transmit_ready (
2322 sock, ntohs (tcp_probe_ctx->message.header.size),
2323 GNUNET_TIME_UNIT_FOREVER_REL, ¬ify_send_probe, tcp_probe_ctx);
2328 * Function obtain the network type for a session
2330 * @param cls closure ('struct Plugin*')
2331 * @param session the session
2332 * @return the network type in HBO or #GNUNET_SYSERR
2334 static enum GNUNET_ATS_Network_Type
2335 tcp_get_network (void *cls, struct Session *session)
2337 GNUNET_assert(NULL != session);
2338 return session->ats_address_network_type;
2342 * Entry point for the plugin.
2344 * @param cls closure, the 'struct GNUNET_TRANSPORT_PluginEnvironment*'
2345 * @return the 'struct GNUNET_TRANSPORT_PluginFunctions*' or NULL on error
2348 libgnunet_plugin_transport_tcp_init (void *cls)
2350 static const struct GNUNET_SERVER_MessageHandler my_handlers[] = { {
2351 &handle_tcp_welcome, NULL, GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME,
2352 sizeof(struct WelcomeMessage) }, { &handle_tcp_nat_probe, NULL,
2353 GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE,
2354 sizeof(struct TCP_NAT_ProbeMessage) }, { &handle_tcp_data, NULL,
2355 GNUNET_MESSAGE_TYPE_ALL, 0 }, { NULL, NULL, 0, 0 } };
2356 struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
2357 struct GNUNET_TRANSPORT_PluginFunctions *api;
2358 struct Plugin *plugin;
2359 struct GNUNET_SERVICE_Context *service;
2360 unsigned long long aport;
2361 unsigned long long bport;
2362 unsigned long long max_connections;
2364 struct GNUNET_TIME_Relative idle_timeout;
2367 struct sockaddr **addrs;
2368 socklen_t *addrlens;
2370 if (NULL == env->receive)
2372 /* run in 'stub' mode (i.e. as part of gnunet-peerinfo), don't fully
2373 initialze the plugin or the API */
2374 api = GNUNET_new (struct GNUNET_TRANSPORT_PluginFunctions);
2376 api->address_pretty_printer = &tcp_plugin_address_pretty_printer;
2377 api->address_to_string = &tcp_address_to_string;
2378 api->string_to_address = &tcp_string_to_address;
2382 GNUNET_assert(NULL != env->cfg);
2384 != GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-tcp",
2385 "MAX_CONNECTIONS", &max_connections))
2386 max_connections = 128;
2390 != GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-tcp",
2391 "PORT", &bport)) || (bport > 65535)
2393 == GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-tcp",
2394 "ADVERTISED-PORT", &aport)) && (aport > 65535)))
2396 LOG(GNUNET_ERROR_TYPE_ERROR,
2397 _("Require valid port number for service `%s' in configuration!\n"),
2407 service = GNUNET_SERVICE_start ("transport-tcp", env->cfg,
2408 GNUNET_SERVICE_OPTION_NONE);
2409 if (service == NULL )
2411 LOG(GNUNET_ERROR_TYPE_WARNING, _("Failed to start service.\n"));
2418 /* Initialize my flags */
2421 plugin = GNUNET_new (struct Plugin);
2422 plugin->sessionmap = GNUNET_CONTAINER_multipeermap_create (max_connections,
2424 plugin->max_connections = max_connections;
2425 plugin->cur_connections = 0;
2426 plugin->open_port = bport;
2427 plugin->adv_port = aport;
2429 plugin->lsock = NULL;
2430 if ((service != NULL )&&
2433 GNUNET_SERVICE_get_server_addresses ("transport-tcp", env->cfg, &addrs,
2435 for (ret = ret_s-1; ret >= 0; ret--)
2436 LOG (GNUNET_ERROR_TYPE_INFO,
2437 "Binding to address `%s'\n",
2438 GNUNET_a2s (addrs[ret], addrlens[ret]));
2440 GNUNET_NAT_register (env->cfg, GNUNET_YES, aport, (unsigned int) ret_s,
2441 (const struct sockaddr **) addrs, addrlens,
2442 &tcp_nat_port_map_callback,
2443 &try_connection_reversal, plugin);
2444 for (ret = ret_s -1; ret >= 0; ret--)
2446 GNUNET_assert (addrs[ret] != NULL);
2447 GNUNET_free (addrs[ret]);
2449 GNUNET_free_non_null (addrs);
2450 GNUNET_free_non_null (addrlens);
2454 plugin->nat = GNUNET_NAT_register (plugin->env->cfg,
2455 GNUNET_YES, 0, 0, NULL, NULL, NULL,
2456 &try_connection_reversal, plugin);
2458 api = GNUNET_new (struct GNUNET_TRANSPORT_PluginFunctions);
2460 api->send = &tcp_plugin_send;
2461 api->get_session = &tcp_plugin_get_session;
2463 api->disconnect_session = &tcp_disconnect_session;
2464 api->query_keepalive_factor = &tcp_query_keepalive_factor;
2465 api->disconnect_peer = &tcp_plugin_disconnect;
2466 api->address_pretty_printer = &tcp_plugin_address_pretty_printer;
2467 api->check_address = &tcp_plugin_check_address;
2468 api->address_to_string = &tcp_address_to_string;
2469 api->string_to_address = &tcp_string_to_address;
2470 api->get_network = &tcp_get_network;
2471 api->update_session_timeout = &tcp_plugin_update_session_timeout;
2472 plugin->service = service;
2473 if (NULL != service)
2475 plugin->server = GNUNET_SERVICE_get_server (service);
2480 != GNUNET_CONFIGURATION_get_value_time (env->cfg, "transport-tcp",
2481 "TIMEOUT", &idle_timeout))
2483 GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR, "transport-tcp",
2485 if (plugin->nat != NULL )
2486 GNUNET_NAT_unregister (plugin->nat);
2487 GNUNET_free(plugin);
2491 plugin->server = GNUNET_SERVER_create_with_sockets (
2492 &plugin_tcp_access_check, plugin, NULL, idle_timeout, GNUNET_YES);
2494 plugin->handlers = GNUNET_malloc (sizeof (my_handlers));
2495 memcpy (plugin->handlers, my_handlers, sizeof(my_handlers));
2497 i < sizeof(my_handlers) / sizeof(struct GNUNET_SERVER_MessageHandler);
2499 plugin->handlers[i].callback_cls = plugin;
2501 GNUNET_SERVER_add_handlers (plugin->server, plugin->handlers);
2502 GNUNET_SERVER_disconnect_notify (plugin->server, &disconnect_notify, plugin);
2503 plugin->nat_wait_conns = GNUNET_CONTAINER_multipeermap_create (16,
2506 LOG(GNUNET_ERROR_TYPE_INFO, _("TCP transport listening on port %llu\n"),
2509 LOG(GNUNET_ERROR_TYPE_INFO,
2510 _("TCP transport not listening on any port (client only)\n"));
2512 LOG(GNUNET_ERROR_TYPE_INFO,
2513 _("TCP transport advertises itself as being on port %llu\n"), aport);
2514 /* Initially set connections to 0 */
2515 GNUNET_assert(NULL != plugin->env->stats);
2516 GNUNET_STATISTICS_set (plugin->env->stats,
2517 gettext_noop ("# TCP sessions active"), 0, GNUNET_NO);
2522 * Exit point from the plugin.
2524 * @param cls the `struct GNUNET_TRANSPORT_PluginFunctions`
2528 libgnunet_plugin_transport_tcp_done (void *cls)
2530 struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
2531 struct Plugin *plugin = api->cls;
2532 struct TCPProbeContext *tcp_probe;
2533 struct PrettyPrinterContext *cur;
2534 struct PrettyPrinterContext *next;
2541 LOG(GNUNET_ERROR_TYPE_DEBUG, "Shutting down TCP plugin\n");
2543 /* Removing leftover sessions */
2544 GNUNET_CONTAINER_multipeermap_iterate (plugin->sessionmap,
2545 &session_disconnect_it, plugin);
2546 /* Removing leftover NAT sessions */
2547 GNUNET_CONTAINER_multipeermap_iterate (plugin->nat_wait_conns,
2548 &session_disconnect_it, plugin);
2550 next = ppc_dll_head;
2551 for (cur = next; NULL != cur; cur = next)
2554 GNUNET_CONTAINER_DLL_remove(ppc_dll_head, ppc_dll_tail, cur);
2555 if (NULL != cur->resolver_handle)
2556 GNUNET_RESOLVER_request_cancel (cur->resolver_handle);
2557 GNUNET_SCHEDULER_cancel (cur->timeout_task);
2562 if (plugin->service != NULL )
2563 GNUNET_SERVICE_stop (plugin->service);
2565 GNUNET_SERVER_destroy (plugin->server);
2566 GNUNET_free(plugin->handlers);
2567 if (plugin->nat != NULL )
2568 GNUNET_NAT_unregister (plugin->nat);
2569 while (NULL != (tcp_probe = plugin->probe_head))
2571 GNUNET_CONTAINER_DLL_remove(plugin->probe_head, plugin->probe_tail,
2573 GNUNET_CONNECTION_destroy (tcp_probe->sock);
2574 GNUNET_free(tcp_probe);
2576 GNUNET_CONTAINER_multipeermap_destroy (plugin->nat_wait_conns);
2577 GNUNET_CONTAINER_multipeermap_destroy (plugin->sessionmap);
2578 GNUNET_free(plugin);
2583 /* end of plugin_transport_tcp.c */