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 /* FIXME: Should this be inbound or outbound?
1577 * I think it should be outbound because we technically
1578 * initiated it... But something goes wrong somewhere. */
1579 /* session->inbound = GNUNET_YES; */
1580 session->inbound = GNUNET_YES;
1583 GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
1586 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1587 "Found address `%s' for incoming connection %p\n",
1588 GNUNET_a2s (vaddr, alen),
1591 if (((const struct sockaddr *)vaddr)->sa_family == AF_INET)
1594 t4 = GNUNET_malloc (sizeof (struct IPv4TcpAddress));
1595 t4->t_port = s4->sin_port;
1596 t4->ipv4_addr = s4->sin_addr.s_addr;
1597 session->connect_addr = t4;
1598 session->connect_alen = sizeof (struct IPv4TcpAddress);
1600 else if (((const struct sockaddr *)vaddr)->sa_family == AF_INET6)
1603 t6 = GNUNET_malloc (sizeof (struct IPv6TcpAddress));
1604 t6->t6_port = s6->sin6_port;
1605 memcpy (&t6->ipv6_addr,
1607 sizeof (struct in6_addr));
1608 session->connect_addr = t6;
1609 session->connect_alen = sizeof (struct IPv6TcpAddress);
1614 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1615 "Bad address for incoming connection!\n");
1618 GNUNET_free (vaddr);
1621 session->next = plugin->sessions;
1622 plugin->sessions = session;
1623 GNUNET_STATISTICS_update (plugin->env->stats,
1624 gettext_noop ("# TCP sessions active"),
1627 process_pending_messages (session);
1632 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Did NOT find session for NAT probe!\n");
1636 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1640 * We've received a welcome from this peer via TCP. Possibly create a
1641 * fresh client record and send back our welcome.
1643 * @param cls closure
1644 * @param client identification of the client
1645 * @param message the actual message
1648 handle_tcp_welcome (void *cls,
1649 struct GNUNET_SERVER_Client *client,
1650 const struct GNUNET_MessageHeader *message)
1652 struct Plugin *plugin = cls;
1653 const struct WelcomeMessage *wm = (const struct WelcomeMessage *) message;
1654 struct Session *session;
1657 struct IPv4TcpAddress *t4;
1658 struct IPv6TcpAddress *t6;
1659 const struct sockaddr_in *s4;
1660 const struct sockaddr_in6 *s6;
1663 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1664 "Received %s message from a `%4s/%p'.\n",
1666 GNUNET_i2s (&wm->clientIdentity), client);
1668 GNUNET_STATISTICS_update (plugin->env->stats,
1669 gettext_noop ("# TCP WELCOME messages received"),
1672 session = find_session_by_client (plugin, client);
1673 if (session == NULL)
1675 GNUNET_SERVER_client_keep (client);
1676 session = create_session (plugin,
1677 &wm->clientIdentity, client, GNUNET_NO);
1678 session->inbound = GNUNET_YES;
1680 GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
1683 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1684 "Found address `%s' for incoming connection %p\n",
1685 GNUNET_a2s (vaddr, alen),
1688 if (alen == sizeof (struct sockaddr_in))
1691 t4 = GNUNET_malloc (sizeof (struct IPv4TcpAddress));
1692 t4->t_port = s4->sin_port;
1693 t4->ipv4_addr = s4->sin_addr.s_addr;
1694 session->connect_addr = t4;
1695 session->connect_alen = sizeof (struct IPv4TcpAddress);
1697 else if (alen == sizeof (struct sockaddr_in6))
1700 t6 = GNUNET_malloc (sizeof (struct IPv6TcpAddress));
1701 t6->t6_port = s6->sin6_port;
1702 memcpy (&t6->ipv6_addr,
1704 sizeof (struct in6_addr));
1705 session->connect_addr = t6;
1706 session->connect_alen = sizeof (struct IPv6TcpAddress);
1708 GNUNET_free (vaddr);
1713 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1714 "Did not obtain TCP socket address for incoming connection\n");
1718 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1719 "Creating new session %p for connection %p\n",
1722 process_pending_messages (session);
1724 if (session->expecting_welcome != GNUNET_YES)
1726 GNUNET_break_op (0);
1727 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1730 session->last_activity = GNUNET_TIME_absolute_get ();
1731 session->expecting_welcome = GNUNET_NO;
1732 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1737 * Task to signal the server that we can continue
1738 * receiving from the TCP client now.
1740 * @param cls the 'struct Session*'
1741 * @param tc task context (unused)
1744 delayed_done (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1746 struct Session *session = cls;
1747 struct GNUNET_TIME_Relative delay;
1749 session->receive_delay_task = GNUNET_SCHEDULER_NO_TASK;
1750 delay = session->plugin->env->receive (session->plugin->env->cls,
1755 if (delay.value == 0)
1756 GNUNET_SERVER_receive_done (session->client, GNUNET_OK);
1758 session->receive_delay_task =
1759 GNUNET_SCHEDULER_add_delayed (session->plugin->env->sched,
1760 delay, &delayed_done, session);
1765 * We've received data for this peer via TCP. Unbox,
1766 * compute latency and forward.
1768 * @param cls closure
1769 * @param client identification of the client
1770 * @param message the actual message
1773 handle_tcp_data (void *cls,
1774 struct GNUNET_SERVER_Client *client,
1775 const struct GNUNET_MessageHeader *message)
1777 struct Plugin *plugin = cls;
1778 struct Session *session;
1779 struct GNUNET_TIME_Relative delay;
1781 if ((GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME == ntohs(message->type)) || (ntohs(message->type) == GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE))
1783 /* We don't want to propagate WELCOME and NAT Probe messages up! */
1784 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1787 session = find_session_by_client (plugin, client);
1788 if ( (NULL == session) || (GNUNET_YES == session->expecting_welcome))
1790 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1793 session->last_activity = GNUNET_TIME_absolute_get ();
1795 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1796 "Passing %u bytes of type %u from `%4s' to transport service.\n",
1797 (unsigned int) ntohs (message->size),
1798 (unsigned int) ntohs (message->type),
1799 GNUNET_i2s (&session->target));
1801 GNUNET_STATISTICS_update (plugin->env->stats,
1802 gettext_noop ("# bytes received via TCP"),
1803 ntohs (message->size),
1805 delay = plugin->env->receive (plugin->env->cls, &session->target, message, 1,
1807 (GNUNET_YES == session->inbound) ? NULL : session->connect_addr,
1808 (GNUNET_YES == session->inbound) ? 0 : session->connect_alen);
1809 if (delay.value == 0)
1810 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1812 session->receive_delay_task =
1813 GNUNET_SCHEDULER_add_delayed (session->plugin->env->sched,
1814 delay, &delayed_done, session);
1819 * Functions with this signature are called whenever a peer
1820 * is disconnected on the network level.
1822 * @param cls closure
1823 * @param client identification of the client
1826 disconnect_notify (void *cls,
1827 struct GNUNET_SERVER_Client *client)
1829 struct Plugin *plugin = cls;
1830 struct Session *session;
1834 session = find_session_by_client (plugin, client);
1835 if (session == NULL)
1836 return; /* unknown, nothing to do */
1838 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1839 "Destroying session of `%4s' with %s (%p) due to network-level disconnect.\n",
1840 GNUNET_i2s (&session->target),
1841 (session->connect_addr != NULL) ?
1842 tcp_address_to_string (session->plugin,
1843 session->connect_addr,
1844 session->connect_alen) : "*",
1847 disconnect_session (session);
1852 * Add the IP of our network interface to the list of
1853 * our external IP addresses.
1855 * @param cls the 'struct Plugin*'
1856 * @param name name of the interface
1857 * @param isDefault do we think this may be our default interface
1858 * @param addr address of the interface
1859 * @param addrlen number of bytes in addr
1860 * @return GNUNET_OK to continue iterating
1863 process_interfaces (void *cls,
1866 const struct sockaddr *addr, socklen_t addrlen)
1868 struct Plugin *plugin = cls;
1870 struct IPv4TcpAddress t4;
1871 struct IPv6TcpAddress t6;
1872 struct IPv4TcpAddress t4_nat;
1873 struct IPv6TcpAddress t6_nat;
1877 char buf[INET_ADDRSTRLEN];
1879 af = addr->sa_family;
1883 t4.ipv4_addr = ((struct sockaddr_in *) addr)->sin_addr.s_addr;
1884 GNUNET_assert(NULL != inet_ntop(AF_INET, &t4.ipv4_addr, &buf[0], INET_ADDRSTRLEN));
1885 if ((plugin->bind_address != NULL) && (0 != strcmp(buf, plugin->bind_address)))
1887 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s: Not notifying transport of address %s\n", "TCP", GNUNET_a2s (addr, addrlen));
1890 add_to_address_list (plugin, &t4.ipv4_addr, sizeof (uint32_t));
1891 if ((plugin->behind_nat == GNUNET_YES) && (plugin->only_nat_addresses == GNUNET_YES))
1892 t4.t_port = htons(0);
1893 else if (plugin->behind_nat == GNUNET_YES) /* We are behind NAT, but will advertise NAT and normal addresses */
1895 t4_nat.ipv4_addr = ((struct sockaddr_in *) addr)->sin_addr.s_addr;
1896 t4_nat.t_port = htons(plugin->adv_port);
1900 t4.t_port = htons (plugin->adv_port);
1904 else if (af == AF_INET6)
1906 if ((IN6_IS_ADDR_LINKLOCAL (&((struct sockaddr_in6 *) addr)->sin6_addr)) || (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno(plugin->env->cfg, "transport-tcp", "disablev6")))
1908 /* skip link local addresses */
1911 memcpy (&t6.ipv6_addr,
1912 &((struct sockaddr_in6 *) addr)->sin6_addr,
1913 sizeof (struct in6_addr));
1914 add_to_address_list (plugin, &t6.ipv6_addr, sizeof (struct in6_addr));
1915 if ((plugin->behind_nat == GNUNET_YES) && (plugin->only_nat_addresses == GNUNET_YES))
1916 t6.t6_port = htons(0);
1917 else if (plugin->behind_nat == GNUNET_YES) /* We are behind NAT, but will advertise NAT and normal addresses */
1919 memcpy (&t6_nat.ipv6_addr,
1920 &((struct sockaddr_in6 *) addr)->sin6_addr,
1921 sizeof (struct in6_addr));
1922 t6_nat.t6_port = htons(plugin->adv_port);
1926 t6.t6_port = htons (plugin->adv_port);
1935 GNUNET_log (GNUNET_ERROR_TYPE_INFO |
1936 GNUNET_ERROR_TYPE_BULK,
1937 _("Found address `%s' (%s)\n"),
1938 GNUNET_a2s (addr, addrlen), name);
1940 plugin->env->notify_address (plugin->env->cls,
1942 arg, args, GNUNET_TIME_UNIT_FOREVER_REL);
1944 if (arg_nat != NULL)
1946 GNUNET_log (GNUNET_ERROR_TYPE_INFO |
1947 GNUNET_ERROR_TYPE_BULK,
1948 _("Found address `%s' (%s)\n"),
1949 GNUNET_a2s (addr, addrlen), name);
1950 plugin->env->notify_address (plugin->env->cls,
1952 arg_nat, args, GNUNET_TIME_UNIT_FOREVER_REL);
1960 * Function called by the resolver for each address obtained from DNS
1961 * for our own hostname. Add the addresses to the list of our
1962 * external IP addresses.
1964 * @param cls closure
1965 * @param addr one of the addresses of the host, NULL for the last address
1966 * @param addrlen length of the address
1969 process_hostname_ips (void *cls,
1970 const struct sockaddr *addr, socklen_t addrlen)
1972 struct Plugin *plugin = cls;
1976 plugin->hostname_dns = NULL;
1979 /* FIXME: Can we figure out our external address here so it doesn't need to be user specified? */
1980 process_interfaces (plugin, "<hostname>", GNUNET_YES, addr, addrlen);
1984 * We can now send a probe message, copy into buffer to really send.
1986 * @param cls closure, a struct TCPProbeContext
1987 * @param size max size to copy
1988 * @param buf buffer to copy message to
1990 static size_t notify_send_probe (void *cls,
1991 size_t size, void *buf)
1993 struct TCPProbeContext *tcp_probe_ctx = cls;
2000 GNUNET_assert(size >= sizeof(tcp_probe_ctx->message));
2001 memcpy(buf, &tcp_probe_ctx->message, sizeof(tcp_probe_ctx->message));
2002 GNUNET_SERVER_connect_socket (tcp_probe_ctx->plugin->server,
2003 tcp_probe_ctx->sock);
2005 GNUNET_free(tcp_probe_ctx);
2006 return sizeof(tcp_probe_ctx->message);
2010 * @param cls the plugin handle
2011 * @param tc the scheduling context (for rescheduling this function again)
2013 * We have been notified that gnunet-nat-server has written something to stdout.
2014 * Handle the output, then reschedule this function to be called again once
2015 * more is available.
2019 tcp_plugin_server_read (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2021 struct Plugin *plugin = cls;
2024 memset(&mybuf, 0, sizeof(mybuf));
2028 struct sockaddr_in in_addr;
2029 struct TCPProbeContext *tcp_probe_ctx;
2030 struct GNUNET_CONNECTION_Handle *sock;
2032 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
2035 bytes = GNUNET_DISK_file_read(plugin->server_stdout_handle, &mybuf, sizeof(mybuf));
2040 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2041 _("Finished reading from server stdout with code: %d\n"), bytes);
2048 for (i = 0; i < sizeof(mybuf); i++)
2050 if (mybuf[i] == '\n')
2053 if ((mybuf[i] == ':') && (i + 1 < sizeof(mybuf)))
2056 port_start = &mybuf[i + 1];
2060 if (port_start != NULL)
2061 port = atoi(port_start);
2064 plugin->server_read_task =
2065 GNUNET_SCHEDULER_add_read_file (plugin->env->sched,
2066 GNUNET_TIME_UNIT_FOREVER_REL,
2067 plugin->server_stdout_handle, &tcp_plugin_server_read, plugin);
2072 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2073 _("nat-server-read read: %s port %d\n"), &mybuf, port);
2077 if (inet_pton(AF_INET, &mybuf[0], &in_addr.sin_addr) != 1)
2080 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2081 _("nat-server-read malformed address\n"), &mybuf, port);
2083 plugin->server_read_task =
2084 GNUNET_SCHEDULER_add_read_file (plugin->env->sched,
2085 GNUNET_TIME_UNIT_FOREVER_REL,
2086 plugin->server_stdout_handle, &tcp_plugin_server_read, plugin);
2090 in_addr.sin_family = AF_INET;
2091 in_addr.sin_port = htons(port);
2093 * We have received an ICMP response, ostensibly from a non-NAT'd peer
2094 * that wants to connect to us! Send a message to establish a connection.
2096 sock = GNUNET_CONNECTION_create_from_sockaddr (plugin->env->sched, AF_INET, (struct sockaddr *)&in_addr,
2102 plugin->server_read_task =
2103 GNUNET_SCHEDULER_add_read_file (plugin->env->sched,
2104 GNUNET_TIME_UNIT_FOREVER_REL,
2105 plugin->server_stdout_handle, &tcp_plugin_server_read, plugin);
2110 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2111 _("Sending TCP probe message!\n"), &mybuf, port);
2113 tcp_probe_ctx = GNUNET_malloc(sizeof(struct TCPProbeContext));
2114 tcp_probe_ctx->message.header.size = htons(sizeof(struct TCP_NAT_ProbeMessage));
2115 tcp_probe_ctx->message.header.type = htons(GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE);
2116 memcpy(&tcp_probe_ctx->message.clientIdentity, plugin->env->my_identity, sizeof(struct GNUNET_PeerIdentity));
2117 tcp_probe_ctx->plugin = plugin;
2118 tcp_probe_ctx->sock = sock;
2119 tcp_probe_ctx->transmit_handle = GNUNET_CONNECTION_notify_transmit_ready (sock,
2120 ntohs(tcp_probe_ctx->message.header.size),
2121 GNUNET_TIME_UNIT_FOREVER_REL,
2122 ¬ify_send_probe, tcp_probe_ctx);
2126 /*GNUNET_SERVER_connect_socket(plugin->server, sock);*/
2127 plugin->server_read_task =
2128 GNUNET_SCHEDULER_add_read_file (plugin->env->sched,
2129 GNUNET_TIME_UNIT_FOREVER_REL,
2130 plugin->server_stdout_handle, &tcp_plugin_server_read, plugin);
2134 * Start the gnunet-nat-server process for users behind NAT.
2136 * @param plugin the transport plugin
2138 * @return GNUNET_YES if process was started, GNUNET_SYSERR on error
2141 tcp_transport_start_nat_server(struct Plugin *plugin)
2144 plugin->server_stdout = GNUNET_DISK_pipe(GNUNET_YES);
2145 if (plugin->server_stdout == NULL)
2146 return GNUNET_SYSERR;
2149 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2150 "Starting gnunet-nat-server process cmd: %s %s\n", "gnunet-nat-server", plugin->internal_address);
2152 /* Start the server process */
2153 plugin->server_pid = GNUNET_OS_start_process(NULL, plugin->server_stdout, "gnunet-nat-server", "gnunet-nat-server", plugin->internal_address, NULL);
2154 if (plugin->server_pid == GNUNET_SYSERR)
2157 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2158 "Failed to start gnunet-nat-server process\n");
2160 return GNUNET_SYSERR;
2162 /* Close the write end of the read pipe */
2163 GNUNET_DISK_pipe_close_end(plugin->server_stdout, GNUNET_DISK_PIPE_END_WRITE);
2165 plugin->server_stdout_handle = GNUNET_DISK_pipe_handle(plugin->server_stdout, GNUNET_DISK_PIPE_END_READ);
2166 plugin->server_read_task =
2167 GNUNET_SCHEDULER_add_read_file (plugin->env->sched,
2168 GNUNET_TIME_UNIT_FOREVER_REL,
2169 plugin->server_stdout_handle, &tcp_plugin_server_read, plugin);
2174 * Return the actual path to a file found in the current
2175 * PATH environment variable.
2177 * @param binary the name of the file to find
2180 get_path_from_PATH (char *binary)
2188 p = getenv ("PATH");
2191 path = GNUNET_strdup (p); /* because we write on it */
2192 buf = GNUNET_malloc (strlen (path) + 20);
2195 while (NULL != (end = strchr (pos, ':')))
2198 sprintf (buf, "%s/%s", pos, binary);
2199 if (GNUNET_DISK_file_test (buf) == GNUNET_YES)
2206 sprintf (buf, "%s/%s", pos, binary);
2207 if (GNUNET_DISK_file_test (buf) == GNUNET_YES)
2218 * Check whether the suid bit is set on a file.
2219 * Attempts to find the file using the current
2220 * PATH environment variable as a search path.
2222 * @param binary the name of the file to check
2225 check_gnunet_nat_binary(char *binary)
2227 struct stat statbuf;
2230 p = get_path_from_PATH (binary);
2233 if (0 != STAT (p, &statbuf))
2236 return GNUNET_SYSERR;
2239 if ( (0 != (statbuf.st_mode & S_ISUID)) &&
2240 (statbuf.st_uid == 0) )
2246 * Entry point for the plugin.
2248 * @param cls closure, the 'struct GNUNET_TRANSPORT_PluginEnvironment*'
2249 * @return the 'struct GNUNET_TRANSPORT_PluginFunctions*' or NULL on error
2252 libgnunet_plugin_transport_tcp_init (void *cls)
2254 static const struct GNUNET_SERVER_MessageHandler my_handlers[] = {
2255 {&handle_tcp_welcome, NULL, GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME,
2256 sizeof (struct WelcomeMessage)},
2257 {&handle_tcp_nat_probe, NULL, GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE, sizeof (struct TCP_NAT_ProbeMessage)},
2258 {&handle_tcp_data, NULL, GNUNET_MESSAGE_TYPE_ALL, 0},
2261 struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
2262 struct GNUNET_TRANSPORT_PluginFunctions *api;
2263 struct Plugin *plugin;
2264 struct GNUNET_SERVICE_Context *service;
2265 unsigned long long aport;
2266 unsigned long long bport;
2270 int only_nat_addresses;
2271 char *internal_address;
2272 char *external_address;
2273 struct sockaddr_in in_addr;
2274 struct IPv4TcpAddress t4;
2276 service = GNUNET_SERVICE_start ("transport-tcp", env->sched, env->cfg);
2277 if (service == NULL)
2279 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2280 _("Failed to start service for `%s' transport plugin.\n"),
2285 if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno (env->cfg,
2289 /* We are behind nat (according to the user) */
2290 if (check_gnunet_nat_binary("gnunet-nat-server") == GNUNET_YES)
2292 behind_nat = GNUNET_YES;
2296 behind_nat = GNUNET_NO;
2297 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");
2301 behind_nat = GNUNET_NO; /* We are not behind nat! */
2303 if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno (env->cfg,
2307 if (check_gnunet_nat_binary("gnunet-nat-client") == GNUNET_YES)
2308 allow_nat = GNUNET_YES; /* We will try to connect to NAT'd peers */
2311 allow_nat = GNUNET_NO;
2312 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");
2316 allow_nat = GNUNET_NO; /* We don't want to try to help NAT'd peers */
2319 if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno (env->cfg,
2321 "ONLY_NAT_ADDRESSES"))
2322 only_nat_addresses = GNUNET_YES; /* We will only report our addresses as NAT'd */
2324 only_nat_addresses = GNUNET_NO; /* We will report our addresses as NAT'd and non-NAT'd */
2326 external_address = NULL;
2327 if (((GNUNET_YES == behind_nat) || (GNUNET_YES == allow_nat)) && (GNUNET_OK !=
2328 GNUNET_CONFIGURATION_get_value_string (env->cfg,
2331 &external_address)))
2333 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2335 ("Require EXTERNAL_ADDRESS for service `%s' in configuration (either BEHIND_NAT or ALLOW_NAT set to YES)!\n"),
2337 GNUNET_SERVICE_stop (service);
2341 if ((external_address != NULL) && (inet_pton(AF_INET, external_address, &in_addr.sin_addr) != 1))
2343 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Malformed EXTERNAL_ADDRESS %s given in configuration!\n", external_address);
2346 internal_address = NULL;
2347 if ((GNUNET_YES == behind_nat) && (GNUNET_OK !=
2348 GNUNET_CONFIGURATION_get_value_string (env->cfg,
2351 &internal_address)))
2353 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2354 _("Require INTERNAL_ADDRESS for service `%s' in configuration!\n"),
2356 GNUNET_SERVICE_stop (service);
2357 GNUNET_free_non_null(external_address);
2361 if ((internal_address != NULL) && (inet_pton(AF_INET, internal_address, &in_addr.sin_addr) != 1))
2363 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Malformed INTERNAL_ADDRESS %s given in configuration!\n", internal_address);
2368 GNUNET_CONFIGURATION_get_value_number (env->cfg,
2374 GNUNET_CONFIGURATION_get_value_number (env->cfg,
2377 &aport)) && (aport > 65535)))
2379 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2381 ("Require valid port number for service `%s' in configuration!\n"),
2383 GNUNET_free_non_null(external_address);
2384 GNUNET_free_non_null(internal_address);
2385 GNUNET_SERVICE_stop (service);
2391 plugin = GNUNET_malloc (sizeof (struct Plugin));
2392 plugin->open_port = bport;
2393 plugin->adv_port = aport;
2394 plugin->external_address = external_address;
2395 plugin->internal_address = internal_address;
2396 plugin->behind_nat = behind_nat;
2397 plugin->allow_nat = allow_nat;
2398 plugin->only_nat_addresses = only_nat_addresses;
2400 plugin->lsock = NULL;
2401 api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
2403 api->send = &tcp_plugin_send;
2404 api->disconnect = &tcp_plugin_disconnect;
2405 api->address_pretty_printer = &tcp_plugin_address_pretty_printer;
2406 api->check_address = &tcp_plugin_check_address;
2407 api->address_to_string = &tcp_address_to_string;
2408 plugin->service = service;
2409 plugin->server = GNUNET_SERVICE_get_server (service);
2410 plugin->handlers = GNUNET_malloc (sizeof (my_handlers));
2411 memcpy (plugin->handlers, my_handlers, sizeof (my_handlers));
2414 sizeof (my_handlers) / sizeof (struct GNUNET_SERVER_MessageHandler);
2416 plugin->handlers[i].callback_cls = plugin;
2417 GNUNET_SERVER_add_handlers (plugin->server, plugin->handlers);
2419 if (plugin->behind_nat == GNUNET_YES)
2421 if (GNUNET_YES != tcp_transport_start_nat_server(plugin))
2423 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2426 ("Failed to start %s required for NAT in %s!\n"),
2429 GNUNET_free_non_null(external_address);
2430 GNUNET_free_non_null(internal_address);
2431 GNUNET_SERVICE_stop (service);
2437 if (allow_nat == GNUNET_YES)
2439 plugin->nat_wait_conns = GNUNET_CONTAINER_multihashmap_create(100);
2440 GNUNET_assert(plugin->nat_wait_conns != NULL);
2443 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _("TCP transport listening on port %llu\n"), bport);
2445 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2446 _("TCP transport advertises itself as being on port %llu\n"),
2448 GNUNET_SERVER_disconnect_notify (plugin->server,
2451 GNUNET_CONFIGURATION_get_value_string(env->cfg, "transport-tcp", "BINDTO", &plugin->bind_address);
2453 if (plugin->behind_nat == GNUNET_NO)
2455 GNUNET_OS_network_interfaces_list (&process_interfaces, plugin);
2458 plugin->hostname_dns = GNUNET_RESOLVER_hostname_resolve (env->sched,
2461 HOSTNAME_RESOLVE_TIMEOUT,
2462 &process_hostname_ips,
2465 if ((plugin->behind_nat == GNUNET_YES) && (inet_pton(AF_INET, plugin->external_address, &t4.ipv4_addr) == 1))
2467 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Notifying transport of address %s:0\n", plugin->external_address);
2468 t4.t_port = htons(0);
2469 add_to_address_list (plugin, &t4.ipv4_addr, sizeof (uint32_t));
2470 plugin->env->notify_address (plugin->env->cls,
2472 &t4, sizeof(t4), GNUNET_TIME_UNIT_FOREVER_REL);
2474 else if ((plugin->external_address != NULL) && (inet_pton(AF_INET, plugin->external_address, &t4.ipv4_addr) == 1))
2476 t4.t_port = htons(plugin->adv_port);
2477 add_to_address_list (plugin, &t4.ipv4_addr, sizeof (uint32_t));
2478 plugin->env->notify_address (plugin->env->cls,
2480 &t4, sizeof(t4), GNUNET_TIME_UNIT_FOREVER_REL);
2488 * Exit point from the plugin.
2491 libgnunet_plugin_transport_tcp_done (void *cls)
2493 struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
2494 struct Plugin *plugin = api->cls;
2495 struct Session *session;
2496 struct LocalAddrList *lal;
2498 while (NULL != (session = plugin->sessions))
2499 disconnect_session (session);
2500 if (NULL != plugin->hostname_dns)
2502 GNUNET_RESOLVER_request_cancel (plugin->hostname_dns);
2503 plugin->hostname_dns = NULL;
2505 GNUNET_SERVICE_stop (plugin->service);
2506 GNUNET_free (plugin->handlers);
2507 while (NULL != (lal = plugin->lal_head))
2509 GNUNET_CONTAINER_DLL_remove (plugin->lal_head,
2515 if (plugin->behind_nat == GNUNET_YES)
2517 if (0 != PLIBC_KILL (plugin->server_pid, SIGTERM))
2518 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "kill");
2519 GNUNET_OS_process_wait (plugin->server_pid);
2521 GNUNET_free_non_null(plugin->bind_address);
2522 GNUNET_free (plugin);
2527 /* end of plugin_transport_tcp.c */