2 This file is part of GNUnet
3 (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 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_connection_lib.h"
29 #include "gnunet_container_lib.h"
30 #include "gnunet_nat_lib.h"
31 #include "gnunet_os_lib.h"
32 #include "gnunet_protocols.h"
33 #include "gnunet_resolver_service.h"
34 #include "gnunet_server_lib.h"
35 #include "gnunet_service_lib.h"
36 #include "gnunet_signatures.h"
37 #include "gnunet_statistics_service.h"
38 #include "gnunet_transport_service.h"
39 #include "gnunet_transport_plugin.h"
40 #include "transport.h"
42 #define DEBUG_TCP GNUNET_EXTRA_LOGGING
44 #define DEBUG_TCP_NAT GNUNET_EXTRA_LOGGING
47 * Initial handshake message for a session.
52 * Type is GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME.
54 struct GNUNET_MessageHeader header;
57 * Identity of the node connecting (TCP client)
59 struct GNUNET_PeerIdentity clientIdentity;
65 * Basically a WELCOME message, but with the purpose
66 * of giving the waiting peer a client handle to use
68 struct TCP_NAT_ProbeMessage
71 * Type is GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE.
73 struct GNUNET_MessageHeader header;
76 * Identity of the sender of the message.
78 struct GNUNET_PeerIdentity clientIdentity;
84 * Context for sending a NAT probe via TCP.
86 struct TCPProbeContext
90 * Active probes are kept in a DLL.
92 struct TCPProbeContext *next;
95 * Active probes are kept in a DLL.
97 struct TCPProbeContext *prev;
102 struct GNUNET_CONNECTION_Handle *sock;
105 * Message to be sent.
107 struct TCP_NAT_ProbeMessage message;
110 * Handle to the transmission.
112 struct GNUNET_CONNECTION_TransmitHandle *transmit_handle;
115 * Transport plugin handle.
117 struct Plugin *plugin;
122 * Network format for IPv4 addresses.
124 struct IPv4TcpAddress
127 * IPv4 address, in network byte order.
129 uint32_t ipv4_addr GNUNET_PACKED;
132 * Port number, in network byte order.
134 uint16_t t4_port GNUNET_PACKED;
140 * Network format for IPv6 addresses.
142 struct IPv6TcpAddress
147 struct in6_addr ipv6_addr GNUNET_PACKED;
150 * Port number, in network byte order.
152 uint16_t t6_port GNUNET_PACKED;
158 * Encapsulation of all of the state of the plugin.
164 * Information kept for each message that is yet to
167 struct PendingMessage
171 * This is a doubly-linked list.
173 struct PendingMessage *next;
176 * This is a doubly-linked list.
178 struct PendingMessage *prev;
181 * The pending message
186 * Continuation function to call once the message
187 * has been sent. Can be NULL if there is no
188 * continuation to call.
190 GNUNET_TRANSPORT_TransmitContinuation transmit_cont;
193 * Closure for transmit_cont.
195 void *transmit_cont_cls;
198 * Timeout value for the pending message.
200 struct GNUNET_TIME_Absolute timeout;
203 * So that the gnunet-service-transport can group messages together,
204 * these pending messages need to accept a message buffer and size
205 * instead of just a GNUNET_MessageHeader.
213 * Session handle for TCP connections.
221 struct SessionHeader header;
224 * Stored in a linked list.
226 struct Session *next;
229 * Pointer to the global plugin struct.
231 struct Plugin *plugin;
234 * The client (used to identify this connection)
236 struct GNUNET_SERVER_Client *client;
239 * Messages currently pending for transmission
240 * to this peer, if any.
242 struct PendingMessage *pending_messages_head;
245 * Messages currently pending for transmission
246 * to this peer, if any.
248 struct PendingMessage *pending_messages_tail;
251 * Handle for pending transmission request.
253 struct GNUNET_CONNECTION_TransmitHandle *transmit_handle;
256 * To whom are we talking to (set to our identity
257 * if we are still waiting for the welcome message)
259 struct GNUNET_PeerIdentity target;
262 * ID of task used to delay receiving more to throttle sender.
264 GNUNET_SCHEDULER_TaskIdentifier receive_delay_task;
267 * Address of the other peer (either based on our 'connect'
268 * call or on our 'accept' call).
273 * Last activity on this connection. Used to select preferred
276 struct GNUNET_TIME_Absolute last_activity;
279 * Length of connect_addr.
284 * Are we still expecting the welcome message? (GNUNET_YES/GNUNET_NO)
286 int expecting_welcome;
289 * Was this a connection that was inbound (we accepted)? (GNUNET_YES/GNUNET_NO)
294 * Was this session created using NAT traversal?
299 * ATS network type in NBO
301 uint32_t ats_address_network_type;
306 * Encapsulation of all of the state of the plugin.
313 struct GNUNET_TRANSPORT_PluginEnvironment *env;
318 struct GNUNET_CONNECTION_Handle *lsock;
321 * Our handle to the NAT module.
323 struct GNUNET_NAT_Handle *nat;
326 * List of open TCP sessions.
328 struct Session *sessions;
331 * Handle to the network service.
333 struct GNUNET_SERVICE_Context *service;
336 * Handle to the server for this service.
338 struct GNUNET_SERVER_Handle *server;
341 * Copy of the handler array where the closures are
342 * set to this struct's instance.
344 struct GNUNET_SERVER_MessageHandler *handlers;
347 * Map of peers we have tried to contact behind a NAT
349 struct GNUNET_CONTAINER_MultiHashMap *nat_wait_conns;
352 * List of active TCP probes.
354 struct TCPProbeContext *probe_head;
357 * List of active TCP probes.
359 struct TCPProbeContext *probe_tail;
362 * Handle for (DYN)DNS lookup of our external IP.
364 struct GNUNET_RESOLVER_RequestHandle *ext_dns;
367 * How many more TCP sessions are we allowed to open right now?
369 unsigned long long max_connections;
372 * ID of task used to update our addresses when one expires.
374 GNUNET_SCHEDULER_TaskIdentifier address_update_task;
377 * Port that we are actually listening on.
382 * Port that the user said we would have visible to the
391 * Function to check if an inbound connection is acceptable.
392 * Mostly used to limit the total number of open connections
395 * @param cls the 'struct Plugin'
396 * @param ucred credentials, if available, otherwise NULL
397 * @param addr address
398 * @param addrlen length of address
399 * @return GNUNET_YES to allow, GNUNET_NO to deny, GNUNET_SYSERR
400 * for unknown address family (will be denied).
403 plugin_tcp_access_check (void *cls,
404 const struct GNUNET_CONNECTION_Credentials *ucred,
405 const struct sockaddr *addr, socklen_t addrlen)
407 struct Plugin *plugin = cls;
409 if (0 == plugin->max_connections)
411 plugin->max_connections--;
417 * Our external IP address/port mapping has changed.
419 * @param cls closure, the 'struct LocalAddrList'
420 * @param add_remove GNUNET_YES to mean the new public IP address, GNUNET_NO to mean
421 * the previous (now invalid) one
422 * @param addr either the previous or the new public IP address
423 * @param addrlen actual lenght of the address
426 tcp_nat_port_map_callback (void *cls, int add_remove,
427 const struct sockaddr *addr, socklen_t addrlen)
429 struct Plugin *plugin = cls;
430 struct IPv4TcpAddress t4;
431 struct IPv6TcpAddress t6;
435 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
436 "NPMC called with %d for address `%s'\n", add_remove,
437 GNUNET_a2s (addr, addrlen));
438 /* convert 'addr' to our internal format */
439 switch (addr->sa_family)
442 GNUNET_assert (addrlen == sizeof (struct sockaddr_in));
443 t4.ipv4_addr = ((struct sockaddr_in *) addr)->sin_addr.s_addr;
444 t4.t4_port = ((struct sockaddr_in *) addr)->sin_port;
449 GNUNET_assert (addrlen == sizeof (struct sockaddr_in6));
450 memcpy (&t6.ipv6_addr, &((struct sockaddr_in6 *) addr)->sin6_addr,
451 sizeof (struct in6_addr));
452 t6.t6_port = ((struct sockaddr_in6 *) addr)->sin6_port;
460 /* modify our published address list */
461 plugin->env->notify_address (plugin->env->cls, add_remove, arg, args);
466 * Function called for a quick conversion of the binary address to
467 * a numeric address. Note that the caller must not free the
468 * address and that the next call to this function is allowed
469 * to override the address again.
471 * @param cls closure ('struct Plugin*')
472 * @param addr binary address
473 * @param addrlen length of the address
474 * @return string representing the same address
477 tcp_address_to_string (void *cls, const void *addr, size_t addrlen)
479 static char rbuf[INET6_ADDRSTRLEN + 12];
480 char buf[INET6_ADDRSTRLEN];
484 const struct IPv4TcpAddress *t4;
485 const struct IPv6TcpAddress *t6;
489 if (addrlen == sizeof (struct IPv6TcpAddress))
493 port = ntohs (t6->t6_port);
494 memcpy (&a6, &t6->ipv6_addr, sizeof (a6));
497 else if (addrlen == sizeof (struct IPv4TcpAddress))
501 port = ntohs (t4->t4_port);
502 memcpy (&a4, &t4->ipv4_addr, sizeof (a4));
507 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, "tcp",
508 _("Unexpected address length: %u bytes\n"),
509 (unsigned int) addrlen);
513 if (NULL == inet_ntop (af, sb, buf, INET6_ADDRSTRLEN))
515 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "inet_ntop");
518 GNUNET_snprintf (rbuf, sizeof (rbuf), (af == AF_INET6) ? "[%s]:%u" : "%s:%u",
525 * Find the session handle for the given client.
527 * @param plugin the plugin
528 * @param client which client to find the session handle for
529 * @return NULL if no matching session exists
531 static struct Session *
532 find_session_by_client (struct Plugin *plugin,
533 const struct GNUNET_SERVER_Client *client)
537 ret = plugin->sessions;
538 while ((ret != NULL) && (client != ret->client))
545 * Create a new session. Also queues a welcome message.
547 * @param plugin the plugin
548 * @param target peer to connect to
549 * @param client client to use
550 * @param is_nat this a NAT session, we should wait for a client to
551 * connect to us from an address, then assign that to
553 * @return new session object
555 static struct Session *
556 create_session (struct Plugin *plugin, const struct GNUNET_PeerIdentity *target,
557 struct GNUNET_SERVER_Client *client, int is_nat)
560 struct PendingMessage *pm;
561 struct WelcomeMessage welcome;
563 if (is_nat != GNUNET_YES)
564 GNUNET_assert (client != NULL);
566 GNUNET_assert (client == NULL);
568 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
569 "Creating new session for peer `%4s'\n",
570 GNUNET_i2s (target));
572 ret = GNUNET_malloc (sizeof (struct Session));
573 ret->last_activity = GNUNET_TIME_absolute_get ();
574 ret->plugin = plugin;
575 ret->is_nat = is_nat;
576 if (is_nat != GNUNET_YES) /* If not a NAT WAIT conn, add it to global list */
578 ret->next = plugin->sessions;
579 plugin->sessions = ret;
581 ret->client = client;
582 ret->target = *target;
583 ret->expecting_welcome = GNUNET_YES;
584 pm = GNUNET_malloc (sizeof (struct PendingMessage) +
585 sizeof (struct WelcomeMessage));
586 pm->msg = (const char *) &pm[1];
587 pm->message_size = sizeof (struct WelcomeMessage);
588 welcome.header.size = htons (sizeof (struct WelcomeMessage));
589 welcome.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME);
590 welcome.clientIdentity = *plugin->env->my_identity;
591 memcpy (&pm[1], &welcome, sizeof (welcome));
592 pm->timeout = GNUNET_TIME_UNIT_FOREVER_ABS;
593 GNUNET_STATISTICS_update (plugin->env->stats,
594 gettext_noop ("# bytes currently in TCP buffers"),
595 pm->message_size, GNUNET_NO);
596 GNUNET_CONTAINER_DLL_insert (ret->pending_messages_head,
597 ret->pending_messages_tail, pm);
598 if (is_nat != GNUNET_YES)
599 GNUNET_STATISTICS_update (plugin->env->stats,
600 gettext_noop ("# TCP sessions active"), 1,
607 * If we have pending messages, ask the server to
608 * transmit them (schedule the respective tasks, etc.)
610 * @param session for which session should we do this
613 process_pending_messages (struct Session *session);
617 * Function called to notify a client about the socket
618 * being ready to queue more data. "buf" will be
619 * NULL and "size" zero if the socket was closed for
620 * writing in the meantime.
623 * @param size number of bytes available in buf
624 * @param buf where the callee should write the message
625 * @return number of bytes written to buf
628 do_transmit (void *cls, size_t size, void *buf)
630 struct Session *session = cls;
631 struct GNUNET_PeerIdentity pid;
632 struct Plugin *plugin;
633 struct PendingMessage *pos;
634 struct PendingMessage *hd;
635 struct PendingMessage *tl;
636 struct GNUNET_TIME_Absolute now;
640 GNUNET_assert (session != NULL);
641 session->transmit_handle = NULL;
642 plugin = session->plugin;
646 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
647 "Timeout trying to transmit to peer `%4s', discarding message queue.\n",
648 GNUNET_i2s (&session->target));
650 /* timeout; cancel all messages that have already expired */
654 now = GNUNET_TIME_absolute_get ();
655 while ((NULL != (pos = session->pending_messages_head)) &&
656 (pos->timeout.abs_value <= now.abs_value))
658 GNUNET_CONTAINER_DLL_remove (session->pending_messages_head,
659 session->pending_messages_tail, pos);
661 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
662 "Failed to transmit %u byte message to `%4s'.\n",
663 pos->message_size, GNUNET_i2s (&session->target));
665 ret += pos->message_size;
666 GNUNET_CONTAINER_DLL_insert_after (hd, tl, tl, pos);
668 /* do this call before callbacks (so that if callbacks destroy
669 * session, they have a chance to cancel actions done by this
671 process_pending_messages (session);
672 pid = session->target;
673 /* no do callbacks and do not use session again since
674 * the callbacks may abort the session */
675 while (NULL != (pos = hd))
677 GNUNET_CONTAINER_DLL_remove (hd, tl, pos);
678 if (pos->transmit_cont != NULL)
679 pos->transmit_cont (pos->transmit_cont_cls, &pid, GNUNET_SYSERR);
682 GNUNET_STATISTICS_update (plugin->env->stats,
683 gettext_noop ("# bytes currently in TCP buffers"),
684 -(int64_t) ret, GNUNET_NO);
685 GNUNET_STATISTICS_update (plugin->env->stats,
687 ("# bytes discarded by TCP (timeout)"), ret,
691 /* copy all pending messages that would fit */
696 while (NULL != (pos = session->pending_messages_head))
698 if (ret + pos->message_size > size)
700 GNUNET_CONTAINER_DLL_remove (session->pending_messages_head,
701 session->pending_messages_tail, pos);
702 GNUNET_assert (size >= pos->message_size);
703 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
704 "Transmitting message of type %u\n",
705 ntohs (((struct GNUNET_MessageHeader *) pos->msg)->type));
706 /* FIXME: this memcpy can be up to 7% of our total runtime */
707 memcpy (cbuf, pos->msg, pos->message_size);
708 cbuf += pos->message_size;
709 ret += pos->message_size;
710 size -= pos->message_size;
711 GNUNET_CONTAINER_DLL_insert_tail (hd, tl, pos);
713 /* schedule 'continuation' before callbacks so that callbacks that
714 * cancel everything don't cause us to use a session that no longer
716 process_pending_messages (session);
717 session->last_activity = GNUNET_TIME_absolute_get ();
718 pid = session->target;
719 /* we'll now call callbacks that may cancel the session; hence
720 * we should not use 'session' after this point */
721 while (NULL != (pos = hd))
723 GNUNET_CONTAINER_DLL_remove (hd, tl, pos);
724 if (pos->transmit_cont != NULL)
725 pos->transmit_cont (pos->transmit_cont_cls, &pid, GNUNET_OK);
728 GNUNET_assert (hd == NULL);
729 GNUNET_assert (tl == NULL);
731 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp", "Transmitting %u bytes\n",
734 GNUNET_STATISTICS_update (plugin->env->stats,
735 gettext_noop ("# bytes currently in TCP buffers"),
736 -(int64_t) ret, GNUNET_NO);
737 GNUNET_STATISTICS_update (plugin->env->stats,
738 gettext_noop ("# bytes transmitted via TCP"), ret,
745 * If we have pending messages, ask the server to
746 * transmit them (schedule the respective tasks, etc.)
748 * @param session for which session should we do this
751 process_pending_messages (struct Session *session)
753 struct PendingMessage *pm;
755 GNUNET_assert (session->client != NULL);
756 if (session->transmit_handle != NULL)
758 if (NULL == (pm = session->pending_messages_head))
761 session->transmit_handle =
762 GNUNET_SERVER_notify_transmit_ready (session->client, pm->message_size,
763 GNUNET_TIME_absolute_get_remaining
764 (pm->timeout), &do_transmit,
770 * Functions with this signature are called whenever we need
771 * to close a session due to a disconnect or failure to
772 * establish a connection.
774 * @param session session to close down
777 disconnect_session (struct Session *session)
779 struct Session *prev;
781 struct PendingMessage *pm;
784 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
785 "Disconnecting from `%4s' at %s.\n",
786 GNUNET_i2s (&session->target),
787 (session->connect_addr !=
788 NULL) ? tcp_address_to_string (session->plugin,
789 session->connect_addr,
790 session->connect_alen) :
793 /* remove from session list */
795 pos = session->plugin->sessions;
796 while (pos != session)
802 session->plugin->sessions = session->next;
804 prev->next = session->next;
807 if (session->transmit_handle != NULL)
809 GNUNET_CONNECTION_notify_transmit_ready_cancel (session->transmit_handle);
810 session->transmit_handle = NULL;
812 session->plugin->env->session_end (session->plugin->env->cls,
813 &session->target, session);
814 while (NULL != (pm = session->pending_messages_head))
817 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
819 NULL ? "Could not deliver message to `%4s'.\n" :
820 "Could not deliver message to `%4s', notifying.\n",
821 GNUNET_i2s (&session->target));
823 GNUNET_STATISTICS_update (session->plugin->env->stats,
824 gettext_noop ("# bytes currently in TCP buffers"),
825 -(int64_t) pm->message_size, GNUNET_NO);
826 GNUNET_STATISTICS_update (session->plugin->env->stats,
828 ("# bytes discarded by TCP (disconnect)"),
829 pm->message_size, GNUNET_NO);
830 GNUNET_CONTAINER_DLL_remove (session->pending_messages_head,
831 session->pending_messages_tail, pm);
832 if (NULL != pm->transmit_cont)
833 pm->transmit_cont (pm->transmit_cont_cls, &session->target,
837 GNUNET_break (session->client != NULL);
838 if (session->receive_delay_task != GNUNET_SCHEDULER_NO_TASK)
840 GNUNET_SCHEDULER_cancel (session->receive_delay_task);
841 if (session->client != NULL)
842 GNUNET_SERVER_receive_done (session->client, GNUNET_SYSERR);
844 if (session->client != NULL)
846 GNUNET_SERVER_client_drop (session->client);
847 session->client = NULL;
849 GNUNET_STATISTICS_update (session->plugin->env->stats,
850 gettext_noop ("# TCP sessions active"), -1,
852 GNUNET_free_non_null (session->connect_addr);
853 GNUNET_assert (NULL == session->transmit_handle);
854 GNUNET_free (session);
859 * Given two otherwise equivalent sessions, pick the better one.
861 * @param s1 one session (also default)
862 * @param s2 other session
863 * @return "better" session (more active)
865 static struct Session *
866 select_better_session (struct Session *s1, struct Session *s2)
872 if ((s1->expecting_welcome == GNUNET_NO) &&
873 (s2->expecting_welcome == GNUNET_YES))
875 if ((s1->expecting_welcome == GNUNET_YES) &&
876 (s2->expecting_welcome == GNUNET_NO))
878 if (s1->last_activity.abs_value < s2->last_activity.abs_value)
880 if (s1->last_activity.abs_value > s2->last_activity.abs_value)
882 if ((GNUNET_YES == s1->inbound) && (GNUNET_NO == s2->inbound))
884 if ((GNUNET_NO == s1->inbound) && (GNUNET_YES == s2->inbound))
892 * Function that can be used by the transport service to transmit
893 * a message using the plugin. Note that in the case of a
894 * peer disconnecting, the continuation MUST be called
895 * prior to the disconnect notification itself. This function
896 * will be called with this peer's HELLO message to initiate
897 * a fresh connection to another peer.
900 * @param target who should receive this message
901 * @param msg the message to transmit
902 * @param msgbuf_size number of bytes in 'msg'
903 * @param priority how important is the message (most plugins will
904 * ignore message priority and just FIFO)
905 * @param timeout how long to wait at most for the transmission (does not
906 * require plugins to discard the message after the timeout,
907 * just advisory for the desired delay; most plugins will ignore
909 * @param session which session must be used (or NULL for "any")
910 * @param addr the address to use (can be NULL if the plugin
911 * is "on its own" (i.e. re-use existing TCP connection))
912 * @param addrlen length of the address in bytes
913 * @param force_address GNUNET_YES if the plugin MUST use the given address,
914 * GNUNET_NO means the plugin may use any other address and
915 * GNUNET_SYSERR means that only reliable existing
916 * bi-directional connections should be used (regardless
918 * @param cont continuation to call once the message has
919 * been transmitted (or if the transport is ready
920 * for the next transmission call; or if the
921 * peer disconnected...); can be NULL
922 * @param cont_cls closure for cont
923 * @return number of bytes used (on the physical network, with overheads);
924 * -1 on hard errors (i.e. address invalid); 0 is a legal value
925 * and does NOT mean that the message was not transmitted (DV and NAT)
928 tcp_plugin_send (void *cls, const struct GNUNET_PeerIdentity *target,
929 const char *msg, size_t msgbuf_size, uint32_t priority,
930 struct GNUNET_TIME_Relative timeout, struct Session *session,
931 const void *addr, size_t addrlen, int force_address,
932 GNUNET_TRANSPORT_TransmitContinuation cont, void *cont_cls)
934 struct Plugin *plugin = cls;
935 struct Session *cand_session;
936 struct Session *next;
937 struct PendingMessage *pm;
938 struct GNUNET_CONNECTION_Handle *sa;
942 struct sockaddr_in a4;
943 struct sockaddr_in6 a6;
944 const struct IPv4TcpAddress *t4;
945 const struct IPv6TcpAddress *t6;
946 unsigned int is_natd;
948 GNUNET_STATISTICS_update (plugin->env->stats,
949 gettext_noop ("# bytes TCP was asked to transmit"),
950 msgbuf_size, GNUNET_NO);
951 /* FIXME: we could do this cheaper with a hash table
952 * where we could restrict the iteration to entries that match
953 * the target peer... */
958 next = plugin->sessions;
959 while (NULL != (session = next))
961 next = session->next;
962 GNUNET_assert (session->client != NULL);
964 memcmp (target, &session->target,
965 sizeof (struct GNUNET_PeerIdentity)))
967 if (((GNUNET_SYSERR == force_address) &&
968 (session->expecting_welcome == GNUNET_NO)) ||
969 (GNUNET_NO == force_address))
971 cand_session = select_better_session (cand_session, session);
974 if (GNUNET_SYSERR == force_address)
976 GNUNET_break (GNUNET_YES == force_address);
982 if ((addrlen != session->connect_alen) && (session->is_nat == GNUNET_NO))
984 if ((0 != memcmp (session->connect_addr, addr, addrlen)) &&
985 (session->is_nat == GNUNET_NO))
987 cand_session = select_better_session (cand_session, session);
989 session = cand_session;
991 if ((session == NULL) && (addrlen == 0))
994 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
995 "Asked to transmit to `%4s' without address and I have no existing connection (failing).\n",
996 GNUNET_i2s (target));
998 GNUNET_STATISTICS_update (plugin->env->stats,
1000 ("# bytes discarded by TCP (no address and no connection)"),
1001 msgbuf_size, GNUNET_NO);
1004 if (session == NULL)
1006 if (addrlen == sizeof (struct IPv6TcpAddress))
1008 GNUNET_assert (NULL != addr); /* make static analysis happy */
1011 memset (&a6, 0, sizeof (a6));
1012 #if HAVE_SOCKADDR_IN_SIN_LEN
1013 a6.sin6_len = sizeof (a6);
1015 a6.sin6_family = AF_INET6;
1016 a6.sin6_port = t6->t6_port;
1017 if (t6->t6_port == 0)
1018 is_natd = GNUNET_YES;
1019 memcpy (&a6.sin6_addr, &t6->ipv6_addr, sizeof (struct in6_addr));
1023 else if (addrlen == sizeof (struct IPv4TcpAddress))
1025 GNUNET_assert (NULL != addr); /* make static analysis happy */
1028 memset (&a4, 0, sizeof (a4));
1029 #if HAVE_SOCKADDR_IN_SIN_LEN
1030 a4.sin_len = sizeof (a4);
1032 a4.sin_family = AF_INET;
1033 a4.sin_port = t4->t4_port;
1034 if (t4->t4_port == 0)
1035 is_natd = GNUNET_YES;
1036 a4.sin_addr.s_addr = t4->ipv4_addr;
1042 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, "tcp",
1043 _("Address of unexpected length: %u\n"), addrlen);
1048 if ((is_natd == GNUNET_YES) && (addrlen == sizeof (struct IPv6TcpAddress)))
1049 return -1; /* NAT client only works with IPv4 addresses */
1050 if (0 == plugin->max_connections)
1051 return -1; /* saturated */
1053 if ((is_natd == GNUNET_YES) && (NULL != plugin->nat) &&
1055 GNUNET_CONTAINER_multihashmap_contains (plugin->nat_wait_conns,
1056 &target->hashPubKey)))
1059 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1060 _("Found valid IPv4 NAT address (creating session)!\n"));
1062 session = create_session (plugin, target, NULL, GNUNET_YES);
1063 GNUNET_assert (session != NULL);
1065 /* create new message entry */
1066 pm = GNUNET_malloc (sizeof (struct PendingMessage) + msgbuf_size);
1067 /* FIXME: the memset of this malloc can be up to 2% of our total runtime */
1068 pm->msg = (const char *) &pm[1];
1069 memcpy (&pm[1], msg, msgbuf_size);
1070 /* FIXME: this memcpy can be up to 7% of our total run-time
1071 * (for transport service) */
1072 pm->message_size = msgbuf_size;
1073 pm->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1074 pm->transmit_cont = cont;
1075 pm->transmit_cont_cls = cont_cls;
1077 /* append pm to pending_messages list */
1078 GNUNET_CONTAINER_DLL_insert_tail (session->pending_messages_head,
1079 session->pending_messages_tail, pm);
1081 GNUNET_assert (GNUNET_CONTAINER_multihashmap_put
1082 (plugin->nat_wait_conns, &target->hashPubKey, session,
1083 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY) ==
1086 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1087 "Created NAT WAIT connection to `%4s' at `%s'\n",
1088 GNUNET_i2s (target), GNUNET_a2s (sb, sbs));
1090 GNUNET_NAT_run_client (plugin->nat, &a4);
1093 if ((is_natd == GNUNET_YES) &&
1095 GNUNET_CONTAINER_multihashmap_contains (plugin->nat_wait_conns,
1096 &target->hashPubKey)))
1098 /* Only do one NAT punch attempt per peer identity */
1101 sa = GNUNET_CONNECTION_create_from_sockaddr (af, sb, sbs);
1105 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1106 "Failed to create connection to `%4s' at `%s'\n",
1107 GNUNET_i2s (target), GNUNET_a2s (sb, sbs));
1109 GNUNET_STATISTICS_update (plugin->env->stats,
1111 ("# bytes discarded by TCP (failed to connect)"),
1112 msgbuf_size, GNUNET_NO);
1115 GNUNET_assert (0 != plugin->max_connections);
1116 plugin->max_connections--;
1118 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1119 "Asked to transmit to `%4s', creating fresh session using address `%s'.\n",
1120 GNUNET_i2s (target), GNUNET_a2s (sb, sbs));
1123 create_session (plugin, target,
1124 GNUNET_SERVER_connect_socket (plugin->server, sa),
1126 session->connect_addr = GNUNET_malloc (addrlen);
1127 memcpy (session->connect_addr, addr, addrlen);
1128 session->connect_alen = addrlen;
1129 if ((addrlen != 0) && (plugin->env->ats != NULL))
1131 struct GNUNET_ATS_Information ats;
1132 GNUNET_assert(plugin->env->ats != NULL);
1133 ats = GNUNET_ATS_address_get_type(plugin->env->ats, sb ,sbs);
1134 session->ats_address_network_type = ats.value;
1139 else /* session != NULL */
1141 /* check if session is valid */
1142 struct Session *ses = plugin->sessions;
1145 memcmp (target, &session->target, sizeof (struct GNUNET_PeerIdentity)))
1148 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1149 "Got session %p for `%s', but should be for peer `%s'!\n",
1150 session, GNUNET_i2s (&session->target),
1151 GNUNET_h2s (&target->hashPubKey));
1155 while ((ses != NULL) && (ses != session))
1162 GNUNET_assert (session != NULL);
1163 GNUNET_assert (session->client != NULL);
1166 GNUNET_SERVER_client_set_timeout (session->client,
1167 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1168 GNUNET_STATISTICS_update (plugin->env->stats,
1169 gettext_noop ("# bytes currently in TCP buffers"),
1170 msgbuf_size, GNUNET_NO);
1171 /* create new message entry */
1172 pm = GNUNET_malloc (sizeof (struct PendingMessage) + msgbuf_size);
1173 pm->msg = (const char *) &pm[1];
1174 memcpy (&pm[1], msg, msgbuf_size);
1175 pm->message_size = msgbuf_size;
1176 pm->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1177 pm->transmit_cont = cont;
1178 pm->transmit_cont_cls = cont_cls;
1180 /* append pm to pending_messages list */
1181 GNUNET_CONTAINER_DLL_insert_tail (session->pending_messages_head,
1182 session->pending_messages_tail, pm);
1184 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1185 "Asked to transmit %u bytes to `%s', added message to list.\n",
1186 msgbuf_size, GNUNET_i2s (target));
1188 process_pending_messages (session);
1194 * Function that can be called to force a disconnect from the
1195 * specified neighbour. This should also cancel all previously
1196 * scheduled transmissions. Obviously the transmission may have been
1197 * partially completed already, which is OK. The plugin is supposed
1198 * to close the connection (if applicable) and no longer call the
1199 * transmit continuation(s).
1201 * Finally, plugin MUST NOT call the services's receive function to
1202 * notify the service that the connection to the specified target was
1203 * closed after a getting this call.
1205 * @param cls closure
1206 * @param target peer for which the last transmission is
1210 tcp_plugin_disconnect (void *cls, const struct GNUNET_PeerIdentity *target)
1212 struct Plugin *plugin = cls;
1213 struct Session *session;
1214 struct Session *next;
1215 struct PendingMessage *pm;
1218 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1219 "Asked to cancel session with `%4s'\n", GNUNET_i2s (target));
1221 next = plugin->sessions;
1222 while (NULL != (session = next))
1224 next = session->next;
1226 memcmp (target, &session->target, sizeof (struct GNUNET_PeerIdentity)))
1228 pm = session->pending_messages_head;
1231 pm->transmit_cont = NULL;
1232 pm->transmit_cont_cls = NULL;
1235 GNUNET_STATISTICS_update (session->plugin->env->stats,
1237 ("# transport-service disconnect requests for TCP"),
1239 disconnect_session (session);
1245 * Context for address to string conversion.
1247 struct PrettyPrinterContext
1250 * Function to call with the result.
1252 GNUNET_TRANSPORT_AddressStringCallback asc;
1255 * Clsoure for 'asc'.
1260 * Port to add after the IP address.
1267 * Append our port and forward the result.
1269 * @param cls the 'struct PrettyPrinterContext*'
1270 * @param hostname hostname part of the address
1273 append_port (void *cls, const char *hostname)
1275 struct PrettyPrinterContext *ppc = cls;
1278 if (hostname == NULL)
1280 ppc->asc (ppc->asc_cls, NULL);
1284 GNUNET_asprintf (&ret, "%s:%d", hostname, ppc->port);
1285 ppc->asc (ppc->asc_cls, ret);
1291 * Convert the transports address to a nice, human-readable
1294 * @param cls closure
1295 * @param type name of the transport that generated the address
1296 * @param addr one of the addresses of the host, NULL for the last address
1297 * the specific address format depends on the transport
1298 * @param addrlen length of the address
1299 * @param numeric should (IP) addresses be displayed in numeric form?
1300 * @param timeout after how long should we give up?
1301 * @param asc function to call on each string
1302 * @param asc_cls closure for asc
1305 tcp_plugin_address_pretty_printer (void *cls, const char *type,
1306 const void *addr, size_t addrlen,
1308 struct GNUNET_TIME_Relative timeout,
1309 GNUNET_TRANSPORT_AddressStringCallback asc,
1312 struct PrettyPrinterContext *ppc;
1315 struct sockaddr_in a4;
1316 struct sockaddr_in6 a6;
1317 const struct IPv4TcpAddress *t4;
1318 const struct IPv6TcpAddress *t6;
1321 if (addrlen == sizeof (struct IPv6TcpAddress))
1324 memset (&a6, 0, sizeof (a6));
1325 a6.sin6_family = AF_INET6;
1326 a6.sin6_port = t6->t6_port;
1327 memcpy (&a6.sin6_addr, &t6->ipv6_addr, sizeof (struct in6_addr));
1328 port = ntohs (t6->t6_port);
1332 else if (addrlen == sizeof (struct IPv4TcpAddress))
1335 memset (&a4, 0, sizeof (a4));
1336 a4.sin_family = AF_INET;
1337 a4.sin_port = t4->t4_port;
1338 a4.sin_addr.s_addr = t4->ipv4_addr;
1339 port = ntohs (t4->t4_port);
1345 /* invalid address */
1346 GNUNET_break_op (0);
1347 asc (asc_cls, NULL);
1350 ppc = GNUNET_malloc (sizeof (struct PrettyPrinterContext));
1352 ppc->asc_cls = asc_cls;
1354 GNUNET_RESOLVER_hostname_get (sb, sbs, !numeric, timeout, &append_port, ppc);
1359 * Check if the given port is plausible (must be either our listen
1360 * port or our advertised port), or any port if we are behind NAT
1361 * and do not have a port open. If it is neither, we return
1364 * @param plugin global variables
1365 * @param in_port port number to check
1366 * @return GNUNET_OK if port is either open_port or adv_port
1369 check_port (struct Plugin *plugin, uint16_t in_port)
1371 if ((in_port == plugin->adv_port) || (in_port == plugin->open_port))
1373 return GNUNET_SYSERR;
1378 * Function that will be called to check if a binary address for this
1379 * plugin is well-formed and corresponds to an address for THIS peer
1380 * (as per our configuration). Naturally, if absolutely necessary,
1381 * plugins can be a bit conservative in their answer, but in general
1382 * plugins should make sure that the address does not redirect
1383 * traffic to a 3rd party that might try to man-in-the-middle our
1386 * @param cls closure, our 'struct Plugin*'
1387 * @param addr pointer to the address
1388 * @param addrlen length of addr
1389 * @return GNUNET_OK if this is a plausible address for this peer
1390 * and transport, GNUNET_SYSERR if not
1393 tcp_plugin_check_address (void *cls, const void *addr, size_t addrlen)
1395 struct Plugin *plugin = cls;
1396 struct IPv4TcpAddress *v4;
1397 struct IPv6TcpAddress *v6;
1399 if ((addrlen != sizeof (struct IPv4TcpAddress)) &&
1400 (addrlen != sizeof (struct IPv6TcpAddress)))
1402 GNUNET_break_op (0);
1403 return GNUNET_SYSERR;
1405 if (addrlen == sizeof (struct IPv4TcpAddress))
1407 v4 = (struct IPv4TcpAddress *) addr;
1408 if (GNUNET_OK != check_port (plugin, ntohs (v4->t4_port)))
1409 return GNUNET_SYSERR;
1411 GNUNET_NAT_test_address (plugin->nat, &v4->ipv4_addr,
1412 sizeof (struct in_addr)))
1413 return GNUNET_SYSERR;
1417 v6 = (struct IPv6TcpAddress *) addr;
1418 if (IN6_IS_ADDR_LINKLOCAL (&v6->ipv6_addr))
1420 GNUNET_break_op (0);
1421 return GNUNET_SYSERR;
1423 if (GNUNET_OK != check_port (plugin, ntohs (v6->t6_port)))
1424 return GNUNET_SYSERR;
1426 GNUNET_NAT_test_address (plugin->nat, &v6->ipv6_addr,
1427 sizeof (struct in6_addr)))
1428 return GNUNET_SYSERR;
1435 * We've received a nat probe from this peer via TCP. Finish
1436 * creating the client session and resume sending of queued
1439 * @param cls closure
1440 * @param client identification of the client
1441 * @param message the actual message
1444 handle_tcp_nat_probe (void *cls, struct GNUNET_SERVER_Client *client,
1445 const struct GNUNET_MessageHeader *message)
1447 struct Plugin *plugin = cls;
1448 struct Session *session;
1449 const struct TCP_NAT_ProbeMessage *tcp_nat_probe;
1452 struct IPv4TcpAddress *t4;
1453 struct IPv6TcpAddress *t6;
1454 const struct sockaddr_in *s4;
1455 const struct sockaddr_in6 *s6;
1458 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp", "received NAT probe\n");
1460 /* We have received a TCP NAT probe, meaning we (hopefully) initiated
1461 * a connection to this peer by running gnunet-nat-client. This peer
1462 * received the punch message and now wants us to use the new connection
1463 * as the default for that peer. Do so and then send a WELCOME message
1464 * so we can really be connected!
1466 if (ntohs (message->size) != sizeof (struct TCP_NAT_ProbeMessage))
1468 GNUNET_break_op (0);
1469 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1473 tcp_nat_probe = (const struct TCP_NAT_ProbeMessage *) message;
1475 memcmp (&tcp_nat_probe->clientIdentity, plugin->env->my_identity,
1476 sizeof (struct GNUNET_PeerIdentity)))
1478 /* refuse connections from ourselves */
1479 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1484 GNUNET_CONTAINER_multihashmap_get (plugin->nat_wait_conns,
1486 clientIdentity.hashPubKey);
1487 if (session == NULL)
1490 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1491 "Did NOT find session for NAT probe!\n");
1493 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1497 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1498 "Found session for NAT probe!\n");
1500 GNUNET_assert (GNUNET_CONTAINER_multihashmap_remove
1501 (plugin->nat_wait_conns,
1502 &tcp_nat_probe->clientIdentity.hashPubKey,
1503 session) == GNUNET_YES);
1504 if (GNUNET_OK != GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
1507 GNUNET_free (session);
1508 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1512 GNUNET_SERVER_client_keep (client);
1513 session->client = client;
1514 session->last_activity = GNUNET_TIME_absolute_get ();
1515 session->inbound = GNUNET_NO;
1518 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1519 "Found address `%s' for incoming connection\n",
1520 GNUNET_a2s (vaddr, alen));
1522 switch (((const struct sockaddr *) vaddr)->sa_family)
1526 t4 = GNUNET_malloc (sizeof (struct IPv4TcpAddress));
1527 t4->t4_port = s4->sin_port;
1528 t4->ipv4_addr = s4->sin_addr.s_addr;
1529 session->connect_addr = t4;
1530 session->connect_alen = sizeof (struct IPv4TcpAddress);
1534 t6 = GNUNET_malloc (sizeof (struct IPv6TcpAddress));
1535 t6->t6_port = s6->sin6_port;
1536 memcpy (&t6->ipv6_addr, &s6->sin6_addr, sizeof (struct in6_addr));
1537 session->connect_addr = t6;
1538 session->connect_alen = sizeof (struct IPv6TcpAddress);
1541 GNUNET_break_op (0);
1543 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1544 "Bad address for incoming connection!\n");
1546 GNUNET_free (vaddr);
1547 GNUNET_SERVER_client_drop (client);
1548 GNUNET_free (session);
1549 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1552 GNUNET_free (vaddr);
1554 session->next = plugin->sessions;
1555 plugin->sessions = session;
1556 GNUNET_STATISTICS_update (plugin->env->stats,
1557 gettext_noop ("# TCP sessions active"), 1,
1559 process_pending_messages (session);
1560 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1565 * We've received a welcome from this peer via TCP. Possibly create a
1566 * fresh client record and send back our welcome.
1568 * @param cls closure
1569 * @param client identification of the client
1570 * @param message the actual message
1573 handle_tcp_welcome (void *cls, struct GNUNET_SERVER_Client *client,
1574 const struct GNUNET_MessageHeader *message)
1576 struct Plugin *plugin = cls;
1577 const struct WelcomeMessage *wm = (const struct WelcomeMessage *) message;
1578 struct Session *session;
1581 struct IPv4TcpAddress *t4;
1582 struct IPv6TcpAddress *t6;
1583 const struct sockaddr_in *s4;
1584 const struct sockaddr_in6 *s6;
1587 memcmp (&wm->clientIdentity, plugin->env->my_identity,
1588 sizeof (struct GNUNET_PeerIdentity)))
1590 /* refuse connections from ourselves */
1591 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1595 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1596 "Received %s message from `%4s'.\n", "WELCOME",
1597 GNUNET_i2s (&wm->clientIdentity));
1599 GNUNET_STATISTICS_update (plugin->env->stats,
1600 gettext_noop ("# TCP WELCOME messages received"), 1,
1602 session = find_session_by_client (plugin, client);
1604 if (session == NULL)
1607 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1608 "Received %s message from a `%4s', creating new session\n",
1609 "WELCOME", GNUNET_i2s (&wm->clientIdentity));
1611 GNUNET_SERVER_client_keep (client);
1612 session = create_session (plugin, &wm->clientIdentity, client, GNUNET_NO);
1613 session->inbound = GNUNET_YES;
1614 if (GNUNET_OK == GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
1617 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1618 "Found address `%s' for incoming connection\n",
1619 GNUNET_a2s (vaddr, alen));
1622 if (alen == sizeof (struct sockaddr_in))
1625 t4 = GNUNET_malloc (sizeof (struct IPv4TcpAddress));
1626 t4->t4_port = s4->sin_port;
1627 t4->ipv4_addr = s4->sin_addr.s_addr;
1628 session->connect_addr = t4;
1629 session->connect_alen = sizeof (struct IPv4TcpAddress);
1631 else if (alen == sizeof (struct sockaddr_in6))
1634 t6 = GNUNET_malloc (sizeof (struct IPv6TcpAddress));
1635 t6->t6_port = s6->sin6_port;
1636 memcpy (&t6->ipv6_addr, &s6->sin6_addr, sizeof (struct in6_addr));
1637 session->connect_addr = t6;
1638 session->connect_alen = sizeof (struct IPv6TcpAddress);
1641 if (plugin->env->ats != NULL)
1643 struct GNUNET_ATS_Information ats;
1644 GNUNET_assert(plugin->env->ats != NULL);
1645 ats = GNUNET_ATS_address_get_type(plugin->env->ats, vaddr ,alen);
1646 session->ats_address_network_type = ats.value;
1650 GNUNET_free (vaddr);
1655 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1656 "Did not obtain TCP socket address for incoming connection\n");
1659 process_pending_messages (session);
1664 if (GNUNET_OK == GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
1666 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1667 "Found address `%s' (already have session)\n",
1668 GNUNET_a2s (vaddr, alen));
1669 GNUNET_free (vaddr);
1674 if (session->expecting_welcome != GNUNET_YES)
1676 GNUNET_break_op (0);
1677 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1680 session->last_activity = GNUNET_TIME_absolute_get ();
1681 session->expecting_welcome = GNUNET_NO;
1682 GNUNET_SERVER_client_set_timeout (client,
1683 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1684 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1689 * Task to signal the server that we can continue
1690 * receiving from the TCP client now.
1692 * @param cls the 'struct Session*'
1693 * @param tc task context (unused)
1696 delayed_done (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1698 struct Session *session = cls;
1699 struct GNUNET_TIME_Relative delay;
1700 struct GNUNET_ATS_Information ats;
1702 session->receive_delay_task = GNUNET_SCHEDULER_NO_TASK;
1704 session->plugin->env->receive (session->plugin->env->cls,
1705 &session->target, NULL, &ats, 0, session,
1707 if (delay.rel_value == 0)
1708 GNUNET_SERVER_receive_done (session->client, GNUNET_OK);
1710 session->receive_delay_task =
1711 GNUNET_SCHEDULER_add_delayed (delay, &delayed_done, session);
1716 * We've received data for this peer via TCP. Unbox,
1717 * compute latency and forward.
1719 * @param cls closure
1720 * @param client identification of the client
1721 * @param message the actual message
1724 handle_tcp_data (void *cls, struct GNUNET_SERVER_Client *client,
1725 const struct GNUNET_MessageHeader *message)
1727 struct Plugin *plugin = cls;
1728 struct Session *session;
1729 struct GNUNET_TIME_Relative delay;
1732 type = ntohs (message->type);
1733 if ((GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME == type) ||
1734 (GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE == type))
1736 /* We don't want to propagate WELCOME and NAT Probe messages up! */
1737 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1740 session = find_session_by_client (plugin, client);
1741 if ((NULL == session) || (GNUNET_YES == session->expecting_welcome))
1743 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1746 session->last_activity = GNUNET_TIME_absolute_get ();
1748 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1749 "Passing %u bytes of type %u from `%4s' to transport service.\n",
1750 (unsigned int) ntohs (message->size),
1751 (unsigned int) ntohs (message->type),
1752 GNUNET_i2s (&session->target));
1754 GNUNET_STATISTICS_update (plugin->env->stats,
1755 gettext_noop ("# bytes received via TCP"),
1756 ntohs (message->size), GNUNET_NO);
1757 struct GNUNET_ATS_Information distance[2];
1759 distance[0].type = htonl (GNUNET_ATS_QUALITY_NET_DISTANCE);
1760 distance[0].value = htonl (1);
1761 distance[1].type = htonl (GNUNET_ATS_NETWORK_TYPE);
1762 distance[1].value = session->ats_address_network_type;
1763 GNUNET_break (ntohl(session->ats_address_network_type) != GNUNET_ATS_NET_UNSPECIFIED);
1766 plugin->env->receive (plugin->env->cls, &session->target, message,
1767 (const struct GNUNET_ATS_Information *) &distance,
1770 session->inbound) ? NULL : session->connect_addr,
1772 session->inbound) ? 0 : session->connect_alen);
1773 if (delay.rel_value == 0)
1775 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1780 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1781 "Throttling receiving from `%s' for %llu ms\n",
1782 GNUNET_i2s (&session->target),
1783 (unsigned long long) delay.rel_value);
1785 GNUNET_SERVER_disable_receive_done_warning (client);
1786 session->receive_delay_task =
1787 GNUNET_SCHEDULER_add_delayed (delay, &delayed_done, session);
1793 * Functions with this signature are called whenever a peer
1794 * is disconnected on the network level.
1796 * @param cls closure
1797 * @param client identification of the client
1800 disconnect_notify (void *cls, struct GNUNET_SERVER_Client *client)
1802 struct Plugin *plugin = cls;
1803 struct Session *session;
1807 plugin->max_connections++;
1808 session = find_session_by_client (plugin, client);
1809 if (session == NULL)
1810 return; /* unknown, nothing to do */
1812 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1813 "Destroying session of `%4s' with %s due to network-level disconnect.\n",
1814 GNUNET_i2s (&session->target),
1815 (session->connect_addr !=
1816 NULL) ? tcp_address_to_string (session->plugin,
1817 session->connect_addr,
1818 session->connect_alen) :
1821 GNUNET_STATISTICS_update (session->plugin->env->stats,
1823 ("# network-level TCP disconnect events"), 1,
1825 disconnect_session (session);
1830 * We can now send a probe message, copy into buffer to really send.
1832 * @param cls closure, a struct TCPProbeContext
1833 * @param size max size to copy
1834 * @param buf buffer to copy message to
1835 * @return number of bytes copied into buf
1838 notify_send_probe (void *cls, size_t size, void *buf)
1840 struct TCPProbeContext *tcp_probe_ctx = cls;
1841 struct Plugin *plugin = tcp_probe_ctx->plugin;
1844 tcp_probe_ctx->transmit_handle = NULL;
1845 GNUNET_CONTAINER_DLL_remove (plugin->probe_head, plugin->probe_tail,
1849 GNUNET_CONNECTION_destroy (tcp_probe_ctx->sock, GNUNET_NO);
1850 GNUNET_free (tcp_probe_ctx);
1853 GNUNET_assert (size >= sizeof (tcp_probe_ctx->message));
1854 memcpy (buf, &tcp_probe_ctx->message, sizeof (tcp_probe_ctx->message));
1855 GNUNET_SERVER_connect_socket (tcp_probe_ctx->plugin->server,
1856 tcp_probe_ctx->sock);
1857 ret = sizeof (tcp_probe_ctx->message);
1858 GNUNET_free (tcp_probe_ctx);
1864 * Function called by the NAT subsystem suggesting another peer wants
1865 * to connect to us via connection reversal. Try to connect back to the
1868 * @param cls closure
1869 * @param addr address to try
1870 * @param addrlen number of bytes in addr
1873 try_connection_reversal (void *cls, const struct sockaddr *addr,
1876 struct Plugin *plugin = cls;
1877 struct GNUNET_CONNECTION_Handle *sock;
1878 struct TCPProbeContext *tcp_probe_ctx;
1881 * We have received an ICMP response, ostensibly from a peer
1882 * that wants to connect to us! Send a message to establish a connection.
1884 sock = GNUNET_CONNECTION_create_from_sockaddr (AF_INET, addr, addrlen);
1887 /* failed for some odd reason (out of sockets?); ignore attempt */
1891 /* FIXME: do we need to track these probe context objects so that
1892 * we can clean them up on plugin unload? */
1893 tcp_probe_ctx = GNUNET_malloc (sizeof (struct TCPProbeContext));
1894 tcp_probe_ctx->message.header.size =
1895 htons (sizeof (struct TCP_NAT_ProbeMessage));
1896 tcp_probe_ctx->message.header.type =
1897 htons (GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE);
1898 memcpy (&tcp_probe_ctx->message.clientIdentity, plugin->env->my_identity,
1899 sizeof (struct GNUNET_PeerIdentity));
1900 tcp_probe_ctx->plugin = plugin;
1901 tcp_probe_ctx->sock = sock;
1902 GNUNET_CONTAINER_DLL_insert (plugin->probe_head, plugin->probe_tail,
1904 tcp_probe_ctx->transmit_handle =
1905 GNUNET_CONNECTION_notify_transmit_ready (sock,
1906 ntohs (tcp_probe_ctx->
1907 message.header.size),
1908 GNUNET_TIME_UNIT_FOREVER_REL,
1916 * Entry point for the plugin.
1918 * @param cls closure, the 'struct GNUNET_TRANSPORT_PluginEnvironment*'
1919 * @return the 'struct GNUNET_TRANSPORT_PluginFunctions*' or NULL on error
1922 libgnunet_plugin_transport_tcp_init (void *cls)
1924 static const struct GNUNET_SERVER_MessageHandler my_handlers[] = {
1925 {&handle_tcp_welcome, NULL, GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME,
1926 sizeof (struct WelcomeMessage)},
1927 {&handle_tcp_nat_probe, NULL, GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE,
1928 sizeof (struct TCP_NAT_ProbeMessage)},
1929 {&handle_tcp_data, NULL, GNUNET_MESSAGE_TYPE_ALL, 0},
1932 struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
1933 struct GNUNET_TRANSPORT_PluginFunctions *api;
1934 struct Plugin *plugin;
1935 struct GNUNET_SERVICE_Context *service;
1936 unsigned long long aport;
1937 unsigned long long bport;
1938 unsigned long long max_connections;
1940 struct GNUNET_TIME_Relative idle_timeout;
1942 struct sockaddr **addrs;
1943 socklen_t *addrlens;
1946 GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-tcp",
1949 max_connections = 128;
1953 GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-tcp", "PORT",
1954 &bport)) || (bport > 65535) ||
1956 GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-tcp",
1957 "ADVERTISED-PORT", &aport)) &&
1960 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, "tcp",
1962 ("Require valid port number for service `%s' in configuration!\n"),
1972 service = GNUNET_SERVICE_start ("transport-tcp", env->cfg);
1973 if (service == NULL)
1975 GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, "tcp",
1976 _("Failed to start service.\n"));
1985 plugin = GNUNET_malloc (sizeof (struct Plugin));
1986 plugin->max_connections = max_connections;
1987 plugin->open_port = bport;
1988 plugin->adv_port = aport;
1990 plugin->lsock = NULL;
1991 if ((service != NULL) &&
1994 GNUNET_SERVICE_get_server_addresses ("transport-tcp", env->cfg, &addrs,
1998 GNUNET_NAT_register (env->cfg, GNUNET_YES, aport, (unsigned int) ret,
1999 (const struct sockaddr **) addrs, addrlens,
2000 &tcp_nat_port_map_callback,
2001 &try_connection_reversal, plugin);
2005 GNUNET_assert (addrs[ret] != NULL);
2006 GNUNET_free (addrs[ret]);
2008 GNUNET_free_non_null (addrs);
2009 GNUNET_free_non_null (addrlens);
2014 GNUNET_NAT_register (env->cfg, GNUNET_YES, 0, 0, NULL, NULL, NULL,
2015 &try_connection_reversal, plugin);
2017 api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
2019 api->send = &tcp_plugin_send;
2020 api->disconnect = &tcp_plugin_disconnect;
2021 api->address_pretty_printer = &tcp_plugin_address_pretty_printer;
2022 api->check_address = &tcp_plugin_check_address;
2023 api->address_to_string = &tcp_address_to_string;
2024 plugin->service = service;
2025 if (service != NULL)
2027 plugin->server = GNUNET_SERVICE_get_server (service);
2032 GNUNET_CONFIGURATION_get_value_time (env->cfg, "transport-tcp",
2033 "TIMEOUT", &idle_timeout))
2035 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, "tcp",
2036 _("Failed to find option %s in section %s!\n"),
2037 "TIMEOUT", "transport-tcp");
2038 if (plugin->nat != NULL)
2039 GNUNET_NAT_unregister (plugin->nat);
2040 GNUNET_free (plugin);
2045 GNUNET_SERVER_create_with_sockets (&plugin_tcp_access_check, plugin,
2046 NULL, idle_timeout, GNUNET_YES);
2048 plugin->handlers = GNUNET_malloc (sizeof (my_handlers));
2049 memcpy (plugin->handlers, my_handlers, sizeof (my_handlers));
2051 i < sizeof (my_handlers) / sizeof (struct GNUNET_SERVER_MessageHandler);
2053 plugin->handlers[i].callback_cls = plugin;
2054 GNUNET_SERVER_add_handlers (plugin->server, plugin->handlers);
2055 GNUNET_SERVER_disconnect_notify (plugin->server, &disconnect_notify, plugin);
2056 plugin->nat_wait_conns = GNUNET_CONTAINER_multihashmap_create (16);
2058 GNUNET_log_from (GNUNET_ERROR_TYPE_INFO, "tcp",
2059 _("TCP transport listening on port %llu\n"), bport);
2061 GNUNET_log_from (GNUNET_ERROR_TYPE_INFO, "tcp",
2063 ("TCP transport not listening on any port (client only)\n"));
2065 GNUNET_log_from (GNUNET_ERROR_TYPE_INFO, "tcp",
2067 ("TCP transport advertises itself as being on port %llu\n"),
2074 * Exit point from the plugin.
2077 libgnunet_plugin_transport_tcp_done (void *cls)
2079 struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
2080 struct Plugin *plugin = api->cls;
2081 struct Session *session;
2082 struct TCPProbeContext *tcp_probe;
2084 while (NULL != (session = plugin->sessions))
2085 disconnect_session (session);
2086 if (plugin->service != NULL)
2087 GNUNET_SERVICE_stop (plugin->service);
2089 GNUNET_SERVER_destroy (plugin->server);
2090 GNUNET_free (plugin->handlers);
2091 if (plugin->nat != NULL)
2092 GNUNET_NAT_unregister (plugin->nat);
2093 while (NULL != (tcp_probe = plugin->probe_head))
2095 GNUNET_CONTAINER_DLL_remove (plugin->probe_head, plugin->probe_tail,
2097 GNUNET_CONNECTION_destroy (tcp_probe->sock, GNUNET_NO);
2098 GNUNET_free (tcp_probe);
2100 GNUNET_CONTAINER_multihashmap_destroy (plugin->nat_wait_conns);
2101 GNUNET_free (plugin);
2106 /* end of plugin_transport_tcp.c */