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_connection_lib.h"
28 #include "gnunet_container_lib.h"
29 #include "gnunet_os_lib.h"
30 #include "gnunet_protocols.h"
31 #include "gnunet_resolver_service.h"
32 #include "gnunet_server_lib.h"
33 #include "gnunet_service_lib.h"
34 #include "gnunet_signatures.h"
35 #include "gnunet_statistics_service.h"
36 #include "gnunet_transport_service.h"
37 #include "plugin_transport.h"
38 #include "transport.h"
40 #define DEBUG_TCP GNUNET_NO
41 #define DEBUG_TCP_NAT GNUNET_NO
42 #define MULTIPLE_PEER_SESSIONS GNUNET_YES
44 * How long until we give up on transmitting the welcome message?
46 #define HOSTNAME_RESOLVE_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 5)
50 * Initial handshake message for a session.
55 * Type is GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME.
57 struct GNUNET_MessageHeader header;
60 * Identity of the node connecting (TCP client)
62 struct GNUNET_PeerIdentity clientIdentity;
67 * Basically a WELCOME message, but with the purpose
68 * of giving the waiting peer a client handle to use
70 struct TCP_NAT_ProbeMessage
73 * Type is GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE.
75 struct GNUNET_MessageHeader header;
78 * Identity of the sender of the message.
80 struct GNUNET_PeerIdentity clientIdentity;
85 * Context for sending a NAT probe via TCP.
87 struct TCPProbeContext
92 struct GNUNET_CONNECTION_Handle *sock;
97 struct TCP_NAT_ProbeMessage message;
100 * Handle to the transmission.
102 struct GNUNET_CONNECTION_TransmitHandle *transmit_handle;
105 * Transport plugin handle.
107 struct Plugin *plugin;
112 * Network format for IPv4 addresses.
114 struct IPv4TcpAddress
117 * IPv4 address, in network byte order.
119 uint32_t ipv4_addr GNUNET_PACKED;
122 * Port number, in network byte order.
124 uint16_t t_port GNUNET_PACKED;
130 * Network format for IPv6 addresses.
132 struct IPv6TcpAddress
137 struct in6_addr ipv6_addr GNUNET_PACKED;
140 * Port number, in network byte order.
142 uint16_t t6_port GNUNET_PACKED;
147 * Encapsulation of all of the state of the plugin.
153 * Local network addresses (actual IP address follows this struct).
154 * PORT is NOT included!
160 * This is a doubly linked list.
162 struct LocalAddrList *next;
165 * This is a doubly linked list.
167 struct LocalAddrList *prev;
170 * Number of bytes of the address that follow
178 * Information kept for each message that is yet to
181 struct PendingMessage
185 * This is a doubly-linked list.
187 struct PendingMessage *next;
190 * This is a doubly-linked list.
192 struct PendingMessage *prev;
195 * The pending message
200 * Continuation function to call once the message
201 * has been sent. Can be NULL if there is no
202 * continuation to call.
204 GNUNET_TRANSPORT_TransmitContinuation transmit_cont;
207 * Closure for transmit_cont.
209 void *transmit_cont_cls;
212 * Timeout value for the pending message.
214 struct GNUNET_TIME_Absolute timeout;
217 * So that the gnunet-service-transport can group messages together,
218 * these pending messages need to accept a message buffer and size
219 * instead of just a GNUNET_MessageHeader.
227 * Session handle for TCP connections.
235 struct SessionHeader header;
238 * Stored in a linked list.
240 struct Session *next;
243 * Pointer to the global plugin struct.
245 struct Plugin *plugin;
248 * The client (used to identify this connection)
250 struct GNUNET_SERVER_Client *client;
253 * Messages currently pending for transmission
254 * to this peer, if any.
256 struct PendingMessage *pending_messages_head;
259 * Messages currently pending for transmission
260 * to this peer, if any.
262 struct PendingMessage *pending_messages_tail;
265 * Handle for pending transmission request.
267 struct GNUNET_CONNECTION_TransmitHandle *transmit_handle;
270 * To whom are we talking to (set to our identity
271 * if we are still waiting for the welcome message)
273 struct GNUNET_PeerIdentity target;
276 * ID of task used to delay receiving more to throttle sender.
278 GNUNET_SCHEDULER_TaskIdentifier receive_delay_task;
281 * Address of the other peer (either based on our 'connect'
282 * call or on our 'accept' call).
287 * Last activity on this connection. Used to select preferred
290 struct GNUNET_TIME_Absolute last_activity;
293 * Length of connect_addr.
298 * Are we still expecting the welcome message? (GNUNET_YES/GNUNET_NO)
300 int expecting_welcome;
303 * Was this a connection that was inbound (we accepted)? (GNUNET_YES/GNUNET_NO)
308 * Was this session created using NAT traversal?
316 * Encapsulation of all of the state of the plugin.
323 struct GNUNET_TRANSPORT_PluginEnvironment *env;
328 struct GNUNET_CONNECTION_Handle *lsock;
331 * stdout pipe handle for the gnunet-nat-server process
333 struct GNUNET_DISK_PipeHandle *server_stdout;
336 * stdout file handle (for reading) for the gnunet-nat-server process
338 const struct GNUNET_DISK_FileHandle *server_stdout_handle;
341 * ID of select gnunet-nat-server stdout read task
343 GNUNET_SCHEDULER_TaskIdentifier server_read_task;
346 * The process id of the server process (if behind NAT)
351 * List of open TCP sessions.
353 struct Session *sessions;
356 * Handle to the network service.
358 struct GNUNET_SERVICE_Context *service;
361 * Handle to the server for this service.
363 struct GNUNET_SERVER_Handle *server;
366 * Copy of the handler array where the closures are
367 * set to this struct's instance.
369 struct GNUNET_SERVER_MessageHandler *handlers;
372 * Handle for request of hostname resolution, non-NULL if pending.
374 struct GNUNET_RESOLVER_RequestHandle *hostname_dns;
377 * Map of peers we have tried to contact behind a NAT
379 struct GNUNET_CONTAINER_MultiHashMap *nat_wait_conns;
382 * The external address given to us by the user. Must be actual
383 * outside visible address for NAT punching to work.
385 char *external_address;
388 * The internal address given to us by the user (or discovered).
390 char *internal_address;
393 * Address given for us to bind to (ONLY).
398 * List of our IP addresses.
400 struct LocalAddrList *lal_head;
403 * Tail of our IP address list.
405 struct LocalAddrList *lal_tail;
408 * ID of task used to update our addresses when one expires.
410 GNUNET_SCHEDULER_TaskIdentifier address_update_task;
413 * Port that we are actually listening on.
418 * Port that the user said we would have visible to the
424 * Is this transport configured to be behind a NAT?
429 * Is this transport configured to allow connections to NAT'd peers?
434 * Should this transport advertise only NAT addresses (port set to 0)?
435 * If not, all addresses will be duplicated for NAT punching and regular
438 int only_nat_addresses;
444 add_to_address_list (struct Plugin *plugin,
448 struct LocalAddrList *lal;
450 lal = plugin->lal_head;
453 if ( (lal->size == arg_size) &&
454 (0 == memcmp (&lal[1], arg, arg_size)) )
458 lal = GNUNET_malloc (sizeof (struct LocalAddrList) + arg_size);
459 lal->size = arg_size;
460 memcpy (&lal[1], arg, arg_size);
461 GNUNET_CONTAINER_DLL_insert (plugin->lal_head,
468 check_local_addr (struct Plugin *plugin,
472 struct LocalAddrList *lal;
474 lal = plugin->lal_head;
477 if ( (lal->size == arg_size) &&
478 (0 == memcmp (&lal[1], arg, arg_size)) )
482 return GNUNET_SYSERR;
487 * Function called for a quick conversion of the binary address to
488 * a numeric address. Note that the caller must not free the
489 * address and that the next call to this function is allowed
490 * to override the address again.
492 * @param cls closure ('struct Plugin*')
493 * @param addr binary address
494 * @param addrlen length of the address
495 * @return string representing the same address
498 tcp_address_to_string (void *cls,
502 static char rbuf[INET6_ADDRSTRLEN + 12];
503 char buf[INET6_ADDRSTRLEN];
507 const struct IPv4TcpAddress *t4;
508 const struct IPv6TcpAddress *t6;
512 if (addrlen == sizeof (struct IPv6TcpAddress))
516 port = ntohs (t6->t6_port);
517 memcpy (&a6, &t6->ipv6_addr, sizeof (a6));
520 else if (addrlen == sizeof (struct IPv4TcpAddress))
524 port = ntohs (t4->t_port);
525 memcpy (&a4, &t4->ipv4_addr, sizeof (a4));
530 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
531 _("Unexpected address length: %u\n"),
536 if (NULL == inet_ntop (af, sb, buf, INET6_ADDRSTRLEN))
538 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "inet_ntop");
541 GNUNET_snprintf (rbuf,
543 (af == AF_INET6) ? "[%s]:%u" : "%s:%u",
551 * Find the session handle for the given client.
553 * @return NULL if no matching session exists
555 static struct Session *
556 find_session_by_client (struct Plugin *plugin,
557 const struct GNUNET_SERVER_Client *client)
561 ret = plugin->sessions;
562 while ((ret != NULL) && (client != ret->client))
567 #if !MULTIPLE_PEER_SESSIONS
569 * Find the session handle for the given client.
571 * @return NULL if no matching session exists
573 static struct Session *
574 find_session_by_id (struct Plugin *plugin,
575 const struct GNUNET_PeerIdentity *peer)
579 ret = plugin->sessions;
580 while ((ret != NULL) && (0 != memcmp(peer, &ret->target, sizeof(struct GNUNET_PeerIdentity))))
587 * Create a new session. Also queues a welcome message.
590 * @param target peer to connect to
591 * @param client client to use
592 * @param is_nat this a NAT session, we should wait for a client to
593 * connect to us from an address, then assign that to
595 * @return new session object
597 static struct Session *
598 create_session (struct Plugin *plugin,
599 const struct GNUNET_PeerIdentity *target,
600 struct GNUNET_SERVER_Client *client, int is_nat)
603 struct PendingMessage *pm;
604 struct WelcomeMessage welcome;
606 if (is_nat != GNUNET_YES)
607 GNUNET_assert (client != NULL);
609 GNUNET_assert (client == NULL);
612 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
613 "Creating new session for peer `%4s'\n",
614 GNUNET_i2s (target));
616 ret = GNUNET_malloc (sizeof (struct Session));
617 ret->last_activity = GNUNET_TIME_absolute_get ();
618 ret->plugin = plugin;
619 ret->is_nat = is_nat;
620 if (is_nat != GNUNET_YES) /* If not a NAT WAIT conn, add it to global list */
622 ret->next = plugin->sessions;
623 plugin->sessions = ret;
625 ret->client = client;
626 ret->target = *target;
627 ret->expecting_welcome = GNUNET_YES;
628 pm = GNUNET_malloc (sizeof (struct PendingMessage) + sizeof (struct WelcomeMessage));
629 pm->msg = (const char*) &pm[1];
630 pm->message_size = sizeof (struct WelcomeMessage);
631 welcome.header.size = htons (sizeof (struct WelcomeMessage));
632 welcome.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME);
633 welcome.clientIdentity = *plugin->env->my_identity;
634 memcpy (&pm[1], &welcome, sizeof (welcome));
635 pm->timeout = GNUNET_TIME_UNIT_FOREVER_ABS;
636 GNUNET_STATISTICS_update (plugin->env->stats,
637 gettext_noop ("# bytes currently in TCP buffers"),
640 GNUNET_CONTAINER_DLL_insert (ret->pending_messages_head,
641 ret->pending_messages_tail,
643 if (is_nat != GNUNET_YES)
644 GNUNET_STATISTICS_update (plugin->env->stats,
645 gettext_noop ("# TCP sessions active"),
653 * If we have pending messages, ask the server to
654 * transmit them (schedule the respective tasks, etc.)
656 * @param session for which session should we do this
658 static void process_pending_messages (struct Session *session);
662 * Function called to notify a client about the socket
663 * being ready to queue more data. "buf" will be
664 * NULL and "size" zero if the socket was closed for
665 * writing in the meantime.
668 * @param size number of bytes available in buf
669 * @param buf where the callee should write the message
670 * @return number of bytes written to buf
673 do_transmit (void *cls, size_t size, void *buf)
675 struct Session *session = cls;
676 struct GNUNET_PeerIdentity pid;
677 struct Plugin *plugin;
678 struct PendingMessage *pos;
679 struct PendingMessage *hd;
680 struct PendingMessage *tl;
681 struct GNUNET_TIME_Absolute now;
685 session->transmit_handle = NULL;
686 plugin = session->plugin;
690 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
691 "Timeout trying to transmit to peer `%4s', discarding message queue.\n",
692 GNUNET_i2s (&session->target));
694 /* timeout; cancel all messages that have already expired */
698 now = GNUNET_TIME_absolute_get ();
699 while ( (NULL != (pos = session->pending_messages_head)) &&
700 (pos->timeout.value <= now.value) )
702 GNUNET_CONTAINER_DLL_remove (session->pending_messages_head,
703 session->pending_messages_tail,
706 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
707 "Failed to transmit %u byte message to `%4s'.\n",
709 GNUNET_i2s (&session->target));
711 ret += pos->message_size;
712 GNUNET_CONTAINER_DLL_insert_after (hd, tl, tl, pos);
714 /* do this call before callbacks (so that if callbacks destroy
715 session, they have a chance to cancel actions done by this
717 process_pending_messages (session);
718 pid = session->target;
719 /* no do callbacks and do not use session again since
720 the callbacks may abort the session */
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,
726 &pid, GNUNET_SYSERR);
729 GNUNET_STATISTICS_update (plugin->env->stats,
730 gettext_noop ("# bytes currently in TCP buffers"),
733 GNUNET_STATISTICS_update (plugin->env->stats,
734 gettext_noop ("# bytes discarded by TCP (timeout)"),
739 /* copy all pending messages that would fit */
744 while (NULL != (pos = session->pending_messages_head))
746 if (ret + pos->message_size > size)
748 GNUNET_CONTAINER_DLL_remove (session->pending_messages_head,
749 session->pending_messages_tail,
751 GNUNET_assert (size >= pos->message_size);
752 /* FIXME: this memcpy can be up to 7% of our total runtime */
753 memcpy (cbuf, pos->msg, pos->message_size);
754 cbuf += pos->message_size;
755 ret += pos->message_size;
756 size -= pos->message_size;
757 GNUNET_CONTAINER_DLL_insert_after (hd, tl, tl, pos);
759 /* schedule 'continuation' before callbacks so that callbacks that
760 cancel everything don't cause us to use a session that no longer
762 process_pending_messages (session);
763 session->last_activity = GNUNET_TIME_absolute_get ();
764 pid = session->target;
765 /* we'll now call callbacks that may cancel the session; hence
766 we should not use 'session' after this point */
767 while (NULL != (pos = hd))
769 GNUNET_CONTAINER_DLL_remove (hd, tl, pos);
770 if (pos->transmit_cont != NULL)
771 pos->transmit_cont (pos->transmit_cont_cls,
775 GNUNET_assert (hd == NULL);
776 GNUNET_assert (tl == NULL);
778 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
779 "Transmitting %u bytes\n", ret);
781 GNUNET_STATISTICS_update (plugin->env->stats,
782 gettext_noop ("# bytes currently in TCP buffers"),
785 GNUNET_STATISTICS_update (plugin->env->stats,
786 gettext_noop ("# bytes transmitted via TCP"),
794 * If we have pending messages, ask the server to
795 * transmit them (schedule the respective tasks, etc.)
797 * @param session for which session should we do this
800 process_pending_messages (struct Session *session)
802 struct PendingMessage *pm;
804 GNUNET_assert (session->client != NULL);
805 if (session->transmit_handle != NULL)
807 if (NULL == (pm = session->pending_messages_head))
810 session->transmit_handle
811 = GNUNET_SERVER_notify_transmit_ready (session->client,
813 GNUNET_TIME_absolute_get_remaining
815 &do_transmit, session);
820 * Functions with this signature are called whenever we need
821 * to close a session due to a disconnect or failure to
822 * establish a connection.
824 * @param session session to close down
827 disconnect_session (struct Session *session)
829 struct Session *prev;
831 struct PendingMessage *pm;
834 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
835 "Disconnecting from `%4s' at %s (session %p).\n",
836 GNUNET_i2s (&session->target),
837 (session->connect_addr != NULL) ?
838 tcp_address_to_string (session->plugin,
839 session->connect_addr,
840 session->connect_alen) : "*",
843 /* remove from session list */
845 pos = session->plugin->sessions;
846 while (pos != session)
852 session->plugin->sessions = session->next;
854 prev->next = session->next;
855 session->plugin->env->session_end (session->plugin->env->cls,
859 if (session->transmit_handle != NULL)
861 GNUNET_CONNECTION_notify_transmit_ready_cancel
862 (session->transmit_handle);
863 session->transmit_handle = NULL;
865 while (NULL != (pm = session->pending_messages_head))
868 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
870 pm->transmit_cont != NULL
871 ? "Could not deliver message to `%4s'.\n"
873 "Could not deliver message to `%4s', notifying.\n",
874 GNUNET_i2s (&session->target));
876 GNUNET_STATISTICS_update (session->plugin->env->stats,
877 gettext_noop ("# bytes currently in TCP buffers"),
878 - (int64_t) pm->message_size,
880 GNUNET_STATISTICS_update (session->plugin->env->stats,
881 gettext_noop ("# bytes discarded by TCP (disconnect)"),
884 GNUNET_CONTAINER_DLL_remove (session->pending_messages_head,
885 session->pending_messages_tail,
887 if (NULL != pm->transmit_cont)
888 pm->transmit_cont (pm->transmit_cont_cls,
889 &session->target, GNUNET_SYSERR);
892 GNUNET_break (session->client != NULL);
893 if (session->receive_delay_task != GNUNET_SCHEDULER_NO_TASK)
895 GNUNET_SCHEDULER_cancel (session->plugin->env->sched,
896 session->receive_delay_task);
897 if (session->client != NULL)
898 GNUNET_SERVER_receive_done (session->client,
901 if (session->client != NULL)
902 GNUNET_SERVER_client_drop (session->client);
903 GNUNET_STATISTICS_update (session->plugin->env->stats,
904 gettext_noop ("# TCP sessions active"),
907 GNUNET_free_non_null (session->connect_addr);
908 GNUNET_free (session);
913 * Given two otherwise equivalent sessions, pick the better one.
915 * @param s1 one session (also default)
916 * @param s2 other session
917 * @return "better" session (more active)
919 static struct Session *
920 select_better_session (struct Session *s1,
927 if ( (s1->expecting_welcome == GNUNET_NO) &&
928 (s2->expecting_welcome == GNUNET_YES) )
930 if ( (s1->expecting_welcome == GNUNET_YES) &&
931 (s2->expecting_welcome == GNUNET_NO) )
933 if (s1->last_activity.value < s2->last_activity.value)
935 if (s1->last_activity.value > s2->last_activity.value)
937 if ( (GNUNET_YES == s1->inbound) &&
938 (GNUNET_NO == s2->inbound) )
940 if ( (GNUNET_NO == s1->inbound) &&
941 (GNUNET_YES == s2->inbound) )
948 * We learned about a peer (possibly behind NAT) so run the
949 * gnunet-nat-client to send dummy ICMP responses
951 * @param plugin the plugin for this transport
952 * @param addr the address of the peer
953 * @param addrlen the length of the address
956 run_gnunet_nat_client (struct Plugin *plugin, const char *addr, size_t addrlen)
958 char inet4[INET_ADDRSTRLEN];
959 char *address_as_string;
960 char *port_as_string;
962 const struct sockaddr *sa = (const struct sockaddr *)addr;
965 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
966 _("called run_gnunet_nat_client addrlen %d others are %d and %d\n"), addrlen, sizeof (struct sockaddr), sizeof (struct sockaddr_in));
969 if (addrlen < sizeof (struct sockaddr))
972 switch (sa->sa_family)
975 if (addrlen != sizeof (struct sockaddr_in))
977 if (NULL == inet_ntop (AF_INET,
978 &((struct sockaddr_in *) sa)->sin_addr,
979 inet4, INET_ADDRSTRLEN))
981 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "inet_ntop");
984 address_as_string = GNUNET_strdup (inet4);
991 GNUNET_asprintf(&port_as_string, "%d", plugin->adv_port);
993 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
994 _("Running gnunet-nat-client with arguments: %s %s %d\n"), plugin->external_address, address_as_string, plugin->adv_port);
997 /* Start the client process */
998 pid = GNUNET_OS_start_process(NULL, NULL, "gnunet-nat-client", "gnunet-nat-client", plugin->external_address, address_as_string, port_as_string, NULL);
999 GNUNET_free(address_as_string);
1000 GNUNET_free(port_as_string);
1001 GNUNET_OS_process_wait (pid);
1006 * Function that can be used by the transport service to transmit
1007 * a message using the plugin. Note that in the case of a
1008 * peer disconnecting, the continuation MUST be called
1009 * prior to the disconnect notification itself. This function
1010 * will be called with this peer's HELLO message to initiate
1011 * a fresh connection to another peer.
1013 * @param cls closure
1014 * @param target who should receive this message
1015 * @param msg the message to transmit
1016 * @param msgbuf_size number of bytes in 'msg'
1017 * @param priority how important is the message (most plugins will
1018 * ignore message priority and just FIFO)
1019 * @param timeout how long to wait at most for the transmission (does not
1020 * require plugins to discard the message after the timeout,
1021 * just advisory for the desired delay; most plugins will ignore
1023 * @param session which session must be used (or NULL for "any")
1024 * @param addr the address to use (can be NULL if the plugin
1025 * is "on its own" (i.e. re-use existing TCP connection))
1026 * @param addrlen length of the address in bytes
1027 * @param force_address GNUNET_YES if the plugin MUST use the given address,
1028 * GNUNET_NO means the plugin may use any other address and
1029 * GNUNET_SYSERR means that only reliable existing
1030 * bi-directional connections should be used (regardless
1032 * @param cont continuation to call once the message has
1033 * been transmitted (or if the transport is ready
1034 * for the next transmission call; or if the
1035 * peer disconnected...); can be NULL
1036 * @param cont_cls closure for cont
1037 * @return number of bytes used (on the physical network, with overheads);
1038 * -1 on hard errors (i.e. address invalid); 0 is a legal value
1039 * and does NOT mean that the message was not transmitted (DV and NAT)
1042 tcp_plugin_send (void *cls,
1043 const struct GNUNET_PeerIdentity *target,
1047 struct GNUNET_TIME_Relative timeout,
1048 struct Session *session,
1052 GNUNET_TRANSPORT_TransmitContinuation cont, void *cont_cls)
1054 struct Plugin *plugin = cls;
1055 struct Session *cand_session;
1056 struct Session *next;
1057 struct PendingMessage *pm;
1058 struct GNUNET_CONNECTION_Handle *sa;
1062 struct sockaddr_in a4;
1063 struct sockaddr_in6 a6;
1064 const struct IPv4TcpAddress *t4;
1065 const struct IPv6TcpAddress *t6;
1066 unsigned int is_natd;
1068 GNUNET_STATISTICS_update (plugin->env->stats,
1069 gettext_noop ("# bytes TCP was asked to transmit"),
1072 /* FIXME: we could do this cheaper with a hash table
1073 where we could restrict the iteration to entries that match
1074 the target peer... */
1075 is_natd = GNUNET_NO;
1076 if (session == NULL)
1078 cand_session = NULL;
1079 next = plugin->sessions;
1080 while (NULL != (session = next))
1082 next = session->next;
1083 GNUNET_assert (session->client != NULL);
1084 if (0 != memcmp (target,
1086 sizeof (struct GNUNET_PeerIdentity)))
1088 if ( ( (GNUNET_SYSERR == force_address) &&
1089 (session->expecting_welcome == GNUNET_NO) ) ||
1090 (GNUNET_NO == force_address) )
1092 cand_session = select_better_session (cand_session,
1096 if (GNUNET_SYSERR == force_address)
1098 GNUNET_break (GNUNET_YES == force_address);
1105 if (session->inbound == GNUNET_YES) /* FIXME: why do we ignore inbound sessions? */
1107 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Ignoring inbound session\n");
1111 if ((addrlen != session->connect_alen) && (session->is_nat == GNUNET_NO))
1113 if ((0 != memcmp (session->connect_addr,
1115 addrlen)) && (session->is_nat == GNUNET_NO))
1117 cand_session = select_better_session (cand_session,
1120 session = cand_session;
1122 if ( (session == NULL) &&
1126 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1127 "Asked to transmit to `%4s' without address and I have no existing connection (failing).\n",
1128 GNUNET_i2s (target));
1130 GNUNET_STATISTICS_update (plugin->env->stats,
1131 gettext_noop ("# bytes discarded by TCP (no address and no connection)"),
1136 if (session == NULL)
1138 if (addrlen == sizeof (struct IPv6TcpAddress))
1142 memset (&a6, 0, sizeof (a6));
1143 #if HAVE_SOCKADDR_IN_SIN_LEN
1144 a6.sin6_len = sizeof (a6);
1146 a6.sin6_family = AF_INET6;
1147 a6.sin6_port = t6->t6_port;
1148 if (t6->t6_port == 0)
1149 is_natd = GNUNET_YES;
1150 memcpy (&a6.sin6_addr,
1152 sizeof (struct in6_addr));
1156 else if (addrlen == sizeof (struct IPv4TcpAddress))
1160 memset (&a4, 0, sizeof (a4));
1161 #if HAVE_SOCKADDR_IN_SIN_LEN
1162 a4.sin_len = sizeof (a4);
1164 a4.sin_family = AF_INET;
1165 a4.sin_port = t4->t_port;
1166 if (t4->t_port == 0)
1167 is_natd = GNUNET_YES;
1168 a4.sin_addr.s_addr = t4->ipv4_addr;
1174 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1175 _("Address of unexpected length: %u\n"),
1181 if ((is_natd == GNUNET_YES) && (addrlen == sizeof (struct IPv6TcpAddress)))
1182 return -1; /* NAT client only works with IPv4 addresses */
1185 if ((plugin->allow_nat == GNUNET_YES) && (is_natd == GNUNET_YES) &&
1186 (GNUNET_NO == GNUNET_CONTAINER_multihashmap_contains(plugin->nat_wait_conns, &target->hashPubKey)))
1189 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1190 _("Found valid IPv4 NAT address (creating session)!\n"));
1192 session = create_session (plugin,
1196 /* create new message entry */
1197 pm = GNUNET_malloc (sizeof (struct PendingMessage) + msgbuf_size);
1198 /* FIXME: the memset of this malloc can be up to 2% of our total runtime */
1199 pm->msg = (const char*) &pm[1];
1200 memcpy (&pm[1], msg, msgbuf_size);
1201 /* FIXME: this memcpy can be up to 7% of our total run-time
1202 (for transport service) */
1203 pm->message_size = msgbuf_size;
1204 pm->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1205 pm->transmit_cont = cont;
1206 pm->transmit_cont_cls = cont_cls;
1208 /* append pm to pending_messages list */
1209 GNUNET_CONTAINER_DLL_insert_after (session->pending_messages_head,
1210 session->pending_messages_tail,
1211 session->pending_messages_tail,
1214 GNUNET_assert(GNUNET_CONTAINER_multihashmap_put(plugin->nat_wait_conns, &target->hashPubKey, session, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY) == GNUNET_OK);
1216 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1217 "Created NAT WAIT connection to `%4s' at `%s'\n",
1218 GNUNET_i2s (target),
1219 GNUNET_a2s (sb, sbs));
1221 run_gnunet_nat_client (plugin, sb, sbs);
1224 else if ((plugin->allow_nat == GNUNET_YES) && (is_natd == GNUNET_YES) && (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains(plugin->nat_wait_conns, &target->hashPubKey)))
1226 /* Only do one NAT punch attempt per peer identity */
1229 sa = GNUNET_CONNECTION_create_from_sockaddr (plugin->env->sched,
1234 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1235 "Failed to create connection to `%4s' at `%s'\n",
1236 GNUNET_i2s (target),
1237 GNUNET_a2s (sb, sbs));
1239 GNUNET_STATISTICS_update (plugin->env->stats,
1240 gettext_noop ("# bytes discarded by TCP (failed to connect)"),
1246 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1247 "Asked to transmit to `%4s', creating fresh session using address `%s'.\n",
1248 GNUNET_i2s (target),
1249 GNUNET_a2s (sb, sbs));
1251 session = create_session (plugin,
1253 GNUNET_SERVER_connect_socket (plugin->server,
1255 session->connect_addr = GNUNET_malloc (addrlen);
1256 memcpy (session->connect_addr,
1259 session->connect_alen = addrlen;
1261 GNUNET_assert (session != NULL);
1262 GNUNET_assert (session->client != NULL);
1263 GNUNET_STATISTICS_update (plugin->env->stats,
1264 gettext_noop ("# bytes currently in TCP buffers"),
1267 /* create new message entry */
1268 pm = GNUNET_malloc (sizeof (struct PendingMessage) + msgbuf_size);
1269 pm->msg = (const char*) &pm[1];
1270 memcpy (&pm[1], msg, msgbuf_size);
1271 pm->message_size = msgbuf_size;
1272 pm->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1273 pm->transmit_cont = cont;
1274 pm->transmit_cont_cls = cont_cls;
1276 /* append pm to pending_messages list */
1277 GNUNET_CONTAINER_DLL_insert_after (session->pending_messages_head,
1278 session->pending_messages_tail,
1279 session->pending_messages_tail,
1282 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1283 "Asked to transmit %u bytes to `%s', added message to list.\n",
1285 GNUNET_i2s (target));
1287 process_pending_messages (session);
1293 * Function that can be called to force a disconnect from the
1294 * specified neighbour. This should also cancel all previously
1295 * scheduled transmissions. Obviously the transmission may have been
1296 * partially completed already, which is OK. The plugin is supposed
1297 * to close the connection (if applicable) and no longer call the
1298 * transmit continuation(s).
1300 * Finally, plugin MUST NOT call the services's receive function to
1301 * notify the service that the connection to the specified target was
1302 * closed after a getting this call.
1304 * @param cls closure
1305 * @param target peer for which the last transmission is
1309 tcp_plugin_disconnect (void *cls,
1310 const struct GNUNET_PeerIdentity *target)
1312 struct Plugin *plugin = cls;
1313 struct Session *session;
1314 struct Session *next;
1315 struct PendingMessage *pm;
1318 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1319 "Asked to cancel session with `%4s'\n",
1320 GNUNET_i2s (target));
1322 next = plugin->sessions;
1323 while (NULL != (session = next))
1325 next = session->next;
1326 if (0 != memcmp (target,
1328 sizeof (struct GNUNET_PeerIdentity)))
1330 pm = session->pending_messages_head;
1333 pm->transmit_cont = NULL;
1334 pm->transmit_cont_cls = NULL;
1337 disconnect_session (session);
1343 * Context for address to string conversion.
1345 struct PrettyPrinterContext
1348 * Function to call with the result.
1350 GNUNET_TRANSPORT_AddressStringCallback asc;
1353 * Clsoure for 'asc'.
1358 * Port to add after the IP address.
1365 * Append our port and forward the result.
1367 * @param cls the 'struct PrettyPrinterContext*'
1368 * @param hostname hostname part of the address
1371 append_port (void *cls, const char *hostname)
1373 struct PrettyPrinterContext *ppc = cls;
1376 if (hostname == NULL)
1378 ppc->asc (ppc->asc_cls, NULL);
1382 GNUNET_asprintf (&ret, "%s:%d", hostname, ppc->port);
1383 ppc->asc (ppc->asc_cls, ret);
1389 * Convert the transports address to a nice, human-readable
1392 * @param cls closure
1393 * @param type name of the transport that generated the address
1394 * @param addr one of the addresses of the host, NULL for the last address
1395 * the specific address format depends on the transport
1396 * @param addrlen length of the address
1397 * @param numeric should (IP) addresses be displayed in numeric form?
1398 * @param timeout after how long should we give up?
1399 * @param asc function to call on each string
1400 * @param asc_cls closure for asc
1403 tcp_plugin_address_pretty_printer (void *cls,
1408 struct GNUNET_TIME_Relative timeout,
1409 GNUNET_TRANSPORT_AddressStringCallback asc,
1412 struct Plugin *plugin = cls;
1413 struct PrettyPrinterContext *ppc;
1416 struct sockaddr_in a4;
1417 struct sockaddr_in6 a6;
1418 const struct IPv4TcpAddress *t4;
1419 const struct IPv6TcpAddress *t6;
1422 if (addrlen == sizeof (struct IPv6TcpAddress))
1425 memset (&a6, 0, sizeof (a6));
1426 a6.sin6_family = AF_INET6;
1427 a6.sin6_port = t6->t6_port;
1428 memcpy (&a6.sin6_addr,
1430 sizeof (struct in6_addr));
1431 port = ntohs (t6->t6_port);
1435 else if (addrlen == sizeof (struct IPv4TcpAddress))
1438 memset (&a4, 0, sizeof (a4));
1439 a4.sin_family = AF_INET;
1440 a4.sin_port = t4->t_port;
1441 a4.sin_addr.s_addr = t4->ipv4_addr;
1442 port = ntohs (t4->t_port);
1448 /* invalid address */
1449 GNUNET_break_op (0);
1450 asc (asc_cls, NULL);
1453 ppc = GNUNET_malloc (sizeof (struct PrettyPrinterContext));
1455 ppc->asc_cls = asc_cls;
1457 GNUNET_RESOLVER_hostname_get (plugin->env->sched,
1461 !numeric, timeout, &append_port, ppc);
1466 * Check if the given port is plausible (must be either
1467 * our listen port or our advertised port). If it is
1468 * neither, we return GNUNET_SYSERR.
1470 * @param plugin global variables
1471 * @param in_port port number to check
1472 * @return GNUNET_OK if port is either open_port or adv_port
1475 check_port (struct Plugin *plugin, uint16_t in_port)
1477 if ( (plugin->behind_nat == GNUNET_YES) && (in_port == 0) )
1479 if ( (plugin->only_nat_addresses == GNUNET_YES) &&
1480 (plugin->behind_nat == GNUNET_YES) )
1482 return GNUNET_SYSERR; /* odd case... */
1484 if ((in_port == plugin->adv_port) || (in_port == plugin->open_port))
1486 return GNUNET_SYSERR;
1491 * Function that will be called to check if a binary address for this
1492 * plugin is well-formed and corresponds to an address for THIS peer
1493 * (as per our configuration). Naturally, if absolutely necessary,
1494 * plugins can be a bit conservative in their answer, but in general
1495 * plugins should make sure that the address does not redirect
1496 * traffic to a 3rd party that might try to man-in-the-middle our
1499 * @param cls closure, our 'struct Plugin*'
1500 * @param addr pointer to the address
1501 * @param addrlen length of addr
1502 * @return GNUNET_OK if this is a plausible address for this peer
1503 * and transport, GNUNET_SYSERR if not
1506 tcp_plugin_check_address (void *cls,
1510 struct Plugin *plugin = cls;
1511 struct IPv4TcpAddress *v4;
1512 struct IPv6TcpAddress *v6;
1514 if ((addrlen != sizeof (struct IPv4TcpAddress)) &&
1515 (addrlen != sizeof (struct IPv6TcpAddress)))
1517 GNUNET_break_op (0);
1518 return GNUNET_SYSERR;
1520 if (addrlen == sizeof (struct IPv4TcpAddress))
1522 v4 = (struct IPv4TcpAddress *) addr;
1524 check_port (plugin, ntohs (v4->t_port)))
1525 return GNUNET_SYSERR;
1527 check_local_addr (plugin, &v4->ipv4_addr, sizeof (uint32_t)))
1529 return GNUNET_SYSERR;
1534 v6 = (struct IPv6TcpAddress *) addr;
1535 if (IN6_IS_ADDR_LINKLOCAL (&v6->ipv6_addr))
1537 GNUNET_break_op (0);
1538 return GNUNET_SYSERR;
1541 check_port (plugin, ntohs (v6->t6_port)))
1542 return GNUNET_SYSERR;
1544 check_local_addr (plugin, &v6->ipv6_addr, sizeof (struct in6_addr)))
1546 return GNUNET_SYSERR;
1553 * We've received a nat probe from this peer via TCP. Finish
1554 * creating the client session and resume sending of queued
1557 * @param cls closure
1558 * @param client identification of the client
1559 * @param message the actual message
1562 handle_tcp_nat_probe (void *cls,
1563 struct GNUNET_SERVER_Client *client,
1564 const struct GNUNET_MessageHeader *message)
1566 struct Plugin *plugin = cls;
1567 struct Session *session;
1568 struct TCP_NAT_ProbeMessage *tcp_nat_probe;
1571 struct IPv4TcpAddress *t4;
1572 struct IPv6TcpAddress *t6;
1573 const struct sockaddr_in *s4;
1574 const struct sockaddr_in6 *s6;
1577 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "received tcp NAT probe\n");
1579 /* We have received a TCP NAT probe, meaning we (hopefully) initiated
1580 * a connection to this peer by running gnunet-nat-client. This peer
1581 * received the punch message and now wants us to use the new connection
1582 * as the default for that peer. Do so and then send a WELCOME message
1583 * so we can really be connected!
1585 if (ntohs(message->size) != sizeof(struct TCP_NAT_ProbeMessage))
1588 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Bad size for tcp NAT probe, expected %d got %d.\n", sizeof(struct TCP_NAT_ProbeMessage), ntohs(message->size));
1593 tcp_nat_probe = (struct TCP_NAT_ProbeMessage *)message;
1595 if (GNUNET_CONTAINER_multihashmap_contains(plugin->nat_wait_conns, &tcp_nat_probe->clientIdentity.hashPubKey) == GNUNET_YES)
1598 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Found session for NAT probe!\n");
1600 session = GNUNET_CONTAINER_multihashmap_get(plugin->nat_wait_conns, &tcp_nat_probe->clientIdentity.hashPubKey);
1601 GNUNET_assert(session != NULL);
1602 GNUNET_assert(GNUNET_CONTAINER_multihashmap_remove(plugin->nat_wait_conns, &tcp_nat_probe->clientIdentity.hashPubKey, session) == GNUNET_YES);
1603 GNUNET_SERVER_client_keep (client);
1604 session->client = client;
1605 session->last_activity = GNUNET_TIME_absolute_get ();
1606 session->inbound = GNUNET_NO;
1609 GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
1612 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1613 "handle_tcp_nat_probe Found address `%s' for incoming connection %p\n",
1614 GNUNET_a2s (vaddr, alen),
1617 if (((const struct sockaddr *)vaddr)->sa_family == AF_INET)
1620 t4 = GNUNET_malloc (sizeof (struct IPv4TcpAddress));
1621 t4->t_port = s4->sin_port;
1622 t4->ipv4_addr = s4->sin_addr.s_addr;
1623 session->connect_addr = t4;
1624 session->connect_alen = sizeof (struct IPv4TcpAddress);
1626 else if (((const struct sockaddr *)vaddr)->sa_family == AF_INET6)
1629 t6 = GNUNET_malloc (sizeof (struct IPv6TcpAddress));
1630 t6->t6_port = s6->sin6_port;
1631 memcpy (&t6->ipv6_addr,
1633 sizeof (struct in6_addr));
1634 session->connect_addr = t6;
1635 session->connect_alen = sizeof (struct IPv6TcpAddress);
1640 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1641 "Bad address for incoming connection!\n");
1644 GNUNET_free (vaddr);
1647 session->next = plugin->sessions;
1648 plugin->sessions = session;
1649 GNUNET_STATISTICS_update (plugin->env->stats,
1650 gettext_noop ("# TCP sessions active"),
1653 process_pending_messages (session);
1658 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Did NOT find session for NAT probe!\n");
1662 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1666 * We've received a welcome from this peer via TCP. Possibly create a
1667 * fresh client record and send back our welcome.
1669 * @param cls closure
1670 * @param client identification of the client
1671 * @param message the actual message
1674 handle_tcp_welcome (void *cls,
1675 struct GNUNET_SERVER_Client *client,
1676 const struct GNUNET_MessageHeader *message)
1678 struct Plugin *plugin = cls;
1679 const struct WelcomeMessage *wm = (const struct WelcomeMessage *) message;
1680 struct Session *session;
1683 struct IPv4TcpAddress *t4;
1684 struct IPv6TcpAddress *t6;
1685 const struct sockaddr_in *s4;
1686 const struct sockaddr_in6 *s6;
1689 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1690 "Received %s message from a `%4s/%p'.\n",
1692 GNUNET_i2s (&wm->clientIdentity), client);
1694 GNUNET_STATISTICS_update (plugin->env->stats,
1695 gettext_noop ("# TCP WELCOME messages received"),
1698 #if MULTIPLE_PEER_SESSIONS
1699 session = find_session_by_client (plugin, client);
1701 session = find_session_by_id(plugin, &wm->clientIdentity);
1704 if (session == NULL)
1706 GNUNET_SERVER_client_keep (client);
1708 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1709 "Received %s message from a `%4s/%p', creating session\n",
1711 GNUNET_i2s (&wm->clientIdentity), client);
1713 session = create_session (plugin,
1714 &wm->clientIdentity, client, GNUNET_NO);
1715 session->inbound = GNUNET_YES;
1717 GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
1720 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1721 "Found address `%s' for incoming connection %p\n",
1722 GNUNET_a2s (vaddr, alen),
1725 if (alen == sizeof (struct sockaddr_in))
1728 t4 = GNUNET_malloc (sizeof (struct IPv4TcpAddress));
1729 t4->t_port = s4->sin_port;
1730 t4->ipv4_addr = s4->sin_addr.s_addr;
1731 session->connect_addr = t4;
1732 session->connect_alen = sizeof (struct IPv4TcpAddress);
1734 else if (alen == sizeof (struct sockaddr_in6))
1737 t6 = GNUNET_malloc (sizeof (struct IPv6TcpAddress));
1738 t6->t6_port = s6->sin6_port;
1739 memcpy (&t6->ipv6_addr,
1741 sizeof (struct in6_addr));
1742 session->connect_addr = t6;
1743 session->connect_alen = sizeof (struct IPv6TcpAddress);
1746 GNUNET_free (vaddr);
1751 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1752 "Did not obtain TCP socket address for incoming connection\n");
1756 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1757 "Creating new session %p for connection %p\n",
1760 process_pending_messages (session);
1766 GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
1768 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1769 "Found address `%s' (already have session) for incoming connection %p\n",
1770 GNUNET_a2s (vaddr, alen),
1776 #if MULTIPLE_PEER_SESSIONS
1777 if (session->expecting_welcome != GNUNET_YES)
1779 GNUNET_break_op (0);
1780 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1784 session->last_activity = GNUNET_TIME_absolute_get ();
1785 session->expecting_welcome = GNUNET_NO;
1786 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1791 * Task to signal the server that we can continue
1792 * receiving from the TCP client now.
1794 * @param cls the 'struct Session*'
1795 * @param tc task context (unused)
1798 delayed_done (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1800 struct Session *session = cls;
1801 struct GNUNET_TIME_Relative delay;
1803 session->receive_delay_task = GNUNET_SCHEDULER_NO_TASK;
1804 delay = session->plugin->env->receive (session->plugin->env->cls,
1809 if (delay.value == 0)
1810 GNUNET_SERVER_receive_done (session->client, GNUNET_OK);
1812 session->receive_delay_task =
1813 GNUNET_SCHEDULER_add_delayed (session->plugin->env->sched,
1814 delay, &delayed_done, session);
1819 * We've received data for this peer via TCP. Unbox,
1820 * compute latency and forward.
1822 * @param cls closure
1823 * @param client identification of the client
1824 * @param message the actual message
1827 handle_tcp_data (void *cls,
1828 struct GNUNET_SERVER_Client *client,
1829 const struct GNUNET_MessageHeader *message)
1831 struct Plugin *plugin = cls;
1832 struct Session *session;
1833 struct GNUNET_TIME_Relative delay;
1835 if ((GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME == ntohs(message->type)) || (ntohs(message->type) == GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE))
1837 /* We don't want to propagate WELCOME and NAT Probe messages up! */
1838 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1841 session = find_session_by_client (plugin, client);
1842 if ( (NULL == session) || (GNUNET_YES == session->expecting_welcome))
1844 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1847 session->last_activity = GNUNET_TIME_absolute_get ();
1849 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1850 "Passing %u bytes of type %u from `%4s' to transport service.\n",
1851 (unsigned int) ntohs (message->size),
1852 (unsigned int) ntohs (message->type),
1853 GNUNET_i2s (&session->target));
1855 GNUNET_STATISTICS_update (plugin->env->stats,
1856 gettext_noop ("# bytes received via TCP"),
1857 ntohs (message->size),
1859 delay = plugin->env->receive (plugin->env->cls, &session->target, message, 1,
1861 (GNUNET_YES == session->inbound) ? NULL : session->connect_addr,
1862 (GNUNET_YES == session->inbound) ? 0 : session->connect_alen);
1863 if (delay.value == 0)
1864 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1866 session->receive_delay_task =
1867 GNUNET_SCHEDULER_add_delayed (session->plugin->env->sched,
1868 delay, &delayed_done, session);
1873 * Functions with this signature are called whenever a peer
1874 * is disconnected on the network level.
1876 * @param cls closure
1877 * @param client identification of the client
1880 disconnect_notify (void *cls,
1881 struct GNUNET_SERVER_Client *client)
1883 struct Plugin *plugin = cls;
1884 struct Session *session;
1888 session = find_session_by_client (plugin, client);
1889 if (session == NULL)
1890 return; /* unknown, nothing to do */
1892 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1893 "Destroying session of `%4s' with %s (%p) due to network-level disconnect.\n",
1894 GNUNET_i2s (&session->target),
1895 (session->connect_addr != NULL) ?
1896 tcp_address_to_string (session->plugin,
1897 session->connect_addr,
1898 session->connect_alen) : "*",
1901 disconnect_session (session);
1906 * Add the IP of our network interface to the list of
1907 * our external IP addresses.
1909 * @param cls the 'struct Plugin*'
1910 * @param name name of the interface
1911 * @param isDefault do we think this may be our default interface
1912 * @param addr address of the interface
1913 * @param addrlen number of bytes in addr
1914 * @return GNUNET_OK to continue iterating
1917 process_interfaces (void *cls,
1920 const struct sockaddr *addr, socklen_t addrlen)
1922 struct Plugin *plugin = cls;
1924 struct IPv4TcpAddress t4;
1925 struct IPv6TcpAddress t6;
1926 struct IPv4TcpAddress t4_nat;
1927 struct IPv6TcpAddress t6_nat;
1931 char buf[INET_ADDRSTRLEN];
1933 af = addr->sa_family;
1937 t4.ipv4_addr = ((struct sockaddr_in *) addr)->sin_addr.s_addr;
1938 GNUNET_assert(NULL != inet_ntop(AF_INET, &t4.ipv4_addr, &buf[0], INET_ADDRSTRLEN));
1939 if ((plugin->bind_address != NULL) && (0 != strcmp(buf, plugin->bind_address)))
1941 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s: Not notifying transport of address %s\n", "TCP", GNUNET_a2s (addr, addrlen));
1944 add_to_address_list (plugin, &t4.ipv4_addr, sizeof (uint32_t));
1945 if ((plugin->behind_nat == GNUNET_YES) && (plugin->only_nat_addresses == GNUNET_YES))
1946 t4.t_port = htons(0);
1947 else if (plugin->behind_nat == GNUNET_YES) /* We are behind NAT, but will advertise NAT and normal addresses */
1949 t4_nat.ipv4_addr = ((struct sockaddr_in *) addr)->sin_addr.s_addr;
1950 t4_nat.t_port = htons(plugin->adv_port);
1954 t4.t_port = htons (plugin->adv_port);
1958 else if (af == AF_INET6)
1960 if ((IN6_IS_ADDR_LINKLOCAL (&((struct sockaddr_in6 *) addr)->sin6_addr)) || (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno(plugin->env->cfg, "transport-tcp", "disablev6")))
1962 /* skip link local addresses */
1965 memcpy (&t6.ipv6_addr,
1966 &((struct sockaddr_in6 *) addr)->sin6_addr,
1967 sizeof (struct in6_addr));
1968 add_to_address_list (plugin, &t6.ipv6_addr, sizeof (struct in6_addr));
1969 if ((plugin->behind_nat == GNUNET_YES) && (plugin->only_nat_addresses == GNUNET_YES))
1970 t6.t6_port = htons(0);
1971 else if (plugin->behind_nat == GNUNET_YES) /* We are behind NAT, but will advertise NAT and normal addresses */
1973 memcpy (&t6_nat.ipv6_addr,
1974 &((struct sockaddr_in6 *) addr)->sin6_addr,
1975 sizeof (struct in6_addr));
1976 t6_nat.t6_port = htons(plugin->adv_port);
1980 t6.t6_port = htons (plugin->adv_port);
1989 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1990 _("Found address `%s' (%s) len %d\n"),
1991 GNUNET_a2s (addr, addrlen), name, args);
1993 plugin->env->notify_address (plugin->env->cls,
1995 arg, args, GNUNET_TIME_UNIT_FOREVER_REL);
1997 if (arg_nat != NULL)
1999 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2000 _("Found address `%s' (%s) len %d\n"),
2001 GNUNET_a2s (addr, addrlen), name, args);
2002 plugin->env->notify_address (plugin->env->cls,
2004 arg_nat, args, GNUNET_TIME_UNIT_FOREVER_REL);
2012 * Function called by the resolver for each address obtained from DNS
2013 * for our own hostname. Add the addresses to the list of our
2014 * external IP addresses.
2016 * @param cls closure
2017 * @param addr one of the addresses of the host, NULL for the last address
2018 * @param addrlen length of the address
2021 process_hostname_ips (void *cls,
2022 const struct sockaddr *addr, socklen_t addrlen)
2024 struct Plugin *plugin = cls;
2028 plugin->hostname_dns = NULL;
2031 /* FIXME: Can we figure out our external address here so it doesn't need to be user specified? */
2032 process_interfaces (plugin, "<hostname>", GNUNET_YES, addr, addrlen);
2036 * We can now send a probe message, copy into buffer to really send.
2038 * @param cls closure, a struct TCPProbeContext
2039 * @param size max size to copy
2040 * @param buf buffer to copy message to
2042 static size_t notify_send_probe (void *cls,
2043 size_t size, void *buf)
2045 struct TCPProbeContext *tcp_probe_ctx = cls;
2052 GNUNET_assert(size >= sizeof(tcp_probe_ctx->message));
2053 memcpy(buf, &tcp_probe_ctx->message, sizeof(tcp_probe_ctx->message));
2054 GNUNET_SERVER_connect_socket (tcp_probe_ctx->plugin->server,
2055 tcp_probe_ctx->sock);
2057 GNUNET_free(tcp_probe_ctx);
2058 return sizeof(tcp_probe_ctx->message);
2062 * @param cls the plugin handle
2063 * @param tc the scheduling context (for rescheduling this function again)
2065 * We have been notified that gnunet-nat-server has written something to stdout.
2066 * Handle the output, then reschedule this function to be called again once
2067 * more is available.
2071 tcp_plugin_server_read (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2073 struct Plugin *plugin = cls;
2076 memset(&mybuf, 0, sizeof(mybuf));
2080 struct sockaddr_in in_addr;
2081 struct TCPProbeContext *tcp_probe_ctx;
2082 struct GNUNET_CONNECTION_Handle *sock;
2084 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
2087 bytes = GNUNET_DISK_file_read(plugin->server_stdout_handle, &mybuf, sizeof(mybuf));
2092 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2093 _("Finished reading from server stdout with code: %d\n"), bytes);
2099 for (i = 0; i < sizeof(mybuf); i++)
2101 if (mybuf[i] == '\n')
2104 if ((mybuf[i] == ':') && (i + 1 < sizeof(mybuf)))
2107 port_start = &mybuf[i + 1];
2111 if (port_start != NULL)
2112 port = atoi(port_start);
2115 plugin->server_read_task =
2116 GNUNET_SCHEDULER_add_read_file (plugin->env->sched,
2117 GNUNET_TIME_UNIT_FOREVER_REL,
2118 plugin->server_stdout_handle, &tcp_plugin_server_read, plugin);
2123 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2124 _("nat-server-read read: %s port %d\n"), &mybuf, port);
2128 if (inet_pton(AF_INET, &mybuf[0], &in_addr.sin_addr) != 1)
2131 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2132 _("nat-server-read malformed address\n"), &mybuf, port);
2134 plugin->server_read_task =
2135 GNUNET_SCHEDULER_add_read_file (plugin->env->sched,
2136 GNUNET_TIME_UNIT_FOREVER_REL,
2137 plugin->server_stdout_handle, &tcp_plugin_server_read, plugin);
2141 in_addr.sin_family = AF_INET;
2142 in_addr.sin_port = htons(port);
2144 * We have received an ICMP response, ostensibly from a non-NAT'd peer
2145 * that wants to connect to us! Send a message to establish a connection.
2147 sock = GNUNET_CONNECTION_create_from_sockaddr (plugin->env->sched, AF_INET, (struct sockaddr *)&in_addr,
2153 plugin->server_read_task =
2154 GNUNET_SCHEDULER_add_read_file (plugin->env->sched,
2155 GNUNET_TIME_UNIT_FOREVER_REL,
2156 plugin->server_stdout_handle, &tcp_plugin_server_read, plugin);
2161 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2162 _("Sending TCP probe message!\n"), &mybuf, port);
2164 tcp_probe_ctx = GNUNET_malloc(sizeof(struct TCPProbeContext));
2165 tcp_probe_ctx->message.header.size = htons(sizeof(struct TCP_NAT_ProbeMessage));
2166 tcp_probe_ctx->message.header.type = htons(GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE);
2167 memcpy(&tcp_probe_ctx->message.clientIdentity, plugin->env->my_identity, sizeof(struct GNUNET_PeerIdentity));
2168 tcp_probe_ctx->plugin = plugin;
2169 tcp_probe_ctx->sock = sock;
2170 tcp_probe_ctx->transmit_handle = GNUNET_CONNECTION_notify_transmit_ready (sock,
2171 ntohs(tcp_probe_ctx->message.header.size),
2172 GNUNET_TIME_UNIT_FOREVER_REL,
2173 ¬ify_send_probe, tcp_probe_ctx);
2177 /*GNUNET_SERVER_connect_socket(plugin->server, sock);*/
2178 plugin->server_read_task =
2179 GNUNET_SCHEDULER_add_read_file (plugin->env->sched,
2180 GNUNET_TIME_UNIT_FOREVER_REL,
2181 plugin->server_stdout_handle, &tcp_plugin_server_read, plugin);
2185 * Start the gnunet-nat-server process for users behind NAT.
2187 * @param plugin the transport plugin
2189 * @return GNUNET_YES if process was started, GNUNET_SYSERR on error
2192 tcp_transport_start_nat_server(struct Plugin *plugin)
2195 plugin->server_stdout = GNUNET_DISK_pipe(GNUNET_YES, GNUNET_YES, GNUNET_YES);
2196 if (plugin->server_stdout == NULL)
2197 return GNUNET_SYSERR;
2200 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2201 "Starting gnunet-nat-server process cmd: %s %s\n", "gnunet-nat-server", plugin->internal_address);
2203 /* Start the server process */
2204 plugin->server_pid = GNUNET_OS_start_process(NULL, plugin->server_stdout, "gnunet-nat-server", "gnunet-nat-server", plugin->internal_address, NULL);
2205 if (plugin->server_pid == GNUNET_SYSERR)
2208 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2209 "Failed to start gnunet-nat-server process\n");
2211 return GNUNET_SYSERR;
2213 /* Close the write end of the read pipe */
2214 GNUNET_DISK_pipe_close_end(plugin->server_stdout, GNUNET_DISK_PIPE_END_WRITE);
2216 plugin->server_stdout_handle = GNUNET_DISK_pipe_handle(plugin->server_stdout, GNUNET_DISK_PIPE_END_READ);
2217 plugin->server_read_task =
2218 GNUNET_SCHEDULER_add_read_file (plugin->env->sched,
2219 GNUNET_TIME_UNIT_FOREVER_REL,
2220 plugin->server_stdout_handle, &tcp_plugin_server_read, plugin);
2225 * Return the actual path to a file found in the current
2226 * PATH environment variable.
2228 * @param binary the name of the file to find
2231 get_path_from_PATH (char *binary)
2239 p = getenv ("PATH");
2242 path = GNUNET_strdup (p); /* because we write on it */
2243 buf = GNUNET_malloc (strlen (path) + 20);
2246 while (NULL != (end = strchr (pos, ':')))
2249 sprintf (buf, "%s/%s", pos, binary);
2250 if (GNUNET_DISK_file_test (buf) == GNUNET_YES)
2257 sprintf (buf, "%s/%s", pos, binary);
2258 if (GNUNET_DISK_file_test (buf) == GNUNET_YES)
2269 * Check whether the suid bit is set on a file.
2270 * Attempts to find the file using the current
2271 * PATH environment variable as a search path.
2273 * @param binary the name of the file to check
2276 check_gnunet_nat_binary(char *binary)
2278 struct stat statbuf;
2281 p = get_path_from_PATH (binary);
2284 if (0 != STAT (p, &statbuf))
2287 return GNUNET_SYSERR;
2290 if ( (0 != (statbuf.st_mode & S_ISUID)) &&
2291 (statbuf.st_uid == 0) )
2297 * Entry point for the plugin.
2299 * @param cls closure, the 'struct GNUNET_TRANSPORT_PluginEnvironment*'
2300 * @return the 'struct GNUNET_TRANSPORT_PluginFunctions*' or NULL on error
2303 libgnunet_plugin_transport_tcp_init (void *cls)
2305 static const struct GNUNET_SERVER_MessageHandler my_handlers[] = {
2306 {&handle_tcp_welcome, NULL, GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME,
2307 sizeof (struct WelcomeMessage)},
2308 {&handle_tcp_nat_probe, NULL, GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE, sizeof (struct TCP_NAT_ProbeMessage)},
2309 {&handle_tcp_data, NULL, GNUNET_MESSAGE_TYPE_ALL, 0},
2312 struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
2313 struct GNUNET_TRANSPORT_PluginFunctions *api;
2314 struct Plugin *plugin;
2315 struct GNUNET_SERVICE_Context *service;
2316 unsigned long long aport;
2317 unsigned long long bport;
2321 int only_nat_addresses;
2322 char *internal_address;
2323 char *external_address;
2324 struct sockaddr_in in_addr;
2325 struct IPv4TcpAddress t4;
2327 service = GNUNET_SERVICE_start ("transport-tcp", env->sched, env->cfg);
2328 if (service == NULL)
2330 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2331 _("Failed to start service for `%s' transport plugin.\n"),
2336 if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno (env->cfg,
2340 /* We are behind nat (according to the user) */
2341 if (check_gnunet_nat_binary("gnunet-nat-server") == GNUNET_YES)
2343 behind_nat = GNUNET_YES;
2347 behind_nat = GNUNET_NO;
2348 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Configuration specified you are behind a NAT, but gnunet-nat-server is not installed properly (suid bit not set)!\n");
2352 behind_nat = GNUNET_NO; /* We are not behind nat! */
2354 if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno (env->cfg,
2358 if (check_gnunet_nat_binary("gnunet-nat-client") == GNUNET_YES)
2359 allow_nat = GNUNET_YES; /* We will try to connect to NAT'd peers */
2362 allow_nat = GNUNET_NO;
2363 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Configuration specified you want to connect to NAT'd peers, but gnunet-nat-client is not installed properly (suid bit not set)!\n");
2367 allow_nat = GNUNET_NO; /* We don't want to try to help NAT'd peers */
2370 if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno (env->cfg,
2372 "ONLY_NAT_ADDRESSES"))
2373 only_nat_addresses = GNUNET_YES; /* We will only report our addresses as NAT'd */
2375 only_nat_addresses = GNUNET_NO; /* We will report our addresses as NAT'd and non-NAT'd */
2377 external_address = NULL;
2378 if (((GNUNET_YES == behind_nat) || (GNUNET_YES == allow_nat)) && (GNUNET_OK !=
2379 GNUNET_CONFIGURATION_get_value_string (env->cfg,
2382 &external_address)))
2384 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2386 ("Require EXTERNAL_ADDRESS for service `%s' in configuration (either BEHIND_NAT or ALLOW_NAT set to YES)!\n"),
2388 GNUNET_SERVICE_stop (service);
2392 if ((external_address != NULL) && (inet_pton(AF_INET, external_address, &in_addr.sin_addr) != 1))
2394 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Malformed EXTERNAL_ADDRESS %s given in configuration!\n", external_address);
2397 internal_address = NULL;
2398 if ((GNUNET_YES == behind_nat) && (GNUNET_OK !=
2399 GNUNET_CONFIGURATION_get_value_string (env->cfg,
2402 &internal_address)))
2404 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2405 _("Require INTERNAL_ADDRESS for service `%s' in configuration!\n"),
2407 GNUNET_SERVICE_stop (service);
2408 GNUNET_free_non_null(external_address);
2412 if ((internal_address != NULL) && (inet_pton(AF_INET, internal_address, &in_addr.sin_addr) != 1))
2414 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Malformed INTERNAL_ADDRESS %s given in configuration!\n", internal_address);
2419 GNUNET_CONFIGURATION_get_value_number (env->cfg,
2425 GNUNET_CONFIGURATION_get_value_number (env->cfg,
2428 &aport)) && (aport > 65535)))
2430 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2432 ("Require valid port number for service `%s' in configuration!\n"),
2434 GNUNET_free_non_null(external_address);
2435 GNUNET_free_non_null(internal_address);
2436 GNUNET_SERVICE_stop (service);
2442 plugin = GNUNET_malloc (sizeof (struct Plugin));
2443 plugin->open_port = bport;
2444 plugin->adv_port = aport;
2445 plugin->external_address = external_address;
2446 plugin->internal_address = internal_address;
2447 plugin->behind_nat = behind_nat;
2448 plugin->allow_nat = allow_nat;
2449 plugin->only_nat_addresses = only_nat_addresses;
2451 plugin->lsock = NULL;
2452 api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
2454 api->send = &tcp_plugin_send;
2455 api->disconnect = &tcp_plugin_disconnect;
2456 api->address_pretty_printer = &tcp_plugin_address_pretty_printer;
2457 api->check_address = &tcp_plugin_check_address;
2458 api->address_to_string = &tcp_address_to_string;
2459 plugin->service = service;
2460 plugin->server = GNUNET_SERVICE_get_server (service);
2461 plugin->handlers = GNUNET_malloc (sizeof (my_handlers));
2462 memcpy (plugin->handlers, my_handlers, sizeof (my_handlers));
2465 sizeof (my_handlers) / sizeof (struct GNUNET_SERVER_MessageHandler);
2467 plugin->handlers[i].callback_cls = plugin;
2468 GNUNET_SERVER_add_handlers (plugin->server, plugin->handlers);
2470 if (plugin->behind_nat == GNUNET_YES)
2472 if (GNUNET_YES != tcp_transport_start_nat_server(plugin))
2474 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2477 ("Failed to start %s required for NAT in %s!\n"),
2480 GNUNET_free_non_null(external_address);
2481 GNUNET_free_non_null(internal_address);
2482 GNUNET_SERVICE_stop (service);
2488 if (allow_nat == GNUNET_YES)
2490 plugin->nat_wait_conns = GNUNET_CONTAINER_multihashmap_create(100);
2491 GNUNET_assert(plugin->nat_wait_conns != NULL);
2494 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _("TCP transport listening on port %llu\n"), bport);
2496 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2497 _("TCP transport advertises itself as being on port %llu\n"),
2499 GNUNET_SERVER_disconnect_notify (plugin->server,
2502 GNUNET_CONFIGURATION_get_value_string(env->cfg, "transport-tcp", "BINDTO", &plugin->bind_address);
2504 if (plugin->behind_nat == GNUNET_NO)
2506 GNUNET_OS_network_interfaces_list (&process_interfaces, plugin);
2509 plugin->hostname_dns = GNUNET_RESOLVER_hostname_resolve (env->sched,
2512 HOSTNAME_RESOLVE_TIMEOUT,
2513 &process_hostname_ips,
2516 if ((plugin->behind_nat == GNUNET_YES) && (inet_pton(AF_INET, plugin->external_address, &t4.ipv4_addr) == 1))
2518 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Notifying transport of address %s:0\n", plugin->external_address);
2519 t4.t_port = htons(0);
2520 add_to_address_list (plugin, &t4.ipv4_addr, sizeof (uint32_t));
2521 plugin->env->notify_address (plugin->env->cls,
2523 &t4, sizeof(t4), GNUNET_TIME_UNIT_FOREVER_REL);
2525 else if ((plugin->external_address != NULL) && (inet_pton(AF_INET, plugin->external_address, &t4.ipv4_addr) == 1))
2527 t4.t_port = htons(plugin->adv_port);
2528 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Notifying transport of address %s:%d\n", plugin->external_address, plugin->adv_port);
2529 add_to_address_list (plugin, &t4.ipv4_addr, sizeof (uint32_t));
2530 plugin->env->notify_address (plugin->env->cls,
2532 &t4, sizeof(t4), GNUNET_TIME_UNIT_FOREVER_REL);
2540 * Exit point from the plugin.
2543 libgnunet_plugin_transport_tcp_done (void *cls)
2545 struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
2546 struct Plugin *plugin = api->cls;
2547 struct Session *session;
2548 struct LocalAddrList *lal;
2550 while (NULL != (session = plugin->sessions))
2551 disconnect_session (session);
2552 if (NULL != plugin->hostname_dns)
2554 GNUNET_RESOLVER_request_cancel (plugin->hostname_dns);
2555 plugin->hostname_dns = NULL;
2557 GNUNET_SERVICE_stop (plugin->service);
2558 GNUNET_free (plugin->handlers);
2559 while (NULL != (lal = plugin->lal_head))
2561 GNUNET_CONTAINER_DLL_remove (plugin->lal_head,
2567 if (plugin->behind_nat == GNUNET_YES)
2569 if (0 != PLIBC_KILL (plugin->server_pid, SIGTERM))
2570 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "kill");
2571 GNUNET_OS_process_wait (plugin->server_pid);
2573 GNUNET_free_non_null(plugin->bind_address);
2574 GNUNET_free (plugin);
2579 /* end of plugin_transport_tcp.c */