2 This file is part of GNUnet
3 (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 Christian Grothoff (and other contributing authors)
5 GNUnet is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published
7 by the Free Software Foundation; either version 3, or (at your
8 option) any later version.
10 GNUnet is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with GNUnet; see the file COPYING. If not, write to the
17 Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18 Boston, MA 02111-1307, USA.
21 * @file transport/plugin_transport_tcp.c
22 * @brief Implementation of the TCP transport service
23 * @author Christian Grothoff
26 #include "gnunet_hello_lib.h"
27 #include "gnunet_connection_lib.h"
28 #include "gnunet_container_lib.h"
29 #include "gnunet_os_lib.h"
30 #include "gnunet_protocols.h"
31 #include "gnunet_resolver_service.h"
32 #include "gnunet_server_lib.h"
33 #include "gnunet_service_lib.h"
34 #include "gnunet_signatures.h"
35 #include "gnunet_statistics_service.h"
36 #include "gnunet_transport_service.h"
37 #include "plugin_transport.h"
38 #include "transport.h"
40 #define DEBUG_TCP GNUNET_YES
41 #define DEBUG_TCP_NAT GNUNET_YES
44 * How long until we give up on transmitting the welcome message?
46 #define HOSTNAME_RESOLVE_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 5)
50 * Initial handshake message for a session.
55 * Type is GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME.
57 struct GNUNET_MessageHeader header;
60 * Identity of the node connecting (TCP client)
62 struct GNUNET_PeerIdentity clientIdentity;
67 * Basically a WELCOME message, but with the purpose
68 * of giving the waiting peer a client handle to use
70 struct TCP_NAT_ProbeMessage
73 * Type is GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE.
75 struct GNUNET_MessageHeader header;
78 * Identity of the sender of the message.
80 struct GNUNET_PeerIdentity clientIdentity;
85 * Context for sending a NAT probe via TCP.
87 struct TCPProbeContext
92 struct GNUNET_CONNECTION_Handle *sock;
97 struct TCP_NAT_ProbeMessage message;
100 * Handle to the transmission.
102 struct GNUNET_CONNECTION_TransmitHandle *transmit_handle;
105 * Transport plugin handle.
107 struct Plugin *plugin;
112 * Network format for IPv4 addresses.
114 struct IPv4TcpAddress
117 * IPv4 address, in network byte order.
119 uint32_t ipv4_addr GNUNET_PACKED;
122 * Port number, in network byte order.
124 uint16_t t_port GNUNET_PACKED;
130 * Network format for IPv6 addresses.
132 struct IPv6TcpAddress
137 struct in6_addr ipv6_addr GNUNET_PACKED;
140 * Port number, in network byte order.
142 uint16_t t6_port GNUNET_PACKED;
147 * Encapsulation of all of the state of the plugin.
153 * Local network addresses (actual IP address follows this struct).
154 * PORT is NOT included!
160 * This is a doubly linked list.
162 struct LocalAddrList *next;
165 * This is a doubly linked list.
167 struct LocalAddrList *prev;
170 * Number of bytes of the address that follow
178 * Information kept for each message that is yet to
181 struct PendingMessage
185 * This is a doubly-linked list.
187 struct PendingMessage *next;
190 * This is a doubly-linked list.
192 struct PendingMessage *prev;
195 * The pending message
200 * Continuation function to call once the message
201 * has been sent. Can be NULL if there is no
202 * continuation to call.
204 GNUNET_TRANSPORT_TransmitContinuation transmit_cont;
207 * Closure for transmit_cont.
209 void *transmit_cont_cls;
212 * Timeout value for the pending message.
214 struct GNUNET_TIME_Absolute timeout;
217 * So that the gnunet-service-transport can group messages together,
218 * these pending messages need to accept a message buffer and size
219 * instead of just a GNUNET_MessageHeader.
227 * Session handle for TCP connections.
235 struct SessionHeader header;
238 * Stored in a linked list.
240 struct Session *next;
243 * Pointer to the global plugin struct.
245 struct Plugin *plugin;
248 * The client (used to identify this connection)
250 struct GNUNET_SERVER_Client *client;
253 * Messages currently pending for transmission
254 * to this peer, if any.
256 struct PendingMessage *pending_messages_head;
259 * Messages currently pending for transmission
260 * to this peer, if any.
262 struct PendingMessage *pending_messages_tail;
265 * Handle for pending transmission request.
267 struct GNUNET_CONNECTION_TransmitHandle *transmit_handle;
270 * To whom are we talking to (set to our identity
271 * if we are still waiting for the welcome message)
273 struct GNUNET_PeerIdentity target;
276 * ID of task used to delay receiving more to throttle sender.
278 GNUNET_SCHEDULER_TaskIdentifier receive_delay_task;
281 * Address of the other peer (either based on our 'connect'
282 * call or on our 'accept' call).
287 * Last activity on this connection. Used to select preferred
290 struct GNUNET_TIME_Absolute last_activity;
293 * Length of connect_addr.
298 * Are we still expecting the welcome message? (GNUNET_YES/GNUNET_NO)
300 int expecting_welcome;
303 * Was this a connection that was inbound (we accepted)? (GNUNET_YES/GNUNET_NO)
311 * Encapsulation of all of the state of the plugin.
318 struct GNUNET_TRANSPORT_PluginEnvironment *env;
323 struct GNUNET_CONNECTION_Handle *lsock;
326 * stdout pipe handle for the gnunet-nat-server process
328 struct GNUNET_DISK_PipeHandle *server_stdout;
331 * stdout file handle (for reading) for the gnunet-nat-server process
333 const struct GNUNET_DISK_FileHandle *server_stdout_handle;
336 * ID of select gnunet-nat-server stdout read task
338 GNUNET_SCHEDULER_TaskIdentifier server_read_task;
341 * The process id of the server process (if behind NAT)
346 * List of open TCP sessions.
348 struct Session *sessions;
351 * Handle to the network service.
353 struct GNUNET_SERVICE_Context *service;
356 * Handle to the server for this service.
358 struct GNUNET_SERVER_Handle *server;
361 * Copy of the handler array where the closures are
362 * set to this struct's instance.
364 struct GNUNET_SERVER_MessageHandler *handlers;
367 * Handle for request of hostname resolution, non-NULL if pending.
369 struct GNUNET_RESOLVER_RequestHandle *hostname_dns;
372 * Map of peers we have tried to contact behind a NAT
374 struct GNUNET_CONTAINER_MultiHashMap *nat_wait_conns;
377 * The external address given to us by the user. Must be actual
378 * outside visible address for NAT punching to work.
380 char *external_address;
383 * The internal address given to us by the user (or discovered).
385 char *internal_address;
388 * Address given for us to bind to (ONLY).
393 * List of our IP addresses.
395 struct LocalAddrList *lal_head;
398 * Tail of our IP address list.
400 struct LocalAddrList *lal_tail;
403 * ID of task used to update our addresses when one expires.
405 GNUNET_SCHEDULER_TaskIdentifier address_update_task;
408 * Port that we are actually listening on.
413 * Port that the user said we would have visible to the
419 * Is this transport configured to be behind a NAT?
424 * Is this transport configured to allow connections to NAT'd peers?
429 * Should this transport advertise only NAT addresses (port set to 0)?
430 * If not, all addresses will be duplicated for NAT punching and regular
433 int only_nat_addresses;
439 add_to_address_list (struct Plugin *plugin,
443 struct LocalAddrList *lal;
445 lal = plugin->lal_head;
448 if ( (lal->size == arg_size) &&
449 (0 == memcmp (&lal[1], arg, arg_size)) )
453 lal = GNUNET_malloc (sizeof (struct LocalAddrList) + arg_size);
454 lal->size = arg_size;
455 memcpy (&lal[1], arg, arg_size);
456 GNUNET_CONTAINER_DLL_insert (plugin->lal_head,
463 check_local_addr (struct Plugin *plugin,
467 struct LocalAddrList *lal;
469 lal = plugin->lal_head;
472 if ( (lal->size == arg_size) &&
473 (0 == memcmp (&lal[1], arg, arg_size)) )
477 return GNUNET_SYSERR;
482 * Function called for a quick conversion of the binary address to
483 * a numeric address. Note that the caller must not free the
484 * address and that the next call to this function is allowed
485 * to override the address again.
487 * @param cls closure ('struct Plugin*')
488 * @param addr binary address
489 * @param addrlen length of the address
490 * @return string representing the same address
493 tcp_address_to_string (void *cls,
497 static char rbuf[INET6_ADDRSTRLEN + 12];
498 char buf[INET6_ADDRSTRLEN];
502 const struct IPv4TcpAddress *t4;
503 const struct IPv6TcpAddress *t6;
507 if (addrlen == sizeof (struct IPv6TcpAddress))
511 port = ntohs (t6->t6_port);
512 memcpy (&a6, &t6->ipv6_addr, sizeof (a6));
515 else if (addrlen == sizeof (struct IPv4TcpAddress))
519 port = ntohs (t4->t_port);
520 memcpy (&a4, &t4->ipv4_addr, sizeof (a4));
525 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
526 _("Unexpected address length: %u\n"),
531 if (NULL == inet_ntop (af, sb, buf, INET6_ADDRSTRLEN))
533 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "inet_ntop");
536 GNUNET_snprintf (rbuf,
538 (af == AF_INET6) ? "[%s]:%u" : "%s:%u",
546 * Find the session handle for the given client.
548 * @return NULL if no matching session exists
550 static struct Session *
551 find_session_by_client (struct Plugin *plugin,
552 const struct GNUNET_SERVER_Client *client)
556 ret = plugin->sessions;
557 while ((ret != NULL) && (client != ret->client))
563 * Create a new session. Also queues a welcome message.
566 * @param target peer to connect to
567 * @param client client to use
568 * @param is_nat this a NAT session, we should wait for a client to
569 * connect to us from an address, then assign that to
571 * @return new session object
573 static struct Session *
574 create_session (struct Plugin *plugin,
575 const struct GNUNET_PeerIdentity *target,
576 struct GNUNET_SERVER_Client *client, int is_nat)
579 struct PendingMessage *pm;
580 struct WelcomeMessage welcome;
582 if (is_nat != GNUNET_YES)
583 GNUNET_assert (client != NULL);
585 GNUNET_assert (client == NULL);
588 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
589 "Creating new session for peer `%4s'\n",
590 GNUNET_i2s (target));
592 ret = GNUNET_malloc (sizeof (struct Session));
593 ret->last_activity = GNUNET_TIME_absolute_get ();
594 ret->plugin = plugin;
595 if (is_nat != GNUNET_YES) /* If not a NAT WAIT conn, add it to global list */
597 ret->next = plugin->sessions;
598 plugin->sessions = ret;
600 ret->client = client;
601 ret->target = *target;
602 ret->expecting_welcome = GNUNET_YES;
603 pm = GNUNET_malloc (sizeof (struct PendingMessage) + sizeof (struct WelcomeMessage));
604 pm->msg = (const char*) &pm[1];
605 pm->message_size = sizeof (struct WelcomeMessage);
606 welcome.header.size = htons (sizeof (struct WelcomeMessage));
607 welcome.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME);
608 welcome.clientIdentity = *plugin->env->my_identity;
609 memcpy (&pm[1], &welcome, sizeof (welcome));
610 pm->timeout = GNUNET_TIME_UNIT_FOREVER_ABS;
611 GNUNET_STATISTICS_update (plugin->env->stats,
612 gettext_noop ("# bytes currently in TCP buffers"),
615 GNUNET_CONTAINER_DLL_insert (ret->pending_messages_head,
616 ret->pending_messages_tail,
618 if (is_nat != GNUNET_YES)
619 GNUNET_STATISTICS_update (plugin->env->stats,
620 gettext_noop ("# TCP sessions active"),
628 * If we have pending messages, ask the server to
629 * transmit them (schedule the respective tasks, etc.)
631 * @param session for which session should we do this
633 static void process_pending_messages (struct Session *session);
637 * Function called to notify a client about the socket
638 * being ready to queue more data. "buf" will be
639 * NULL and "size" zero if the socket was closed for
640 * writing in the meantime.
643 * @param size number of bytes available in buf
644 * @param buf where the callee should write the message
645 * @return number of bytes written to buf
648 do_transmit (void *cls, size_t size, void *buf)
650 struct Session *session = cls;
651 struct GNUNET_PeerIdentity pid;
652 struct Plugin *plugin;
653 struct PendingMessage *pos;
654 struct PendingMessage *hd;
655 struct PendingMessage *tl;
656 struct GNUNET_TIME_Absolute now;
660 session->transmit_handle = NULL;
661 plugin = session->plugin;
665 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
666 "Timeout trying to transmit to peer `%4s', discarding message queue.\n",
667 GNUNET_i2s (&session->target));
669 /* timeout; cancel all messages that have already expired */
673 now = GNUNET_TIME_absolute_get ();
674 while ( (NULL != (pos = session->pending_messages_head)) &&
675 (pos->timeout.value <= now.value) )
677 GNUNET_CONTAINER_DLL_remove (session->pending_messages_head,
678 session->pending_messages_tail,
681 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
682 "Failed to transmit %u byte message to `%4s'.\n",
684 GNUNET_i2s (&session->target));
686 ret += pos->message_size;
687 GNUNET_CONTAINER_DLL_insert_after (hd, tl, tl, pos);
689 /* do this call before callbacks (so that if callbacks destroy
690 session, they have a chance to cancel actions done by this
692 process_pending_messages (session);
693 pid = session->target;
694 /* no do callbacks and do not use session again since
695 the callbacks may abort the session */
696 while (NULL != (pos = hd))
698 GNUNET_CONTAINER_DLL_remove (hd, tl, pos);
699 if (pos->transmit_cont != NULL)
700 pos->transmit_cont (pos->transmit_cont_cls,
701 &pid, GNUNET_SYSERR);
704 GNUNET_STATISTICS_update (plugin->env->stats,
705 gettext_noop ("# bytes currently in TCP buffers"),
708 GNUNET_STATISTICS_update (plugin->env->stats,
709 gettext_noop ("# bytes discarded by TCP (timeout)"),
714 /* copy all pending messages that would fit */
719 while (NULL != (pos = session->pending_messages_head))
721 if (ret + pos->message_size > size)
723 GNUNET_CONTAINER_DLL_remove (session->pending_messages_head,
724 session->pending_messages_tail,
726 GNUNET_assert (size >= pos->message_size);
727 /* FIXME: this memcpy can be up to 7% of our total runtime */
728 memcpy (cbuf, pos->msg, pos->message_size);
729 cbuf += pos->message_size;
730 ret += pos->message_size;
731 size -= pos->message_size;
732 GNUNET_CONTAINER_DLL_insert_after (hd, tl, tl, pos);
734 /* schedule 'continuation' before callbacks so that callbacks that
735 cancel everything don't cause us to use a session that no longer
737 process_pending_messages (session);
738 session->last_activity = GNUNET_TIME_absolute_get ();
739 pid = session->target;
740 /* we'll now call callbacks that may cancel the session; hence
741 we should not use 'session' after this point */
742 while (NULL != (pos = hd))
744 GNUNET_CONTAINER_DLL_remove (hd, tl, pos);
745 if (pos->transmit_cont != NULL)
746 pos->transmit_cont (pos->transmit_cont_cls,
750 GNUNET_assert (hd == NULL);
751 GNUNET_assert (tl == NULL);
753 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
754 "Transmitting %u bytes\n", ret);
756 GNUNET_STATISTICS_update (plugin->env->stats,
757 gettext_noop ("# bytes currently in TCP buffers"),
760 GNUNET_STATISTICS_update (plugin->env->stats,
761 gettext_noop ("# bytes transmitted via TCP"),
769 * If we have pending messages, ask the server to
770 * transmit them (schedule the respective tasks, etc.)
772 * @param session for which session should we do this
775 process_pending_messages (struct Session *session)
777 struct PendingMessage *pm;
779 GNUNET_assert (session->client != NULL);
780 if (session->transmit_handle != NULL)
782 if (NULL == (pm = session->pending_messages_head))
785 session->transmit_handle
786 = GNUNET_SERVER_notify_transmit_ready (session->client,
788 GNUNET_TIME_absolute_get_remaining
790 &do_transmit, session);
795 * Functions with this signature are called whenever we need
796 * to close a session due to a disconnect or failure to
797 * establish a connection.
799 * @param session session to close down
802 disconnect_session (struct Session *session)
804 struct Session *prev;
806 struct PendingMessage *pm;
809 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
810 "Disconnecting from `%4s' at %s (session %p).\n",
811 GNUNET_i2s (&session->target),
812 (session->connect_addr != NULL) ?
813 tcp_address_to_string (session->plugin,
814 session->connect_addr,
815 session->connect_alen) : "*",
818 /* remove from session list */
820 pos = session->plugin->sessions;
821 while (pos != session)
827 session->plugin->sessions = session->next;
829 prev->next = session->next;
830 session->plugin->env->session_end (session->plugin->env->cls,
834 if (session->transmit_handle != NULL)
836 GNUNET_CONNECTION_notify_transmit_ready_cancel
837 (session->transmit_handle);
838 session->transmit_handle = NULL;
840 while (NULL != (pm = session->pending_messages_head))
843 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
845 pm->transmit_cont != NULL
846 ? "Could not deliver message to `%4s'.\n"
848 "Could not deliver message to `%4s', notifying.\n",
849 GNUNET_i2s (&session->target));
851 GNUNET_STATISTICS_update (session->plugin->env->stats,
852 gettext_noop ("# bytes currently in TCP buffers"),
853 - (int64_t) pm->message_size,
855 GNUNET_STATISTICS_update (session->plugin->env->stats,
856 gettext_noop ("# bytes discarded by TCP (disconnect)"),
859 GNUNET_CONTAINER_DLL_remove (session->pending_messages_head,
860 session->pending_messages_tail,
862 if (NULL != pm->transmit_cont)
863 pm->transmit_cont (pm->transmit_cont_cls,
864 &session->target, GNUNET_SYSERR);
867 GNUNET_break (session->client != NULL);
868 if (session->receive_delay_task != GNUNET_SCHEDULER_NO_TASK)
870 GNUNET_SCHEDULER_cancel (session->plugin->env->sched,
871 session->receive_delay_task);
872 if (session->client != NULL)
873 GNUNET_SERVER_receive_done (session->client,
876 if (session->client != NULL)
877 GNUNET_SERVER_client_drop (session->client);
878 GNUNET_STATISTICS_update (session->plugin->env->stats,
879 gettext_noop ("# TCP sessions active"),
882 GNUNET_free_non_null (session->connect_addr);
883 GNUNET_free (session);
888 * Given two otherwise equivalent sessions, pick the better one.
890 * @param s1 one session (also default)
891 * @param s2 other session
892 * @return "better" session (more active)
894 static struct Session *
895 select_better_session (struct Session *s1,
902 if ( (s1->expecting_welcome == GNUNET_NO) &&
903 (s2->expecting_welcome == GNUNET_YES) )
905 if ( (s1->expecting_welcome == GNUNET_YES) &&
906 (s2->expecting_welcome == GNUNET_NO) )
908 if (s1->last_activity.value < s2->last_activity.value)
910 if (s1->last_activity.value > s2->last_activity.value)
912 if ( (GNUNET_YES == s1->inbound) &&
913 (GNUNET_NO == s2->inbound) )
915 if ( (GNUNET_NO == s1->inbound) &&
916 (GNUNET_YES == s2->inbound) )
923 * We learned about a peer (possibly behind NAT) so run the
924 * gnunet-nat-client to send dummy ICMP responses
926 * @param plugin the plugin for this transport
927 * @param addr the address of the peer
928 * @param addrlen the length of the address
931 run_gnunet_nat_client (struct Plugin *plugin, const char *addr, size_t addrlen)
933 char inet4[INET_ADDRSTRLEN];
934 char *address_as_string;
935 char *port_as_string;
937 const struct sockaddr *sa = (const struct sockaddr *)addr;
940 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
941 _("called run_gnunet_nat_client addrlen %d others are %d and %d\n"), addrlen, sizeof (struct sockaddr), sizeof (struct sockaddr_in));
944 if (addrlen < sizeof (struct sockaddr))
947 switch (sa->sa_family)
950 if (addrlen != sizeof (struct sockaddr_in))
952 if (NULL == inet_ntop (AF_INET,
953 &((struct sockaddr_in *) sa)->sin_addr,
954 inet4, INET_ADDRSTRLEN))
956 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "inet_ntop");
959 address_as_string = GNUNET_strdup (inet4);
966 GNUNET_asprintf(&port_as_string, "%d", plugin->adv_port);
968 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
969 _("Running gnunet-nat-client with arguments: %s %s %d\n"), plugin->external_address, address_as_string, plugin->adv_port);
972 /* Start the client process */
973 pid = GNUNET_OS_start_process(NULL, NULL, "gnunet-nat-client", "gnunet-nat-client", plugin->external_address, address_as_string, port_as_string, NULL);
974 GNUNET_free(address_as_string);
975 GNUNET_free(port_as_string);
976 GNUNET_OS_process_wait (pid);
981 * Function that can be used by the transport service to transmit
982 * a message using the plugin. Note that in the case of a
983 * peer disconnecting, the continuation MUST be called
984 * prior to the disconnect notification itself. This function
985 * will be called with this peer's HELLO message to initiate
986 * a fresh connection to another peer.
989 * @param target who should receive this message
990 * @param msg the message to transmit
991 * @param msgbuf_size number of bytes in 'msg'
992 * @param priority how important is the message (most plugins will
993 * ignore message priority and just FIFO)
994 * @param timeout how long to wait at most for the transmission (does not
995 * require plugins to discard the message after the timeout,
996 * just advisory for the desired delay; most plugins will ignore
998 * @param session which session must be used (or NULL for "any")
999 * @param addr the address to use (can be NULL if the plugin
1000 * is "on its own" (i.e. re-use existing TCP connection))
1001 * @param addrlen length of the address in bytes
1002 * @param force_address GNUNET_YES if the plugin MUST use the given address,
1003 * GNUNET_NO means the plugin may use any other address and
1004 * GNUNET_SYSERR means that only reliable existing
1005 * bi-directional connections should be used (regardless
1007 * @param cont continuation to call once the message has
1008 * been transmitted (or if the transport is ready
1009 * for the next transmission call; or if the
1010 * peer disconnected...); can be NULL
1011 * @param cont_cls closure for cont
1012 * @return number of bytes used (on the physical network, with overheads);
1013 * -1 on hard errors (i.e. address invalid); 0 is a legal value
1014 * and does NOT mean that the message was not transmitted (DV and NAT)
1017 tcp_plugin_send (void *cls,
1018 const struct GNUNET_PeerIdentity *target,
1022 struct GNUNET_TIME_Relative timeout,
1023 struct Session *session,
1027 GNUNET_TRANSPORT_TransmitContinuation cont, void *cont_cls)
1029 struct Plugin *plugin = cls;
1030 struct Session *cand_session;
1031 struct Session *next;
1032 struct PendingMessage *pm;
1033 struct GNUNET_CONNECTION_Handle *sa;
1037 struct sockaddr_in a4;
1038 struct sockaddr_in6 a6;
1039 const struct IPv4TcpAddress *t4;
1040 const struct IPv6TcpAddress *t6;
1041 unsigned int is_natd;
1043 GNUNET_STATISTICS_update (plugin->env->stats,
1044 gettext_noop ("# bytes TCP was asked to transmit"),
1047 /* FIXME: we could do this cheaper with a hash table
1048 where we could restrict the iteration to entries that match
1049 the target peer... */
1050 is_natd = GNUNET_NO;
1051 if (session == NULL)
1053 cand_session = NULL;
1054 next = plugin->sessions;
1055 while (NULL != (session = next))
1057 next = session->next;
1058 GNUNET_assert (session->client != NULL);
1059 if (0 != memcmp (target,
1061 sizeof (struct GNUNET_PeerIdentity)))
1063 if ( ( (GNUNET_SYSERR == force_address) &&
1064 (session->expecting_welcome == GNUNET_NO) ) ||
1065 (GNUNET_NO == force_address) )
1067 cand_session = select_better_session (cand_session,
1071 if (GNUNET_SYSERR == force_address)
1073 GNUNET_break (GNUNET_YES == force_address);
1079 if (session->inbound == GNUNET_YES)
1081 if (addrlen != session->connect_alen)
1083 if (0 != memcmp (session->connect_addr,
1087 cand_session = select_better_session (cand_session,
1090 session = cand_session;
1092 if ( (session == NULL) &&
1096 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1097 "Asked to transmit to `%4s' without address and I have no existing connection (failing).\n",
1098 GNUNET_i2s (target));
1100 GNUNET_STATISTICS_update (plugin->env->stats,
1101 gettext_noop ("# bytes discarded by TCP (no address and no connection)"),
1106 if (session == NULL)
1108 if (addrlen == sizeof (struct IPv6TcpAddress))
1112 memset (&a6, 0, sizeof (a6));
1113 #if HAVE_SOCKADDR_IN_SIN_LEN
1114 a6.sin6_len = sizeof (a6);
1116 a6.sin6_family = AF_INET6;
1117 a6.sin6_port = t6->t6_port;
1118 if (t6->t6_port == 0)
1119 is_natd = GNUNET_YES;
1120 memcpy (&a6.sin6_addr,
1122 sizeof (struct in6_addr));
1126 else if (addrlen == sizeof (struct IPv4TcpAddress))
1130 memset (&a4, 0, sizeof (a4));
1131 #if HAVE_SOCKADDR_IN_SIN_LEN
1132 a4.sin_len = sizeof (a4);
1134 a4.sin_family = AF_INET;
1135 a4.sin_port = t4->t_port;
1136 if (t4->t_port == 0)
1137 is_natd = GNUNET_YES;
1138 a4.sin_addr.s_addr = t4->ipv4_addr;
1144 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1145 _("Address of unexpected length: %u\n"),
1151 if ((is_natd == GNUNET_YES) && (addrlen == sizeof (struct IPv6TcpAddress)))
1152 return -1; /* NAT client only works with IPv4 addresses */
1155 if ( (plugin->allow_nat == GNUNET_YES) && (is_natd == GNUNET_YES) &&
1156 (GNUNET_NO == GNUNET_CONTAINER_multihashmap_contains(plugin->nat_wait_conns, &target->hashPubKey)))
1159 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1160 _("Found valid IPv4 NAT address!\n"));
1162 session = create_session (plugin,
1166 /* create new message entry */
1167 pm = GNUNET_malloc (sizeof (struct PendingMessage) + msgbuf_size);
1168 /* FIXME: the memset of this malloc can be up to 2% of our total runtime */
1169 pm->msg = (const char*) &pm[1];
1170 memcpy (&pm[1], msg, msgbuf_size);
1171 /* FIXME: this memcpy can be up to 7% of our total run-time
1172 (for transport service) */
1173 pm->message_size = msgbuf_size;
1174 pm->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1175 pm->transmit_cont = cont;
1176 pm->transmit_cont_cls = cont_cls;
1178 /* append pm to pending_messages list */
1179 GNUNET_CONTAINER_DLL_insert_after (session->pending_messages_head,
1180 session->pending_messages_tail,
1181 session->pending_messages_tail,
1184 GNUNET_assert(GNUNET_CONTAINER_multihashmap_put(plugin->nat_wait_conns, &target->hashPubKey, session, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY) == GNUNET_OK);
1186 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1187 "Created NAT WAIT connection to `%4s' at `%s'\n",
1188 GNUNET_i2s (target),
1189 GNUNET_a2s (sb, sbs));
1191 run_gnunet_nat_client (plugin, sb, sbs);
1194 else if ((plugin->allow_nat == GNUNET_YES) && (is_natd == GNUNET_YES) && (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains(plugin->nat_wait_conns, &target->hashPubKey)))
1196 /* Only do one NAT punch attempt per peer identity */
1199 sa = GNUNET_CONNECTION_create_from_sockaddr (plugin->env->sched,
1204 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1205 "Failed to create connection to `%4s' at `%s'\n",
1206 GNUNET_i2s (target),
1207 GNUNET_a2s (sb, sbs));
1209 GNUNET_STATISTICS_update (plugin->env->stats,
1210 gettext_noop ("# bytes discarded by TCP (failed to connect)"),
1216 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1217 "Asked to transmit to `%4s', creating fresh session using address `%s'.\n",
1218 GNUNET_i2s (target),
1219 GNUNET_a2s (sb, sbs));
1221 session = create_session (plugin,
1223 GNUNET_SERVER_connect_socket (plugin->server,
1225 session->connect_addr = GNUNET_malloc (addrlen);
1226 memcpy (session->connect_addr,
1229 session->connect_alen = addrlen;
1231 GNUNET_assert (session != NULL);
1232 GNUNET_assert (session->client != NULL);
1233 GNUNET_STATISTICS_update (plugin->env->stats,
1234 gettext_noop ("# bytes currently in TCP buffers"),
1237 /* create new message entry */
1238 pm = GNUNET_malloc (sizeof (struct PendingMessage) + msgbuf_size);
1239 pm->msg = (const char*) &pm[1];
1240 memcpy (&pm[1], msg, msgbuf_size);
1241 pm->message_size = msgbuf_size;
1242 pm->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1243 pm->transmit_cont = cont;
1244 pm->transmit_cont_cls = cont_cls;
1246 /* append pm to pending_messages list */
1247 GNUNET_CONTAINER_DLL_insert_after (session->pending_messages_head,
1248 session->pending_messages_tail,
1249 session->pending_messages_tail,
1252 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1253 "Asked to transmit %u bytes to `%s', added message to list.\n",
1255 GNUNET_i2s (target));
1257 process_pending_messages (session);
1263 * Function that can be called to force a disconnect from the
1264 * specified neighbour. This should also cancel all previously
1265 * scheduled transmissions. Obviously the transmission may have been
1266 * partially completed already, which is OK. The plugin is supposed
1267 * to close the connection (if applicable) and no longer call the
1268 * transmit continuation(s).
1270 * Finally, plugin MUST NOT call the services's receive function to
1271 * notify the service that the connection to the specified target was
1272 * closed after a getting this call.
1274 * @param cls closure
1275 * @param target peer for which the last transmission is
1279 tcp_plugin_disconnect (void *cls,
1280 const struct GNUNET_PeerIdentity *target)
1282 struct Plugin *plugin = cls;
1283 struct Session *session;
1284 struct Session *next;
1285 struct PendingMessage *pm;
1288 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1289 "Asked to cancel session with `%4s'\n",
1290 GNUNET_i2s (target));
1292 next = plugin->sessions;
1293 while (NULL != (session = next))
1295 next = session->next;
1296 if (0 != memcmp (target,
1298 sizeof (struct GNUNET_PeerIdentity)))
1300 pm = session->pending_messages_head;
1303 pm->transmit_cont = NULL;
1304 pm->transmit_cont_cls = NULL;
1307 disconnect_session (session);
1313 * Context for address to string conversion.
1315 struct PrettyPrinterContext
1318 * Function to call with the result.
1320 GNUNET_TRANSPORT_AddressStringCallback asc;
1323 * Clsoure for 'asc'.
1328 * Port to add after the IP address.
1335 * Append our port and forward the result.
1337 * @param cls the 'struct PrettyPrinterContext*'
1338 * @param hostname hostname part of the address
1341 append_port (void *cls, const char *hostname)
1343 struct PrettyPrinterContext *ppc = cls;
1346 if (hostname == NULL)
1348 ppc->asc (ppc->asc_cls, NULL);
1352 GNUNET_asprintf (&ret, "%s:%d", hostname, ppc->port);
1353 ppc->asc (ppc->asc_cls, ret);
1359 * Convert the transports address to a nice, human-readable
1362 * @param cls closure
1363 * @param type name of the transport that generated the address
1364 * @param addr one of the addresses of the host, NULL for the last address
1365 * the specific address format depends on the transport
1366 * @param addrlen length of the address
1367 * @param numeric should (IP) addresses be displayed in numeric form?
1368 * @param timeout after how long should we give up?
1369 * @param asc function to call on each string
1370 * @param asc_cls closure for asc
1373 tcp_plugin_address_pretty_printer (void *cls,
1378 struct GNUNET_TIME_Relative timeout,
1379 GNUNET_TRANSPORT_AddressStringCallback asc,
1382 struct Plugin *plugin = cls;
1383 struct PrettyPrinterContext *ppc;
1386 struct sockaddr_in a4;
1387 struct sockaddr_in6 a6;
1388 const struct IPv4TcpAddress *t4;
1389 const struct IPv6TcpAddress *t6;
1392 if (addrlen == sizeof (struct IPv6TcpAddress))
1395 memset (&a6, 0, sizeof (a6));
1396 a6.sin6_family = AF_INET6;
1397 a6.sin6_port = t6->t6_port;
1398 memcpy (&a6.sin6_addr,
1400 sizeof (struct in6_addr));
1401 port = ntohs (t6->t6_port);
1405 else if (addrlen == sizeof (struct IPv4TcpAddress))
1408 memset (&a4, 0, sizeof (a4));
1409 a4.sin_family = AF_INET;
1410 a4.sin_port = t4->t_port;
1411 a4.sin_addr.s_addr = t4->ipv4_addr;
1412 port = ntohs (t4->t_port);
1418 /* invalid address */
1419 GNUNET_break_op (0);
1420 asc (asc_cls, NULL);
1423 ppc = GNUNET_malloc (sizeof (struct PrettyPrinterContext));
1425 ppc->asc_cls = asc_cls;
1427 GNUNET_RESOLVER_hostname_get (plugin->env->sched,
1431 !numeric, timeout, &append_port, ppc);
1436 * Check if the given port is plausible (must be either
1437 * our listen port or our advertised port). If it is
1438 * neither, we return GNUNET_SYSERR.
1440 * @param plugin global variables
1441 * @param in_port port number to check
1442 * @return GNUNET_OK if port is either open_port or adv_port
1445 check_port (struct Plugin *plugin, uint16_t in_port)
1447 if ( (plugin->behind_nat == GNUNET_YES) && (in_port == 0) )
1449 if ( (plugin->only_nat_addresses == GNUNET_YES) &&
1450 (plugin->behind_nat == GNUNET_YES) )
1452 return GNUNET_SYSERR; /* odd case... */
1454 if ((in_port == plugin->adv_port) || (in_port == plugin->open_port))
1456 return GNUNET_SYSERR;
1461 * Function that will be called to check if a binary address for this
1462 * plugin is well-formed and corresponds to an address for THIS peer
1463 * (as per our configuration). Naturally, if absolutely necessary,
1464 * plugins can be a bit conservative in their answer, but in general
1465 * plugins should make sure that the address does not redirect
1466 * traffic to a 3rd party that might try to man-in-the-middle our
1469 * @param cls closure, our 'struct Plugin*'
1470 * @param addr pointer to the address
1471 * @param addrlen length of addr
1472 * @return GNUNET_OK if this is a plausible address for this peer
1473 * and transport, GNUNET_SYSERR if not
1476 tcp_plugin_check_address (void *cls,
1480 struct Plugin *plugin = cls;
1481 struct IPv4TcpAddress *v4;
1482 struct IPv6TcpAddress *v6;
1484 if ((addrlen != sizeof (struct IPv4TcpAddress)) &&
1485 (addrlen != sizeof (struct IPv6TcpAddress)))
1487 GNUNET_break_op (0);
1488 return GNUNET_SYSERR;
1490 if (addrlen == sizeof (struct IPv4TcpAddress))
1492 v4 = (struct IPv4TcpAddress *) addr;
1494 check_port (plugin, ntohs (v4->t_port)))
1495 return GNUNET_SYSERR;
1497 check_local_addr (plugin, &v4->ipv4_addr, sizeof (uint32_t)))
1499 return GNUNET_SYSERR;
1504 v6 = (struct IPv6TcpAddress *) addr;
1505 if (IN6_IS_ADDR_LINKLOCAL (&v6->ipv6_addr))
1507 GNUNET_break_op (0);
1508 return GNUNET_SYSERR;
1511 check_port (plugin, ntohs (v6->t6_port)))
1512 return GNUNET_SYSERR;
1514 check_local_addr (plugin, &v6->ipv6_addr, sizeof (struct in6_addr)))
1516 return GNUNET_SYSERR;
1523 * We've received a nat probe from this peer via TCP. Finish
1524 * creating the client session and resume sending of queued
1527 * @param cls closure
1528 * @param client identification of the client
1529 * @param message the actual message
1532 handle_tcp_nat_probe (void *cls,
1533 struct GNUNET_SERVER_Client *client,
1534 const struct GNUNET_MessageHeader *message)
1536 struct Plugin *plugin = cls;
1537 struct Session *session;
1538 struct TCP_NAT_ProbeMessage *tcp_nat_probe;
1541 struct IPv4TcpAddress *t4;
1542 struct IPv6TcpAddress *t6;
1543 const struct sockaddr_in *s4;
1544 const struct sockaddr_in6 *s6;
1547 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "received tcp NAT probe\n");
1549 /* We have received a TCP NAT probe, meaning we (hopefully) initiated
1550 * a connection to this peer by running gnunet-nat-client. This peer
1551 * received the punch message and now wants us to use the new connection
1552 * as the default for that peer. Do so and then send a WELCOME message
1553 * so we can really be connected!
1555 if (ntohs(message->size) != sizeof(struct TCP_NAT_ProbeMessage))
1558 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Bad size for tcp NAT probe, expected %d got %d.\n", sizeof(struct TCP_NAT_ProbeMessage), ntohs(message->size));
1563 tcp_nat_probe = (struct TCP_NAT_ProbeMessage *)message;
1565 if (GNUNET_CONTAINER_multihashmap_contains(plugin->nat_wait_conns, &tcp_nat_probe->clientIdentity.hashPubKey) == GNUNET_YES)
1568 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Found session for NAT probe!\n");
1570 session = GNUNET_CONTAINER_multihashmap_get(plugin->nat_wait_conns, &tcp_nat_probe->clientIdentity.hashPubKey);
1571 GNUNET_assert(session != NULL);
1572 GNUNET_assert(GNUNET_CONTAINER_multihashmap_remove(plugin->nat_wait_conns, &tcp_nat_probe->clientIdentity.hashPubKey, session) == GNUNET_YES);
1573 GNUNET_SERVER_client_keep (client);
1574 session->client = client;
1575 session->last_activity = GNUNET_TIME_absolute_get ();
1576 session->inbound = GNUNET_NO;
1579 GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
1582 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1583 "Found address `%s' for incoming connection %p\n",
1584 GNUNET_a2s (vaddr, alen),
1587 if (((const struct sockaddr *)vaddr)->sa_family == AF_INET)
1590 t4 = GNUNET_malloc (sizeof (struct IPv4TcpAddress));
1591 t4->t_port = s4->sin_port;
1592 t4->ipv4_addr = s4->sin_addr.s_addr;
1593 session->connect_addr = t4;
1594 session->connect_alen = sizeof (struct IPv4TcpAddress);
1596 else if (((const struct sockaddr *)vaddr)->sa_family == AF_INET6)
1599 t6 = GNUNET_malloc (sizeof (struct IPv6TcpAddress));
1600 t6->t6_port = s6->sin6_port;
1601 memcpy (&t6->ipv6_addr,
1603 sizeof (struct in6_addr));
1604 session->connect_addr = t6;
1605 session->connect_alen = sizeof (struct IPv6TcpAddress);
1610 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1611 "Bad address for incoming connection!\n");
1614 GNUNET_free (vaddr);
1617 session->next = plugin->sessions;
1618 plugin->sessions = session;
1619 GNUNET_STATISTICS_update (plugin->env->stats,
1620 gettext_noop ("# TCP sessions active"),
1623 process_pending_messages (session);
1628 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Did NOT find session for NAT probe!\n");
1632 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1636 * We've received a welcome from this peer via TCP. Possibly create a
1637 * fresh client record and send back our welcome.
1639 * @param cls closure
1640 * @param client identification of the client
1641 * @param message the actual message
1644 handle_tcp_welcome (void *cls,
1645 struct GNUNET_SERVER_Client *client,
1646 const struct GNUNET_MessageHeader *message)
1648 struct Plugin *plugin = cls;
1649 const struct WelcomeMessage *wm = (const struct WelcomeMessage *) message;
1650 struct Session *session;
1653 struct IPv4TcpAddress *t4;
1654 struct IPv6TcpAddress *t6;
1655 const struct sockaddr_in *s4;
1656 const struct sockaddr_in6 *s6;
1659 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1660 "Received %s message from a `%4s/%p'.\n",
1662 GNUNET_i2s (&wm->clientIdentity), client);
1664 GNUNET_STATISTICS_update (plugin->env->stats,
1665 gettext_noop ("# TCP WELCOME messages received"),
1668 session = find_session_by_client (plugin, client);
1669 if (session == NULL)
1671 GNUNET_SERVER_client_keep (client);
1672 session = create_session (plugin,
1673 &wm->clientIdentity, client, GNUNET_NO);
1674 session->inbound = GNUNET_YES;
1676 GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
1679 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1680 "Found address `%s' for incoming connection %p\n",
1681 GNUNET_a2s (vaddr, alen),
1684 if (alen == sizeof (struct sockaddr_in))
1687 t4 = GNUNET_malloc (sizeof (struct IPv4TcpAddress));
1688 t4->t_port = s4->sin_port;
1689 t4->ipv4_addr = s4->sin_addr.s_addr;
1690 session->connect_addr = t4;
1691 session->connect_alen = sizeof (struct IPv4TcpAddress);
1693 else if (alen == sizeof (struct sockaddr_in6))
1696 t6 = GNUNET_malloc (sizeof (struct IPv6TcpAddress));
1697 t6->t6_port = s6->sin6_port;
1698 memcpy (&t6->ipv6_addr,
1700 sizeof (struct in6_addr));
1701 session->connect_addr = t6;
1702 session->connect_alen = sizeof (struct IPv6TcpAddress);
1704 GNUNET_free (vaddr);
1709 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1710 "Did not obtain TCP socket address for incoming connection\n");
1714 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1715 "Creating new session %p for connection %p\n",
1718 process_pending_messages (session);
1720 if (session->expecting_welcome != GNUNET_YES)
1722 GNUNET_break_op (0);
1723 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1726 session->last_activity = GNUNET_TIME_absolute_get ();
1727 session->expecting_welcome = GNUNET_NO;
1728 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1733 * Task to signal the server that we can continue
1734 * receiving from the TCP client now.
1736 * @param cls the 'struct Session*'
1737 * @param tc task context (unused)
1740 delayed_done (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1742 struct Session *session = cls;
1743 struct GNUNET_TIME_Relative delay;
1745 session->receive_delay_task = GNUNET_SCHEDULER_NO_TASK;
1746 delay = session->plugin->env->receive (session->plugin->env->cls,
1751 if (delay.value == 0)
1752 GNUNET_SERVER_receive_done (session->client, GNUNET_OK);
1754 session->receive_delay_task =
1755 GNUNET_SCHEDULER_add_delayed (session->plugin->env->sched,
1756 delay, &delayed_done, session);
1761 * We've received data for this peer via TCP. Unbox,
1762 * compute latency and forward.
1764 * @param cls closure
1765 * @param client identification of the client
1766 * @param message the actual message
1769 handle_tcp_data (void *cls,
1770 struct GNUNET_SERVER_Client *client,
1771 const struct GNUNET_MessageHeader *message)
1773 struct Plugin *plugin = cls;
1774 struct Session *session;
1775 struct GNUNET_TIME_Relative delay;
1777 if ((GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME == ntohs(message->type)) || (ntohs(message->type) == GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE))
1779 /* We don't want to propagate WELCOME and NAT Probe messages up! */
1780 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1783 session = find_session_by_client (plugin, client);
1784 if ( (NULL == session) || (GNUNET_YES == session->expecting_welcome))
1786 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1789 session->last_activity = GNUNET_TIME_absolute_get ();
1791 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1792 "Passing %u bytes of type %u from `%4s' to transport service.\n",
1793 (unsigned int) ntohs (message->size),
1794 (unsigned int) ntohs (message->type),
1795 GNUNET_i2s (&session->target));
1797 GNUNET_STATISTICS_update (plugin->env->stats,
1798 gettext_noop ("# bytes received via TCP"),
1799 ntohs (message->size),
1801 delay = plugin->env->receive (plugin->env->cls, &session->target, message, 1,
1803 (GNUNET_YES == session->inbound) ? NULL : session->connect_addr,
1804 (GNUNET_YES == session->inbound) ? 0 : session->connect_alen);
1805 if (delay.value == 0)
1806 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1808 session->receive_delay_task =
1809 GNUNET_SCHEDULER_add_delayed (session->plugin->env->sched,
1810 delay, &delayed_done, session);
1815 * Functions with this signature are called whenever a peer
1816 * is disconnected on the network level.
1818 * @param cls closure
1819 * @param client identification of the client
1822 disconnect_notify (void *cls,
1823 struct GNUNET_SERVER_Client *client)
1825 struct Plugin *plugin = cls;
1826 struct Session *session;
1830 session = find_session_by_client (plugin, client);
1831 if (session == NULL)
1832 return; /* unknown, nothing to do */
1834 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1835 "Destroying session of `%4s' with %s (%p) due to network-level disconnect.\n",
1836 GNUNET_i2s (&session->target),
1837 (session->connect_addr != NULL) ?
1838 tcp_address_to_string (session->plugin,
1839 session->connect_addr,
1840 session->connect_alen) : "*",
1843 disconnect_session (session);
1848 * Add the IP of our network interface to the list of
1849 * our external IP addresses.
1851 * @param cls the 'struct Plugin*'
1852 * @param name name of the interface
1853 * @param isDefault do we think this may be our default interface
1854 * @param addr address of the interface
1855 * @param addrlen number of bytes in addr
1856 * @return GNUNET_OK to continue iterating
1859 process_interfaces (void *cls,
1862 const struct sockaddr *addr, socklen_t addrlen)
1864 struct Plugin *plugin = cls;
1866 struct IPv4TcpAddress t4;
1867 struct IPv6TcpAddress t6;
1868 struct IPv4TcpAddress t4_nat;
1869 struct IPv6TcpAddress t6_nat;
1873 char buf[INET_ADDRSTRLEN];
1875 af = addr->sa_family;
1879 t4.ipv4_addr = ((struct sockaddr_in *) addr)->sin_addr.s_addr;
1880 GNUNET_assert(NULL != inet_ntop(AF_INET, &t4.ipv4_addr, &buf[0], INET_ADDRSTRLEN));
1881 if ((plugin->bind_address != NULL) && (0 != strcmp(buf, plugin->bind_address)))
1883 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s: Not notifying transport of address %s\n", "TCP", GNUNET_a2s (addr, addrlen));
1886 add_to_address_list (plugin, &t4.ipv4_addr, sizeof (uint32_t));
1887 if ((plugin->behind_nat == GNUNET_YES) && (plugin->only_nat_addresses == GNUNET_YES))
1888 t4.t_port = htons(0);
1889 else if (plugin->behind_nat == GNUNET_YES) /* We are behind NAT, but will advertise NAT and normal addresses */
1891 t4_nat.ipv4_addr = ((struct sockaddr_in *) addr)->sin_addr.s_addr;
1892 t4_nat.t_port = htons(plugin->adv_port);
1896 t4.t_port = htons (plugin->adv_port);
1900 else if (af == AF_INET6)
1902 if ((IN6_IS_ADDR_LINKLOCAL (&((struct sockaddr_in6 *) addr)->sin6_addr)) || (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno(plugin->env->cfg, "transport-tcp", "disablev6")))
1904 /* skip link local addresses */
1907 memcpy (&t6.ipv6_addr,
1908 &((struct sockaddr_in6 *) addr)->sin6_addr,
1909 sizeof (struct in6_addr));
1910 add_to_address_list (plugin, &t6.ipv6_addr, sizeof (struct in6_addr));
1911 if ((plugin->behind_nat == GNUNET_YES) && (plugin->only_nat_addresses == GNUNET_YES))
1912 t6.t6_port = htons(0);
1913 else if (plugin->behind_nat == GNUNET_YES) /* We are behind NAT, but will advertise NAT and normal addresses */
1915 memcpy (&t6_nat.ipv6_addr,
1916 &((struct sockaddr_in6 *) addr)->sin6_addr,
1917 sizeof (struct in6_addr));
1918 t6_nat.t6_port = htons(plugin->adv_port);
1922 t6.t6_port = htons (plugin->adv_port);
1931 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1932 _("Found address `%s' (%s) len %d\n"),
1933 GNUNET_a2s (addr, addrlen), name, args);
1935 plugin->env->notify_address (plugin->env->cls,
1937 arg, args, GNUNET_TIME_UNIT_FOREVER_REL);
1939 if (arg_nat != NULL)
1941 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1942 _("Found address `%s' (%s) len %d\n"),
1943 GNUNET_a2s (addr, addrlen), name, args);
1944 plugin->env->notify_address (plugin->env->cls,
1946 arg_nat, args, GNUNET_TIME_UNIT_FOREVER_REL);
1954 * Function called by the resolver for each address obtained from DNS
1955 * for our own hostname. Add the addresses to the list of our
1956 * external IP addresses.
1958 * @param cls closure
1959 * @param addr one of the addresses of the host, NULL for the last address
1960 * @param addrlen length of the address
1963 process_hostname_ips (void *cls,
1964 const struct sockaddr *addr, socklen_t addrlen)
1966 struct Plugin *plugin = cls;
1970 plugin->hostname_dns = NULL;
1973 /* FIXME: Can we figure out our external address here so it doesn't need to be user specified? */
1974 process_interfaces (plugin, "<hostname>", GNUNET_YES, addr, addrlen);
1978 * We can now send a probe message, copy into buffer to really send.
1980 * @param cls closure, a struct TCPProbeContext
1981 * @param size max size to copy
1982 * @param buf buffer to copy message to
1984 static size_t notify_send_probe (void *cls,
1985 size_t size, void *buf)
1987 struct TCPProbeContext *tcp_probe_ctx = cls;
1994 GNUNET_assert(size >= sizeof(tcp_probe_ctx->message));
1995 memcpy(buf, &tcp_probe_ctx->message, sizeof(tcp_probe_ctx->message));
1996 GNUNET_SERVER_connect_socket (tcp_probe_ctx->plugin->server,
1997 tcp_probe_ctx->sock);
1999 GNUNET_free(tcp_probe_ctx);
2000 return sizeof(tcp_probe_ctx->message);
2004 * @param cls the plugin handle
2005 * @param tc the scheduling context (for rescheduling this function again)
2007 * We have been notified that gnunet-nat-server has written something to stdout.
2008 * Handle the output, then reschedule this function to be called again once
2009 * more is available.
2013 tcp_plugin_server_read (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2015 struct Plugin *plugin = cls;
2018 memset(&mybuf, 0, sizeof(mybuf));
2022 struct sockaddr_in in_addr;
2023 struct TCPProbeContext *tcp_probe_ctx;
2024 struct GNUNET_CONNECTION_Handle *sock;
2026 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
2029 bytes = GNUNET_DISK_file_read(plugin->server_stdout_handle, &mybuf, sizeof(mybuf));
2034 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2035 _("Finished reading from server stdout with code: %d\n"), bytes);
2041 for (i = 0; i < sizeof(mybuf); i++)
2043 if (mybuf[i] == '\n')
2046 if ((mybuf[i] == ':') && (i + 1 < sizeof(mybuf)))
2049 port_start = &mybuf[i + 1];
2053 if (port_start != NULL)
2054 port = atoi(port_start);
2057 plugin->server_read_task =
2058 GNUNET_SCHEDULER_add_read_file (plugin->env->sched,
2059 GNUNET_TIME_UNIT_FOREVER_REL,
2060 plugin->server_stdout_handle, &tcp_plugin_server_read, plugin);
2065 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2066 _("nat-server-read read: %s port %d\n"), &mybuf, port);
2070 if (inet_pton(AF_INET, &mybuf[0], &in_addr.sin_addr) != 1)
2073 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2074 _("nat-server-read malformed address\n"), &mybuf, port);
2076 plugin->server_read_task =
2077 GNUNET_SCHEDULER_add_read_file (plugin->env->sched,
2078 GNUNET_TIME_UNIT_FOREVER_REL,
2079 plugin->server_stdout_handle, &tcp_plugin_server_read, plugin);
2083 in_addr.sin_family = AF_INET;
2084 in_addr.sin_port = htons(port);
2086 * We have received an ICMP response, ostensibly from a non-NAT'd peer
2087 * that wants to connect to us! Send a message to establish a connection.
2089 sock = GNUNET_CONNECTION_create_from_sockaddr (plugin->env->sched, AF_INET, (struct sockaddr *)&in_addr,
2095 plugin->server_read_task =
2096 GNUNET_SCHEDULER_add_read_file (plugin->env->sched,
2097 GNUNET_TIME_UNIT_FOREVER_REL,
2098 plugin->server_stdout_handle, &tcp_plugin_server_read, plugin);
2103 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2104 _("Sending TCP probe message!\n"), &mybuf, port);
2106 tcp_probe_ctx = GNUNET_malloc(sizeof(struct TCPProbeContext));
2107 tcp_probe_ctx->message.header.size = htons(sizeof(struct TCP_NAT_ProbeMessage));
2108 tcp_probe_ctx->message.header.type = htons(GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE);
2109 memcpy(&tcp_probe_ctx->message.clientIdentity, plugin->env->my_identity, sizeof(struct GNUNET_PeerIdentity));
2110 tcp_probe_ctx->plugin = plugin;
2111 tcp_probe_ctx->sock = sock;
2112 tcp_probe_ctx->transmit_handle = GNUNET_CONNECTION_notify_transmit_ready (sock,
2113 ntohs(tcp_probe_ctx->message.header.size),
2114 GNUNET_TIME_UNIT_FOREVER_REL,
2115 ¬ify_send_probe, tcp_probe_ctx);
2119 /*GNUNET_SERVER_connect_socket(plugin->server, sock);*/
2120 plugin->server_read_task =
2121 GNUNET_SCHEDULER_add_read_file (plugin->env->sched,
2122 GNUNET_TIME_UNIT_FOREVER_REL,
2123 plugin->server_stdout_handle, &tcp_plugin_server_read, plugin);
2127 * Start the gnunet-nat-server process for users behind NAT.
2129 * @param plugin the transport plugin
2131 * @return GNUNET_YES if process was started, GNUNET_SYSERR on error
2134 tcp_transport_start_nat_server(struct Plugin *plugin)
2137 plugin->server_stdout = GNUNET_DISK_pipe(GNUNET_YES);
2138 if (plugin->server_stdout == NULL)
2139 return GNUNET_SYSERR;
2142 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2143 "Starting gnunet-nat-server process cmd: %s %s\n", "gnunet-nat-server", plugin->internal_address);
2145 /* Start the server process */
2146 plugin->server_pid = GNUNET_OS_start_process(NULL, plugin->server_stdout, "gnunet-nat-server", "gnunet-nat-server", plugin->internal_address, NULL);
2147 if (plugin->server_pid == GNUNET_SYSERR)
2150 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2151 "Failed to start gnunet-nat-server process\n");
2153 return GNUNET_SYSERR;
2155 /* Close the write end of the read pipe */
2156 GNUNET_DISK_pipe_close_end(plugin->server_stdout, GNUNET_DISK_PIPE_END_WRITE);
2158 plugin->server_stdout_handle = GNUNET_DISK_pipe_handle(plugin->server_stdout, GNUNET_DISK_PIPE_END_READ);
2159 plugin->server_read_task =
2160 GNUNET_SCHEDULER_add_read_file (plugin->env->sched,
2161 GNUNET_TIME_UNIT_FOREVER_REL,
2162 plugin->server_stdout_handle, &tcp_plugin_server_read, plugin);
2167 * Return the actual path to a file found in the current
2168 * PATH environment variable.
2170 * @param binary the name of the file to find
2173 get_path_from_PATH (char *binary)
2181 p = getenv ("PATH");
2184 path = GNUNET_strdup (p); /* because we write on it */
2185 buf = GNUNET_malloc (strlen (path) + 20);
2188 while (NULL != (end = strchr (pos, ':')))
2191 sprintf (buf, "%s/%s", pos, binary);
2192 if (GNUNET_DISK_file_test (buf) == GNUNET_YES)
2199 sprintf (buf, "%s/%s", pos, binary);
2200 if (GNUNET_DISK_file_test (buf) == GNUNET_YES)
2211 * Check whether the suid bit is set on a file.
2212 * Attempts to find the file using the current
2213 * PATH environment variable as a search path.
2215 * @param binary the name of the file to check
2218 check_gnunet_nat_binary(char *binary)
2220 struct stat statbuf;
2223 p = get_path_from_PATH (binary);
2226 if (0 != STAT (p, &statbuf))
2229 return GNUNET_SYSERR;
2232 if ( (0 != (statbuf.st_mode & S_ISUID)) &&
2233 (statbuf.st_uid == 0) )
2239 * Entry point for the plugin.
2241 * @param cls closure, the 'struct GNUNET_TRANSPORT_PluginEnvironment*'
2242 * @return the 'struct GNUNET_TRANSPORT_PluginFunctions*' or NULL on error
2245 libgnunet_plugin_transport_tcp_init (void *cls)
2247 static const struct GNUNET_SERVER_MessageHandler my_handlers[] = {
2248 {&handle_tcp_welcome, NULL, GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME,
2249 sizeof (struct WelcomeMessage)},
2250 {&handle_tcp_nat_probe, NULL, GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE, sizeof (struct TCP_NAT_ProbeMessage)},
2251 {&handle_tcp_data, NULL, GNUNET_MESSAGE_TYPE_ALL, 0},
2254 struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
2255 struct GNUNET_TRANSPORT_PluginFunctions *api;
2256 struct Plugin *plugin;
2257 struct GNUNET_SERVICE_Context *service;
2258 unsigned long long aport;
2259 unsigned long long bport;
2263 int only_nat_addresses;
2264 char *internal_address;
2265 char *external_address;
2266 struct sockaddr_in in_addr;
2267 struct IPv4TcpAddress t4;
2269 service = GNUNET_SERVICE_start ("transport-tcp", env->sched, env->cfg);
2270 if (service == NULL)
2272 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2273 _("Failed to start service for `%s' transport plugin.\n"),
2278 if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno (env->cfg,
2282 /* We are behind nat (according to the user) */
2283 if (check_gnunet_nat_binary("gnunet-nat-server") == GNUNET_YES)
2285 behind_nat = GNUNET_YES;
2289 behind_nat = GNUNET_NO;
2290 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Configuration specified you are behind a NAT, but gnunet-nat-server is not installed properly (suid bit not set)!\n");
2294 behind_nat = GNUNET_NO; /* We are not behind nat! */
2296 if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno (env->cfg,
2300 if (check_gnunet_nat_binary("gnunet-nat-client") == GNUNET_YES)
2301 allow_nat = GNUNET_YES; /* We will try to connect to NAT'd peers */
2304 allow_nat = GNUNET_NO;
2305 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Configuration specified you want to connect to NAT'd peers, but gnunet-nat-client is not installed properly (suid bit not set)!\n");
2309 allow_nat = GNUNET_NO; /* We don't want to try to help NAT'd peers */
2312 if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno (env->cfg,
2314 "ONLY_NAT_ADDRESSES"))
2315 only_nat_addresses = GNUNET_YES; /* We will only report our addresses as NAT'd */
2317 only_nat_addresses = GNUNET_NO; /* We will report our addresses as NAT'd and non-NAT'd */
2319 external_address = NULL;
2320 if (((GNUNET_YES == behind_nat) || (GNUNET_YES == allow_nat)) && (GNUNET_OK !=
2321 GNUNET_CONFIGURATION_get_value_string (env->cfg,
2324 &external_address)))
2326 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2328 ("Require EXTERNAL_ADDRESS for service `%s' in configuration (either BEHIND_NAT or ALLOW_NAT set to YES)!\n"),
2330 GNUNET_SERVICE_stop (service);
2334 if ((external_address != NULL) && (inet_pton(AF_INET, external_address, &in_addr.sin_addr) != 1))
2336 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Malformed EXTERNAL_ADDRESS %s given in configuration!\n", external_address);
2339 internal_address = NULL;
2340 if ((GNUNET_YES == behind_nat) && (GNUNET_OK !=
2341 GNUNET_CONFIGURATION_get_value_string (env->cfg,
2344 &internal_address)))
2346 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2347 _("Require INTERNAL_ADDRESS for service `%s' in configuration!\n"),
2349 GNUNET_SERVICE_stop (service);
2350 GNUNET_free_non_null(external_address);
2354 if ((internal_address != NULL) && (inet_pton(AF_INET, internal_address, &in_addr.sin_addr) != 1))
2356 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Malformed INTERNAL_ADDRESS %s given in configuration!\n", internal_address);
2361 GNUNET_CONFIGURATION_get_value_number (env->cfg,
2367 GNUNET_CONFIGURATION_get_value_number (env->cfg,
2370 &aport)) && (aport > 65535)))
2372 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2374 ("Require valid port number for service `%s' in configuration!\n"),
2376 GNUNET_free_non_null(external_address);
2377 GNUNET_free_non_null(internal_address);
2378 GNUNET_SERVICE_stop (service);
2384 plugin = GNUNET_malloc (sizeof (struct Plugin));
2385 plugin->open_port = bport;
2386 plugin->adv_port = aport;
2387 plugin->external_address = external_address;
2388 plugin->internal_address = internal_address;
2389 plugin->behind_nat = behind_nat;
2390 plugin->allow_nat = allow_nat;
2391 plugin->only_nat_addresses = only_nat_addresses;
2393 plugin->lsock = NULL;
2394 api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
2396 api->send = &tcp_plugin_send;
2397 api->disconnect = &tcp_plugin_disconnect;
2398 api->address_pretty_printer = &tcp_plugin_address_pretty_printer;
2399 api->check_address = &tcp_plugin_check_address;
2400 api->address_to_string = &tcp_address_to_string;
2401 plugin->service = service;
2402 plugin->server = GNUNET_SERVICE_get_server (service);
2403 plugin->handlers = GNUNET_malloc (sizeof (my_handlers));
2404 memcpy (plugin->handlers, my_handlers, sizeof (my_handlers));
2407 sizeof (my_handlers) / sizeof (struct GNUNET_SERVER_MessageHandler);
2409 plugin->handlers[i].callback_cls = plugin;
2410 GNUNET_SERVER_add_handlers (plugin->server, plugin->handlers);
2412 if (plugin->behind_nat == GNUNET_YES)
2414 if (GNUNET_YES != tcp_transport_start_nat_server(plugin))
2416 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2419 ("Failed to start %s required for NAT in %s!\n"),
2422 GNUNET_free_non_null(external_address);
2423 GNUNET_free_non_null(internal_address);
2424 GNUNET_SERVICE_stop (service);
2430 if (allow_nat == GNUNET_YES)
2432 plugin->nat_wait_conns = GNUNET_CONTAINER_multihashmap_create(100);
2433 GNUNET_assert(plugin->nat_wait_conns != NULL);
2436 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _("TCP transport listening on port %llu\n"), bport);
2438 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2439 _("TCP transport advertises itself as being on port %llu\n"),
2441 GNUNET_SERVER_disconnect_notify (plugin->server,
2444 GNUNET_CONFIGURATION_get_value_string(env->cfg, "transport-tcp", "BINDTO", &plugin->bind_address);
2446 if (plugin->behind_nat == GNUNET_NO)
2448 GNUNET_OS_network_interfaces_list (&process_interfaces, plugin);
2451 plugin->hostname_dns = GNUNET_RESOLVER_hostname_resolve (env->sched,
2454 HOSTNAME_RESOLVE_TIMEOUT,
2455 &process_hostname_ips,
2458 if ((plugin->behind_nat == GNUNET_YES) && (inet_pton(AF_INET, plugin->external_address, &t4.ipv4_addr) == 1))
2460 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Notifying transport of address %s:0\n", plugin->external_address);
2461 t4.t_port = htons(0);
2462 add_to_address_list (plugin, &t4.ipv4_addr, sizeof (uint32_t));
2463 plugin->env->notify_address (plugin->env->cls,
2465 &t4, sizeof(t4), GNUNET_TIME_UNIT_FOREVER_REL);
2467 else if ((plugin->external_address != NULL) && (inet_pton(AF_INET, plugin->external_address, &t4.ipv4_addr) == 1))
2469 t4.t_port = htons(plugin->adv_port);
2470 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Notifying transport of address %s:%d\n", plugin->external_address, plugin->adv_port);
2471 add_to_address_list (plugin, &t4.ipv4_addr, sizeof (uint32_t));
2472 plugin->env->notify_address (plugin->env->cls,
2474 &t4, sizeof(t4), GNUNET_TIME_UNIT_FOREVER_REL);
2482 * Exit point from the plugin.
2485 libgnunet_plugin_transport_tcp_done (void *cls)
2487 struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
2488 struct Plugin *plugin = api->cls;
2489 struct Session *session;
2490 struct LocalAddrList *lal;
2492 while (NULL != (session = plugin->sessions))
2493 disconnect_session (session);
2494 if (NULL != plugin->hostname_dns)
2496 GNUNET_RESOLVER_request_cancel (plugin->hostname_dns);
2497 plugin->hostname_dns = NULL;
2499 GNUNET_SERVICE_stop (plugin->service);
2500 GNUNET_free (plugin->handlers);
2501 while (NULL != (lal = plugin->lal_head))
2503 GNUNET_CONTAINER_DLL_remove (plugin->lal_head,
2509 if (plugin->behind_nat == GNUNET_YES)
2511 if (0 != PLIBC_KILL (plugin->server_pid, SIGTERM))
2512 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "kill");
2513 GNUNET_OS_process_wait (plugin->server_pid);
2515 GNUNET_free_non_null(plugin->bind_address);
2516 GNUNET_free (plugin);
2521 /* end of plugin_transport_tcp.c */