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 2, 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
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.
122 * Port number, in network byte order.
130 * Network format for IPv6 addresses.
132 struct IPv6TcpAddress
137 struct in6_addr ipv6_addr;
140 * Port number, in network byte order.
147 * Encapsulation of all of the state of the plugin.
153 * Information kept for each message that is yet to
156 struct PendingMessage
160 * This is a doubly-linked list.
162 struct PendingMessage *next;
165 * This is a doubly-linked list.
167 struct PendingMessage *prev;
170 * The pending message
175 * Continuation function to call once the message
176 * has been sent. Can be NULL if there is no
177 * continuation to call.
179 GNUNET_TRANSPORT_TransmitContinuation transmit_cont;
182 * Closure for transmit_cont.
184 void *transmit_cont_cls;
187 * Timeout value for the pending message.
189 struct GNUNET_TIME_Absolute timeout;
192 * So that the gnunet-service-transport can group messages together,
193 * these pending messages need to accept a message buffer and size
194 * instead of just a GNUNET_MessageHeader.
202 * Session handle for TCP connections.
210 struct SessionHeader header;
213 * Stored in a linked list.
215 struct Session *next;
218 * Pointer to the global plugin struct.
220 struct Plugin *plugin;
223 * The client (used to identify this connection)
225 struct GNUNET_SERVER_Client *client;
228 * Messages currently pending for transmission
229 * to this peer, if any.
231 struct PendingMessage *pending_messages_head;
234 * Messages currently pending for transmission
235 * to this peer, if any.
237 struct PendingMessage *pending_messages_tail;
240 * Handle for pending transmission request.
242 struct GNUNET_CONNECTION_TransmitHandle *transmit_handle;
245 * To whom are we talking to (set to our identity
246 * if we are still waiting for the welcome message)
248 struct GNUNET_PeerIdentity target;
251 * ID of task used to delay receiving more to throttle sender.
253 GNUNET_SCHEDULER_TaskIdentifier receive_delay_task;
256 * Address of the other peer (either based on our 'connect'
257 * call or on our 'accept' call).
262 * Last activity on this connection. Used to select preferred
265 struct GNUNET_TIME_Absolute last_activity;
268 * Length of connect_addr.
273 * Are we still expecting the welcome message? (GNUNET_YES/GNUNET_NO)
275 int expecting_welcome;
278 * Was this a connection that was inbound (we accepted)? (GNUNET_YES/GNUNET_NO)
286 * Encapsulation of all of the state of the plugin.
293 struct GNUNET_TRANSPORT_PluginEnvironment *env;
298 struct GNUNET_CONNECTION_Handle *lsock;
301 * stdout pipe handle for the gnunet-nat-server process
303 struct GNUNET_DISK_PipeHandle *server_stdout;
306 * stdout file handle (for reading) for the gnunet-nat-server process
308 const struct GNUNET_DISK_FileHandle *server_stdout_handle;
311 * ID of select gnunet-nat-server stdout read task
313 GNUNET_SCHEDULER_TaskIdentifier server_read_task;
316 * The process id of the server process (if behind NAT)
321 * List of open TCP sessions.
323 struct Session *sessions;
326 * Handle to the network service.
328 struct GNUNET_SERVICE_Context *service;
331 * Handle to the server for this service.
333 struct GNUNET_SERVER_Handle *server;
336 * Copy of the handler array where the closures are
337 * set to this struct's instance.
339 struct GNUNET_SERVER_MessageHandler *handlers;
342 * Handle for request of hostname resolution, non-NULL if pending.
344 struct GNUNET_RESOLVER_RequestHandle *hostname_dns;
347 * Map of peers we have tried to contact behind a NAT
349 struct GNUNET_CONTAINER_MultiHashMap *nat_wait_conns;
352 * The external address given to us by the user. Must be actual
353 * outside visible address for NAT punching to work.
355 char *external_address;
358 * The internal address given to us by the user (or discovered).
360 char *internal_address;
363 * ID of task used to update our addresses when one expires.
365 GNUNET_SCHEDULER_TaskIdentifier address_update_task;
368 * Port that we are actually listening on.
373 * Port that the user said we would have visible to the
379 * Is this transport configured to be behind a NAT?
384 * Is this transport configured to allow connections to NAT'd peers?
389 * Should this transport advertise only NAT addresses (port set to 0)?
390 * If not, all addresses will be duplicated for NAT punching and regular
393 int only_nat_addresses;
401 * Function called for a quick conversion of the binary address to
402 * a numeric address. Note that the caller must not free the
403 * address and that the next call to this function is allowed
404 * to override the address again.
406 * @param cls closure ('struct Plugin*')
407 * @param addr binary address
408 * @param addrlen length of the address
409 * @return string representing the same address
412 tcp_address_to_string (void *cls,
416 static char rbuf[INET6_ADDRSTRLEN + 12];
417 char buf[INET6_ADDRSTRLEN];
421 const struct IPv4TcpAddress *t4;
422 const struct IPv6TcpAddress *t6;
426 if (addrlen == sizeof (struct IPv6TcpAddress))
430 port = ntohs (t6->t6_port);
431 memcpy (&a6, &t6->ipv6_addr, sizeof (a6));
434 else if (addrlen == sizeof (struct IPv4TcpAddress))
438 port = ntohs (t4->t_port);
439 memcpy (&a4, &t4->ipv4_addr, sizeof (a4));
444 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
446 _("Unexpected address length: %u\n"),
451 if (NULL == inet_ntop (af, sb, buf, INET6_ADDRSTRLEN))
453 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "inet_ntop");
456 GNUNET_snprintf (rbuf,
458 (af == AF_INET6) ? "[%s]:%u" : "%s:%u",
466 * Find the session handle for the given client.
468 * @return NULL if no matching session exists
470 static struct Session *
471 find_session_by_client (struct Plugin *plugin,
472 const struct GNUNET_SERVER_Client *client)
476 ret = plugin->sessions;
477 while ((ret != NULL) && (client != ret->client))
483 * Create a new session. Also queues a welcome message.
486 * @param target peer to connect to
487 * @param client client to use
488 * @param is_nat this a NAT session, we should wait for a client to
489 * connect to us from an address, then assign that to
491 * @return new session object
493 static struct Session *
494 create_session (struct Plugin *plugin,
495 const struct GNUNET_PeerIdentity *target,
496 struct GNUNET_SERVER_Client *client, int is_nat)
499 struct PendingMessage *pm;
500 struct WelcomeMessage welcome;
502 if (is_nat != GNUNET_YES)
503 GNUNET_assert (client != NULL);
505 GNUNET_assert (client == NULL);
508 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
510 "Creating new session for peer `%4s'\n",
511 GNUNET_i2s (target));
513 ret = GNUNET_malloc (sizeof (struct Session));
514 ret->last_activity = GNUNET_TIME_absolute_get ();
515 ret->plugin = plugin;
516 if (is_nat != GNUNET_YES) /* If not a NAT WAIT conn, add it to global list */
518 ret->next = plugin->sessions;
519 plugin->sessions = ret;
521 ret->client = client;
522 ret->target = *target;
523 ret->expecting_welcome = GNUNET_YES;
524 pm = GNUNET_malloc (sizeof (struct PendingMessage) + sizeof (struct WelcomeMessage));
525 pm->msg = (const char*) &pm[1];
526 pm->message_size = sizeof (struct WelcomeMessage);
527 welcome.header.size = htons (sizeof (struct WelcomeMessage));
528 welcome.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME);
529 welcome.clientIdentity = *plugin->env->my_identity;
530 memcpy (&pm[1], &welcome, sizeof (welcome));
531 pm->timeout = GNUNET_TIME_UNIT_FOREVER_ABS;
532 GNUNET_STATISTICS_update (plugin->env->stats,
533 gettext_noop ("# bytes currently in TCP buffers"),
536 GNUNET_CONTAINER_DLL_insert (ret->pending_messages_head,
537 ret->pending_messages_tail,
539 if (is_nat != GNUNET_YES)
540 GNUNET_STATISTICS_update (plugin->env->stats,
541 gettext_noop ("# TCP sessions active"),
549 * If we have pending messages, ask the server to
550 * transmit them (schedule the respective tasks, etc.)
552 * @param session for which session should we do this
554 static void process_pending_messages (struct Session *session);
558 * Function called to notify a client about the socket
559 * being ready to queue more data. "buf" will be
560 * NULL and "size" zero if the socket was closed for
561 * writing in the meantime.
564 * @param size number of bytes available in buf
565 * @param buf where the callee should write the message
566 * @return number of bytes written to buf
569 do_transmit (void *cls, size_t size, void *buf)
571 struct Session *session = cls;
572 struct GNUNET_PeerIdentity pid;
573 struct Plugin *plugin;
574 struct PendingMessage *pos;
575 struct PendingMessage *hd;
576 struct PendingMessage *tl;
577 struct GNUNET_TIME_Absolute now;
581 session->transmit_handle = NULL;
582 plugin = session->plugin;
586 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
588 "Timeout trying to transmit to peer `%4s', discarding message queue.\n",
589 GNUNET_i2s (&session->target));
591 /* timeout; cancel all messages that have already expired */
595 now = GNUNET_TIME_absolute_get ();
596 while ( (NULL != (pos = session->pending_messages_head)) &&
597 (pos->timeout.value <= now.value) )
599 GNUNET_CONTAINER_DLL_remove (session->pending_messages_head,
600 session->pending_messages_tail,
603 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
605 "Failed to transmit %u byte message to `%4s'.\n",
607 GNUNET_i2s (&session->target));
609 ret += pos->message_size;
610 GNUNET_CONTAINER_DLL_insert_after (hd, tl, tl, pos);
612 /* do this call before callbacks (so that if callbacks destroy
613 session, they have a chance to cancel actions done by this
615 process_pending_messages (session);
616 pid = session->target;
617 /* no do callbacks and do not use session again since
618 the callbacks may abort the session */
619 while (NULL != (pos = hd))
621 GNUNET_CONTAINER_DLL_remove (hd, tl, pos);
622 if (pos->transmit_cont != NULL)
623 pos->transmit_cont (pos->transmit_cont_cls,
624 &pid, GNUNET_SYSERR);
627 GNUNET_STATISTICS_update (plugin->env->stats,
628 gettext_noop ("# bytes currently in TCP buffers"),
631 GNUNET_STATISTICS_update (plugin->env->stats,
632 gettext_noop ("# bytes discarded by TCP (timeout)"),
637 /* copy all pending messages that would fit */
642 while (NULL != (pos = session->pending_messages_head))
644 if (ret + pos->message_size > size)
646 GNUNET_CONTAINER_DLL_remove (session->pending_messages_head,
647 session->pending_messages_tail,
649 GNUNET_assert (size >= pos->message_size);
650 /* FIXME: this memcpy can be up to 7% of our total runtime */
651 memcpy (cbuf, pos->msg, pos->message_size);
652 cbuf += pos->message_size;
653 ret += pos->message_size;
654 size -= pos->message_size;
655 GNUNET_CONTAINER_DLL_insert_after (hd, tl, tl, pos);
657 /* schedule 'continuation' before callbacks so that callbacks that
658 cancel everything don't cause us to use a session that no longer
660 process_pending_messages (session);
661 session->last_activity = GNUNET_TIME_absolute_get ();
662 pid = session->target;
663 /* we'll now call callbacks that may cancel the session; hence
664 we should not use 'session' after this point */
665 while (NULL != (pos = hd))
667 GNUNET_CONTAINER_DLL_remove (hd, tl, pos);
668 if (pos->transmit_cont != NULL)
669 pos->transmit_cont (pos->transmit_cont_cls,
673 GNUNET_assert (hd == NULL);
674 GNUNET_assert (tl == NULL);
676 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
677 "tcp", "Transmitting %u bytes\n", ret);
679 GNUNET_STATISTICS_update (plugin->env->stats,
680 gettext_noop ("# bytes currently in TCP buffers"),
683 GNUNET_STATISTICS_update (plugin->env->stats,
684 gettext_noop ("# bytes transmitted via TCP"),
692 * If we have pending messages, ask the server to
693 * transmit them (schedule the respective tasks, etc.)
695 * @param session for which session should we do this
698 process_pending_messages (struct Session *session)
700 struct PendingMessage *pm;
702 GNUNET_assert (session->client != NULL);
703 if (session->transmit_handle != NULL)
705 if (NULL == (pm = session->pending_messages_head))
707 session->transmit_handle
708 = GNUNET_SERVER_notify_transmit_ready (session->client,
710 GNUNET_TIME_absolute_get_remaining
712 &do_transmit, session);
717 * Functions with this signature are called whenever we need
718 * to close a session due to a disconnect or failure to
719 * establish a connection.
721 * @param session session to close down
724 disconnect_session (struct Session *session)
726 struct Session *prev;
728 struct PendingMessage *pm;
731 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
733 "Disconnecting from `%4s' at %s (session %p).\n",
734 GNUNET_i2s (&session->target),
735 (session->connect_addr != NULL) ?
736 tcp_address_to_string (session->plugin,
737 session->connect_addr,
738 session->connect_alen) : "*",
741 /* remove from session list */
743 pos = session->plugin->sessions;
744 while (pos != session)
750 session->plugin->sessions = session->next;
752 prev->next = session->next;
753 session->plugin->env->session_end (session->plugin->env->cls,
757 if (session->transmit_handle != NULL)
759 GNUNET_CONNECTION_notify_transmit_ready_cancel
760 (session->transmit_handle);
761 session->transmit_handle = NULL;
763 while (NULL != (pm = session->pending_messages_head))
766 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
768 pm->transmit_cont != NULL
769 ? "Could not deliver message to `%4s'.\n"
771 "Could not deliver message to `%4s', notifying.\n",
772 GNUNET_i2s (&session->target));
774 GNUNET_STATISTICS_update (session->plugin->env->stats,
775 gettext_noop ("# bytes currently in TCP buffers"),
776 - (int64_t) pm->message_size,
778 GNUNET_STATISTICS_update (session->plugin->env->stats,
779 gettext_noop ("# bytes discarded by TCP (disconnect)"),
782 GNUNET_CONTAINER_DLL_remove (session->pending_messages_head,
783 session->pending_messages_tail,
785 if (NULL != pm->transmit_cont)
786 pm->transmit_cont (pm->transmit_cont_cls,
787 &session->target, GNUNET_SYSERR);
790 GNUNET_break (session->client != NULL);
791 if (session->receive_delay_task != GNUNET_SCHEDULER_NO_TASK)
793 GNUNET_SCHEDULER_cancel (session->plugin->env->sched,
794 session->receive_delay_task);
795 if (session->client != NULL)
796 GNUNET_SERVER_receive_done (session->client,
799 if (session->client != NULL)
800 GNUNET_SERVER_client_drop (session->client);
801 GNUNET_STATISTICS_update (session->plugin->env->stats,
802 gettext_noop ("# TCP sessions active"),
805 GNUNET_free_non_null (session->connect_addr);
806 GNUNET_free (session);
811 * Given two otherwise equivalent sessions, pick the better one.
813 * @param s1 one session (also default)
814 * @param s2 other session
815 * @return "better" session (more active)
817 static struct Session *
818 select_better_session (struct Session *s1,
825 if ( (s1->expecting_welcome == GNUNET_NO) &&
826 (s2->expecting_welcome == GNUNET_YES) )
828 if ( (s1->expecting_welcome == GNUNET_YES) &&
829 (s2->expecting_welcome == GNUNET_NO) )
831 if (s1->last_activity.value < s2->last_activity.value)
833 if (s1->last_activity.value > s2->last_activity.value)
835 if ( (GNUNET_YES == s1->inbound) &&
836 (GNUNET_NO == s2->inbound) )
838 if ( (GNUNET_NO == s1->inbound) &&
839 (GNUNET_YES == s2->inbound) )
846 * We learned about a peer (possibly behind NAT) so run the
847 * gnunet-nat-client to send dummy ICMP responses
849 * @param plugin the plugin for this transport
850 * @param addr the address of the peer
851 * @param addrlen the length of the address
854 run_gnunet_nat_client (struct Plugin *plugin, const char *addr, size_t addrlen)
856 char inet4[INET_ADDRSTRLEN];
857 char *address_as_string;
858 char *port_as_string;
860 const struct sockaddr *sa = (const struct sockaddr *)addr;
862 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
863 _("called run_gnunet_nat_client addrlen %d others are %d and %d\n"), addrlen, sizeof (struct sockaddr), sizeof (struct sockaddr_in));
866 if (addrlen < sizeof (struct sockaddr))
869 switch (sa->sa_family)
872 if (addrlen != sizeof (struct sockaddr_in))
874 if (NULL == inet_ntop (AF_INET,
875 &((struct sockaddr_in *) sa)->sin_addr,
876 inet4, INET_ADDRSTRLEN))
878 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "inet_ntop");
881 address_as_string = GNUNET_strdup (inet4);
888 GNUNET_asprintf(&port_as_string, "%d", plugin->adv_port);
890 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
891 _("Running gnunet-nat-client with arguments: %s %s %d\n"), plugin->external_address, address_as_string, plugin->adv_port);
894 /* Start the client process */
895 pid = GNUNET_OS_start_process(NULL, NULL, "gnunet-nat-client", "gnunet-nat-client", plugin->external_address, address_as_string, port_as_string, NULL);
896 GNUNET_free(address_as_string);
897 GNUNET_free(port_as_string);
898 GNUNET_OS_process_wait (pid);
903 * Function that can be used by the transport service to transmit
904 * a message using the plugin. Note that in the case of a
905 * peer disconnecting, the continuation MUST be called
906 * prior to the disconnect notification itself. This function
907 * will be called with this peer's HELLO message to initiate
908 * a fresh connection to another peer.
911 * @param target who should receive this message
912 * @param msg the message to transmit
913 * @param msgbuf_size number of bytes in 'msg'
914 * @param priority how important is the message (most plugins will
915 * ignore message priority and just FIFO)
916 * @param timeout how long to wait at most for the transmission (does not
917 * require plugins to discard the message after the timeout,
918 * just advisory for the desired delay; most plugins will ignore
920 * @param session which session must be used (or NULL for "any")
921 * @param addr the address to use (can be NULL if the plugin
922 * is "on its own" (i.e. re-use existing TCP connection))
923 * @param addrlen length of the address in bytes
924 * @param force_address GNUNET_YES if the plugin MUST use the given address,
925 * GNUNET_NO means the plugin may use any other address and
926 * GNUNET_SYSERR means that only reliable existing
927 * bi-directional connections should be used (regardless
929 * @param cont continuation to call once the message has
930 * been transmitted (or if the transport is ready
931 * for the next transmission call; or if the
932 * peer disconnected...); can be NULL
933 * @param cont_cls closure for cont
934 * @return number of bytes used (on the physical network, with overheads);
935 * -1 on hard errors (i.e. address invalid); 0 is a legal value
936 * and does NOT mean that the message was not transmitted (DV and NAT)
939 tcp_plugin_send (void *cls,
940 const struct GNUNET_PeerIdentity *target,
944 struct GNUNET_TIME_Relative timeout,
945 struct Session *session,
949 GNUNET_TRANSPORT_TransmitContinuation cont, void *cont_cls)
951 struct Plugin *plugin = cls;
952 struct Session *cand_session;
953 struct Session *next;
954 struct PendingMessage *pm;
955 struct GNUNET_CONNECTION_Handle *sa;
959 struct sockaddr_in a4;
960 struct sockaddr_in6 a6;
961 const struct IPv4TcpAddress *t4;
962 const struct IPv6TcpAddress *t6;
963 unsigned int is_natd;
965 GNUNET_STATISTICS_update (plugin->env->stats,
966 gettext_noop ("# bytes TCP was asked to transmit"),
969 /* FIXME: we could do this cheaper with a hash table
970 where we could restrict the iteration to entries that match
971 the target peer... */
976 next = plugin->sessions;
977 while (NULL != (session = next))
979 next = session->next;
980 GNUNET_assert (session->client != NULL);
981 if (0 != memcmp (target,
983 sizeof (struct GNUNET_PeerIdentity)))
985 if ( ( (GNUNET_SYSERR == force_address) &&
986 (session->expecting_welcome == GNUNET_NO) ) ||
987 (GNUNET_NO == force_address) )
989 cand_session = select_better_session (cand_session,
993 if (GNUNET_SYSERR == force_address)
995 GNUNET_break (GNUNET_YES == force_address);
1001 if (session->inbound == GNUNET_YES)
1003 if (addrlen != session->connect_alen)
1005 if (0 != memcmp (session->connect_addr,
1009 cand_session = select_better_session (cand_session,
1012 session = cand_session;
1014 if ( (session == NULL) &&
1018 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1020 "Asked to transmit to `%4s' without address and I have no existing connection (failing).\n",
1021 GNUNET_i2s (target));
1023 GNUNET_STATISTICS_update (plugin->env->stats,
1024 gettext_noop ("# bytes discarded by TCP (no address and no connection)"),
1029 if (session == NULL)
1031 if (addrlen == sizeof (struct IPv6TcpAddress))
1035 memset (&a6, 0, sizeof (a6));
1036 #if HAVE_SOCKADDR_IN_SIN_LEN
1037 a6.sin6_len = sizeof (a6);
1039 a6.sin6_family = AF_INET6;
1040 a6.sin6_port = t6->t6_port;
1041 if (t6->t6_port == 0)
1042 is_natd = GNUNET_YES;
1043 memcpy (&a6.sin6_addr,
1045 sizeof (struct in6_addr));
1049 else if (addrlen == sizeof (struct IPv4TcpAddress))
1053 memset (&a4, 0, sizeof (a4));
1054 #if HAVE_SOCKADDR_IN_SIN_LEN
1055 a4.sin_len = sizeof (a4);
1057 a4.sin_family = AF_INET;
1058 a4.sin_port = t4->t_port;
1059 if (t4->t_port == 0)
1060 is_natd = GNUNET_YES;
1061 a4.sin_addr.s_addr = t4->ipv4_addr;
1067 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
1069 _("Address of unexpected length: %u\n"),
1075 if ((is_natd == GNUNET_YES) && (addrlen == sizeof (struct IPv6TcpAddress)))
1076 return -1; /* NAT client only works with IPv4 addresses */
1079 if ( (plugin->allow_nat == GNUNET_YES) && (is_natd == GNUNET_YES) &&
1080 (GNUNET_NO == GNUNET_CONTAINER_multihashmap_contains(plugin->nat_wait_conns, &target->hashPubKey)))
1083 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1085 _("Found valid IPv4 NAT address!\n"));
1087 session = create_session (plugin,
1091 /* create new message entry */
1092 pm = GNUNET_malloc (sizeof (struct PendingMessage) + msgbuf_size);
1093 /* FIXME: the memset of this malloc can be up to 2% of our total runtime */
1094 pm->msg = (const char*) &pm[1];
1095 memcpy (&pm[1], msg, msgbuf_size);
1096 /* FIXME: this memcpy can be up to 7% of our total run-time
1097 (for transport service) */
1098 pm->message_size = msgbuf_size;
1099 pm->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1100 pm->transmit_cont = cont;
1101 pm->transmit_cont_cls = cont_cls;
1103 /* append pm to pending_messages list */
1104 GNUNET_CONTAINER_DLL_insert_after (session->pending_messages_head,
1105 session->pending_messages_tail,
1106 session->pending_messages_tail,
1109 GNUNET_assert(GNUNET_CONTAINER_multihashmap_put(plugin->nat_wait_conns, &target->hashPubKey, session, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY) == GNUNET_OK);
1111 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1113 "Created NAT WAIT connection to `%4s' at `%s'\n",
1114 GNUNET_i2s (target),
1115 GNUNET_a2s (sb, sbs));
1117 run_gnunet_nat_client(plugin, sb, sbs);
1120 else if ((plugin->allow_nat == GNUNET_YES) && (is_natd == GNUNET_YES) && (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains(plugin->nat_wait_conns, &target->hashPubKey)))
1122 /* Only do one NAT punch attempt per peer identity */
1125 sa = GNUNET_CONNECTION_create_from_sockaddr (plugin->env->sched,
1127 GNUNET_SERVER_MAX_MESSAGE_SIZE - 1);
1131 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1133 "Failed to create connection to `%4s' at `%s'\n",
1134 GNUNET_i2s (target),
1135 GNUNET_a2s (sb, sbs));
1137 GNUNET_STATISTICS_update (plugin->env->stats,
1138 gettext_noop ("# bytes discarded by TCP (failed to connect)"),
1144 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1146 "Asked to transmit to `%4s', creating fresh session using address `%s'.\n",
1147 GNUNET_i2s (target),
1148 GNUNET_a2s (sb, sbs));
1150 session = create_session (plugin,
1152 GNUNET_SERVER_connect_socket (plugin->server,
1154 session->connect_addr = GNUNET_malloc (addrlen);
1155 memcpy (session->connect_addr,
1158 session->connect_alen = addrlen;
1160 GNUNET_assert (session != NULL);
1161 GNUNET_assert (session->client != NULL);
1162 GNUNET_STATISTICS_update (plugin->env->stats,
1163 gettext_noop ("# bytes currently in TCP buffers"),
1166 /* create new message entry */
1167 pm = GNUNET_malloc (sizeof (struct PendingMessage) + msgbuf_size);
1168 pm->msg = (const char*) &pm[1];
1169 memcpy (&pm[1], msg, msgbuf_size);
1170 pm->message_size = msgbuf_size;
1171 pm->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1172 pm->transmit_cont = cont;
1173 pm->transmit_cont_cls = cont_cls;
1175 /* append pm to pending_messages list */
1176 GNUNET_CONTAINER_DLL_insert_after (session->pending_messages_head,
1177 session->pending_messages_tail,
1178 session->pending_messages_tail,
1181 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1183 "Asked to transmit %u bytes to `%s', added message to list.\n",
1185 GNUNET_i2s (target));
1187 process_pending_messages (session);
1193 * Function that can be called to force a disconnect from the
1194 * specified neighbour. This should also cancel all previously
1195 * scheduled transmissions. Obviously the transmission may have been
1196 * partially completed already, which is OK. The plugin is supposed
1197 * to close the connection (if applicable) and no longer call the
1198 * transmit continuation(s).
1200 * Finally, plugin MUST NOT call the services's receive function to
1201 * notify the service that the connection to the specified target was
1202 * closed after a getting this call.
1204 * @param cls closure
1205 * @param target peer for which the last transmission is
1209 tcp_plugin_disconnect (void *cls,
1210 const struct GNUNET_PeerIdentity *target)
1212 struct Plugin *plugin = cls;
1213 struct Session *session;
1214 struct Session *next;
1215 struct PendingMessage *pm;
1218 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1220 "Asked to cancel session with `%4s'\n",
1221 GNUNET_i2s (target));
1223 next = plugin->sessions;
1224 while (NULL != (session = next))
1226 next = session->next;
1227 if (0 != memcmp (target,
1229 sizeof (struct GNUNET_PeerIdentity)))
1231 pm = session->pending_messages_head;
1234 pm->transmit_cont = NULL;
1235 pm->transmit_cont_cls = NULL;
1238 disconnect_session (session);
1244 * Context for address to string conversion.
1246 struct PrettyPrinterContext
1249 * Function to call with the result.
1251 GNUNET_TRANSPORT_AddressStringCallback asc;
1254 * Clsoure for 'asc'.
1259 * Port to add after the IP address.
1266 * Append our port and forward the result.
1268 * @param cls the 'struct PrettyPrinterContext*'
1269 * @param hostname hostname part of the address
1272 append_port (void *cls, const char *hostname)
1274 struct PrettyPrinterContext *ppc = cls;
1277 if (hostname == NULL)
1279 ppc->asc (ppc->asc_cls, NULL);
1283 GNUNET_asprintf (&ret, "%s:%d", hostname, ppc->port);
1284 ppc->asc (ppc->asc_cls, ret);
1290 * Convert the transports address to a nice, human-readable
1293 * @param cls closure
1294 * @param type name of the transport that generated the address
1295 * @param addr one of the addresses of the host, NULL for the last address
1296 * the specific address format depends on the transport
1297 * @param addrlen length of the address
1298 * @param numeric should (IP) addresses be displayed in numeric form?
1299 * @param timeout after how long should we give up?
1300 * @param asc function to call on each string
1301 * @param asc_cls closure for asc
1304 tcp_plugin_address_pretty_printer (void *cls,
1309 struct GNUNET_TIME_Relative timeout,
1310 GNUNET_TRANSPORT_AddressStringCallback asc,
1313 struct Plugin *plugin = cls;
1314 struct PrettyPrinterContext *ppc;
1317 struct sockaddr_in a4;
1318 struct sockaddr_in6 a6;
1319 const struct IPv4TcpAddress *t4;
1320 const struct IPv6TcpAddress *t6;
1323 if (addrlen == sizeof (struct IPv6TcpAddress))
1326 memset (&a6, 0, sizeof (a6));
1327 a6.sin6_family = AF_INET6;
1328 a6.sin6_port = t6->t6_port;
1329 memcpy (&a6.sin6_addr,
1331 sizeof (struct in6_addr));
1332 port = ntohs (t6->t6_port);
1336 else if (addrlen == sizeof (struct IPv4TcpAddress))
1339 memset (&a4, 0, sizeof (a4));
1340 a4.sin_family = AF_INET;
1341 a4.sin_port = t4->t_port;
1342 a4.sin_addr.s_addr = t4->ipv4_addr;
1343 port = ntohs (t4->t_port);
1349 /* invalid address */
1350 GNUNET_break_op (0);
1351 asc (asc_cls, NULL);
1354 ppc = GNUNET_malloc (sizeof (struct PrettyPrinterContext));
1356 ppc->asc_cls = asc_cls;
1358 GNUNET_RESOLVER_hostname_get (plugin->env->sched,
1362 !numeric, timeout, &append_port, ppc);
1367 * Check if the given port is plausible (must be either
1368 * our listen port or our advertised port). If it is
1369 * neither, we return one of these two ports at random.
1371 * @param plugin global variables
1372 * @param in_port port number to check
1373 * @return either in_port or a more plausible port
1376 check_port (struct Plugin *plugin, uint16_t in_port)
1378 if ((in_port == plugin->adv_port) || (in_port == plugin->open_port))
1380 return (GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
1382 ? plugin->open_port : plugin->adv_port;
1387 * Another peer has suggested an address for this peer and transport
1388 * plugin. Check that this could be a valid address. This function
1389 * is not expected to 'validate' the address in the sense of trying to
1390 * connect to it but simply to see if the binary format is technically
1391 * legal for establishing a connection.
1393 * @param cls closure, our 'struct Plugin*'
1394 * @param addr pointer to the address
1395 * @param addrlen length of addr
1396 * @return GNUNET_OK if this is a plausible address for this peer
1397 * and transport, GNUNET_SYSERR if not
1400 tcp_plugin_check_address (void *cls, void *addr, size_t addrlen)
1402 struct Plugin *plugin = cls;
1403 struct IPv4TcpAddress *v4;
1404 struct IPv6TcpAddress *v6;
1406 if ((addrlen != sizeof (struct IPv4TcpAddress)) &&
1407 (addrlen != sizeof (struct IPv6TcpAddress)))
1409 GNUNET_break_op (0);
1410 return GNUNET_SYSERR;
1412 if (addrlen == sizeof (struct IPv4TcpAddress))
1414 v4 = (struct IPv4TcpAddress *) addr;
1415 v4->t_port = htons (check_port (plugin, ntohs (v4->t_port)));
1419 v6 = (struct IPv6TcpAddress *) addr;
1420 if (IN6_IS_ADDR_LINKLOCAL (&v6->ipv6_addr))
1422 GNUNET_break_op (0);
1423 return GNUNET_SYSERR;
1425 v6->t6_port = htons (check_port (plugin, ntohs (v6->t6_port)));
1431 * We've received a nat probe from this peer via TCP. Finish
1432 * creating the client session and resume sending of queued
1435 * @param cls closure
1436 * @param client identification of the client
1437 * @param message the actual message
1440 handle_tcp_nat_probe (void *cls,
1441 struct GNUNET_SERVER_Client *client,
1442 const struct GNUNET_MessageHeader *message)
1444 struct Plugin *plugin = cls;
1445 struct Session *session;
1446 struct TCP_NAT_ProbeMessage *tcp_nat_probe;
1449 struct IPv4TcpAddress *t4;
1450 struct IPv6TcpAddress *t6;
1451 const struct sockaddr_in *s4;
1452 const struct sockaddr_in6 *s6;
1455 GNUNET_log_from(GNUNET_ERROR_TYPE_DEBUG, "tcp", "received tcp NAT probe\n");
1457 /* We have received a TCP NAT probe, meaning we (hopefully) initiated
1458 * a connection to this peer by running gnunet-nat-client. This peer
1459 * received the punch message and now wants us to use the new connection
1460 * as the default for that peer. Do so and then send a WELCOME message
1461 * so we can really be connected!
1463 if (ntohs(message->size) != sizeof(struct TCP_NAT_ProbeMessage))
1466 GNUNET_log_from(GNUNET_ERROR_TYPE_DEBUG, "tcp", "Bad size fo tcp NAT probe, expected %d got %d.\n", sizeof(struct TCP_NAT_ProbeMessage), ntohs(message->size));
1471 tcp_nat_probe = (struct TCP_NAT_ProbeMessage *)message;
1473 if (GNUNET_CONTAINER_multihashmap_contains(plugin->nat_wait_conns, &tcp_nat_probe->clientIdentity.hashPubKey) == GNUNET_YES)
1476 GNUNET_log_from(GNUNET_ERROR_TYPE_DEBUG, "tcp", "Found session for NAT probe!\n");
1478 session = GNUNET_CONTAINER_multihashmap_get(plugin->nat_wait_conns, &tcp_nat_probe->clientIdentity.hashPubKey);
1479 GNUNET_assert(session != NULL);
1480 GNUNET_assert(GNUNET_CONTAINER_multihashmap_remove(plugin->nat_wait_conns, &tcp_nat_probe->clientIdentity.hashPubKey, session) == GNUNET_YES);
1481 GNUNET_SERVER_client_keep (client);
1482 session->client = client;
1483 session->last_activity = GNUNET_TIME_absolute_get ();
1486 GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
1489 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1491 "Found address `%s' for incoming connection %p\n",
1492 GNUNET_a2s (vaddr, alen),
1495 if (alen == sizeof (struct sockaddr_in))
1498 t4 = GNUNET_malloc (sizeof (struct IPv4TcpAddress));
1499 t4->t_port = s4->sin_port;
1500 t4->ipv4_addr = s4->sin_addr.s_addr;
1501 session->connect_addr = t4;
1502 session->connect_alen = sizeof (struct IPv4TcpAddress);
1504 else if (alen == sizeof (struct sockaddr_in6))
1507 t6 = GNUNET_malloc (sizeof (struct IPv6TcpAddress));
1508 t6->t6_port = s6->sin6_port;
1509 memcpy (&t6->ipv6_addr,
1511 sizeof (struct in6_addr));
1512 session->connect_addr = t6;
1513 session->connect_alen = sizeof (struct IPv6TcpAddress);
1516 session->connect_addr = GNUNET_malloc (alen);
1517 memcpy (session->connect_addr,
1520 session->connect_alen = alen;
1521 GNUNET_free (vaddr);
1524 session->next = plugin->sessions;
1525 plugin->sessions = session;
1526 GNUNET_STATISTICS_update (plugin->env->stats,
1527 gettext_noop ("# TCP sessions active"),
1530 process_pending_messages (session);
1535 GNUNET_log_from(GNUNET_ERROR_TYPE_DEBUG, "tcp", "Did NOT find session for NAT probe!\n");
1541 * We've received a welcome from this peer via TCP. Possibly create a
1542 * fresh client record and send back our welcome.
1544 * @param cls closure
1545 * @param client identification of the client
1546 * @param message the actual message
1549 handle_tcp_welcome (void *cls,
1550 struct GNUNET_SERVER_Client *client,
1551 const struct GNUNET_MessageHeader *message)
1553 struct Plugin *plugin = cls;
1554 const struct WelcomeMessage *wm = (const struct WelcomeMessage *) message;
1555 struct Session *session;
1558 struct IPv4TcpAddress *t4;
1559 struct IPv6TcpAddress *t6;
1560 const struct sockaddr_in *s4;
1561 const struct sockaddr_in6 *s6;
1565 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1567 "Received %s message from a `%4s/%p'.\n",
1569 GNUNET_i2s (&wm->clientIdentity), client);
1571 GNUNET_STATISTICS_update (plugin->env->stats,
1572 gettext_noop ("# TCP WELCOME messages received"),
1575 session = find_session_by_client (plugin, client);
1576 if (session == NULL)
1578 GNUNET_SERVER_client_keep (client);
1579 session = create_session (plugin,
1580 &wm->clientIdentity, client, GNUNET_NO);
1581 session->inbound = GNUNET_YES;
1583 GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
1586 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1588 "Found address `%s' for incoming connection %p\n",
1589 GNUNET_a2s (vaddr, alen),
1592 if (alen == sizeof (struct sockaddr_in))
1595 t4 = GNUNET_malloc (sizeof (struct IPv4TcpAddress));
1596 t4->t_port = s4->sin_port;
1597 t4->ipv4_addr = s4->sin_addr.s_addr;
1598 session->connect_addr = t4;
1599 session->connect_alen = sizeof (struct IPv4TcpAddress);
1601 else if (alen == sizeof (struct sockaddr_in6))
1604 t6 = GNUNET_malloc (sizeof (struct IPv6TcpAddress));
1605 t6->t6_port = s6->sin6_port;
1606 memcpy (&t6->ipv6_addr,
1608 sizeof (struct in6_addr));
1609 session->connect_addr = t6;
1610 session->connect_alen = sizeof (struct IPv6TcpAddress);
1612 GNUNET_free (vaddr);
1617 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1619 "Did not obtain TCP socket address for incoming connection\n");
1623 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1625 "Creating new session %p for connection %p\n",
1628 process_pending_messages (session);
1630 if (session->expecting_welcome != GNUNET_YES)
1632 GNUNET_break_op (0);
1633 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1636 session->last_activity = GNUNET_TIME_absolute_get ();
1637 session->expecting_welcome = GNUNET_NO;
1638 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1643 * Task to signal the server that we can continue
1644 * receiving from the TCP client now.
1646 * @param cls the 'struct Session*'
1647 * @param tc task context (unused)
1650 delayed_done (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1652 struct Session *session = cls;
1653 struct GNUNET_TIME_Relative delay;
1655 session->receive_delay_task = GNUNET_SCHEDULER_NO_TASK;
1656 delay = session->plugin->env->receive (session->plugin->env->cls,
1661 if (delay.value == 0)
1662 GNUNET_SERVER_receive_done (session->client, GNUNET_OK);
1664 session->receive_delay_task =
1665 GNUNET_SCHEDULER_add_delayed (session->plugin->env->sched,
1666 delay, &delayed_done, session);
1671 * We've received data for this peer via TCP. Unbox,
1672 * compute latency and forward.
1674 * @param cls closure
1675 * @param client identification of the client
1676 * @param message the actual message
1679 handle_tcp_data (void *cls,
1680 struct GNUNET_SERVER_Client *client,
1681 const struct GNUNET_MessageHeader *message)
1683 struct Plugin *plugin = cls;
1684 struct Session *session;
1685 struct GNUNET_TIME_Relative delay;
1687 if ((GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME == ntohs(message->type)) || (ntohs(message->type) == GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE))
1689 /* We don't want to propagate WELCOME and NAT Probe messages up! */
1690 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1693 session = find_session_by_client (plugin, client);
1694 if ( (NULL == session) || (GNUNET_YES == session->expecting_welcome))
1696 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1699 session->last_activity = GNUNET_TIME_absolute_get ();
1701 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1703 "Passing %u bytes of type %u from `%4s' to transport service.\n",
1704 (unsigned int) ntohs (message->size),
1705 (unsigned int) ntohs (message->type),
1706 GNUNET_i2s (&session->target));
1708 GNUNET_STATISTICS_update (plugin->env->stats,
1709 gettext_noop ("# bytes received via TCP"),
1710 ntohs (message->size),
1712 delay = plugin->env->receive (plugin->env->cls, &session->target, message, 1,
1714 (GNUNET_YES == session->inbound) ? NULL : session->connect_addr,
1715 (GNUNET_YES == session->inbound) ? 0 : session->connect_alen);
1716 if (delay.value == 0)
1717 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1719 session->receive_delay_task =
1720 GNUNET_SCHEDULER_add_delayed (session->plugin->env->sched,
1721 delay, &delayed_done, session);
1726 * Functions with this signature are called whenever a peer
1727 * is disconnected on the network level.
1729 * @param cls closure
1730 * @param client identification of the client
1733 disconnect_notify (void *cls,
1734 struct GNUNET_SERVER_Client *client)
1736 struct Plugin *plugin = cls;
1737 struct Session *session;
1741 session = find_session_by_client (plugin, client);
1742 if (session == NULL)
1743 return; /* unknown, nothing to do */
1745 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1747 "Destroying session of `%4s' with %s (%p) due to network-level disconnect.\n",
1748 GNUNET_i2s (&session->target),
1749 (session->connect_addr != NULL) ?
1750 tcp_address_to_string (session->plugin,
1751 session->connect_addr,
1752 session->connect_alen) : "*",
1755 disconnect_session (session);
1760 * Add the IP of our network interface to the list of
1761 * our external IP addresses.
1763 * @param cls the 'struct Plugin*'
1764 * @param name name of the interface
1765 * @param isDefault do we think this may be our default interface
1766 * @param addr address of the interface
1767 * @param addrlen number of bytes in addr
1768 * @return GNUNET_OK to continue iterating
1771 process_interfaces (void *cls,
1774 const struct sockaddr *addr, socklen_t addrlen)
1776 struct Plugin *plugin = cls;
1778 struct IPv4TcpAddress t4;
1779 struct IPv6TcpAddress t6;
1780 struct IPv4TcpAddress t4_nat;
1781 struct IPv6TcpAddress t6_nat;
1786 af = addr->sa_family;
1790 t4.ipv4_addr = ((struct sockaddr_in *) addr)->sin_addr.s_addr;
1791 if ((plugin->behind_nat == GNUNET_YES) && (plugin->only_nat_addresses == GNUNET_YES))
1792 t4.t_port = htons(0);
1793 else if (plugin->behind_nat == GNUNET_YES) /* We are behind NAT, but will advertise NAT and normal addresses */
1795 t4_nat.ipv4_addr = ((struct sockaddr_in *) addr)->sin_addr.s_addr;
1796 t4_nat.t_port = htons(plugin->adv_port);
1800 t4.t_port = htons (plugin->adv_port);
1804 else if (af == AF_INET6)
1806 if (IN6_IS_ADDR_LINKLOCAL (&((struct sockaddr_in6 *) addr)->sin6_addr))
1808 /* skip link local addresses */
1811 memcpy (&t6.ipv6_addr,
1812 &((struct sockaddr_in6 *) addr)->sin6_addr,
1813 sizeof (struct in6_addr));
1814 if ((plugin->behind_nat == GNUNET_YES) && (plugin->only_nat_addresses == GNUNET_YES))
1815 t6.t6_port = htons(0);
1816 else if (plugin->behind_nat == GNUNET_YES) /* We are behind NAT, but will advertise NAT and normal addresses */
1818 memcpy (&t6_nat.ipv6_addr,
1819 &((struct sockaddr_in6 *) addr)->sin6_addr,
1820 sizeof (struct in6_addr));
1821 t6_nat.t6_port = htons(plugin->adv_port);
1825 t6.t6_port = htons (plugin->adv_port);
1834 GNUNET_log_from (GNUNET_ERROR_TYPE_INFO |
1835 GNUNET_ERROR_TYPE_BULK,
1837 _("Found address `%s' (%s)\n"),
1838 GNUNET_a2s (addr, addrlen), name);
1840 plugin->env->notify_address (plugin->env->cls,
1842 arg, args, GNUNET_TIME_UNIT_FOREVER_REL);
1844 if (arg_nat != NULL)
1846 GNUNET_log_from (GNUNET_ERROR_TYPE_INFO |
1847 GNUNET_ERROR_TYPE_BULK,
1849 _("Found address `%s' (%s)\n"),
1850 GNUNET_a2s (addr, addrlen), name);
1851 plugin->env->notify_address (plugin->env->cls,
1853 arg_nat, args, GNUNET_TIME_UNIT_FOREVER_REL);
1861 * Function called by the resolver for each address obtained from DNS
1862 * for our own hostname. Add the addresses to the list of our
1863 * external IP addresses.
1865 * @param cls closure
1866 * @param addr one of the addresses of the host, NULL for the last address
1867 * @param addrlen length of the address
1870 process_hostname_ips (void *cls,
1871 const struct sockaddr *addr, socklen_t addrlen)
1873 struct Plugin *plugin = cls;
1877 plugin->hostname_dns = NULL;
1880 /* FIXME: Can we figure out our external address here so it doesn't need to be user specified? */
1881 process_interfaces (plugin, "<hostname>", GNUNET_YES, addr, addrlen);
1885 * We can now send a probe message, copy into buffer to really send.
1887 * @param cls closure, a struct TCPProbeContext
1888 * @param size max size to copy
1889 * @param buf buffer to copy message to
1891 static size_t notify_send_probe (void *cls,
1892 size_t size, void *buf)
1894 struct TCPProbeContext *tcp_probe_ctx = cls;
1901 GNUNET_assert(size >= sizeof(tcp_probe_ctx->message));
1902 memcpy(buf, &tcp_probe_ctx->message, sizeof(tcp_probe_ctx->message));
1903 GNUNET_SERVER_connect_socket (tcp_probe_ctx->plugin->server,
1904 tcp_probe_ctx->sock);
1906 GNUNET_free(tcp_probe_ctx);
1907 return sizeof(tcp_probe_ctx->message);
1911 * @param cls the plugin handle
1912 * @param tc the scheduling context (for rescheduling this function again)
1914 * We have been notified that gnunet-nat-server has written something to stdout.
1915 * Handle the output, then reschedule this function to be called again once
1916 * more is available.
1920 tcp_plugin_server_read (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1922 struct Plugin *plugin = cls;
1925 memset(&mybuf, 0, sizeof(mybuf));
1929 struct sockaddr_in in_addr;
1930 struct TCPProbeContext *tcp_probe_ctx;
1931 struct GNUNET_CONNECTION_Handle *sock;
1933 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
1936 bytes = GNUNET_DISK_file_read(plugin->server_stdout_handle, &mybuf, sizeof(mybuf));
1941 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1942 _("Finished reading from server stdout with code: %d\n"), bytes);
1949 for (i = 0; i < sizeof(mybuf); i++)
1951 if (mybuf[i] == '\n')
1954 if ((mybuf[i] == ':') && (i + 1 < sizeof(mybuf)))
1957 port_start = &mybuf[i + 1];
1961 if (port_start != NULL)
1962 port = atoi(port_start);
1965 plugin->server_read_task =
1966 GNUNET_SCHEDULER_add_read_file (plugin->env->sched,
1967 GNUNET_TIME_UNIT_FOREVER_REL,
1968 plugin->server_stdout_handle, &tcp_plugin_server_read, plugin);
1973 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1974 _("nat-server-read read: %s port %d\n"), &mybuf, port);
1978 if (inet_pton(AF_INET, &mybuf[0], &in_addr.sin_addr) != 1)
1981 GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, "tcp",
1982 _("nat-server-read malformed address\n"), &mybuf, port);
1984 plugin->server_read_task =
1985 GNUNET_SCHEDULER_add_read_file (plugin->env->sched,
1986 GNUNET_TIME_UNIT_FOREVER_REL,
1987 plugin->server_stdout_handle, &tcp_plugin_server_read, plugin);
1991 in_addr.sin_family = AF_INET;
1992 in_addr.sin_port = htons(port);
1994 * We have received an ICMP response, ostensibly from a non-NAT'd peer
1995 * that wants to connect to us! Send a message to establish a connection.
1997 sock = GNUNET_CONNECTION_create_from_sockaddr (plugin->env->sched, AF_INET, (struct sockaddr *)&in_addr,
1998 sizeof(in_addr), GNUNET_SERVER_MAX_MESSAGE_SIZE - 1);
2001 plugin->server_read_task =
2002 GNUNET_SCHEDULER_add_read_file (plugin->env->sched,
2003 GNUNET_TIME_UNIT_FOREVER_REL,
2004 plugin->server_stdout_handle, &tcp_plugin_server_read, plugin);
2009 tcp_probe_ctx = GNUNET_malloc(sizeof(struct TCPProbeContext));
2011 tcp_probe_ctx->message.header.size = htons(sizeof(struct TCP_NAT_ProbeMessage));
2012 tcp_probe_ctx->message.header.type = htons(GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE);
2013 memcpy(&tcp_probe_ctx->message.clientIdentity, plugin->env->my_identity, sizeof(struct GNUNET_PeerIdentity));
2014 tcp_probe_ctx->plugin = plugin;
2015 tcp_probe_ctx->sock = sock;
2016 tcp_probe_ctx->transmit_handle = GNUNET_CONNECTION_notify_transmit_ready (sock,
2017 ntohs(tcp_probe_ctx->message.header.size),
2018 GNUNET_TIME_UNIT_FOREVER_REL,
2019 ¬ify_send_probe, tcp_probe_ctx);
2023 plugin->server_read_task =
2024 GNUNET_SCHEDULER_add_read_file (plugin->env->sched,
2025 GNUNET_TIME_UNIT_FOREVER_REL,
2026 plugin->server_stdout_handle, &tcp_plugin_server_read, plugin);
2030 * Start the gnunet-nat-server process for users behind NAT.
2032 * @param plugin the transport plugin
2034 * @return GNUNET_YES if process was started, GNUNET_SYSERR on error
2037 tcp_transport_start_nat_server(struct Plugin *plugin)
2040 plugin->server_stdout = GNUNET_DISK_pipe(GNUNET_YES);
2041 if (plugin->server_stdout == NULL)
2042 return GNUNET_SYSERR;
2045 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
2047 "Starting gnunet-nat-server process cmd: %s %s\n", "gnunet-nat-server", plugin->internal_address);
2049 /* Start the server process */
2050 plugin->server_pid = GNUNET_OS_start_process(NULL, plugin->server_stdout, "gnunet-nat-server", "gnunet-nat-server", plugin->internal_address, NULL);
2051 if (plugin->server_pid == GNUNET_SYSERR)
2054 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
2056 "Failed to start gnunet-nat-server process\n");
2058 return GNUNET_SYSERR;
2060 /* Close the write end of the read pipe */
2061 GNUNET_DISK_pipe_close_end(plugin->server_stdout, GNUNET_DISK_PIPE_END_WRITE);
2063 plugin->server_stdout_handle = GNUNET_DISK_pipe_handle(plugin->server_stdout, GNUNET_DISK_PIPE_END_READ);
2064 plugin->server_read_task =
2065 GNUNET_SCHEDULER_add_read_file (plugin->env->sched,
2066 GNUNET_TIME_UNIT_FOREVER_REL,
2067 plugin->server_stdout_handle, &tcp_plugin_server_read, plugin);
2072 * Return the actual path to a file found in the current
2073 * PATH environment variable.
2075 * @param binary the name of the file to find
2078 get_path_from_PATH (char *binary)
2086 p = getenv ("PATH");
2089 path = GNUNET_strdup (p); /* because we write on it */
2090 buf = GNUNET_malloc (strlen (path) + 20);
2093 while (NULL != (end = strchr (pos, ':')))
2096 sprintf (buf, "%s/%s", pos, binary);
2097 if (GNUNET_DISK_file_test (buf) == GNUNET_YES)
2104 sprintf (buf, "%s/%s", pos, binary);
2105 if (GNUNET_DISK_file_test (buf) == GNUNET_YES)
2116 * Check whether the suid bit is set on a file.
2117 * Attempts to find the file using the current
2118 * PATH environment variable as a search path.
2120 * @param binary the name of the file to check
2123 check_gnunet_nat_binary(char *binary)
2125 struct stat statbuf;
2128 p = get_path_from_PATH (binary);
2131 if (0 != STAT (p, &statbuf))
2134 return GNUNET_SYSERR;
2137 if ( (0 != (statbuf.st_mode & S_ISUID)) &&
2138 (statbuf.st_uid == 0) )
2144 * Entry point for the plugin.
2146 * @param cls closure, the 'struct GNUNET_TRANSPORT_PluginEnvironment*'
2147 * @return the 'struct GNUNET_TRANSPORT_PluginFunctions*' or NULL on error
2150 libgnunet_plugin_transport_tcp_init (void *cls)
2152 static const struct GNUNET_SERVER_MessageHandler my_handlers[] = {
2153 {&handle_tcp_welcome, NULL, GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME,
2154 sizeof (struct WelcomeMessage)},
2155 {&handle_tcp_nat_probe, NULL, GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE, sizeof (struct TCP_NAT_ProbeMessage)},
2156 {&handle_tcp_data, NULL, GNUNET_MESSAGE_TYPE_ALL, 0},
2159 struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
2160 struct GNUNET_TRANSPORT_PluginFunctions *api;
2161 struct Plugin *plugin;
2162 struct GNUNET_SERVICE_Context *service;
2163 unsigned long long aport;
2164 unsigned long long bport;
2168 int only_nat_addresses;
2169 char *internal_address;
2170 char *external_address;
2171 struct sockaddr_in in_addr;
2172 struct IPv4TcpAddress t4;
2174 service = GNUNET_SERVICE_start ("transport-tcp", env->sched, env->cfg);
2175 if (service == NULL)
2177 GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING,
2180 ("Failed to start service for `%s' transport plugin.\n"),
2185 if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno (env->cfg,
2189 /* We are behind nat (according to the user) */
2190 if (check_gnunet_nat_binary("gnunet-nat-server") == GNUNET_YES)
2192 behind_nat = GNUNET_YES;
2196 behind_nat = GNUNET_NO;
2197 GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, "tcp", "Configuration specified you are behind a NAT, but gnunet-nat-server is not installed properly (suid bit not set)!\n");
2201 behind_nat = GNUNET_NO; /* We are not behind nat! */
2203 if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno (env->cfg,
2207 if (check_gnunet_nat_binary("gnunet-nat-client") == GNUNET_YES)
2208 allow_nat = GNUNET_YES; /* We will try to connect to NAT'd peers */
2211 allow_nat = GNUNET_NO;
2212 GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, "tcp", "Configuration specified you want to connect to NAT'd peers, but gnunet-nat-client is not installed properly (suid bit not set)!\n");
2216 allow_nat = GNUNET_NO; /* We don't want to try to help NAT'd peers */
2219 if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno (env->cfg,
2221 "ONLY_NAT_ADDRESSES"))
2222 only_nat_addresses = GNUNET_YES; /* We will only report our addresses as NAT'd */
2224 only_nat_addresses = GNUNET_NO; /* We will report our addresses as NAT'd and non-NAT'd */
2226 external_address = NULL;
2227 if (((GNUNET_YES == behind_nat) || (GNUNET_YES == allow_nat)) && (GNUNET_OK !=
2228 GNUNET_CONFIGURATION_get_value_string (env->cfg,
2231 &external_address)))
2233 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
2236 ("Require EXTERNAL_ADDRESS for service `%s' in configuration (either BEHIND_NAT or ALLOW_NAT set to YES)!\n"),
2238 GNUNET_SERVICE_stop (service);
2242 if ((external_address != NULL) && (inet_pton(AF_INET, external_address, &in_addr.sin_addr) != 1))
2244 GNUNET_log_from(GNUNET_ERROR_TYPE_WARNING, "udp", "Malformed EXTERNAL_ADDRESS %s given in configuration!\n", external_address);
2247 internal_address = NULL;
2248 if ((GNUNET_YES == behind_nat) && (GNUNET_OK !=
2249 GNUNET_CONFIGURATION_get_value_string (env->cfg,
2252 &internal_address)))
2254 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
2257 ("Require INTERNAL_ADDRESS for service `%s' in configuration!\n"),
2259 GNUNET_SERVICE_stop (service);
2260 GNUNET_free_non_null(external_address);
2264 if ((internal_address != NULL) && (inet_pton(AF_INET, internal_address, &in_addr.sin_addr) != 1))
2266 GNUNET_log_from(GNUNET_ERROR_TYPE_WARNING, "udp", "Malformed INTERNAL_ADDRESS %s given in configuration!\n", internal_address);
2271 GNUNET_CONFIGURATION_get_value_number (env->cfg,
2277 GNUNET_CONFIGURATION_get_value_number (env->cfg,
2280 &aport)) && (aport > 65535)))
2282 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
2285 ("Require valid port number for service `%s' in configuration!\n"),
2287 GNUNET_free_non_null(external_address);
2288 GNUNET_free_non_null(internal_address);
2289 GNUNET_SERVICE_stop (service);
2295 plugin = GNUNET_malloc (sizeof (struct Plugin));
2296 plugin->open_port = bport;
2297 plugin->adv_port = aport;
2298 plugin->external_address = external_address;
2299 plugin->internal_address = internal_address;
2300 plugin->behind_nat = behind_nat;
2301 plugin->allow_nat = allow_nat;
2302 plugin->only_nat_addresses = only_nat_addresses;
2304 plugin->lsock = NULL;
2305 api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
2307 api->send = &tcp_plugin_send;
2308 api->disconnect = &tcp_plugin_disconnect;
2309 api->address_pretty_printer = &tcp_plugin_address_pretty_printer;
2310 api->check_address = &tcp_plugin_check_address;
2311 api->address_to_string = &tcp_address_to_string;
2312 plugin->service = service;
2313 plugin->server = GNUNET_SERVICE_get_server (service);
2314 plugin->handlers = GNUNET_malloc (sizeof (my_handlers));
2315 memcpy (plugin->handlers, my_handlers, sizeof (my_handlers));
2318 sizeof (my_handlers) / sizeof (struct GNUNET_SERVER_MessageHandler);
2320 plugin->handlers[i].callback_cls = plugin;
2321 GNUNET_SERVER_add_handlers (plugin->server, plugin->handlers);
2323 if (behind_nat == GNUNET_YES)
2325 if (GNUNET_YES != tcp_transport_start_nat_server(plugin))
2327 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
2330 ("Failed to start %s required for NAT in %s!\n"),
2333 GNUNET_free_non_null(external_address);
2334 GNUNET_free_non_null(internal_address);
2335 GNUNET_SERVICE_stop (service);
2340 if (allow_nat == GNUNET_YES)
2342 plugin->nat_wait_conns = GNUNET_CONTAINER_multihashmap_create(100);
2343 GNUNET_assert(plugin->nat_wait_conns != NULL);
2346 GNUNET_log_from (GNUNET_ERROR_TYPE_INFO,
2347 "tcp", _("TCP transport listening on port %llu\n"), bport);
2349 GNUNET_log_from (GNUNET_ERROR_TYPE_INFO,
2351 _("TCP transport advertises itself as being on port %llu\n"),
2353 GNUNET_SERVER_disconnect_notify (plugin->server,
2356 if (plugin->behind_nat == GNUNET_NO)
2358 GNUNET_OS_network_interfaces_list (&process_interfaces, plugin);
2361 plugin->hostname_dns = GNUNET_RESOLVER_hostname_resolve (env->sched,
2364 HOSTNAME_RESOLVE_TIMEOUT,
2365 &process_hostname_ips,
2368 if ((plugin->behind_nat == GNUNET_YES) && (inet_pton(AF_INET, plugin->external_address, &t4.ipv4_addr) == 1))
2370 t4.t_port = htons(0);
2371 plugin->env->notify_address (plugin->env->cls,
2373 &t4, sizeof(t4), GNUNET_TIME_UNIT_FOREVER_REL);
2375 else if ((plugin->external_address != NULL) && (inet_pton(AF_INET, plugin->external_address, &t4.ipv4_addr) == 1))
2377 t4.t_port = htons(plugin->adv_port);
2378 plugin->env->notify_address (plugin->env->cls,
2380 &t4, sizeof(t4), GNUNET_TIME_UNIT_FOREVER_REL);
2388 * Exit point from the plugin.
2391 libgnunet_plugin_transport_tcp_done (void *cls)
2393 struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
2394 struct Plugin *plugin = api->cls;
2395 struct Session *session;
2397 while (NULL != (session = plugin->sessions))
2398 disconnect_session (session);
2399 if (NULL != plugin->hostname_dns)
2401 GNUNET_RESOLVER_request_cancel (plugin->hostname_dns);
2402 plugin->hostname_dns = NULL;
2404 GNUNET_SERVICE_stop (plugin->service);
2405 GNUNET_free (plugin->handlers);
2406 GNUNET_free (plugin);
2411 /* end of plugin_transport_tcp.c */