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 memcpy (cbuf, pos->msg, pos->message_size);
651 cbuf += pos->message_size;
652 ret += pos->message_size;
653 size -= pos->message_size;
654 GNUNET_CONTAINER_DLL_insert_after (hd, tl, tl, pos);
656 /* schedule 'continuation' before callbacks so that callbacks that
657 cancel everything don't cause us to use a session that no longer
659 process_pending_messages (session);
660 session->last_activity = GNUNET_TIME_absolute_get ();
661 pid = session->target;
662 /* we'll now call callbacks that may cancel the session; hence
663 we should not use 'session' after this point */
664 while (NULL != (pos = hd))
666 GNUNET_CONTAINER_DLL_remove (hd, tl, pos);
667 if (pos->transmit_cont != NULL)
668 pos->transmit_cont (pos->transmit_cont_cls,
672 GNUNET_assert (hd == NULL);
673 GNUNET_assert (tl == NULL);
675 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
676 "tcp", "Transmitting %u bytes\n", ret);
678 GNUNET_STATISTICS_update (plugin->env->stats,
679 gettext_noop ("# bytes currently in TCP buffers"),
682 GNUNET_STATISTICS_update (plugin->env->stats,
683 gettext_noop ("# bytes transmitted via TCP"),
691 * If we have pending messages, ask the server to
692 * transmit them (schedule the respective tasks, etc.)
694 * @param session for which session should we do this
697 process_pending_messages (struct Session *session)
699 struct PendingMessage *pm;
701 GNUNET_assert (session->client != NULL);
702 if (session->transmit_handle != NULL)
704 if (NULL == (pm = session->pending_messages_head))
706 session->transmit_handle
707 = GNUNET_SERVER_notify_transmit_ready (session->client,
709 GNUNET_TIME_absolute_get_remaining
711 &do_transmit, session);
716 * Functions with this signature are called whenever we need
717 * to close a session due to a disconnect or failure to
718 * establish a connection.
720 * @param session session to close down
723 disconnect_session (struct Session *session)
725 struct Session *prev;
727 struct PendingMessage *pm;
730 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
732 "Disconnecting from `%4s' at %s (session %p).\n",
733 GNUNET_i2s (&session->target),
734 (session->connect_addr != NULL) ?
735 tcp_address_to_string (session->plugin,
736 session->connect_addr,
737 session->connect_alen) : "*",
740 /* remove from session list */
742 pos = session->plugin->sessions;
743 while (pos != session)
749 session->plugin->sessions = session->next;
751 prev->next = session->next;
752 session->plugin->env->session_end (session->plugin->env->cls,
756 if (session->transmit_handle != NULL)
758 GNUNET_CONNECTION_notify_transmit_ready_cancel
759 (session->transmit_handle);
760 session->transmit_handle = NULL;
762 while (NULL != (pm = session->pending_messages_head))
765 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
767 pm->transmit_cont != NULL
768 ? "Could not deliver message to `%4s'.\n"
770 "Could not deliver message to `%4s', notifying.\n",
771 GNUNET_i2s (&session->target));
773 GNUNET_STATISTICS_update (session->plugin->env->stats,
774 gettext_noop ("# bytes currently in TCP buffers"),
775 - (int64_t) pm->message_size,
777 GNUNET_STATISTICS_update (session->plugin->env->stats,
778 gettext_noop ("# bytes discarded by TCP (disconnect)"),
781 GNUNET_CONTAINER_DLL_remove (session->pending_messages_head,
782 session->pending_messages_tail,
784 if (NULL != pm->transmit_cont)
785 pm->transmit_cont (pm->transmit_cont_cls,
786 &session->target, GNUNET_SYSERR);
789 GNUNET_break (session->client != NULL);
790 if (session->receive_delay_task != GNUNET_SCHEDULER_NO_TASK)
792 GNUNET_SCHEDULER_cancel (session->plugin->env->sched,
793 session->receive_delay_task);
794 if (session->client != NULL)
795 GNUNET_SERVER_receive_done (session->client,
798 if (session->client != NULL)
799 GNUNET_SERVER_client_drop (session->client);
800 GNUNET_STATISTICS_update (session->plugin->env->stats,
801 gettext_noop ("# TCP sessions active"),
804 GNUNET_free_non_null (session->connect_addr);
805 GNUNET_free (session);
810 * Given two otherwise equivalent sessions, pick the better one.
812 * @param s1 one session (also default)
813 * @param s2 other session
814 * @return "better" session (more active)
816 static struct Session *
817 select_better_session (struct Session *s1,
824 if ( (s1->expecting_welcome == GNUNET_NO) &&
825 (s2->expecting_welcome == GNUNET_YES) )
827 if ( (s1->expecting_welcome == GNUNET_YES) &&
828 (s2->expecting_welcome == GNUNET_NO) )
830 if (s1->last_activity.value < s2->last_activity.value)
832 if (s1->last_activity.value > s2->last_activity.value)
834 if ( (GNUNET_YES == s1->inbound) &&
835 (GNUNET_NO == s2->inbound) )
837 if ( (GNUNET_NO == s1->inbound) &&
838 (GNUNET_YES == s2->inbound) )
845 * We learned about a peer (possibly behind NAT) so run the
846 * gnunet-nat-client to send dummy ICMP responses
848 * @param plugin the plugin for this transport
849 * @param addr the address of the peer
850 * @param addrlen the length of the address
853 run_gnunet_nat_client (struct Plugin *plugin, const char *addr, size_t addrlen)
855 char inet4[INET_ADDRSTRLEN];
856 char *address_as_string;
857 char *port_as_string;
859 const struct sockaddr *sa = (const struct sockaddr *)addr;
861 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
862 _("called run_gnunet_nat_client addrlen %d others are %d and %d\n"), addrlen, sizeof (struct sockaddr), sizeof (struct sockaddr_in));
865 if (addrlen < sizeof (struct sockaddr))
868 switch (sa->sa_family)
871 if (addrlen != sizeof (struct sockaddr_in))
873 if (NULL == inet_ntop (AF_INET,
874 &((struct sockaddr_in *) sa)->sin_addr,
875 inet4, INET_ADDRSTRLEN))
877 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "inet_ntop");
880 address_as_string = GNUNET_strdup (inet4);
887 GNUNET_asprintf(&port_as_string, "%d", plugin->adv_port);
889 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
890 _("Running gnunet-nat-client with arguments: %s %s %d\n"), plugin->external_address, address_as_string, plugin->adv_port);
893 /* Start the client process */
894 pid = GNUNET_OS_start_process(NULL, NULL, "gnunet-nat-client", "gnunet-nat-client", plugin->external_address, address_as_string, port_as_string, NULL);
895 GNUNET_free(address_as_string);
896 GNUNET_free(port_as_string);
897 GNUNET_OS_process_wait (pid);
902 * Function that can be used by the transport service to transmit
903 * a message using the plugin. Note that in the case of a
904 * peer disconnecting, the continuation MUST be called
905 * prior to the disconnect notification itself. This function
906 * will be called with this peer's HELLO message to initiate
907 * a fresh connection to another peer.
910 * @param target who should receive this message
911 * @param msg the message to transmit
912 * @param msgbuf_size number of bytes in 'msg'
913 * @param priority how important is the message (most plugins will
914 * ignore message priority and just FIFO)
915 * @param timeout how long to wait at most for the transmission (does not
916 * require plugins to discard the message after the timeout,
917 * just advisory for the desired delay; most plugins will ignore
919 * @param session which session must be used (or NULL for "any")
920 * @param addr the address to use (can be NULL if the plugin
921 * is "on its own" (i.e. re-use existing TCP connection))
922 * @param addrlen length of the address in bytes
923 * @param force_address GNUNET_YES if the plugin MUST use the given address,
924 * GNUNET_NO means the plugin may use any other address and
925 * GNUNET_SYSERR means that only reliable existing
926 * bi-directional connections should be used (regardless
928 * @param cont continuation to call once the message has
929 * been transmitted (or if the transport is ready
930 * for the next transmission call; or if the
931 * peer disconnected...); can be NULL
932 * @param cont_cls closure for cont
933 * @return number of bytes used (on the physical network, with overheads);
934 * -1 on hard errors (i.e. address invalid); 0 is a legal value
935 * and does NOT mean that the message was not transmitted (DV and NAT)
938 tcp_plugin_send (void *cls,
939 const struct GNUNET_PeerIdentity *target,
943 struct GNUNET_TIME_Relative timeout,
944 struct Session *session,
948 GNUNET_TRANSPORT_TransmitContinuation cont, void *cont_cls)
950 struct Plugin *plugin = cls;
951 struct Session *cand_session;
952 struct Session *next;
953 struct PendingMessage *pm;
954 struct GNUNET_CONNECTION_Handle *sa;
958 struct sockaddr_in a4;
959 struct sockaddr_in6 a6;
960 const struct IPv4TcpAddress *t4;
961 const struct IPv6TcpAddress *t6;
962 unsigned int is_natd;
964 GNUNET_STATISTICS_update (plugin->env->stats,
965 gettext_noop ("# bytes TCP was asked to transmit"),
968 /* FIXME: we could do this cheaper with a hash table
969 where we could restrict the iteration to entries that match
970 the target peer... */
975 next = plugin->sessions;
976 while (NULL != (session = next))
978 next = session->next;
979 GNUNET_assert (session->client != NULL);
980 if (0 != memcmp (target,
982 sizeof (struct GNUNET_PeerIdentity)))
984 if ( ( (GNUNET_SYSERR == force_address) &&
985 (session->expecting_welcome == GNUNET_NO) ) ||
986 (GNUNET_NO == force_address) )
988 cand_session = select_better_session (cand_session,
992 if (GNUNET_SYSERR == force_address)
994 GNUNET_break (GNUNET_YES == force_address);
1000 if (session->inbound == GNUNET_YES)
1002 if (addrlen != session->connect_alen)
1004 if (0 != memcmp (session->connect_addr,
1008 cand_session = select_better_session (cand_session,
1011 session = cand_session;
1013 if ( (session == NULL) &&
1017 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1019 "Asked to transmit to `%4s' without address and I have no existing connection (failing).\n",
1020 GNUNET_i2s (target));
1022 GNUNET_STATISTICS_update (plugin->env->stats,
1023 gettext_noop ("# bytes discarded by TCP (no address and no connection)"),
1028 if (session == NULL)
1030 if (addrlen == sizeof (struct IPv6TcpAddress))
1034 memset (&a6, 0, sizeof (a6));
1035 #if HAVE_SOCKADDR_IN_SIN_LEN
1036 a6.sin6_len = sizeof (a6);
1038 a6.sin6_family = AF_INET6;
1039 a6.sin6_port = t6->t6_port;
1040 if (t6->t6_port == 0)
1041 is_natd = GNUNET_YES;
1042 memcpy (&a6.sin6_addr,
1044 sizeof (struct in6_addr));
1048 else if (addrlen == sizeof (struct IPv4TcpAddress))
1052 memset (&a4, 0, sizeof (a4));
1053 #if HAVE_SOCKADDR_IN_SIN_LEN
1054 a4.sin_len = sizeof (a4);
1056 a4.sin_family = AF_INET;
1057 a4.sin_port = t4->t_port;
1058 if (t4->t_port == 0)
1059 is_natd = GNUNET_YES;
1060 a4.sin_addr.s_addr = t4->ipv4_addr;
1066 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
1068 _("Address of unexpected length: %u\n"),
1074 if ((is_natd == GNUNET_YES) && (addrlen == sizeof (struct IPv6TcpAddress)))
1075 return -1; /* NAT client only works with IPv4 addresses */
1078 if ( (plugin->allow_nat == GNUNET_YES) && (is_natd == GNUNET_YES) &&
1079 (GNUNET_NO == GNUNET_CONTAINER_multihashmap_contains(plugin->nat_wait_conns, &target->hashPubKey)))
1082 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1084 _("Found valid IPv4 NAT address!\n"));
1086 session = create_session (plugin,
1090 /* create new message entry */
1091 pm = GNUNET_malloc (sizeof (struct PendingMessage) + msgbuf_size);
1092 pm->msg = (const char*) &pm[1];
1093 memcpy (&pm[1], msg, msgbuf_size);
1094 pm->message_size = msgbuf_size;
1095 pm->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1096 pm->transmit_cont = cont;
1097 pm->transmit_cont_cls = cont_cls;
1099 /* append pm to pending_messages list */
1100 GNUNET_CONTAINER_DLL_insert_after (session->pending_messages_head,
1101 session->pending_messages_tail,
1102 session->pending_messages_tail,
1105 GNUNET_assert(GNUNET_CONTAINER_multihashmap_put(plugin->nat_wait_conns, &target->hashPubKey, session, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY) == GNUNET_OK);
1107 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1109 "Created NAT WAIT connection to `%4s' at `%s'\n",
1110 GNUNET_i2s (target),
1111 GNUNET_a2s (sb, sbs));
1113 run_gnunet_nat_client(plugin, sb, sbs);
1116 else if ((plugin->allow_nat == GNUNET_YES) && (is_natd == GNUNET_YES) && (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains(plugin->nat_wait_conns, &target->hashPubKey)))
1118 /* Only do one NAT punch attempt per peer identity */
1121 sa = GNUNET_CONNECTION_create_from_sockaddr (plugin->env->sched,
1123 GNUNET_SERVER_MAX_MESSAGE_SIZE);
1127 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1129 "Failed to create connection to `%4s' at `%s'\n",
1130 GNUNET_i2s (target),
1131 GNUNET_a2s (sb, sbs));
1133 GNUNET_STATISTICS_update (plugin->env->stats,
1134 gettext_noop ("# bytes discarded by TCP (failed to connect)"),
1140 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1142 "Asked to transmit to `%4s', creating fresh session using address `%s'.\n",
1143 GNUNET_i2s (target),
1144 GNUNET_a2s (sb, sbs));
1146 session = create_session (plugin,
1148 GNUNET_SERVER_connect_socket (plugin->server,
1150 session->connect_addr = GNUNET_malloc (addrlen);
1151 memcpy (session->connect_addr,
1154 session->connect_alen = addrlen;
1156 GNUNET_assert (session != NULL);
1157 GNUNET_assert (session->client != NULL);
1158 GNUNET_STATISTICS_update (plugin->env->stats,
1159 gettext_noop ("# bytes currently in TCP buffers"),
1162 /* create new message entry */
1163 pm = GNUNET_malloc (sizeof (struct PendingMessage) + msgbuf_size);
1164 pm->msg = (const char*) &pm[1];
1165 memcpy (&pm[1], msg, msgbuf_size);
1166 pm->message_size = msgbuf_size;
1167 pm->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1168 pm->transmit_cont = cont;
1169 pm->transmit_cont_cls = cont_cls;
1171 /* append pm to pending_messages list */
1172 GNUNET_CONTAINER_DLL_insert_after (session->pending_messages_head,
1173 session->pending_messages_tail,
1174 session->pending_messages_tail,
1177 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1179 "Asked to transmit %u bytes to `%s', added message to list.\n",
1181 GNUNET_i2s (target));
1183 process_pending_messages (session);
1189 * Function that can be called to force a disconnect from the
1190 * specified neighbour. This should also cancel all previously
1191 * scheduled transmissions. Obviously the transmission may have been
1192 * partially completed already, which is OK. The plugin is supposed
1193 * to close the connection (if applicable) and no longer call the
1194 * transmit continuation(s).
1196 * Finally, plugin MUST NOT call the services's receive function to
1197 * notify the service that the connection to the specified target was
1198 * closed after a getting this call.
1200 * @param cls closure
1201 * @param target peer for which the last transmission is
1205 tcp_plugin_disconnect (void *cls,
1206 const struct GNUNET_PeerIdentity *target)
1208 struct Plugin *plugin = cls;
1209 struct Session *session;
1210 struct Session *next;
1211 struct PendingMessage *pm;
1214 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1216 "Asked to cancel session with `%4s'\n",
1217 GNUNET_i2s (target));
1219 next = plugin->sessions;
1220 while (NULL != (session = next))
1222 next = session->next;
1223 if (0 != memcmp (target,
1225 sizeof (struct GNUNET_PeerIdentity)))
1227 pm = session->pending_messages_head;
1230 pm->transmit_cont = NULL;
1231 pm->transmit_cont_cls = NULL;
1234 disconnect_session (session);
1240 * Context for address to string conversion.
1242 struct PrettyPrinterContext
1245 * Function to call with the result.
1247 GNUNET_TRANSPORT_AddressStringCallback asc;
1250 * Clsoure for 'asc'.
1255 * Port to add after the IP address.
1262 * Append our port and forward the result.
1264 * @param cls the 'struct PrettyPrinterContext*'
1265 * @param hostname hostname part of the address
1268 append_port (void *cls, const char *hostname)
1270 struct PrettyPrinterContext *ppc = cls;
1273 if (hostname == NULL)
1275 ppc->asc (ppc->asc_cls, NULL);
1279 GNUNET_asprintf (&ret, "%s:%d", hostname, ppc->port);
1280 ppc->asc (ppc->asc_cls, ret);
1286 * Convert the transports address to a nice, human-readable
1289 * @param cls closure
1290 * @param type name of the transport that generated the address
1291 * @param addr one of the addresses of the host, NULL for the last address
1292 * the specific address format depends on the transport
1293 * @param addrlen length of the address
1294 * @param numeric should (IP) addresses be displayed in numeric form?
1295 * @param timeout after how long should we give up?
1296 * @param asc function to call on each string
1297 * @param asc_cls closure for asc
1300 tcp_plugin_address_pretty_printer (void *cls,
1305 struct GNUNET_TIME_Relative timeout,
1306 GNUNET_TRANSPORT_AddressStringCallback asc,
1309 struct Plugin *plugin = cls;
1310 struct PrettyPrinterContext *ppc;
1313 struct sockaddr_in a4;
1314 struct sockaddr_in6 a6;
1315 const struct IPv4TcpAddress *t4;
1316 const struct IPv6TcpAddress *t6;
1319 if (addrlen == sizeof (struct IPv6TcpAddress))
1322 memset (&a6, 0, sizeof (a6));
1323 a6.sin6_family = AF_INET6;
1324 a6.sin6_port = t6->t6_port;
1325 memcpy (&a6.sin6_addr,
1327 sizeof (struct in6_addr));
1328 port = ntohs (t6->t6_port);
1332 else if (addrlen == sizeof (struct IPv4TcpAddress))
1335 memset (&a4, 0, sizeof (a4));
1336 a4.sin_family = AF_INET;
1337 a4.sin_port = t4->t_port;
1338 a4.sin_addr.s_addr = t4->ipv4_addr;
1339 port = ntohs (t4->t_port);
1345 /* invalid address */
1346 GNUNET_break_op (0);
1347 asc (asc_cls, NULL);
1350 ppc = GNUNET_malloc (sizeof (struct PrettyPrinterContext));
1352 ppc->asc_cls = asc_cls;
1354 GNUNET_RESOLVER_hostname_get (plugin->env->sched,
1358 !numeric, timeout, &append_port, ppc);
1363 * Check if the given port is plausible (must be either
1364 * our listen port or our advertised port). If it is
1365 * neither, we return one of these two ports at random.
1367 * @param plugin global variables
1368 * @param in_port port number to check
1369 * @return either in_port or a more plausible port
1372 check_port (struct Plugin *plugin, uint16_t in_port)
1374 if ((in_port == plugin->adv_port) || (in_port == plugin->open_port))
1376 return (GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
1378 ? plugin->open_port : plugin->adv_port;
1383 * Another peer has suggested an address for this peer and transport
1384 * plugin. Check that this could be a valid address. This function
1385 * is not expected to 'validate' the address in the sense of trying to
1386 * connect to it but simply to see if the binary format is technically
1387 * legal for establishing a connection.
1389 * @param cls closure, our 'struct Plugin*'
1390 * @param addr pointer to the address
1391 * @param addrlen length of addr
1392 * @return GNUNET_OK if this is a plausible address for this peer
1393 * and transport, GNUNET_SYSERR if not
1396 tcp_plugin_check_address (void *cls, void *addr, size_t addrlen)
1398 struct Plugin *plugin = cls;
1399 struct IPv4TcpAddress *v4;
1400 struct IPv6TcpAddress *v6;
1402 if ((addrlen != sizeof (struct IPv4TcpAddress)) &&
1403 (addrlen != sizeof (struct IPv6TcpAddress)))
1405 GNUNET_break_op (0);
1406 return GNUNET_SYSERR;
1408 if (addrlen == sizeof (struct IPv4TcpAddress))
1410 v4 = (struct IPv4TcpAddress *) addr;
1411 v4->t_port = htons (check_port (plugin, ntohs (v4->t_port)));
1415 v6 = (struct IPv6TcpAddress *) addr;
1416 if (IN6_IS_ADDR_LINKLOCAL (&v6->ipv6_addr))
1418 GNUNET_break_op (0);
1419 return GNUNET_SYSERR;
1421 v6->t6_port = htons (check_port (plugin, ntohs (v6->t6_port)));
1427 * We've received a nat probe from this peer via TCP. Finish
1428 * creating the client session and resume sending of queued
1431 * @param cls closure
1432 * @param client identification of the client
1433 * @param message the actual message
1436 handle_tcp_nat_probe (void *cls,
1437 struct GNUNET_SERVER_Client *client,
1438 const struct GNUNET_MessageHeader *message)
1440 struct Plugin *plugin = cls;
1441 struct Session *session;
1442 struct TCP_NAT_ProbeMessage *tcp_nat_probe;
1445 struct IPv4TcpAddress *t4;
1446 struct IPv6TcpAddress *t6;
1447 const struct sockaddr_in *s4;
1448 const struct sockaddr_in6 *s6;
1451 GNUNET_log_from(GNUNET_ERROR_TYPE_DEBUG, "tcp", "received tcp NAT probe\n");
1453 /* We have received a TCP NAT probe, meaning we (hopefully) initiated
1454 * a connection to this peer by running gnunet-nat-client. This peer
1455 * received the punch message and now wants us to use the new connection
1456 * as the default for that peer. Do so and then send a WELCOME message
1457 * so we can really be connected!
1459 if (ntohs(message->size) != sizeof(struct TCP_NAT_ProbeMessage))
1462 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));
1467 tcp_nat_probe = (struct TCP_NAT_ProbeMessage *)message;
1469 if (GNUNET_CONTAINER_multihashmap_contains(plugin->nat_wait_conns, &tcp_nat_probe->clientIdentity.hashPubKey) == GNUNET_YES)
1472 GNUNET_log_from(GNUNET_ERROR_TYPE_DEBUG, "tcp", "Found session for NAT probe!\n");
1474 session = GNUNET_CONTAINER_multihashmap_get(plugin->nat_wait_conns, &tcp_nat_probe->clientIdentity.hashPubKey);
1475 GNUNET_assert(session != NULL);
1476 GNUNET_assert(GNUNET_CONTAINER_multihashmap_remove(plugin->nat_wait_conns, &tcp_nat_probe->clientIdentity.hashPubKey, session) == GNUNET_YES);
1477 GNUNET_SERVER_client_keep (client);
1478 session->client = client;
1479 session->last_activity = GNUNET_TIME_absolute_get ();
1482 GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
1485 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1487 "Found address `%s' for incoming connection %p\n",
1488 GNUNET_a2s (vaddr, alen),
1491 if (alen == sizeof (struct sockaddr_in))
1494 t4 = GNUNET_malloc (sizeof (struct IPv4TcpAddress));
1495 t4->t_port = s4->sin_port;
1496 t4->ipv4_addr = s4->sin_addr.s_addr;
1497 session->connect_addr = t4;
1498 session->connect_alen = sizeof (struct IPv4TcpAddress);
1500 else if (alen == sizeof (struct sockaddr_in6))
1503 t6 = GNUNET_malloc (sizeof (struct IPv6TcpAddress));
1504 t6->t6_port = s6->sin6_port;
1505 memcpy (&t6->ipv6_addr,
1507 sizeof (struct in6_addr));
1508 session->connect_addr = t6;
1509 session->connect_alen = sizeof (struct IPv6TcpAddress);
1512 session->connect_addr = GNUNET_malloc (alen);
1513 memcpy (session->connect_addr,
1516 session->connect_alen = alen;
1517 GNUNET_free (vaddr);
1520 session->next = plugin->sessions;
1521 plugin->sessions = session;
1522 GNUNET_STATISTICS_update (plugin->env->stats,
1523 gettext_noop ("# TCP sessions active"),
1526 process_pending_messages (session);
1531 GNUNET_log_from(GNUNET_ERROR_TYPE_DEBUG, "tcp", "Did NOT find session for NAT probe!\n");
1537 * We've received a welcome from this peer via TCP. Possibly create a
1538 * fresh client record and send back our welcome.
1540 * @param cls closure
1541 * @param client identification of the client
1542 * @param message the actual message
1545 handle_tcp_welcome (void *cls,
1546 struct GNUNET_SERVER_Client *client,
1547 const struct GNUNET_MessageHeader *message)
1549 struct Plugin *plugin = cls;
1550 const struct WelcomeMessage *wm = (const struct WelcomeMessage *) message;
1551 struct Session *session;
1554 struct IPv4TcpAddress *t4;
1555 struct IPv6TcpAddress *t6;
1556 const struct sockaddr_in *s4;
1557 const struct sockaddr_in6 *s6;
1561 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1563 "Received %s message from a `%4s/%p'.\n",
1565 GNUNET_i2s (&wm->clientIdentity), client);
1567 GNUNET_STATISTICS_update (plugin->env->stats,
1568 gettext_noop ("# TCP WELCOME messages received"),
1571 session = find_session_by_client (plugin, client);
1572 if (session == NULL)
1574 GNUNET_SERVER_client_keep (client);
1575 session = create_session (plugin,
1576 &wm->clientIdentity, client, GNUNET_NO);
1577 session->inbound = GNUNET_YES;
1579 GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
1582 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1584 "Found address `%s' for incoming connection %p\n",
1585 GNUNET_a2s (vaddr, alen),
1588 if (alen == sizeof (struct sockaddr_in))
1591 t4 = GNUNET_malloc (sizeof (struct IPv4TcpAddress));
1592 t4->t_port = s4->sin_port;
1593 t4->ipv4_addr = s4->sin_addr.s_addr;
1594 session->connect_addr = t4;
1595 session->connect_alen = sizeof (struct IPv4TcpAddress);
1597 else if (alen == sizeof (struct sockaddr_in6))
1600 t6 = GNUNET_malloc (sizeof (struct IPv6TcpAddress));
1601 t6->t6_port = s6->sin6_port;
1602 memcpy (&t6->ipv6_addr,
1604 sizeof (struct in6_addr));
1605 session->connect_addr = t6;
1606 session->connect_alen = sizeof (struct IPv6TcpAddress);
1608 GNUNET_free (vaddr);
1613 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1615 "Did not obtain TCP socket address for incoming connection\n");
1619 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1621 "Creating new session %p for connection %p\n",
1624 process_pending_messages (session);
1626 if (session->expecting_welcome != GNUNET_YES)
1628 GNUNET_break_op (0);
1629 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1632 session->last_activity = GNUNET_TIME_absolute_get ();
1633 session->expecting_welcome = GNUNET_NO;
1634 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1639 * Task to signal the server that we can continue
1640 * receiving from the TCP client now.
1642 * @param cls the 'struct Session*'
1643 * @param tc task context (unused)
1646 delayed_done (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1648 struct Session *session = cls;
1649 struct GNUNET_TIME_Relative delay;
1651 session->receive_delay_task = GNUNET_SCHEDULER_NO_TASK;
1652 delay = session->plugin->env->receive (session->plugin->env->cls,
1657 if (delay.value == 0)
1658 GNUNET_SERVER_receive_done (session->client, GNUNET_OK);
1660 session->receive_delay_task =
1661 GNUNET_SCHEDULER_add_delayed (session->plugin->env->sched,
1662 delay, &delayed_done, session);
1667 * We've received data for this peer via TCP. Unbox,
1668 * compute latency and forward.
1670 * @param cls closure
1671 * @param client identification of the client
1672 * @param message the actual message
1675 handle_tcp_data (void *cls,
1676 struct GNUNET_SERVER_Client *client,
1677 const struct GNUNET_MessageHeader *message)
1679 struct Plugin *plugin = cls;
1680 struct Session *session;
1681 struct GNUNET_TIME_Relative delay;
1683 if ((GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME == ntohs(message->type)) || (ntohs(message->type) == GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE))
1685 /* We don't want to propagate WELCOME and NAT Probe messages up! */
1686 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1689 session = find_session_by_client (plugin, client);
1690 if ( (NULL == session) || (GNUNET_YES == session->expecting_welcome))
1692 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1695 session->last_activity = GNUNET_TIME_absolute_get ();
1697 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1699 "Passing %u bytes of type %u from `%4s' to transport service.\n",
1700 (unsigned int) ntohs (message->size),
1701 (unsigned int) ntohs (message->type),
1702 GNUNET_i2s (&session->target));
1704 GNUNET_STATISTICS_update (plugin->env->stats,
1705 gettext_noop ("# bytes received via TCP"),
1706 ntohs (message->size),
1708 delay = plugin->env->receive (plugin->env->cls, &session->target, message, 1,
1710 (GNUNET_YES == session->inbound) ? NULL : session->connect_addr,
1711 (GNUNET_YES == session->inbound) ? 0 : session->connect_alen);
1712 if (delay.value == 0)
1713 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1715 session->receive_delay_task =
1716 GNUNET_SCHEDULER_add_delayed (session->plugin->env->sched,
1717 delay, &delayed_done, session);
1722 * Functions with this signature are called whenever a peer
1723 * is disconnected on the network level.
1725 * @param cls closure
1726 * @param client identification of the client
1729 disconnect_notify (void *cls,
1730 struct GNUNET_SERVER_Client *client)
1732 struct Plugin *plugin = cls;
1733 struct Session *session;
1737 session = find_session_by_client (plugin, client);
1738 if (session == NULL)
1739 return; /* unknown, nothing to do */
1741 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1743 "Destroying session of `%4s' with %s (%p) due to network-level disconnect.\n",
1744 GNUNET_i2s (&session->target),
1745 (session->connect_addr != NULL) ?
1746 tcp_address_to_string (session->plugin,
1747 session->connect_addr,
1748 session->connect_alen) : "*",
1751 disconnect_session (session);
1756 * Add the IP of our network interface to the list of
1757 * our external IP addresses.
1759 * @param cls the 'struct Plugin*'
1760 * @param name name of the interface
1761 * @param isDefault do we think this may be our default interface
1762 * @param addr address of the interface
1763 * @param addrlen number of bytes in addr
1764 * @return GNUNET_OK to continue iterating
1767 process_interfaces (void *cls,
1770 const struct sockaddr *addr, socklen_t addrlen)
1772 struct Plugin *plugin = cls;
1774 struct IPv4TcpAddress t4;
1775 struct IPv6TcpAddress t6;
1776 struct IPv4TcpAddress t4_nat;
1777 struct IPv6TcpAddress t6_nat;
1782 af = addr->sa_family;
1786 t4.ipv4_addr = ((struct sockaddr_in *) addr)->sin_addr.s_addr;
1787 if ((plugin->behind_nat == GNUNET_YES) && (plugin->only_nat_addresses == GNUNET_YES))
1788 t4.t_port = htons(0);
1789 else if (plugin->behind_nat == GNUNET_YES) /* We are behind NAT, but will advertise NAT and normal addresses */
1791 t4_nat.ipv4_addr = ((struct sockaddr_in *) addr)->sin_addr.s_addr;
1792 t4_nat.t_port = htons(plugin->adv_port);
1796 t4.t_port = htons (plugin->adv_port);
1800 else if (af == AF_INET6)
1802 if (IN6_IS_ADDR_LINKLOCAL (&((struct sockaddr_in6 *) addr)->sin6_addr))
1804 /* skip link local addresses */
1807 memcpy (&t6.ipv6_addr,
1808 &((struct sockaddr_in6 *) addr)->sin6_addr,
1809 sizeof (struct in6_addr));
1810 if ((plugin->behind_nat == GNUNET_YES) && (plugin->only_nat_addresses == GNUNET_YES))
1811 t6.t6_port = htons(0);
1812 else if (plugin->behind_nat == GNUNET_YES) /* We are behind NAT, but will advertise NAT and normal addresses */
1814 memcpy (&t6_nat.ipv6_addr,
1815 &((struct sockaddr_in6 *) addr)->sin6_addr,
1816 sizeof (struct in6_addr));
1817 t6_nat.t6_port = htons(plugin->adv_port);
1821 t6.t6_port = htons (plugin->adv_port);
1830 GNUNET_log_from (GNUNET_ERROR_TYPE_INFO |
1831 GNUNET_ERROR_TYPE_BULK,
1833 _("Found address `%s' (%s)\n"),
1834 GNUNET_a2s (addr, addrlen), name);
1836 plugin->env->notify_address (plugin->env->cls,
1838 arg, args, GNUNET_TIME_UNIT_FOREVER_REL);
1840 if (arg_nat != NULL)
1842 GNUNET_log_from (GNUNET_ERROR_TYPE_INFO |
1843 GNUNET_ERROR_TYPE_BULK,
1845 _("Found address `%s' (%s)\n"),
1846 GNUNET_a2s (addr, addrlen), name);
1847 plugin->env->notify_address (plugin->env->cls,
1849 arg_nat, args, GNUNET_TIME_UNIT_FOREVER_REL);
1857 * Function called by the resolver for each address obtained from DNS
1858 * for our own hostname. Add the addresses to the list of our
1859 * external IP addresses.
1861 * @param cls closure
1862 * @param addr one of the addresses of the host, NULL for the last address
1863 * @param addrlen length of the address
1866 process_hostname_ips (void *cls,
1867 const struct sockaddr *addr, socklen_t addrlen)
1869 struct Plugin *plugin = cls;
1873 plugin->hostname_dns = NULL;
1876 /* FIXME: Can we figure out our external address here so it doesn't need to be user specified? */
1877 process_interfaces (plugin, "<hostname>", GNUNET_YES, addr, addrlen);
1881 * We can now send a probe message, copy into buffer to really send.
1883 * @param cls closure, a struct TCPProbeContext
1884 * @param size max size to copy
1885 * @param buf buffer to copy message to
1887 static size_t notify_send_probe (void *cls,
1888 size_t size, void *buf)
1890 struct TCPProbeContext *tcp_probe_ctx = cls;
1897 GNUNET_assert(size >= sizeof(tcp_probe_ctx->message));
1898 memcpy(buf, &tcp_probe_ctx->message, sizeof(tcp_probe_ctx->message));
1899 GNUNET_SERVER_connect_socket (tcp_probe_ctx->plugin->server,
1900 tcp_probe_ctx->sock);
1902 GNUNET_free(tcp_probe_ctx);
1903 return sizeof(tcp_probe_ctx->message);
1907 * @param cls the plugin handle
1908 * @param tc the scheduling context (for rescheduling this function again)
1910 * We have been notified that gnunet-nat-server has written something to stdout.
1911 * Handle the output, then reschedule this function to be called again once
1912 * more is available.
1916 tcp_plugin_server_read (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1918 struct Plugin *plugin = cls;
1921 memset(&mybuf, 0, sizeof(mybuf));
1925 struct sockaddr_in in_addr;
1926 struct TCPProbeContext *tcp_probe_ctx;
1927 struct GNUNET_CONNECTION_Handle *sock;
1929 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
1932 bytes = GNUNET_DISK_file_read(plugin->server_stdout_handle, &mybuf, sizeof(mybuf));
1937 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1938 _("Finished reading from server stdout with code: %d\n"), bytes);
1945 for (i = 0; i < sizeof(mybuf); i++)
1947 if (mybuf[i] == '\n')
1950 if ((mybuf[i] == ':') && (i + 1 < sizeof(mybuf)))
1953 port_start = &mybuf[i + 1];
1957 if (port_start != NULL)
1958 port = atoi(port_start);
1961 plugin->server_read_task =
1962 GNUNET_SCHEDULER_add_read_file (plugin->env->sched,
1963 GNUNET_TIME_UNIT_FOREVER_REL,
1964 plugin->server_stdout_handle, &tcp_plugin_server_read, plugin);
1969 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1970 _("nat-server-read read: %s port %d\n"), &mybuf, port);
1974 if (inet_pton(AF_INET, &mybuf[0], &in_addr.sin_addr) != 1)
1977 GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, "tcp",
1978 _("nat-server-read malformed address\n"), &mybuf, port);
1980 plugin->server_read_task =
1981 GNUNET_SCHEDULER_add_read_file (plugin->env->sched,
1982 GNUNET_TIME_UNIT_FOREVER_REL,
1983 plugin->server_stdout_handle, &tcp_plugin_server_read, plugin);
1987 in_addr.sin_family = AF_INET;
1988 in_addr.sin_port = htons(port);
1990 * We have received an ICMP response, ostensibly from a non-NAT'd peer
1991 * that wants to connect to us! Send a message to establish a connection.
1993 sock = GNUNET_CONNECTION_create_from_sockaddr (plugin->env->sched, AF_INET, (struct sockaddr *)&in_addr,
1994 sizeof(in_addr), GNUNET_SERVER_MAX_MESSAGE_SIZE);
1997 plugin->server_read_task =
1998 GNUNET_SCHEDULER_add_read_file (plugin->env->sched,
1999 GNUNET_TIME_UNIT_FOREVER_REL,
2000 plugin->server_stdout_handle, &tcp_plugin_server_read, plugin);
2005 tcp_probe_ctx = GNUNET_malloc(sizeof(struct TCPProbeContext));
2007 tcp_probe_ctx->message.header.size = htons(sizeof(struct TCP_NAT_ProbeMessage));
2008 tcp_probe_ctx->message.header.type = htons(GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE);
2009 memcpy(&tcp_probe_ctx->message.clientIdentity, plugin->env->my_identity, sizeof(struct GNUNET_PeerIdentity));
2010 tcp_probe_ctx->plugin = plugin;
2011 tcp_probe_ctx->sock = sock;
2012 tcp_probe_ctx->transmit_handle = GNUNET_CONNECTION_notify_transmit_ready (sock,
2013 ntohs(tcp_probe_ctx->message.header.size),
2014 GNUNET_TIME_UNIT_FOREVER_REL,
2015 ¬ify_send_probe, tcp_probe_ctx);
2019 plugin->server_read_task =
2020 GNUNET_SCHEDULER_add_read_file (plugin->env->sched,
2021 GNUNET_TIME_UNIT_FOREVER_REL,
2022 plugin->server_stdout_handle, &tcp_plugin_server_read, plugin);
2026 * Start the gnunet-nat-server process for users behind NAT.
2028 * @param plugin the transport plugin
2030 * @return GNUNET_YES if process was started, GNUNET_SYSERR on error
2033 tcp_transport_start_nat_server(struct Plugin *plugin)
2036 plugin->server_stdout = GNUNET_DISK_pipe(GNUNET_YES);
2037 if (plugin->server_stdout == NULL)
2038 return GNUNET_SYSERR;
2041 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
2043 "Starting gnunet-nat-server process cmd: %s %s\n", "gnunet-nat-server", plugin->internal_address);
2045 /* Start the server process */
2046 plugin->server_pid = GNUNET_OS_start_process(NULL, plugin->server_stdout, "gnunet-nat-server", "gnunet-nat-server", plugin->internal_address, NULL);
2047 if (plugin->server_pid == GNUNET_SYSERR)
2050 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
2052 "Failed to start gnunet-nat-server process\n");
2054 return GNUNET_SYSERR;
2056 /* Close the write end of the read pipe */
2057 GNUNET_DISK_pipe_close_end(plugin->server_stdout, GNUNET_DISK_PIPE_END_WRITE);
2059 plugin->server_stdout_handle = GNUNET_DISK_pipe_handle(plugin->server_stdout, GNUNET_DISK_PIPE_END_READ);
2060 plugin->server_read_task =
2061 GNUNET_SCHEDULER_add_read_file (plugin->env->sched,
2062 GNUNET_TIME_UNIT_FOREVER_REL,
2063 plugin->server_stdout_handle, &tcp_plugin_server_read, plugin);
2068 * Return the actual path to a file found in the current
2069 * PATH environment variable.
2071 * @param binary the name of the file to find
2074 get_path_from_PATH (char *binary)
2082 p = getenv ("PATH");
2085 path = GNUNET_strdup (p); /* because we write on it */
2086 buf = GNUNET_malloc (strlen (path) + 20);
2089 while (NULL != (end = strchr (pos, ':')))
2092 sprintf (buf, "%s/%s", pos, binary);
2093 if (GNUNET_DISK_file_test (buf) == GNUNET_YES)
2100 sprintf (buf, "%s/%s", pos, binary);
2101 if (GNUNET_DISK_file_test (buf) == GNUNET_YES)
2112 * Check whether the suid bit is set on a file.
2113 * Attempts to find the file using the current
2114 * PATH environment variable as a search path.
2116 * @param binary the name of the file to check
2119 check_gnunet_nat_binary(char *binary)
2121 struct stat statbuf;
2124 p = get_path_from_PATH (binary);
2127 if (0 != STAT (p, &statbuf))
2130 return GNUNET_SYSERR;
2133 if ( (0 != (statbuf.st_mode & S_ISUID)) &&
2134 (statbuf.st_uid == 0) )
2140 * Entry point for the plugin.
2142 * @param cls closure, the 'struct GNUNET_TRANSPORT_PluginEnvironment*'
2143 * @return the 'struct GNUNET_TRANSPORT_PluginFunctions*' or NULL on error
2146 libgnunet_plugin_transport_tcp_init (void *cls)
2148 static const struct GNUNET_SERVER_MessageHandler my_handlers[] = {
2149 {&handle_tcp_welcome, NULL, GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME,
2150 sizeof (struct WelcomeMessage)},
2151 {&handle_tcp_nat_probe, NULL, GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE, sizeof (struct TCP_NAT_ProbeMessage)},
2152 {&handle_tcp_data, NULL, GNUNET_MESSAGE_TYPE_ALL, 0},
2155 struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
2156 struct GNUNET_TRANSPORT_PluginFunctions *api;
2157 struct Plugin *plugin;
2158 struct GNUNET_SERVICE_Context *service;
2159 unsigned long long aport;
2160 unsigned long long bport;
2164 int only_nat_addresses;
2165 char *internal_address;
2166 char *external_address;
2167 struct sockaddr_in in_addr;
2168 struct IPv4TcpAddress t4;
2170 service = GNUNET_SERVICE_start ("transport-tcp", env->sched, env->cfg);
2171 if (service == NULL)
2173 GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING,
2176 ("Failed to start service for `%s' transport plugin.\n"),
2181 if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno (env->cfg,
2185 /* We are behind nat (according to the user) */
2186 if (check_gnunet_nat_binary("gnunet-nat-server") == GNUNET_YES)
2188 behind_nat = GNUNET_YES;
2192 behind_nat = GNUNET_NO;
2193 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");
2197 behind_nat = GNUNET_NO; /* We are not behind nat! */
2199 if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno (env->cfg,
2203 if (check_gnunet_nat_binary("gnunet-nat-client") == GNUNET_YES)
2204 allow_nat = GNUNET_YES; /* We will try to connect to NAT'd peers */
2207 allow_nat = GNUNET_NO;
2208 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");
2212 allow_nat = GNUNET_NO; /* We don't want to try to help NAT'd peers */
2215 if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno (env->cfg,
2217 "ONLY_NAT_ADDRESSES"))
2218 only_nat_addresses = GNUNET_YES; /* We will only report our addresses as NAT'd */
2220 only_nat_addresses = GNUNET_NO; /* We will report our addresses as NAT'd and non-NAT'd */
2222 external_address = NULL;
2223 if (((GNUNET_YES == behind_nat) || (GNUNET_YES == allow_nat)) && (GNUNET_OK !=
2224 GNUNET_CONFIGURATION_get_value_string (env->cfg,
2227 &external_address)))
2229 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
2232 ("Require EXTERNAL_ADDRESS for service `%s' in configuration (either BEHIND_NAT or ALLOW_NAT set to YES)!\n"),
2234 GNUNET_SERVICE_stop (service);
2238 if ((external_address != NULL) && (inet_pton(AF_INET, external_address, &in_addr.sin_addr) != 1))
2240 GNUNET_log_from(GNUNET_ERROR_TYPE_WARNING, "udp", "Malformed EXTERNAL_ADDRESS %s given in configuration!\n", external_address);
2243 internal_address = NULL;
2244 if ((GNUNET_YES == behind_nat) && (GNUNET_OK !=
2245 GNUNET_CONFIGURATION_get_value_string (env->cfg,
2248 &internal_address)))
2250 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
2253 ("Require INTERNAL_ADDRESS for service `%s' in configuration!\n"),
2255 GNUNET_SERVICE_stop (service);
2256 GNUNET_free_non_null(external_address);
2260 if ((internal_address != NULL) && (inet_pton(AF_INET, internal_address, &in_addr.sin_addr) != 1))
2262 GNUNET_log_from(GNUNET_ERROR_TYPE_WARNING, "udp", "Malformed INTERNAL_ADDRESS %s given in configuration!\n", internal_address);
2267 GNUNET_CONFIGURATION_get_value_number (env->cfg,
2273 GNUNET_CONFIGURATION_get_value_number (env->cfg,
2276 &aport)) && (aport > 65535)))
2278 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
2281 ("Require valid port number for service `%s' in configuration!\n"),
2283 GNUNET_free_non_null(external_address);
2284 GNUNET_free_non_null(internal_address);
2285 GNUNET_SERVICE_stop (service);
2291 plugin = GNUNET_malloc (sizeof (struct Plugin));
2292 plugin->open_port = bport;
2293 plugin->adv_port = aport;
2294 plugin->external_address = external_address;
2295 plugin->internal_address = internal_address;
2296 plugin->behind_nat = behind_nat;
2297 plugin->allow_nat = allow_nat;
2298 plugin->only_nat_addresses = only_nat_addresses;
2300 plugin->lsock = NULL;
2301 api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
2303 api->send = &tcp_plugin_send;
2304 api->disconnect = &tcp_plugin_disconnect;
2305 api->address_pretty_printer = &tcp_plugin_address_pretty_printer;
2306 api->check_address = &tcp_plugin_check_address;
2307 api->address_to_string = &tcp_address_to_string;
2308 plugin->service = service;
2309 plugin->server = GNUNET_SERVICE_get_server (service);
2310 plugin->handlers = GNUNET_malloc (sizeof (my_handlers));
2311 memcpy (plugin->handlers, my_handlers, sizeof (my_handlers));
2314 sizeof (my_handlers) / sizeof (struct GNUNET_SERVER_MessageHandler);
2316 plugin->handlers[i].callback_cls = plugin;
2317 GNUNET_SERVER_add_handlers (plugin->server, plugin->handlers);
2319 if (behind_nat == GNUNET_YES)
2321 if (GNUNET_YES != tcp_transport_start_nat_server(plugin))
2323 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
2326 ("Failed to start %s required for NAT in %s!\n"),
2329 GNUNET_free_non_null(external_address);
2330 GNUNET_free_non_null(internal_address);
2331 GNUNET_SERVICE_stop (service);
2336 if (allow_nat == GNUNET_YES)
2338 plugin->nat_wait_conns = GNUNET_CONTAINER_multihashmap_create(100);
2339 GNUNET_assert(plugin->nat_wait_conns != NULL);
2342 GNUNET_log_from (GNUNET_ERROR_TYPE_INFO,
2343 "tcp", _("TCP transport listening on port %llu\n"), bport);
2345 GNUNET_log_from (GNUNET_ERROR_TYPE_INFO,
2347 _("TCP transport advertises itself as being on port %llu\n"),
2349 GNUNET_SERVER_disconnect_notify (plugin->server,
2352 if (plugin->behind_nat == GNUNET_NO)
2354 GNUNET_OS_network_interfaces_list (&process_interfaces, plugin);
2357 plugin->hostname_dns = GNUNET_RESOLVER_hostname_resolve (env->sched,
2360 HOSTNAME_RESOLVE_TIMEOUT,
2361 &process_hostname_ips,
2364 if ((plugin->behind_nat == GNUNET_YES) && (inet_pton(AF_INET, plugin->external_address, &t4.ipv4_addr) == 1))
2366 t4.t_port = htons(0);
2367 plugin->env->notify_address (plugin->env->cls,
2369 &t4, sizeof(t4), GNUNET_TIME_UNIT_FOREVER_REL);
2371 else if ((plugin->external_address != NULL) && (inet_pton(AF_INET, plugin->external_address, &t4.ipv4_addr) == 1))
2373 t4.t_port = htons(plugin->adv_port);
2374 plugin->env->notify_address (plugin->env->cls,
2376 &t4, sizeof(t4), GNUNET_TIME_UNIT_FOREVER_REL);
2384 * Exit point from the plugin.
2387 libgnunet_plugin_transport_tcp_done (void *cls)
2389 struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
2390 struct Plugin *plugin = api->cls;
2391 struct Session *session;
2393 while (NULL != (session = plugin->sessions))
2394 disconnect_session (session);
2395 if (NULL != plugin->hostname_dns)
2397 GNUNET_RESOLVER_request_cancel (plugin->hostname_dns);
2398 plugin->hostname_dns = NULL;
2400 GNUNET_SERVICE_stop (plugin->service);
2401 GNUNET_free (plugin->handlers);
2402 GNUNET_free (plugin);
2407 /* end of plugin_transport_tcp.c */