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?
302 * Encapsulation of all of the state of the plugin.
309 struct GNUNET_TRANSPORT_PluginEnvironment *env;
314 struct GNUNET_CONNECTION_Handle *lsock;
317 * Our handle to the NAT module.
319 struct GNUNET_NAT_Handle *nat;
322 * List of open TCP sessions.
324 struct Session *sessions;
327 * Handle to the network service.
329 struct GNUNET_SERVICE_Context *service;
332 * Handle to the server for this service.
334 struct GNUNET_SERVER_Handle *server;
337 * Copy of the handler array where the closures are
338 * set to this struct's instance.
340 struct GNUNET_SERVER_MessageHandler *handlers;
343 * Map of peers we have tried to contact behind a NAT
345 struct GNUNET_CONTAINER_MultiHashMap *nat_wait_conns;
348 * List of active TCP probes.
350 struct TCPProbeContext *probe_head;
353 * List of active TCP probes.
355 struct TCPProbeContext *probe_tail;
358 * Handle for (DYN)DNS lookup of our external IP.
360 struct GNUNET_RESOLVER_RequestHandle *ext_dns;
363 * How many more TCP sessions are we allowed to open right now?
365 unsigned long long max_connections;
368 * ID of task used to update our addresses when one expires.
370 GNUNET_SCHEDULER_TaskIdentifier address_update_task;
373 * Port that we are actually listening on.
378 * Port that the user said we would have visible to the
387 * Function to check if an inbound connection is acceptable.
388 * Mostly used to limit the total number of open connections
391 * @param cls the 'struct Plugin'
392 * @param ucred credentials, if available, otherwise NULL
393 * @param addr address
394 * @param addrlen length of address
395 * @return GNUNET_YES to allow, GNUNET_NO to deny, GNUNET_SYSERR
396 * for unknown address family (will be denied).
399 plugin_tcp_access_check (void *cls,
400 const struct GNUNET_CONNECTION_Credentials *ucred,
401 const struct sockaddr *addr, socklen_t addrlen)
403 struct Plugin *plugin = cls;
405 if (0 == plugin->max_connections)
407 plugin->max_connections--;
413 * Our external IP address/port mapping has changed.
415 * @param cls closure, the 'struct LocalAddrList'
416 * @param add_remove GNUNET_YES to mean the new public IP address, GNUNET_NO to mean
417 * the previous (now invalid) one
418 * @param addr either the previous or the new public IP address
419 * @param addrlen actual lenght of the address
422 tcp_nat_port_map_callback (void *cls, int add_remove,
423 const struct sockaddr *addr, socklen_t addrlen)
425 struct Plugin *plugin = cls;
426 struct IPv4TcpAddress t4;
427 struct IPv6TcpAddress t6;
431 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
432 "NPMC called with %d for address `%s'\n", add_remove,
433 GNUNET_a2s (addr, addrlen));
434 /* convert 'addr' to our internal format */
435 switch (addr->sa_family)
438 GNUNET_assert (addrlen == sizeof (struct sockaddr_in));
439 t4.ipv4_addr = ((struct sockaddr_in *) addr)->sin_addr.s_addr;
440 t4.t4_port = ((struct sockaddr_in *) addr)->sin_port;
445 GNUNET_assert (addrlen == sizeof (struct sockaddr_in6));
446 memcpy (&t6.ipv6_addr, &((struct sockaddr_in6 *) addr)->sin6_addr,
447 sizeof (struct in6_addr));
448 t6.t6_port = ((struct sockaddr_in6 *) addr)->sin6_port;
456 /* modify our published address list */
457 plugin->env->notify_address (plugin->env->cls, add_remove, arg, args);
462 * Function called for a quick conversion of the binary address to
463 * a numeric address. Note that the caller must not free the
464 * address and that the next call to this function is allowed
465 * to override the address again.
467 * @param cls closure ('struct Plugin*')
468 * @param addr binary address
469 * @param addrlen length of the address
470 * @return string representing the same address
473 tcp_address_to_string (void *cls, const void *addr, size_t addrlen)
475 static char rbuf[INET6_ADDRSTRLEN + 12];
476 char buf[INET6_ADDRSTRLEN];
480 const struct IPv4TcpAddress *t4;
481 const struct IPv6TcpAddress *t6;
485 if (addrlen == sizeof (struct IPv6TcpAddress))
489 port = ntohs (t6->t6_port);
490 memcpy (&a6, &t6->ipv6_addr, sizeof (a6));
493 else if (addrlen == sizeof (struct IPv4TcpAddress))
497 port = ntohs (t4->t4_port);
498 memcpy (&a4, &t4->ipv4_addr, sizeof (a4));
503 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, "tcp",
504 _("Unexpected address length: %u bytes\n"),
505 (unsigned int) addrlen);
509 if (NULL == inet_ntop (af, sb, buf, INET6_ADDRSTRLEN))
511 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "inet_ntop");
514 GNUNET_snprintf (rbuf, sizeof (rbuf), (af == AF_INET6) ? "[%s]:%u" : "%s:%u",
521 * Find the session handle for the given client.
523 * @param plugin the plugin
524 * @param client which client to find the session handle for
525 * @return NULL if no matching session exists
527 static struct Session *
528 find_session_by_client (struct Plugin *plugin,
529 const struct GNUNET_SERVER_Client *client)
533 ret = plugin->sessions;
534 while ((ret != NULL) && (client != ret->client))
541 * Create a new session. Also queues a welcome message.
543 * @param plugin the plugin
544 * @param target peer to connect to
545 * @param client client to use
546 * @param is_nat this a NAT session, we should wait for a client to
547 * connect to us from an address, then assign that to
549 * @return new session object
551 static struct Session *
552 create_session (struct Plugin *plugin, const struct GNUNET_PeerIdentity *target,
553 struct GNUNET_SERVER_Client *client, int is_nat)
556 struct PendingMessage *pm;
557 struct WelcomeMessage welcome;
559 if (is_nat != GNUNET_YES)
560 GNUNET_assert (client != NULL);
562 GNUNET_assert (client == NULL);
564 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
565 "Creating new session for peer `%4s'\n",
566 GNUNET_i2s (target));
568 ret = GNUNET_malloc (sizeof (struct Session));
569 ret->last_activity = GNUNET_TIME_absolute_get ();
570 ret->plugin = plugin;
571 ret->is_nat = is_nat;
572 if (is_nat != GNUNET_YES) /* If not a NAT WAIT conn, add it to global list */
574 ret->next = plugin->sessions;
575 plugin->sessions = ret;
577 ret->client = client;
578 ret->target = *target;
579 ret->expecting_welcome = GNUNET_YES;
580 pm = GNUNET_malloc (sizeof (struct PendingMessage) +
581 sizeof (struct WelcomeMessage));
582 pm->msg = (const char *) &pm[1];
583 pm->message_size = sizeof (struct WelcomeMessage);
584 welcome.header.size = htons (sizeof (struct WelcomeMessage));
585 welcome.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME);
586 welcome.clientIdentity = *plugin->env->my_identity;
587 memcpy (&pm[1], &welcome, sizeof (welcome));
588 pm->timeout = GNUNET_TIME_UNIT_FOREVER_ABS;
589 GNUNET_STATISTICS_update (plugin->env->stats,
590 gettext_noop ("# bytes currently in TCP buffers"),
591 pm->message_size, GNUNET_NO);
592 GNUNET_CONTAINER_DLL_insert (ret->pending_messages_head,
593 ret->pending_messages_tail, pm);
594 if (is_nat != GNUNET_YES)
595 GNUNET_STATISTICS_update (plugin->env->stats,
596 gettext_noop ("# TCP sessions active"), 1,
603 * If we have pending messages, ask the server to
604 * transmit them (schedule the respective tasks, etc.)
606 * @param session for which session should we do this
609 process_pending_messages (struct Session *session);
613 * Function called to notify a client about the socket
614 * being ready to queue more data. "buf" will be
615 * NULL and "size" zero if the socket was closed for
616 * writing in the meantime.
619 * @param size number of bytes available in buf
620 * @param buf where the callee should write the message
621 * @return number of bytes written to buf
624 do_transmit (void *cls, size_t size, void *buf)
626 struct Session *session = cls;
627 struct GNUNET_PeerIdentity pid;
628 struct Plugin *plugin;
629 struct PendingMessage *pos;
630 struct PendingMessage *hd;
631 struct PendingMessage *tl;
632 struct GNUNET_TIME_Absolute now;
636 GNUNET_assert (session != NULL);
637 session->transmit_handle = NULL;
638 plugin = session->plugin;
642 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
643 "Timeout trying to transmit to peer `%4s', discarding message queue.\n",
644 GNUNET_i2s (&session->target));
646 /* timeout; cancel all messages that have already expired */
650 now = GNUNET_TIME_absolute_get ();
651 while ((NULL != (pos = session->pending_messages_head)) &&
652 (pos->timeout.abs_value <= now.abs_value))
654 GNUNET_CONTAINER_DLL_remove (session->pending_messages_head,
655 session->pending_messages_tail, pos);
657 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
658 "Failed to transmit %u byte message to `%4s'.\n",
659 pos->message_size, GNUNET_i2s (&session->target));
661 ret += pos->message_size;
662 GNUNET_CONTAINER_DLL_insert_after (hd, tl, tl, pos);
664 /* do this call before callbacks (so that if callbacks destroy
665 * session, they have a chance to cancel actions done by this
667 process_pending_messages (session);
668 pid = session->target;
669 /* no do callbacks and do not use session again since
670 * the callbacks may abort the session */
671 while (NULL != (pos = hd))
673 GNUNET_CONTAINER_DLL_remove (hd, tl, pos);
674 if (pos->transmit_cont != NULL)
675 pos->transmit_cont (pos->transmit_cont_cls, &pid, GNUNET_SYSERR);
678 GNUNET_STATISTICS_update (plugin->env->stats,
679 gettext_noop ("# bytes currently in TCP buffers"),
680 -(int64_t) ret, GNUNET_NO);
681 GNUNET_STATISTICS_update (plugin->env->stats,
683 ("# bytes discarded by TCP (timeout)"), ret,
687 /* copy all pending messages that would fit */
692 while (NULL != (pos = session->pending_messages_head))
694 if (ret + pos->message_size > size)
696 GNUNET_CONTAINER_DLL_remove (session->pending_messages_head,
697 session->pending_messages_tail, pos);
698 GNUNET_assert (size >= pos->message_size);
699 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
700 "Transmitting message of type %u\n",
701 ntohs (((struct GNUNET_MessageHeader *) pos->msg)->type));
702 /* FIXME: this memcpy can be up to 7% of our total runtime */
703 memcpy (cbuf, pos->msg, pos->message_size);
704 cbuf += pos->message_size;
705 ret += pos->message_size;
706 size -= pos->message_size;
707 GNUNET_CONTAINER_DLL_insert_tail (hd, tl, pos);
709 /* schedule 'continuation' before callbacks so that callbacks that
710 * cancel everything don't cause us to use a session that no longer
712 process_pending_messages (session);
713 session->last_activity = GNUNET_TIME_absolute_get ();
714 pid = session->target;
715 /* we'll now call callbacks that may cancel the session; hence
716 * we should not use 'session' after this point */
717 while (NULL != (pos = hd))
719 GNUNET_CONTAINER_DLL_remove (hd, tl, pos);
720 if (pos->transmit_cont != NULL)
721 pos->transmit_cont (pos->transmit_cont_cls, &pid, GNUNET_OK);
724 GNUNET_assert (hd == NULL);
725 GNUNET_assert (tl == NULL);
727 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp", "Transmitting %u bytes\n",
730 GNUNET_STATISTICS_update (plugin->env->stats,
731 gettext_noop ("# bytes currently in TCP buffers"),
732 -(int64_t) ret, GNUNET_NO);
733 GNUNET_STATISTICS_update (plugin->env->stats,
734 gettext_noop ("# bytes transmitted via TCP"), ret,
741 * If we have pending messages, ask the server to
742 * transmit them (schedule the respective tasks, etc.)
744 * @param session for which session should we do this
747 process_pending_messages (struct Session *session)
749 struct PendingMessage *pm;
751 GNUNET_assert (session->client != NULL);
752 if (session->transmit_handle != NULL)
754 if (NULL == (pm = session->pending_messages_head))
757 session->transmit_handle =
758 GNUNET_SERVER_notify_transmit_ready (session->client, pm->message_size,
759 GNUNET_TIME_absolute_get_remaining
760 (pm->timeout), &do_transmit,
766 * Functions with this signature are called whenever we need
767 * to close a session due to a disconnect or failure to
768 * establish a connection.
770 * @param session session to close down
773 disconnect_session (struct Session *session)
775 struct Session *prev;
777 struct PendingMessage *pm;
780 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
781 "Disconnecting from `%4s' at %s.\n",
782 GNUNET_i2s (&session->target),
783 (session->connect_addr !=
784 NULL) ? tcp_address_to_string (session->plugin,
785 session->connect_addr,
786 session->connect_alen) :
789 /* remove from session list */
791 pos = session->plugin->sessions;
792 while (pos != session)
798 session->plugin->sessions = session->next;
800 prev->next = session->next;
803 if (session->transmit_handle != NULL)
805 GNUNET_CONNECTION_notify_transmit_ready_cancel (session->transmit_handle);
806 session->transmit_handle = NULL;
808 session->plugin->env->session_end (session->plugin->env->cls,
809 &session->target, session);
810 while (NULL != (pm = session->pending_messages_head))
813 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
815 NULL ? "Could not deliver message to `%4s'.\n" :
816 "Could not deliver message to `%4s', notifying.\n",
817 GNUNET_i2s (&session->target));
819 GNUNET_STATISTICS_update (session->plugin->env->stats,
820 gettext_noop ("# bytes currently in TCP buffers"),
821 -(int64_t) pm->message_size, GNUNET_NO);
822 GNUNET_STATISTICS_update (session->plugin->env->stats,
824 ("# bytes discarded by TCP (disconnect)"),
825 pm->message_size, GNUNET_NO);
826 GNUNET_CONTAINER_DLL_remove (session->pending_messages_head,
827 session->pending_messages_tail, pm);
828 if (NULL != pm->transmit_cont)
829 pm->transmit_cont (pm->transmit_cont_cls, &session->target,
833 GNUNET_break (session->client != NULL);
834 if (session->receive_delay_task != GNUNET_SCHEDULER_NO_TASK)
836 GNUNET_SCHEDULER_cancel (session->receive_delay_task);
837 if (session->client != NULL)
838 GNUNET_SERVER_receive_done (session->client, GNUNET_SYSERR);
840 if (session->client != NULL)
842 GNUNET_SERVER_client_drop (session->client);
843 session->client = NULL;
845 GNUNET_STATISTICS_update (session->plugin->env->stats,
846 gettext_noop ("# TCP sessions active"), -1,
848 GNUNET_free_non_null (session->connect_addr);
849 GNUNET_assert (NULL == session->transmit_handle);
850 GNUNET_free (session);
855 * Given two otherwise equivalent sessions, pick the better one.
857 * @param s1 one session (also default)
858 * @param s2 other session
859 * @return "better" session (more active)
861 static struct Session *
862 select_better_session (struct Session *s1, struct Session *s2)
868 if ((s1->expecting_welcome == GNUNET_NO) &&
869 (s2->expecting_welcome == GNUNET_YES))
871 if ((s1->expecting_welcome == GNUNET_YES) &&
872 (s2->expecting_welcome == GNUNET_NO))
874 if (s1->last_activity.abs_value < s2->last_activity.abs_value)
876 if (s1->last_activity.abs_value > s2->last_activity.abs_value)
878 if ((GNUNET_YES == s1->inbound) && (GNUNET_NO == s2->inbound))
880 if ((GNUNET_NO == s1->inbound) && (GNUNET_YES == s2->inbound))
888 * Function that can be used by the transport service to transmit
889 * a message using the plugin. Note that in the case of a
890 * peer disconnecting, the continuation MUST be called
891 * prior to the disconnect notification itself. This function
892 * will be called with this peer's HELLO message to initiate
893 * a fresh connection to another peer.
896 * @param target who should receive this message
897 * @param msg the message to transmit
898 * @param msgbuf_size number of bytes in 'msg'
899 * @param priority how important is the message (most plugins will
900 * ignore message priority and just FIFO)
901 * @param timeout how long to wait at most for the transmission (does not
902 * require plugins to discard the message after the timeout,
903 * just advisory for the desired delay; most plugins will ignore
905 * @param session which session must be used (or NULL for "any")
906 * @param addr the address to use (can be NULL if the plugin
907 * is "on its own" (i.e. re-use existing TCP connection))
908 * @param addrlen length of the address in bytes
909 * @param force_address GNUNET_YES if the plugin MUST use the given address,
910 * GNUNET_NO means the plugin may use any other address and
911 * GNUNET_SYSERR means that only reliable existing
912 * bi-directional connections should be used (regardless
914 * @param cont continuation to call once the message has
915 * been transmitted (or if the transport is ready
916 * for the next transmission call; or if the
917 * peer disconnected...); can be NULL
918 * @param cont_cls closure for cont
919 * @return number of bytes used (on the physical network, with overheads);
920 * -1 on hard errors (i.e. address invalid); 0 is a legal value
921 * and does NOT mean that the message was not transmitted (DV and NAT)
924 tcp_plugin_send (void *cls, const struct GNUNET_PeerIdentity *target,
925 const char *msg, size_t msgbuf_size, uint32_t priority,
926 struct GNUNET_TIME_Relative timeout, struct Session *session,
927 const void *addr, size_t addrlen, int force_address,
928 GNUNET_TRANSPORT_TransmitContinuation cont, void *cont_cls)
930 struct Plugin *plugin = cls;
931 struct Session *cand_session;
932 struct Session *next;
933 struct PendingMessage *pm;
934 struct GNUNET_CONNECTION_Handle *sa;
938 struct sockaddr_in a4;
939 struct sockaddr_in6 a6;
940 const struct IPv4TcpAddress *t4;
941 const struct IPv6TcpAddress *t6;
942 unsigned int is_natd;
944 GNUNET_STATISTICS_update (plugin->env->stats,
945 gettext_noop ("# bytes TCP was asked to transmit"),
946 msgbuf_size, GNUNET_NO);
947 /* FIXME: we could do this cheaper with a hash table
948 * where we could restrict the iteration to entries that match
949 * the target peer... */
954 next = plugin->sessions;
955 while (NULL != (session = next))
957 next = session->next;
958 GNUNET_assert (session->client != NULL);
960 memcmp (target, &session->target,
961 sizeof (struct GNUNET_PeerIdentity)))
963 if (((GNUNET_SYSERR == force_address) &&
964 (session->expecting_welcome == GNUNET_NO)) ||
965 (GNUNET_NO == force_address))
967 cand_session = select_better_session (cand_session, session);
970 if (GNUNET_SYSERR == force_address)
972 GNUNET_break (GNUNET_YES == force_address);
978 if ((addrlen != session->connect_alen) && (session->is_nat == GNUNET_NO))
980 if ((0 != memcmp (session->connect_addr, addr, addrlen)) &&
981 (session->is_nat == GNUNET_NO))
983 cand_session = select_better_session (cand_session, session);
985 session = cand_session;
987 if ((session == NULL) && (addrlen == 0))
990 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
991 "Asked to transmit to `%4s' without address and I have no existing connection (failing).\n",
992 GNUNET_i2s (target));
994 GNUNET_STATISTICS_update (plugin->env->stats,
996 ("# bytes discarded by TCP (no address and no connection)"),
997 msgbuf_size, GNUNET_NO);
1000 if (session == NULL)
1002 if (addrlen == sizeof (struct IPv6TcpAddress))
1004 GNUNET_assert (NULL != addr); /* make static analysis happy */
1007 memset (&a6, 0, sizeof (a6));
1008 #if HAVE_SOCKADDR_IN_SIN_LEN
1009 a6.sin6_len = sizeof (a6);
1011 a6.sin6_family = AF_INET6;
1012 a6.sin6_port = t6->t6_port;
1013 if (t6->t6_port == 0)
1014 is_natd = GNUNET_YES;
1015 memcpy (&a6.sin6_addr, &t6->ipv6_addr, sizeof (struct in6_addr));
1019 else if (addrlen == sizeof (struct IPv4TcpAddress))
1021 GNUNET_assert (NULL != addr); /* make static analysis happy */
1024 memset (&a4, 0, sizeof (a4));
1025 #if HAVE_SOCKADDR_IN_SIN_LEN
1026 a4.sin_len = sizeof (a4);
1028 a4.sin_family = AF_INET;
1029 a4.sin_port = t4->t4_port;
1030 if (t4->t4_port == 0)
1031 is_natd = GNUNET_YES;
1032 a4.sin_addr.s_addr = t4->ipv4_addr;
1038 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, "tcp",
1039 _("Address of unexpected length: %u\n"), addrlen);
1044 if ((is_natd == GNUNET_YES) && (addrlen == sizeof (struct IPv6TcpAddress)))
1045 return -1; /* NAT client only works with IPv4 addresses */
1046 if (0 == plugin->max_connections)
1047 return -1; /* saturated */
1049 if ((is_natd == GNUNET_YES) && (NULL != plugin->nat) &&
1051 GNUNET_CONTAINER_multihashmap_contains (plugin->nat_wait_conns,
1052 &target->hashPubKey)))
1055 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1056 _("Found valid IPv4 NAT address (creating session)!\n"));
1058 session = create_session (plugin, target, NULL, GNUNET_YES);
1059 GNUNET_assert (session != NULL);
1061 /* create new message entry */
1062 pm = GNUNET_malloc (sizeof (struct PendingMessage) + msgbuf_size);
1063 /* FIXME: the memset of this malloc can be up to 2% of our total runtime */
1064 pm->msg = (const char *) &pm[1];
1065 memcpy (&pm[1], msg, msgbuf_size);
1066 /* FIXME: this memcpy can be up to 7% of our total run-time
1067 * (for transport service) */
1068 pm->message_size = msgbuf_size;
1069 pm->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1070 pm->transmit_cont = cont;
1071 pm->transmit_cont_cls = cont_cls;
1073 /* append pm to pending_messages list */
1074 GNUNET_CONTAINER_DLL_insert_tail (session->pending_messages_head,
1075 session->pending_messages_tail, pm);
1077 GNUNET_assert (GNUNET_CONTAINER_multihashmap_put
1078 (plugin->nat_wait_conns, &target->hashPubKey, session,
1079 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY) ==
1082 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1083 "Created NAT WAIT connection to `%4s' at `%s'\n",
1084 GNUNET_i2s (target), GNUNET_a2s (sb, sbs));
1086 GNUNET_NAT_run_client (plugin->nat, &a4);
1089 if ((is_natd == GNUNET_YES) &&
1091 GNUNET_CONTAINER_multihashmap_contains (plugin->nat_wait_conns,
1092 &target->hashPubKey)))
1094 /* Only do one NAT punch attempt per peer identity */
1097 sa = GNUNET_CONNECTION_create_from_sockaddr (af, sb, sbs);
1101 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1102 "Failed to create connection to `%4s' at `%s'\n",
1103 GNUNET_i2s (target), GNUNET_a2s (sb, sbs));
1105 GNUNET_STATISTICS_update (plugin->env->stats,
1107 ("# bytes discarded by TCP (failed to connect)"),
1108 msgbuf_size, GNUNET_NO);
1111 GNUNET_assert (0 != plugin->max_connections);
1112 plugin->max_connections--;
1114 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1115 "Asked to transmit to `%4s', creating fresh session using address `%s'.\n",
1116 GNUNET_i2s (target), GNUNET_a2s (sb, sbs));
1119 create_session (plugin, target,
1120 GNUNET_SERVER_connect_socket (plugin->server, sa),
1122 session->connect_addr = GNUNET_malloc (addrlen);
1123 memcpy (session->connect_addr, addr, addrlen);
1124 session->connect_alen = addrlen;
1126 else /* session != NULL */
1128 /* check if session is valid */
1129 struct Session *ses = plugin->sessions;
1132 memcmp (target, &session->target, sizeof (struct GNUNET_PeerIdentity)))
1135 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1136 "Got session %p for `%s', but should be for peer `%s'!\n",
1137 session, GNUNET_i2s (&session->target),
1138 GNUNET_h2s (&target->hashPubKey));
1142 while ((ses != NULL) && (ses != session))
1149 GNUNET_assert (session != NULL);
1150 GNUNET_assert (session->client != NULL);
1153 GNUNET_SERVER_client_set_timeout (session->client,
1154 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1155 GNUNET_STATISTICS_update (plugin->env->stats,
1156 gettext_noop ("# bytes currently in TCP buffers"),
1157 msgbuf_size, GNUNET_NO);
1158 /* create new message entry */
1159 pm = GNUNET_malloc (sizeof (struct PendingMessage) + msgbuf_size);
1160 pm->msg = (const char *) &pm[1];
1161 memcpy (&pm[1], msg, msgbuf_size);
1162 pm->message_size = msgbuf_size;
1163 pm->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1164 pm->transmit_cont = cont;
1165 pm->transmit_cont_cls = cont_cls;
1167 /* append pm to pending_messages list */
1168 GNUNET_CONTAINER_DLL_insert_tail (session->pending_messages_head,
1169 session->pending_messages_tail, pm);
1171 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1172 "Asked to transmit %u bytes to `%s', added message to list.\n",
1173 msgbuf_size, GNUNET_i2s (target));
1175 process_pending_messages (session);
1181 * Function that can be called to force a disconnect from the
1182 * specified neighbour. This should also cancel all previously
1183 * scheduled transmissions. Obviously the transmission may have been
1184 * partially completed already, which is OK. The plugin is supposed
1185 * to close the connection (if applicable) and no longer call the
1186 * transmit continuation(s).
1188 * Finally, plugin MUST NOT call the services's receive function to
1189 * notify the service that the connection to the specified target was
1190 * closed after a getting this call.
1192 * @param cls closure
1193 * @param target peer for which the last transmission is
1197 tcp_plugin_disconnect (void *cls, const struct GNUNET_PeerIdentity *target)
1199 struct Plugin *plugin = cls;
1200 struct Session *session;
1201 struct Session *next;
1202 struct PendingMessage *pm;
1205 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1206 "Asked to cancel session with `%4s'\n", GNUNET_i2s (target));
1208 next = plugin->sessions;
1209 while (NULL != (session = next))
1211 next = session->next;
1213 memcmp (target, &session->target, sizeof (struct GNUNET_PeerIdentity)))
1215 pm = session->pending_messages_head;
1218 pm->transmit_cont = NULL;
1219 pm->transmit_cont_cls = NULL;
1222 GNUNET_STATISTICS_update (session->plugin->env->stats,
1224 ("# transport-service disconnect requests for TCP"),
1226 disconnect_session (session);
1232 * Context for address to string conversion.
1234 struct PrettyPrinterContext
1237 * Function to call with the result.
1239 GNUNET_TRANSPORT_AddressStringCallback asc;
1242 * Clsoure for 'asc'.
1247 * Port to add after the IP address.
1254 * Append our port and forward the result.
1256 * @param cls the 'struct PrettyPrinterContext*'
1257 * @param hostname hostname part of the address
1260 append_port (void *cls, const char *hostname)
1262 struct PrettyPrinterContext *ppc = cls;
1265 if (hostname == NULL)
1267 ppc->asc (ppc->asc_cls, NULL);
1271 GNUNET_asprintf (&ret, "%s:%d", hostname, ppc->port);
1272 ppc->asc (ppc->asc_cls, ret);
1278 * Convert the transports address to a nice, human-readable
1281 * @param cls closure
1282 * @param type name of the transport that generated the address
1283 * @param addr one of the addresses of the host, NULL for the last address
1284 * the specific address format depends on the transport
1285 * @param addrlen length of the address
1286 * @param numeric should (IP) addresses be displayed in numeric form?
1287 * @param timeout after how long should we give up?
1288 * @param asc function to call on each string
1289 * @param asc_cls closure for asc
1292 tcp_plugin_address_pretty_printer (void *cls, const char *type,
1293 const void *addr, size_t addrlen,
1295 struct GNUNET_TIME_Relative timeout,
1296 GNUNET_TRANSPORT_AddressStringCallback asc,
1299 struct PrettyPrinterContext *ppc;
1302 struct sockaddr_in a4;
1303 struct sockaddr_in6 a6;
1304 const struct IPv4TcpAddress *t4;
1305 const struct IPv6TcpAddress *t6;
1308 if (addrlen == sizeof (struct IPv6TcpAddress))
1311 memset (&a6, 0, sizeof (a6));
1312 a6.sin6_family = AF_INET6;
1313 a6.sin6_port = t6->t6_port;
1314 memcpy (&a6.sin6_addr, &t6->ipv6_addr, sizeof (struct in6_addr));
1315 port = ntohs (t6->t6_port);
1319 else if (addrlen == sizeof (struct IPv4TcpAddress))
1322 memset (&a4, 0, sizeof (a4));
1323 a4.sin_family = AF_INET;
1324 a4.sin_port = t4->t4_port;
1325 a4.sin_addr.s_addr = t4->ipv4_addr;
1326 port = ntohs (t4->t4_port);
1332 /* invalid address */
1333 GNUNET_break_op (0);
1334 asc (asc_cls, NULL);
1337 ppc = GNUNET_malloc (sizeof (struct PrettyPrinterContext));
1339 ppc->asc_cls = asc_cls;
1341 GNUNET_RESOLVER_hostname_get (sb, sbs, !numeric, timeout, &append_port, ppc);
1346 * Check if the given port is plausible (must be either our listen
1347 * port or our advertised port), or any port if we are behind NAT
1348 * and do not have a port open. If it is neither, we return
1351 * @param plugin global variables
1352 * @param in_port port number to check
1353 * @return GNUNET_OK if port is either open_port or adv_port
1356 check_port (struct Plugin *plugin, uint16_t in_port)
1358 if ((in_port == plugin->adv_port) || (in_port == plugin->open_port))
1360 return GNUNET_SYSERR;
1365 * Function that will be called to check if a binary address for this
1366 * plugin is well-formed and corresponds to an address for THIS peer
1367 * (as per our configuration). Naturally, if absolutely necessary,
1368 * plugins can be a bit conservative in their answer, but in general
1369 * plugins should make sure that the address does not redirect
1370 * traffic to a 3rd party that might try to man-in-the-middle our
1373 * @param cls closure, our 'struct Plugin*'
1374 * @param addr pointer to the address
1375 * @param addrlen length of addr
1376 * @return GNUNET_OK if this is a plausible address for this peer
1377 * and transport, GNUNET_SYSERR if not
1380 tcp_plugin_check_address (void *cls, const void *addr, size_t addrlen)
1382 struct Plugin *plugin = cls;
1383 struct IPv4TcpAddress *v4;
1384 struct IPv6TcpAddress *v6;
1386 if ((addrlen != sizeof (struct IPv4TcpAddress)) &&
1387 (addrlen != sizeof (struct IPv6TcpAddress)))
1389 GNUNET_break_op (0);
1390 return GNUNET_SYSERR;
1392 if (addrlen == sizeof (struct IPv4TcpAddress))
1394 v4 = (struct IPv4TcpAddress *) addr;
1395 if (GNUNET_OK != check_port (plugin, ntohs (v4->t4_port)))
1396 return GNUNET_SYSERR;
1398 GNUNET_NAT_test_address (plugin->nat, &v4->ipv4_addr,
1399 sizeof (struct in_addr)))
1400 return GNUNET_SYSERR;
1404 v6 = (struct IPv6TcpAddress *) addr;
1405 if (IN6_IS_ADDR_LINKLOCAL (&v6->ipv6_addr))
1407 GNUNET_break_op (0);
1408 return GNUNET_SYSERR;
1410 if (GNUNET_OK != check_port (plugin, ntohs (v6->t6_port)))
1411 return GNUNET_SYSERR;
1413 GNUNET_NAT_test_address (plugin->nat, &v6->ipv6_addr,
1414 sizeof (struct in6_addr)))
1415 return GNUNET_SYSERR;
1422 * We've received a nat probe from this peer via TCP. Finish
1423 * creating the client session and resume sending of queued
1426 * @param cls closure
1427 * @param client identification of the client
1428 * @param message the actual message
1431 handle_tcp_nat_probe (void *cls, struct GNUNET_SERVER_Client *client,
1432 const struct GNUNET_MessageHeader *message)
1434 struct Plugin *plugin = cls;
1435 struct Session *session;
1436 const struct TCP_NAT_ProbeMessage *tcp_nat_probe;
1439 struct IPv4TcpAddress *t4;
1440 struct IPv6TcpAddress *t6;
1441 const struct sockaddr_in *s4;
1442 const struct sockaddr_in6 *s6;
1445 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp", "received NAT probe\n");
1447 /* We have received a TCP NAT probe, meaning we (hopefully) initiated
1448 * a connection to this peer by running gnunet-nat-client. This peer
1449 * received the punch message and now wants us to use the new connection
1450 * as the default for that peer. Do so and then send a WELCOME message
1451 * so we can really be connected!
1453 if (ntohs (message->size) != sizeof (struct TCP_NAT_ProbeMessage))
1455 GNUNET_break_op (0);
1456 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1460 tcp_nat_probe = (const struct TCP_NAT_ProbeMessage *) message;
1462 memcmp (&tcp_nat_probe->clientIdentity, plugin->env->my_identity,
1463 sizeof (struct GNUNET_PeerIdentity)))
1465 /* refuse connections from ourselves */
1466 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1471 GNUNET_CONTAINER_multihashmap_get (plugin->nat_wait_conns,
1473 clientIdentity.hashPubKey);
1474 if (session == NULL)
1477 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1478 "Did NOT find session for NAT probe!\n");
1480 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1484 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1485 "Found session for NAT probe!\n");
1487 GNUNET_assert (GNUNET_CONTAINER_multihashmap_remove
1488 (plugin->nat_wait_conns,
1489 &tcp_nat_probe->clientIdentity.hashPubKey,
1490 session) == GNUNET_YES);
1491 if (GNUNET_OK != GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
1494 GNUNET_free (session);
1495 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1499 GNUNET_SERVER_client_keep (client);
1500 session->client = client;
1501 session->last_activity = GNUNET_TIME_absolute_get ();
1502 session->inbound = GNUNET_NO;
1505 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1506 "Found address `%s' for incoming connection\n",
1507 GNUNET_a2s (vaddr, alen));
1509 switch (((const struct sockaddr *) vaddr)->sa_family)
1513 t4 = GNUNET_malloc (sizeof (struct IPv4TcpAddress));
1514 t4->t4_port = s4->sin_port;
1515 t4->ipv4_addr = s4->sin_addr.s_addr;
1516 session->connect_addr = t4;
1517 session->connect_alen = sizeof (struct IPv4TcpAddress);
1521 t6 = GNUNET_malloc (sizeof (struct IPv6TcpAddress));
1522 t6->t6_port = s6->sin6_port;
1523 memcpy (&t6->ipv6_addr, &s6->sin6_addr, sizeof (struct in6_addr));
1524 session->connect_addr = t6;
1525 session->connect_alen = sizeof (struct IPv6TcpAddress);
1528 GNUNET_break_op (0);
1530 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1531 "Bad address for incoming connection!\n");
1533 GNUNET_free (vaddr);
1534 GNUNET_SERVER_client_drop (client);
1535 GNUNET_free (session);
1536 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1539 GNUNET_free (vaddr);
1541 session->next = plugin->sessions;
1542 plugin->sessions = session;
1543 GNUNET_STATISTICS_update (plugin->env->stats,
1544 gettext_noop ("# TCP sessions active"), 1,
1546 process_pending_messages (session);
1547 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1552 * We've received a welcome from this peer via TCP. Possibly create a
1553 * fresh client record and send back our welcome.
1555 * @param cls closure
1556 * @param client identification of the client
1557 * @param message the actual message
1560 handle_tcp_welcome (void *cls, struct GNUNET_SERVER_Client *client,
1561 const struct GNUNET_MessageHeader *message)
1563 struct Plugin *plugin = cls;
1564 const struct WelcomeMessage *wm = (const struct WelcomeMessage *) message;
1565 struct Session *session;
1568 struct IPv4TcpAddress *t4;
1569 struct IPv6TcpAddress *t6;
1570 const struct sockaddr_in *s4;
1571 const struct sockaddr_in6 *s6;
1574 memcmp (&wm->clientIdentity, plugin->env->my_identity,
1575 sizeof (struct GNUNET_PeerIdentity)))
1577 /* refuse connections from ourselves */
1578 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1582 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1583 "Received %s message from `%4s'.\n", "WELCOME",
1584 GNUNET_i2s (&wm->clientIdentity));
1586 GNUNET_STATISTICS_update (plugin->env->stats,
1587 gettext_noop ("# TCP WELCOME messages received"), 1,
1589 session = find_session_by_client (plugin, client);
1591 if (session == NULL)
1594 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1595 "Received %s message from a `%4s', creating new session\n",
1596 "WELCOME", GNUNET_i2s (&wm->clientIdentity));
1598 GNUNET_SERVER_client_keep (client);
1599 session = create_session (plugin, &wm->clientIdentity, client, GNUNET_NO);
1600 session->inbound = GNUNET_YES;
1601 if (GNUNET_OK == GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
1604 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1605 "Found address `%s' for incoming connection\n",
1606 GNUNET_a2s (vaddr, alen));
1608 if (alen == sizeof (struct sockaddr_in))
1611 t4 = GNUNET_malloc (sizeof (struct IPv4TcpAddress));
1612 t4->t4_port = s4->sin_port;
1613 t4->ipv4_addr = s4->sin_addr.s_addr;
1614 session->connect_addr = t4;
1615 session->connect_alen = sizeof (struct IPv4TcpAddress);
1617 else if (alen == sizeof (struct sockaddr_in6))
1620 t6 = GNUNET_malloc (sizeof (struct IPv6TcpAddress));
1621 t6->t6_port = s6->sin6_port;
1622 memcpy (&t6->ipv6_addr, &s6->sin6_addr, sizeof (struct in6_addr));
1623 session->connect_addr = t6;
1624 session->connect_alen = sizeof (struct IPv6TcpAddress);
1627 GNUNET_free (vaddr);
1632 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1633 "Did not obtain TCP socket address for incoming connection\n");
1636 process_pending_messages (session);
1641 if (GNUNET_OK == GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
1643 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1644 "Found address `%s' (already have session)\n",
1645 GNUNET_a2s (vaddr, alen));
1646 GNUNET_free (vaddr);
1651 if (session->expecting_welcome != GNUNET_YES)
1653 GNUNET_break_op (0);
1654 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1657 session->last_activity = GNUNET_TIME_absolute_get ();
1658 session->expecting_welcome = GNUNET_NO;
1659 GNUNET_SERVER_client_set_timeout (client,
1660 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1661 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1666 * Task to signal the server that we can continue
1667 * receiving from the TCP client now.
1669 * @param cls the 'struct Session*'
1670 * @param tc task context (unused)
1673 delayed_done (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1675 struct Session *session = cls;
1676 struct GNUNET_TIME_Relative delay;
1677 struct GNUNET_ATS_Information ats;
1679 session->receive_delay_task = GNUNET_SCHEDULER_NO_TASK;
1681 session->plugin->env->receive (session->plugin->env->cls,
1682 &session->target, NULL, &ats, 0, session,
1684 if (delay.rel_value == 0)
1685 GNUNET_SERVER_receive_done (session->client, GNUNET_OK);
1687 session->receive_delay_task =
1688 GNUNET_SCHEDULER_add_delayed (delay, &delayed_done, session);
1693 * We've received data for this peer via TCP. Unbox,
1694 * compute latency and forward.
1696 * @param cls closure
1697 * @param client identification of the client
1698 * @param message the actual message
1701 handle_tcp_data (void *cls, struct GNUNET_SERVER_Client *client,
1702 const struct GNUNET_MessageHeader *message)
1704 struct Plugin *plugin = cls;
1705 struct Session *session;
1706 struct GNUNET_TIME_Relative delay;
1709 type = ntohs (message->type);
1710 if ((GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME == type) ||
1711 (GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE == type))
1713 /* We don't want to propagate WELCOME and NAT Probe messages up! */
1714 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1717 session = find_session_by_client (plugin, client);
1718 if ((NULL == session) || (GNUNET_YES == session->expecting_welcome))
1720 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1723 session->last_activity = GNUNET_TIME_absolute_get ();
1725 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1726 "Passing %u bytes of type %u from `%4s' to transport service.\n",
1727 (unsigned int) ntohs (message->size),
1728 (unsigned int) ntohs (message->type),
1729 GNUNET_i2s (&session->target));
1731 GNUNET_STATISTICS_update (plugin->env->stats,
1732 gettext_noop ("# bytes received via TCP"),
1733 ntohs (message->size), GNUNET_NO);
1734 struct GNUNET_ATS_Information distance;
1736 distance.type = htonl (GNUNET_ATS_QUALITY_NET_DISTANCE);
1737 distance.value = htonl (1);
1739 plugin->env->receive (plugin->env->cls, &session->target, message,
1740 (const struct GNUNET_ATS_Information *) &distance,
1743 session->inbound) ? NULL : session->connect_addr,
1745 session->inbound) ? 0 : session->connect_alen);
1746 if (delay.rel_value == 0)
1748 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1753 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1754 "Throttling receiving from `%s' for %llu ms\n",
1755 GNUNET_i2s (&session->target),
1756 (unsigned long long) delay.rel_value);
1758 GNUNET_SERVER_disable_receive_done_warning (client);
1759 session->receive_delay_task =
1760 GNUNET_SCHEDULER_add_delayed (delay, &delayed_done, session);
1766 * Functions with this signature are called whenever a peer
1767 * is disconnected on the network level.
1769 * @param cls closure
1770 * @param client identification of the client
1773 disconnect_notify (void *cls, struct GNUNET_SERVER_Client *client)
1775 struct Plugin *plugin = cls;
1776 struct Session *session;
1780 plugin->max_connections++;
1781 session = find_session_by_client (plugin, client);
1782 if (session == NULL)
1783 return; /* unknown, nothing to do */
1785 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1786 "Destroying session of `%4s' with %s due to network-level disconnect.\n",
1787 GNUNET_i2s (&session->target),
1788 (session->connect_addr !=
1789 NULL) ? tcp_address_to_string (session->plugin,
1790 session->connect_addr,
1791 session->connect_alen) :
1794 GNUNET_STATISTICS_update (session->plugin->env->stats,
1796 ("# network-level TCP disconnect events"), 1,
1798 disconnect_session (session);
1803 * We can now send a probe message, copy into buffer to really send.
1805 * @param cls closure, a struct TCPProbeContext
1806 * @param size max size to copy
1807 * @param buf buffer to copy message to
1808 * @return number of bytes copied into buf
1811 notify_send_probe (void *cls, size_t size, void *buf)
1813 struct TCPProbeContext *tcp_probe_ctx = cls;
1814 struct Plugin *plugin = tcp_probe_ctx->plugin;
1817 tcp_probe_ctx->transmit_handle = NULL;
1818 GNUNET_CONTAINER_DLL_remove (plugin->probe_head, plugin->probe_tail,
1822 GNUNET_CONNECTION_destroy (tcp_probe_ctx->sock, GNUNET_NO);
1823 GNUNET_free (tcp_probe_ctx);
1826 GNUNET_assert (size >= sizeof (tcp_probe_ctx->message));
1827 memcpy (buf, &tcp_probe_ctx->message, sizeof (tcp_probe_ctx->message));
1828 GNUNET_SERVER_connect_socket (tcp_probe_ctx->plugin->server,
1829 tcp_probe_ctx->sock);
1830 ret = sizeof (tcp_probe_ctx->message);
1831 GNUNET_free (tcp_probe_ctx);
1837 * Function called by the NAT subsystem suggesting another peer wants
1838 * to connect to us via connection reversal. Try to connect back to the
1841 * @param cls closure
1842 * @param addr address to try
1843 * @param addrlen number of bytes in addr
1846 try_connection_reversal (void *cls, const struct sockaddr *addr,
1849 struct Plugin *plugin = cls;
1850 struct GNUNET_CONNECTION_Handle *sock;
1851 struct TCPProbeContext *tcp_probe_ctx;
1854 * We have received an ICMP response, ostensibly from a peer
1855 * that wants to connect to us! Send a message to establish a connection.
1857 sock = GNUNET_CONNECTION_create_from_sockaddr (AF_INET, addr, addrlen);
1860 /* failed for some odd reason (out of sockets?); ignore attempt */
1864 /* FIXME: do we need to track these probe context objects so that
1865 * we can clean them up on plugin unload? */
1866 tcp_probe_ctx = GNUNET_malloc (sizeof (struct TCPProbeContext));
1867 tcp_probe_ctx->message.header.size =
1868 htons (sizeof (struct TCP_NAT_ProbeMessage));
1869 tcp_probe_ctx->message.header.type =
1870 htons (GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE);
1871 memcpy (&tcp_probe_ctx->message.clientIdentity, plugin->env->my_identity,
1872 sizeof (struct GNUNET_PeerIdentity));
1873 tcp_probe_ctx->plugin = plugin;
1874 tcp_probe_ctx->sock = sock;
1875 GNUNET_CONTAINER_DLL_insert (plugin->probe_head, plugin->probe_tail,
1877 tcp_probe_ctx->transmit_handle =
1878 GNUNET_CONNECTION_notify_transmit_ready (sock,
1879 ntohs (tcp_probe_ctx->
1880 message.header.size),
1881 GNUNET_TIME_UNIT_FOREVER_REL,
1889 * Entry point for the plugin.
1891 * @param cls closure, the 'struct GNUNET_TRANSPORT_PluginEnvironment*'
1892 * @return the 'struct GNUNET_TRANSPORT_PluginFunctions*' or NULL on error
1895 libgnunet_plugin_transport_tcp_init (void *cls)
1897 static const struct GNUNET_SERVER_MessageHandler my_handlers[] = {
1898 {&handle_tcp_welcome, NULL, GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME,
1899 sizeof (struct WelcomeMessage)},
1900 {&handle_tcp_nat_probe, NULL, GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE,
1901 sizeof (struct TCP_NAT_ProbeMessage)},
1902 {&handle_tcp_data, NULL, GNUNET_MESSAGE_TYPE_ALL, 0},
1905 struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
1906 struct GNUNET_TRANSPORT_PluginFunctions *api;
1907 struct Plugin *plugin;
1908 struct GNUNET_SERVICE_Context *service;
1909 unsigned long long aport;
1910 unsigned long long bport;
1911 unsigned long long max_connections;
1913 struct GNUNET_TIME_Relative idle_timeout;
1915 struct sockaddr **addrs;
1916 socklen_t *addrlens;
1919 GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-tcp",
1922 max_connections = 128;
1926 GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-tcp", "PORT",
1927 &bport)) || (bport > 65535) ||
1929 GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-tcp",
1930 "ADVERTISED-PORT", &aport)) &&
1933 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, "tcp",
1935 ("Require valid port number for service `%s' in configuration!\n"),
1945 service = GNUNET_SERVICE_start ("transport-tcp", env->cfg);
1946 if (service == NULL)
1948 GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, "tcp",
1949 _("Failed to start service.\n"));
1958 plugin = GNUNET_malloc (sizeof (struct Plugin));
1959 plugin->max_connections = max_connections;
1960 plugin->open_port = bport;
1961 plugin->adv_port = aport;
1963 plugin->lsock = NULL;
1964 if ((service != NULL) &&
1967 GNUNET_SERVICE_get_server_addresses ("transport-tcp", env->cfg, &addrs,
1971 GNUNET_NAT_register (env->cfg, GNUNET_YES, aport, (unsigned int) ret,
1972 (const struct sockaddr **) addrs, addrlens,
1973 &tcp_nat_port_map_callback,
1974 &try_connection_reversal, plugin);
1978 GNUNET_assert (addrs[ret] != NULL);
1979 GNUNET_free (addrs[ret]);
1981 GNUNET_free_non_null (addrs);
1982 GNUNET_free_non_null (addrlens);
1987 GNUNET_NAT_register (env->cfg, GNUNET_YES, 0, 0, NULL, NULL, NULL,
1988 &try_connection_reversal, plugin);
1990 api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
1992 api->send = &tcp_plugin_send;
1993 api->disconnect = &tcp_plugin_disconnect;
1994 api->address_pretty_printer = &tcp_plugin_address_pretty_printer;
1995 api->check_address = &tcp_plugin_check_address;
1996 api->address_to_string = &tcp_address_to_string;
1997 plugin->service = service;
1998 if (service != NULL)
2000 plugin->server = GNUNET_SERVICE_get_server (service);
2005 GNUNET_CONFIGURATION_get_value_time (env->cfg, "transport-tcp",
2006 "TIMEOUT", &idle_timeout))
2008 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, "tcp",
2009 _("Failed to find option %s in section %s!\n"),
2010 "TIMEOUT", "transport-tcp");
2011 if (plugin->nat != NULL)
2012 GNUNET_NAT_unregister (plugin->nat);
2013 GNUNET_free (plugin);
2018 GNUNET_SERVER_create_with_sockets (&plugin_tcp_access_check, plugin,
2019 NULL, idle_timeout, GNUNET_YES);
2021 plugin->handlers = GNUNET_malloc (sizeof (my_handlers));
2022 memcpy (plugin->handlers, my_handlers, sizeof (my_handlers));
2024 i < sizeof (my_handlers) / sizeof (struct GNUNET_SERVER_MessageHandler);
2026 plugin->handlers[i].callback_cls = plugin;
2027 GNUNET_SERVER_add_handlers (plugin->server, plugin->handlers);
2028 GNUNET_SERVER_disconnect_notify (plugin->server, &disconnect_notify, plugin);
2029 plugin->nat_wait_conns = GNUNET_CONTAINER_multihashmap_create (16);
2031 GNUNET_log_from (GNUNET_ERROR_TYPE_INFO, "tcp",
2032 _("TCP transport listening on port %llu\n"), bport);
2034 GNUNET_log_from (GNUNET_ERROR_TYPE_INFO, "tcp",
2036 ("TCP transport not listening on any port (client only)\n"));
2038 GNUNET_log_from (GNUNET_ERROR_TYPE_INFO, "tcp",
2040 ("TCP transport advertises itself as being on port %llu\n"),
2047 * Exit point from the plugin.
2050 libgnunet_plugin_transport_tcp_done (void *cls)
2052 struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
2053 struct Plugin *plugin = api->cls;
2054 struct Session *session;
2055 struct TCPProbeContext *tcp_probe;
2057 while (NULL != (session = plugin->sessions))
2058 disconnect_session (session);
2059 if (plugin->service != NULL)
2060 GNUNET_SERVICE_stop (plugin->service);
2062 GNUNET_SERVER_destroy (plugin->server);
2063 GNUNET_free (plugin->handlers);
2064 if (plugin->nat != NULL)
2065 GNUNET_NAT_unregister (plugin->nat);
2066 while (NULL != (tcp_probe = plugin->probe_head))
2068 GNUNET_CONTAINER_DLL_remove (plugin->probe_head, plugin->probe_tail,
2070 GNUNET_CONNECTION_destroy (tcp_probe->sock, GNUNET_NO);
2071 GNUNET_free (tcp_probe);
2073 GNUNET_CONTAINER_multihashmap_destroy (plugin->nat_wait_conns);
2074 GNUNET_free (plugin);
2079 /* end of plugin_transport_tcp.c */