2 This file is part of GNUnet
3 (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 Christian Grothoff (and other contributing authors)
5 GNUnet is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published
7 by the Free Software Foundation; either version 3, or (at your
8 option) any later version.
10 GNUnet is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with GNUnet; see the file COPYING. If not, write to the
17 Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18 Boston, MA 02111-1307, USA.
21 * @file transport/plugin_transport_tcp.c
22 * @brief Implementation of the TCP transport service
23 * @author Christian Grothoff
26 #include "gnunet_hello_lib.h"
27 #include "gnunet_connection_lib.h"
28 #include "gnunet_container_lib.h"
29 #include "gnunet_os_lib.h"
30 #include "gnunet_protocols.h"
31 #include "gnunet_resolver_service.h"
32 #include "gnunet_server_lib.h"
33 #include "gnunet_service_lib.h"
34 #include "gnunet_signatures.h"
35 #include "gnunet_statistics_service.h"
36 #include "gnunet_transport_service.h"
37 #include "plugin_transport.h"
38 #include "transport.h"
40 #define DEBUG_TCP GNUNET_NO
41 #define DEBUG_TCP_NAT GNUNET_NO
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 * List of our IP addresses.
390 struct LocalAddrList *lal_head;
393 * Tail of our IP address list.
395 struct LocalAddrList *lal_tail;
398 * ID of task used to update our addresses when one expires.
400 GNUNET_SCHEDULER_TaskIdentifier address_update_task;
403 * Port that we are actually listening on.
408 * Port that the user said we would have visible to the
414 * Is this transport configured to be behind a NAT?
419 * Is this transport configured to allow connections to NAT'd peers?
424 * Should this transport advertise only NAT addresses (port set to 0)?
425 * If not, all addresses will be duplicated for NAT punching and regular
428 int only_nat_addresses;
434 add_to_address_list (struct Plugin *plugin,
438 struct LocalAddrList *lal;
440 lal = plugin->lal_head;
443 if ( (lal->size == arg_size) &&
444 (0 == memcmp (&lal[1], arg, arg_size)) )
448 lal = GNUNET_malloc (sizeof (struct LocalAddrList) + arg_size);
449 lal->size = arg_size;
450 memcpy (&lal[1], arg, arg_size);
451 GNUNET_CONTAINER_DLL_insert (plugin->lal_head,
458 check_local_addr (struct Plugin *plugin,
462 struct LocalAddrList *lal;
464 lal = plugin->lal_head;
467 if ( (lal->size == arg_size) &&
468 (0 == memcmp (&lal[1], arg, arg_size)) )
472 return GNUNET_SYSERR;
477 * Function called for a quick conversion of the binary address to
478 * a numeric address. Note that the caller must not free the
479 * address and that the next call to this function is allowed
480 * to override the address again.
482 * @param cls closure ('struct Plugin*')
483 * @param addr binary address
484 * @param addrlen length of the address
485 * @return string representing the same address
488 tcp_address_to_string (void *cls,
492 static char rbuf[INET6_ADDRSTRLEN + 12];
493 char buf[INET6_ADDRSTRLEN];
497 const struct IPv4TcpAddress *t4;
498 const struct IPv6TcpAddress *t6;
502 if (addrlen == sizeof (struct IPv6TcpAddress))
506 port = ntohs (t6->t6_port);
507 memcpy (&a6, &t6->ipv6_addr, sizeof (a6));
510 else if (addrlen == sizeof (struct IPv4TcpAddress))
514 port = ntohs (t4->t_port);
515 memcpy (&a4, &t4->ipv4_addr, sizeof (a4));
520 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
522 _("Unexpected address length: %u\n"),
527 if (NULL == inet_ntop (af, sb, buf, INET6_ADDRSTRLEN))
529 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "inet_ntop");
532 GNUNET_snprintf (rbuf,
534 (af == AF_INET6) ? "[%s]:%u" : "%s:%u",
542 * Find the session handle for the given client.
544 * @return NULL if no matching session exists
546 static struct Session *
547 find_session_by_client (struct Plugin *plugin,
548 const struct GNUNET_SERVER_Client *client)
552 ret = plugin->sessions;
553 while ((ret != NULL) && (client != ret->client))
559 * Create a new session. Also queues a welcome message.
562 * @param target peer to connect to
563 * @param client client to use
564 * @param is_nat this a NAT session, we should wait for a client to
565 * connect to us from an address, then assign that to
567 * @return new session object
569 static struct Session *
570 create_session (struct Plugin *plugin,
571 const struct GNUNET_PeerIdentity *target,
572 struct GNUNET_SERVER_Client *client, int is_nat)
575 struct PendingMessage *pm;
576 struct WelcomeMessage welcome;
578 if (is_nat != GNUNET_YES)
579 GNUNET_assert (client != NULL);
581 GNUNET_assert (client == NULL);
584 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
586 "Creating new session for peer `%4s'\n",
587 GNUNET_i2s (target));
589 ret = GNUNET_malloc (sizeof (struct Session));
590 ret->last_activity = GNUNET_TIME_absolute_get ();
591 ret->plugin = plugin;
592 if (is_nat != GNUNET_YES) /* If not a NAT WAIT conn, add it to global list */
594 ret->next = plugin->sessions;
595 plugin->sessions = ret;
597 ret->client = client;
598 ret->target = *target;
599 ret->expecting_welcome = GNUNET_YES;
600 pm = GNUNET_malloc (sizeof (struct PendingMessage) + sizeof (struct WelcomeMessage));
601 pm->msg = (const char*) &pm[1];
602 pm->message_size = sizeof (struct WelcomeMessage);
603 welcome.header.size = htons (sizeof (struct WelcomeMessage));
604 welcome.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME);
605 welcome.clientIdentity = *plugin->env->my_identity;
606 memcpy (&pm[1], &welcome, sizeof (welcome));
607 pm->timeout = GNUNET_TIME_UNIT_FOREVER_ABS;
608 GNUNET_STATISTICS_update (plugin->env->stats,
609 gettext_noop ("# bytes currently in TCP buffers"),
612 GNUNET_CONTAINER_DLL_insert (ret->pending_messages_head,
613 ret->pending_messages_tail,
615 if (is_nat != GNUNET_YES)
616 GNUNET_STATISTICS_update (plugin->env->stats,
617 gettext_noop ("# TCP sessions active"),
625 * If we have pending messages, ask the server to
626 * transmit them (schedule the respective tasks, etc.)
628 * @param session for which session should we do this
630 static void process_pending_messages (struct Session *session);
634 * Function called to notify a client about the socket
635 * being ready to queue more data. "buf" will be
636 * NULL and "size" zero if the socket was closed for
637 * writing in the meantime.
640 * @param size number of bytes available in buf
641 * @param buf where the callee should write the message
642 * @return number of bytes written to buf
645 do_transmit (void *cls, size_t size, void *buf)
647 struct Session *session = cls;
648 struct GNUNET_PeerIdentity pid;
649 struct Plugin *plugin;
650 struct PendingMessage *pos;
651 struct PendingMessage *hd;
652 struct PendingMessage *tl;
653 struct GNUNET_TIME_Absolute now;
657 session->transmit_handle = NULL;
658 plugin = session->plugin;
662 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
664 "Timeout trying to transmit to peer `%4s', discarding message queue.\n",
665 GNUNET_i2s (&session->target));
667 /* timeout; cancel all messages that have already expired */
671 now = GNUNET_TIME_absolute_get ();
672 while ( (NULL != (pos = session->pending_messages_head)) &&
673 (pos->timeout.value <= now.value) )
675 GNUNET_CONTAINER_DLL_remove (session->pending_messages_head,
676 session->pending_messages_tail,
679 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
681 "Failed to transmit %u byte message to `%4s'.\n",
683 GNUNET_i2s (&session->target));
685 ret += pos->message_size;
686 GNUNET_CONTAINER_DLL_insert_after (hd, tl, tl, pos);
688 /* do this call before callbacks (so that if callbacks destroy
689 session, they have a chance to cancel actions done by this
691 process_pending_messages (session);
692 pid = session->target;
693 /* no do callbacks and do not use session again since
694 the callbacks may abort the session */
695 while (NULL != (pos = hd))
697 GNUNET_CONTAINER_DLL_remove (hd, tl, pos);
698 if (pos->transmit_cont != NULL)
699 pos->transmit_cont (pos->transmit_cont_cls,
700 &pid, GNUNET_SYSERR);
703 GNUNET_STATISTICS_update (plugin->env->stats,
704 gettext_noop ("# bytes currently in TCP buffers"),
707 GNUNET_STATISTICS_update (plugin->env->stats,
708 gettext_noop ("# bytes discarded by TCP (timeout)"),
713 /* copy all pending messages that would fit */
718 while (NULL != (pos = session->pending_messages_head))
720 if (ret + pos->message_size > size)
722 GNUNET_CONTAINER_DLL_remove (session->pending_messages_head,
723 session->pending_messages_tail,
725 GNUNET_assert (size >= pos->message_size);
726 /* FIXME: this memcpy can be up to 7% of our total runtime */
727 memcpy (cbuf, pos->msg, pos->message_size);
728 cbuf += pos->message_size;
729 ret += pos->message_size;
730 size -= pos->message_size;
731 GNUNET_CONTAINER_DLL_insert_after (hd, tl, tl, pos);
733 /* schedule 'continuation' before callbacks so that callbacks that
734 cancel everything don't cause us to use a session that no longer
736 process_pending_messages (session);
737 session->last_activity = GNUNET_TIME_absolute_get ();
738 pid = session->target;
739 /* we'll now call callbacks that may cancel the session; hence
740 we should not use 'session' after this point */
741 while (NULL != (pos = hd))
743 GNUNET_CONTAINER_DLL_remove (hd, tl, pos);
744 if (pos->transmit_cont != NULL)
745 pos->transmit_cont (pos->transmit_cont_cls,
749 GNUNET_assert (hd == NULL);
750 GNUNET_assert (tl == NULL);
752 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
753 "tcp", "Transmitting %u bytes\n", ret);
755 GNUNET_STATISTICS_update (plugin->env->stats,
756 gettext_noop ("# bytes currently in TCP buffers"),
759 GNUNET_STATISTICS_update (plugin->env->stats,
760 gettext_noop ("# bytes transmitted via TCP"),
768 * If we have pending messages, ask the server to
769 * transmit them (schedule the respective tasks, etc.)
771 * @param session for which session should we do this
774 process_pending_messages (struct Session *session)
776 struct PendingMessage *pm;
778 GNUNET_assert (session->client != NULL);
779 if (session->transmit_handle != NULL)
781 if (NULL == (pm = session->pending_messages_head))
783 session->transmit_handle
784 = GNUNET_SERVER_notify_transmit_ready (session->client,
786 GNUNET_TIME_absolute_get_remaining
788 &do_transmit, session);
793 * Functions with this signature are called whenever we need
794 * to close a session due to a disconnect or failure to
795 * establish a connection.
797 * @param session session to close down
800 disconnect_session (struct Session *session)
802 struct Session *prev;
804 struct PendingMessage *pm;
807 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
809 "Disconnecting from `%4s' at %s (session %p).\n",
810 GNUNET_i2s (&session->target),
811 (session->connect_addr != NULL) ?
812 tcp_address_to_string (session->plugin,
813 session->connect_addr,
814 session->connect_alen) : "*",
817 /* remove from session list */
819 pos = session->plugin->sessions;
820 while (pos != session)
826 session->plugin->sessions = session->next;
828 prev->next = session->next;
829 session->plugin->env->session_end (session->plugin->env->cls,
833 if (session->transmit_handle != NULL)
835 GNUNET_CONNECTION_notify_transmit_ready_cancel
836 (session->transmit_handle);
837 session->transmit_handle = NULL;
839 while (NULL != (pm = session->pending_messages_head))
842 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
844 pm->transmit_cont != NULL
845 ? "Could not deliver message to `%4s'.\n"
847 "Could not deliver message to `%4s', notifying.\n",
848 GNUNET_i2s (&session->target));
850 GNUNET_STATISTICS_update (session->plugin->env->stats,
851 gettext_noop ("# bytes currently in TCP buffers"),
852 - (int64_t) pm->message_size,
854 GNUNET_STATISTICS_update (session->plugin->env->stats,
855 gettext_noop ("# bytes discarded by TCP (disconnect)"),
858 GNUNET_CONTAINER_DLL_remove (session->pending_messages_head,
859 session->pending_messages_tail,
861 if (NULL != pm->transmit_cont)
862 pm->transmit_cont (pm->transmit_cont_cls,
863 &session->target, GNUNET_SYSERR);
866 GNUNET_break (session->client != NULL);
867 if (session->receive_delay_task != GNUNET_SCHEDULER_NO_TASK)
869 GNUNET_SCHEDULER_cancel (session->plugin->env->sched,
870 session->receive_delay_task);
871 if (session->client != NULL)
872 GNUNET_SERVER_receive_done (session->client,
875 if (session->client != NULL)
876 GNUNET_SERVER_client_drop (session->client);
877 GNUNET_STATISTICS_update (session->plugin->env->stats,
878 gettext_noop ("# TCP sessions active"),
881 GNUNET_free_non_null (session->connect_addr);
882 GNUNET_free (session);
887 * Given two otherwise equivalent sessions, pick the better one.
889 * @param s1 one session (also default)
890 * @param s2 other session
891 * @return "better" session (more active)
893 static struct Session *
894 select_better_session (struct Session *s1,
901 if ( (s1->expecting_welcome == GNUNET_NO) &&
902 (s2->expecting_welcome == GNUNET_YES) )
904 if ( (s1->expecting_welcome == GNUNET_YES) &&
905 (s2->expecting_welcome == GNUNET_NO) )
907 if (s1->last_activity.value < s2->last_activity.value)
909 if (s1->last_activity.value > s2->last_activity.value)
911 if ( (GNUNET_YES == s1->inbound) &&
912 (GNUNET_NO == s2->inbound) )
914 if ( (GNUNET_NO == s1->inbound) &&
915 (GNUNET_YES == s2->inbound) )
922 * We learned about a peer (possibly behind NAT) so run the
923 * gnunet-nat-client to send dummy ICMP responses
925 * @param plugin the plugin for this transport
926 * @param addr the address of the peer
927 * @param addrlen the length of the address
930 run_gnunet_nat_client (struct Plugin *plugin, const char *addr, size_t addrlen)
932 char inet4[INET_ADDRSTRLEN];
933 char *address_as_string;
934 char *port_as_string;
936 const struct sockaddr *sa = (const struct sockaddr *)addr;
938 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
939 _("called run_gnunet_nat_client addrlen %d others are %d and %d\n"), addrlen, sizeof (struct sockaddr), sizeof (struct sockaddr_in));
942 if (addrlen < sizeof (struct sockaddr))
945 switch (sa->sa_family)
948 if (addrlen != sizeof (struct sockaddr_in))
950 if (NULL == inet_ntop (AF_INET,
951 &((struct sockaddr_in *) sa)->sin_addr,
952 inet4, INET_ADDRSTRLEN))
954 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "inet_ntop");
957 address_as_string = GNUNET_strdup (inet4);
964 GNUNET_asprintf(&port_as_string, "%d", plugin->adv_port);
966 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
967 _("Running gnunet-nat-client with arguments: %s %s %d\n"), plugin->external_address, address_as_string, plugin->adv_port);
970 /* Start the client process */
971 pid = GNUNET_OS_start_process(NULL, NULL, "gnunet-nat-client", "gnunet-nat-client", plugin->external_address, address_as_string, port_as_string, NULL);
972 GNUNET_free(address_as_string);
973 GNUNET_free(port_as_string);
974 GNUNET_OS_process_wait (pid);
979 * Function that can be used by the transport service to transmit
980 * a message using the plugin. Note that in the case of a
981 * peer disconnecting, the continuation MUST be called
982 * prior to the disconnect notification itself. This function
983 * will be called with this peer's HELLO message to initiate
984 * a fresh connection to another peer.
987 * @param target who should receive this message
988 * @param msg the message to transmit
989 * @param msgbuf_size number of bytes in 'msg'
990 * @param priority how important is the message (most plugins will
991 * ignore message priority and just FIFO)
992 * @param timeout how long to wait at most for the transmission (does not
993 * require plugins to discard the message after the timeout,
994 * just advisory for the desired delay; most plugins will ignore
996 * @param session which session must be used (or NULL for "any")
997 * @param addr the address to use (can be NULL if the plugin
998 * is "on its own" (i.e. re-use existing TCP connection))
999 * @param addrlen length of the address in bytes
1000 * @param force_address GNUNET_YES if the plugin MUST use the given address,
1001 * GNUNET_NO means the plugin may use any other address and
1002 * GNUNET_SYSERR means that only reliable existing
1003 * bi-directional connections should be used (regardless
1005 * @param cont continuation to call once the message has
1006 * been transmitted (or if the transport is ready
1007 * for the next transmission call; or if the
1008 * peer disconnected...); can be NULL
1009 * @param cont_cls closure for cont
1010 * @return number of bytes used (on the physical network, with overheads);
1011 * -1 on hard errors (i.e. address invalid); 0 is a legal value
1012 * and does NOT mean that the message was not transmitted (DV and NAT)
1015 tcp_plugin_send (void *cls,
1016 const struct GNUNET_PeerIdentity *target,
1020 struct GNUNET_TIME_Relative timeout,
1021 struct Session *session,
1025 GNUNET_TRANSPORT_TransmitContinuation cont, void *cont_cls)
1027 struct Plugin *plugin = cls;
1028 struct Session *cand_session;
1029 struct Session *next;
1030 struct PendingMessage *pm;
1031 struct GNUNET_CONNECTION_Handle *sa;
1035 struct sockaddr_in a4;
1036 struct sockaddr_in6 a6;
1037 const struct IPv4TcpAddress *t4;
1038 const struct IPv6TcpAddress *t6;
1039 unsigned int is_natd;
1041 GNUNET_STATISTICS_update (plugin->env->stats,
1042 gettext_noop ("# bytes TCP was asked to transmit"),
1045 /* FIXME: we could do this cheaper with a hash table
1046 where we could restrict the iteration to entries that match
1047 the target peer... */
1048 is_natd = GNUNET_NO;
1049 if (session == NULL)
1051 cand_session = NULL;
1052 next = plugin->sessions;
1053 while (NULL != (session = next))
1055 next = session->next;
1056 GNUNET_assert (session->client != NULL);
1057 if (0 != memcmp (target,
1059 sizeof (struct GNUNET_PeerIdentity)))
1061 if ( ( (GNUNET_SYSERR == force_address) &&
1062 (session->expecting_welcome == GNUNET_NO) ) ||
1063 (GNUNET_NO == force_address) )
1065 cand_session = select_better_session (cand_session,
1069 if (GNUNET_SYSERR == force_address)
1071 GNUNET_break (GNUNET_YES == force_address);
1077 if (session->inbound == GNUNET_YES)
1079 if (addrlen != session->connect_alen)
1081 if (0 != memcmp (session->connect_addr,
1085 cand_session = select_better_session (cand_session,
1088 session = cand_session;
1090 if ( (session == NULL) &&
1094 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1096 "Asked to transmit to `%4s' without address and I have no existing connection (failing).\n",
1097 GNUNET_i2s (target));
1099 GNUNET_STATISTICS_update (plugin->env->stats,
1100 gettext_noop ("# bytes discarded by TCP (no address and no connection)"),
1105 if (session == NULL)
1107 if (addrlen == sizeof (struct IPv6TcpAddress))
1111 memset (&a6, 0, sizeof (a6));
1112 #if HAVE_SOCKADDR_IN_SIN_LEN
1113 a6.sin6_len = sizeof (a6);
1115 a6.sin6_family = AF_INET6;
1116 a6.sin6_port = t6->t6_port;
1117 if (t6->t6_port == 0)
1118 is_natd = GNUNET_YES;
1119 memcpy (&a6.sin6_addr,
1121 sizeof (struct in6_addr));
1125 else if (addrlen == sizeof (struct IPv4TcpAddress))
1129 memset (&a4, 0, sizeof (a4));
1130 #if HAVE_SOCKADDR_IN_SIN_LEN
1131 a4.sin_len = sizeof (a4);
1133 a4.sin_family = AF_INET;
1134 a4.sin_port = t4->t_port;
1135 if (t4->t_port == 0)
1136 is_natd = GNUNET_YES;
1137 a4.sin_addr.s_addr = t4->ipv4_addr;
1143 GNUNET_log_from (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_from (GNUNET_ERROR_TYPE_DEBUG,
1161 _("Found valid IPv4 NAT address!\n"));
1163 session = create_session (plugin,
1167 /* create new message entry */
1168 pm = GNUNET_malloc (sizeof (struct PendingMessage) + msgbuf_size);
1169 /* FIXME: the memset of this malloc can be up to 2% of our total runtime */
1170 pm->msg = (const char*) &pm[1];
1171 memcpy (&pm[1], msg, msgbuf_size);
1172 /* FIXME: this memcpy can be up to 7% of our total run-time
1173 (for transport service) */
1174 pm->message_size = msgbuf_size;
1175 pm->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1176 pm->transmit_cont = cont;
1177 pm->transmit_cont_cls = cont_cls;
1179 /* append pm to pending_messages list */
1180 GNUNET_CONTAINER_DLL_insert_after (session->pending_messages_head,
1181 session->pending_messages_tail,
1182 session->pending_messages_tail,
1185 GNUNET_assert(GNUNET_CONTAINER_multihashmap_put(plugin->nat_wait_conns, &target->hashPubKey, session, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY) == GNUNET_OK);
1187 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1189 "Created NAT WAIT connection to `%4s' at `%s'\n",
1190 GNUNET_i2s (target),
1191 GNUNET_a2s (sb, sbs));
1193 run_gnunet_nat_client(plugin, sb, sbs);
1196 else if ((plugin->allow_nat == GNUNET_YES) && (is_natd == GNUNET_YES) && (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains(plugin->nat_wait_conns, &target->hashPubKey)))
1198 /* Only do one NAT punch attempt per peer identity */
1201 sa = GNUNET_CONNECTION_create_from_sockaddr (plugin->env->sched,
1206 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1208 "Failed to create connection to `%4s' at `%s'\n",
1209 GNUNET_i2s (target),
1210 GNUNET_a2s (sb, sbs));
1212 GNUNET_STATISTICS_update (plugin->env->stats,
1213 gettext_noop ("# bytes discarded by TCP (failed to connect)"),
1219 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1221 "Asked to transmit to `%4s', creating fresh session using address `%s'.\n",
1222 GNUNET_i2s (target),
1223 GNUNET_a2s (sb, sbs));
1225 session = create_session (plugin,
1227 GNUNET_SERVER_connect_socket (plugin->server,
1229 session->connect_addr = GNUNET_malloc (addrlen);
1230 memcpy (session->connect_addr,
1233 session->connect_alen = addrlen;
1235 GNUNET_assert (session != NULL);
1236 GNUNET_assert (session->client != NULL);
1237 GNUNET_STATISTICS_update (plugin->env->stats,
1238 gettext_noop ("# bytes currently in TCP buffers"),
1241 /* create new message entry */
1242 pm = GNUNET_malloc (sizeof (struct PendingMessage) + msgbuf_size);
1243 pm->msg = (const char*) &pm[1];
1244 memcpy (&pm[1], msg, msgbuf_size);
1245 pm->message_size = msgbuf_size;
1246 pm->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1247 pm->transmit_cont = cont;
1248 pm->transmit_cont_cls = cont_cls;
1250 /* append pm to pending_messages list */
1251 GNUNET_CONTAINER_DLL_insert_after (session->pending_messages_head,
1252 session->pending_messages_tail,
1253 session->pending_messages_tail,
1256 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1258 "Asked to transmit %u bytes to `%s', added message to list.\n",
1260 GNUNET_i2s (target));
1262 process_pending_messages (session);
1268 * Function that can be called to force a disconnect from the
1269 * specified neighbour. This should also cancel all previously
1270 * scheduled transmissions. Obviously the transmission may have been
1271 * partially completed already, which is OK. The plugin is supposed
1272 * to close the connection (if applicable) and no longer call the
1273 * transmit continuation(s).
1275 * Finally, plugin MUST NOT call the services's receive function to
1276 * notify the service that the connection to the specified target was
1277 * closed after a getting this call.
1279 * @param cls closure
1280 * @param target peer for which the last transmission is
1284 tcp_plugin_disconnect (void *cls,
1285 const struct GNUNET_PeerIdentity *target)
1287 struct Plugin *plugin = cls;
1288 struct Session *session;
1289 struct Session *next;
1290 struct PendingMessage *pm;
1293 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1295 "Asked to cancel session with `%4s'\n",
1296 GNUNET_i2s (target));
1298 next = plugin->sessions;
1299 while (NULL != (session = next))
1301 next = session->next;
1302 if (0 != memcmp (target,
1304 sizeof (struct GNUNET_PeerIdentity)))
1306 pm = session->pending_messages_head;
1309 pm->transmit_cont = NULL;
1310 pm->transmit_cont_cls = NULL;
1313 disconnect_session (session);
1319 * Context for address to string conversion.
1321 struct PrettyPrinterContext
1324 * Function to call with the result.
1326 GNUNET_TRANSPORT_AddressStringCallback asc;
1329 * Clsoure for 'asc'.
1334 * Port to add after the IP address.
1341 * Append our port and forward the result.
1343 * @param cls the 'struct PrettyPrinterContext*'
1344 * @param hostname hostname part of the address
1347 append_port (void *cls, const char *hostname)
1349 struct PrettyPrinterContext *ppc = cls;
1352 if (hostname == NULL)
1354 ppc->asc (ppc->asc_cls, NULL);
1358 GNUNET_asprintf (&ret, "%s:%d", hostname, ppc->port);
1359 ppc->asc (ppc->asc_cls, ret);
1365 * Convert the transports address to a nice, human-readable
1368 * @param cls closure
1369 * @param type name of the transport that generated the address
1370 * @param addr one of the addresses of the host, NULL for the last address
1371 * the specific address format depends on the transport
1372 * @param addrlen length of the address
1373 * @param numeric should (IP) addresses be displayed in numeric form?
1374 * @param timeout after how long should we give up?
1375 * @param asc function to call on each string
1376 * @param asc_cls closure for asc
1379 tcp_plugin_address_pretty_printer (void *cls,
1384 struct GNUNET_TIME_Relative timeout,
1385 GNUNET_TRANSPORT_AddressStringCallback asc,
1388 struct Plugin *plugin = cls;
1389 struct PrettyPrinterContext *ppc;
1392 struct sockaddr_in a4;
1393 struct sockaddr_in6 a6;
1394 const struct IPv4TcpAddress *t4;
1395 const struct IPv6TcpAddress *t6;
1398 if (addrlen == sizeof (struct IPv6TcpAddress))
1401 memset (&a6, 0, sizeof (a6));
1402 a6.sin6_family = AF_INET6;
1403 a6.sin6_port = t6->t6_port;
1404 memcpy (&a6.sin6_addr,
1406 sizeof (struct in6_addr));
1407 port = ntohs (t6->t6_port);
1411 else if (addrlen == sizeof (struct IPv4TcpAddress))
1414 memset (&a4, 0, sizeof (a4));
1415 a4.sin_family = AF_INET;
1416 a4.sin_port = t4->t_port;
1417 a4.sin_addr.s_addr = t4->ipv4_addr;
1418 port = ntohs (t4->t_port);
1424 /* invalid address */
1425 GNUNET_break_op (0);
1426 asc (asc_cls, NULL);
1429 ppc = GNUNET_malloc (sizeof (struct PrettyPrinterContext));
1431 ppc->asc_cls = asc_cls;
1433 GNUNET_RESOLVER_hostname_get (plugin->env->sched,
1437 !numeric, timeout, &append_port, ppc);
1442 * Check if the given port is plausible (must be either
1443 * our listen port or our advertised port). If it is
1444 * neither, we return GNUNET_SYSERR.
1446 * @param plugin global variables
1447 * @param in_port port number to check
1448 * @return GNUNET_OK if port is either open_port or adv_port
1451 check_port (struct Plugin *plugin, uint16_t in_port)
1453 if ( (plugin->behind_nat == GNUNET_YES) && (in_port == 0) )
1455 if ( (plugin->only_nat_addresses == GNUNET_YES) &&
1456 (plugin->behind_nat == GNUNET_YES) )
1458 return GNUNET_SYSERR; /* odd case... */
1460 if ((in_port == plugin->adv_port) || (in_port == plugin->open_port))
1462 return GNUNET_SYSERR;
1467 * Function that will be called to check if a binary address for this
1468 * plugin is well-formed and corresponds to an address for THIS peer
1469 * (as per our configuration). Naturally, if absolutely necessary,
1470 * plugins can be a bit conservative in their answer, but in general
1471 * plugins should make sure that the address does not redirect
1472 * traffic to a 3rd party that might try to man-in-the-middle our
1475 * @param cls closure, our 'struct Plugin*'
1476 * @param addr pointer to the address
1477 * @param addrlen length of addr
1478 * @return GNUNET_OK if this is a plausible address for this peer
1479 * and transport, GNUNET_SYSERR if not
1482 tcp_plugin_check_address (void *cls,
1486 struct Plugin *plugin = cls;
1487 struct IPv4TcpAddress *v4;
1488 struct IPv6TcpAddress *v6;
1490 if ((addrlen != sizeof (struct IPv4TcpAddress)) &&
1491 (addrlen != sizeof (struct IPv6TcpAddress)))
1493 GNUNET_break_op (0);
1494 return GNUNET_SYSERR;
1496 if (addrlen == sizeof (struct IPv4TcpAddress))
1498 v4 = (struct IPv4TcpAddress *) addr;
1500 check_port (plugin, ntohs (v4->t_port)))
1501 return GNUNET_SYSERR;
1503 check_local_addr (plugin, &v4->ipv4_addr, sizeof (uint32_t)))
1505 return GNUNET_SYSERR;
1510 v6 = (struct IPv6TcpAddress *) addr;
1511 if (IN6_IS_ADDR_LINKLOCAL (&v6->ipv6_addr))
1513 GNUNET_break_op (0);
1514 return GNUNET_SYSERR;
1517 check_port (plugin, ntohs (v6->t6_port)))
1518 return GNUNET_SYSERR;
1520 check_local_addr (plugin, &v6->ipv6_addr, sizeof (struct in6_addr)))
1522 return GNUNET_SYSERR;
1529 * We've received a nat probe from this peer via TCP. Finish
1530 * creating the client session and resume sending of queued
1533 * @param cls closure
1534 * @param client identification of the client
1535 * @param message the actual message
1538 handle_tcp_nat_probe (void *cls,
1539 struct GNUNET_SERVER_Client *client,
1540 const struct GNUNET_MessageHeader *message)
1542 struct Plugin *plugin = cls;
1543 struct Session *session;
1544 struct TCP_NAT_ProbeMessage *tcp_nat_probe;
1547 struct IPv4TcpAddress *t4;
1548 struct IPv6TcpAddress *t6;
1549 const struct sockaddr_in *s4;
1550 const struct sockaddr_in6 *s6;
1553 GNUNET_log_from(GNUNET_ERROR_TYPE_DEBUG, "tcp", "received tcp NAT probe\n");
1555 /* We have received a TCP NAT probe, meaning we (hopefully) initiated
1556 * a connection to this peer by running gnunet-nat-client. This peer
1557 * received the punch message and now wants us to use the new connection
1558 * as the default for that peer. Do so and then send a WELCOME message
1559 * so we can really be connected!
1561 if (ntohs(message->size) != sizeof(struct TCP_NAT_ProbeMessage))
1564 GNUNET_log_from(GNUNET_ERROR_TYPE_DEBUG, "tcp", "Bad size fo tcp NAT probe, expected %d got %d.\n", sizeof(struct TCP_NAT_ProbeMessage), ntohs(message->size));
1569 tcp_nat_probe = (struct TCP_NAT_ProbeMessage *)message;
1571 if (GNUNET_CONTAINER_multihashmap_contains(plugin->nat_wait_conns, &tcp_nat_probe->clientIdentity.hashPubKey) == GNUNET_YES)
1574 GNUNET_log_from(GNUNET_ERROR_TYPE_DEBUG, "tcp", "Found session for NAT probe!\n");
1576 session = GNUNET_CONTAINER_multihashmap_get(plugin->nat_wait_conns, &tcp_nat_probe->clientIdentity.hashPubKey);
1577 GNUNET_assert(session != NULL);
1578 GNUNET_assert(GNUNET_CONTAINER_multihashmap_remove(plugin->nat_wait_conns, &tcp_nat_probe->clientIdentity.hashPubKey, session) == GNUNET_YES);
1579 GNUNET_SERVER_client_keep (client);
1580 session->client = client;
1581 session->last_activity = GNUNET_TIME_absolute_get ();
1584 GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
1587 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1589 "Found address `%s' for incoming connection %p\n",
1590 GNUNET_a2s (vaddr, alen),
1593 if (alen == sizeof (struct sockaddr_in))
1596 t4 = GNUNET_malloc (sizeof (struct IPv4TcpAddress));
1597 t4->t_port = s4->sin_port;
1598 t4->ipv4_addr = s4->sin_addr.s_addr;
1599 session->connect_addr = t4;
1600 session->connect_alen = sizeof (struct IPv4TcpAddress);
1602 else if (alen == sizeof (struct sockaddr_in6))
1605 t6 = GNUNET_malloc (sizeof (struct IPv6TcpAddress));
1606 t6->t6_port = s6->sin6_port;
1607 memcpy (&t6->ipv6_addr,
1609 sizeof (struct in6_addr));
1610 session->connect_addr = t6;
1611 session->connect_alen = sizeof (struct IPv6TcpAddress);
1614 session->connect_addr = GNUNET_malloc (alen);
1615 memcpy (session->connect_addr,
1618 session->connect_alen = alen;
1619 GNUNET_free (vaddr);
1622 session->next = plugin->sessions;
1623 plugin->sessions = session;
1624 GNUNET_STATISTICS_update (plugin->env->stats,
1625 gettext_noop ("# TCP sessions active"),
1628 process_pending_messages (session);
1633 GNUNET_log_from(GNUNET_ERROR_TYPE_DEBUG, "tcp", "Did NOT find session for NAT probe!\n");
1639 * We've received a welcome from this peer via TCP. Possibly create a
1640 * fresh client record and send back our welcome.
1642 * @param cls closure
1643 * @param client identification of the client
1644 * @param message the actual message
1647 handle_tcp_welcome (void *cls,
1648 struct GNUNET_SERVER_Client *client,
1649 const struct GNUNET_MessageHeader *message)
1651 struct Plugin *plugin = cls;
1652 const struct WelcomeMessage *wm = (const struct WelcomeMessage *) message;
1653 struct Session *session;
1656 struct IPv4TcpAddress *t4;
1657 struct IPv6TcpAddress *t6;
1658 const struct sockaddr_in *s4;
1659 const struct sockaddr_in6 *s6;
1663 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1665 "Received %s message from a `%4s/%p'.\n",
1667 GNUNET_i2s (&wm->clientIdentity), client);
1669 GNUNET_STATISTICS_update (plugin->env->stats,
1670 gettext_noop ("# TCP WELCOME messages received"),
1673 session = find_session_by_client (plugin, client);
1674 if (session == NULL)
1676 GNUNET_SERVER_client_keep (client);
1677 session = create_session (plugin,
1678 &wm->clientIdentity, client, GNUNET_NO);
1679 session->inbound = GNUNET_YES;
1681 GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
1684 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1686 "Found address `%s' for incoming connection %p\n",
1687 GNUNET_a2s (vaddr, alen),
1690 if (alen == sizeof (struct sockaddr_in))
1693 t4 = GNUNET_malloc (sizeof (struct IPv4TcpAddress));
1694 t4->t_port = s4->sin_port;
1695 t4->ipv4_addr = s4->sin_addr.s_addr;
1696 session->connect_addr = t4;
1697 session->connect_alen = sizeof (struct IPv4TcpAddress);
1699 else if (alen == sizeof (struct sockaddr_in6))
1702 t6 = GNUNET_malloc (sizeof (struct IPv6TcpAddress));
1703 t6->t6_port = s6->sin6_port;
1704 memcpy (&t6->ipv6_addr,
1706 sizeof (struct in6_addr));
1707 session->connect_addr = t6;
1708 session->connect_alen = sizeof (struct IPv6TcpAddress);
1710 GNUNET_free (vaddr);
1715 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1717 "Did not obtain TCP socket address for incoming connection\n");
1721 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1723 "Creating new session %p for connection %p\n",
1726 process_pending_messages (session);
1728 if (session->expecting_welcome != GNUNET_YES)
1730 GNUNET_break_op (0);
1731 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1734 session->last_activity = GNUNET_TIME_absolute_get ();
1735 session->expecting_welcome = GNUNET_NO;
1736 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1741 * Task to signal the server that we can continue
1742 * receiving from the TCP client now.
1744 * @param cls the 'struct Session*'
1745 * @param tc task context (unused)
1748 delayed_done (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1750 struct Session *session = cls;
1751 struct GNUNET_TIME_Relative delay;
1753 session->receive_delay_task = GNUNET_SCHEDULER_NO_TASK;
1754 delay = session->plugin->env->receive (session->plugin->env->cls,
1759 if (delay.value == 0)
1760 GNUNET_SERVER_receive_done (session->client, GNUNET_OK);
1762 session->receive_delay_task =
1763 GNUNET_SCHEDULER_add_delayed (session->plugin->env->sched,
1764 delay, &delayed_done, session);
1769 * We've received data for this peer via TCP. Unbox,
1770 * compute latency and forward.
1772 * @param cls closure
1773 * @param client identification of the client
1774 * @param message the actual message
1777 handle_tcp_data (void *cls,
1778 struct GNUNET_SERVER_Client *client,
1779 const struct GNUNET_MessageHeader *message)
1781 struct Plugin *plugin = cls;
1782 struct Session *session;
1783 struct GNUNET_TIME_Relative delay;
1785 if ((GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME == ntohs(message->type)) || (ntohs(message->type) == GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE))
1787 /* We don't want to propagate WELCOME and NAT Probe messages up! */
1788 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1791 session = find_session_by_client (plugin, client);
1792 if ( (NULL == session) || (GNUNET_YES == session->expecting_welcome))
1794 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1797 session->last_activity = GNUNET_TIME_absolute_get ();
1799 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1801 "Passing %u bytes of type %u from `%4s' to transport service.\n",
1802 (unsigned int) ntohs (message->size),
1803 (unsigned int) ntohs (message->type),
1804 GNUNET_i2s (&session->target));
1806 GNUNET_STATISTICS_update (plugin->env->stats,
1807 gettext_noop ("# bytes received via TCP"),
1808 ntohs (message->size),
1810 delay = plugin->env->receive (plugin->env->cls, &session->target, message, 1,
1812 (GNUNET_YES == session->inbound) ? NULL : session->connect_addr,
1813 (GNUNET_YES == session->inbound) ? 0 : session->connect_alen);
1814 if (delay.value == 0)
1815 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1817 session->receive_delay_task =
1818 GNUNET_SCHEDULER_add_delayed (session->plugin->env->sched,
1819 delay, &delayed_done, session);
1824 * Functions with this signature are called whenever a peer
1825 * is disconnected on the network level.
1827 * @param cls closure
1828 * @param client identification of the client
1831 disconnect_notify (void *cls,
1832 struct GNUNET_SERVER_Client *client)
1834 struct Plugin *plugin = cls;
1835 struct Session *session;
1839 session = find_session_by_client (plugin, client);
1840 if (session == NULL)
1841 return; /* unknown, nothing to do */
1843 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1845 "Destroying session of `%4s' with %s (%p) due to network-level disconnect.\n",
1846 GNUNET_i2s (&session->target),
1847 (session->connect_addr != NULL) ?
1848 tcp_address_to_string (session->plugin,
1849 session->connect_addr,
1850 session->connect_alen) : "*",
1853 disconnect_session (session);
1858 * Add the IP of our network interface to the list of
1859 * our external IP addresses.
1861 * @param cls the 'struct Plugin*'
1862 * @param name name of the interface
1863 * @param isDefault do we think this may be our default interface
1864 * @param addr address of the interface
1865 * @param addrlen number of bytes in addr
1866 * @return GNUNET_OK to continue iterating
1869 process_interfaces (void *cls,
1872 const struct sockaddr *addr, socklen_t addrlen)
1874 struct Plugin *plugin = cls;
1876 struct IPv4TcpAddress t4;
1877 struct IPv6TcpAddress t6;
1878 struct IPv4TcpAddress t4_nat;
1879 struct IPv6TcpAddress t6_nat;
1884 af = addr->sa_family;
1888 t4.ipv4_addr = ((struct sockaddr_in *) addr)->sin_addr.s_addr;
1889 add_to_address_list (plugin, &t4.ipv4_addr, sizeof (uint32_t));
1890 if ((plugin->behind_nat == GNUNET_YES) && (plugin->only_nat_addresses == GNUNET_YES))
1891 t4.t_port = htons(0);
1892 else if (plugin->behind_nat == GNUNET_YES) /* We are behind NAT, but will advertise NAT and normal addresses */
1894 t4_nat.ipv4_addr = ((struct sockaddr_in *) addr)->sin_addr.s_addr;
1895 t4_nat.t_port = htons(plugin->adv_port);
1899 t4.t_port = htons (plugin->adv_port);
1903 else if (af == AF_INET6)
1905 if (IN6_IS_ADDR_LINKLOCAL (&((struct sockaddr_in6 *) addr)->sin6_addr))
1907 /* skip link local addresses */
1910 memcpy (&t6.ipv6_addr,
1911 &((struct sockaddr_in6 *) addr)->sin6_addr,
1912 sizeof (struct in6_addr));
1913 add_to_address_list (plugin, &t6.ipv6_addr, sizeof (struct in6_addr));
1914 if ((plugin->behind_nat == GNUNET_YES) && (plugin->only_nat_addresses == GNUNET_YES))
1915 t6.t6_port = htons(0);
1916 else if (plugin->behind_nat == GNUNET_YES) /* We are behind NAT, but will advertise NAT and normal addresses */
1918 memcpy (&t6_nat.ipv6_addr,
1919 &((struct sockaddr_in6 *) addr)->sin6_addr,
1920 sizeof (struct in6_addr));
1921 t6_nat.t6_port = htons(plugin->adv_port);
1925 t6.t6_port = htons (plugin->adv_port);
1934 GNUNET_log_from (GNUNET_ERROR_TYPE_INFO |
1935 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_from (GNUNET_ERROR_TYPE_INFO |
1947 GNUNET_ERROR_TYPE_BULK,
1949 _("Found address `%s' (%s)\n"),
1950 GNUNET_a2s (addr, addrlen), name);
1951 plugin->env->notify_address (plugin->env->cls,
1953 arg_nat, args, GNUNET_TIME_UNIT_FOREVER_REL);
1961 * Function called by the resolver for each address obtained from DNS
1962 * for our own hostname. Add the addresses to the list of our
1963 * external IP addresses.
1965 * @param cls closure
1966 * @param addr one of the addresses of the host, NULL for the last address
1967 * @param addrlen length of the address
1970 process_hostname_ips (void *cls,
1971 const struct sockaddr *addr, socklen_t addrlen)
1973 struct Plugin *plugin = cls;
1977 plugin->hostname_dns = NULL;
1980 /* FIXME: Can we figure out our external address here so it doesn't need to be user specified? */
1981 process_interfaces (plugin, "<hostname>", GNUNET_YES, addr, addrlen);
1985 * We can now send a probe message, copy into buffer to really send.
1987 * @param cls closure, a struct TCPProbeContext
1988 * @param size max size to copy
1989 * @param buf buffer to copy message to
1991 static size_t notify_send_probe (void *cls,
1992 size_t size, void *buf)
1994 struct TCPProbeContext *tcp_probe_ctx = cls;
2001 GNUNET_assert(size >= sizeof(tcp_probe_ctx->message));
2002 memcpy(buf, &tcp_probe_ctx->message, sizeof(tcp_probe_ctx->message));
2003 GNUNET_SERVER_connect_socket (tcp_probe_ctx->plugin->server,
2004 tcp_probe_ctx->sock);
2006 GNUNET_free(tcp_probe_ctx);
2007 return sizeof(tcp_probe_ctx->message);
2011 * @param cls the plugin handle
2012 * @param tc the scheduling context (for rescheduling this function again)
2014 * We have been notified that gnunet-nat-server has written something to stdout.
2015 * Handle the output, then reschedule this function to be called again once
2016 * more is available.
2020 tcp_plugin_server_read (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2022 struct Plugin *plugin = cls;
2025 memset(&mybuf, 0, sizeof(mybuf));
2029 struct sockaddr_in in_addr;
2030 struct TCPProbeContext *tcp_probe_ctx;
2031 struct GNUNET_CONNECTION_Handle *sock;
2033 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
2036 bytes = GNUNET_DISK_file_read(plugin->server_stdout_handle, &mybuf, sizeof(mybuf));
2041 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
2042 _("Finished reading from server stdout with code: %d\n"), bytes);
2049 for (i = 0; i < sizeof(mybuf); i++)
2051 if (mybuf[i] == '\n')
2054 if ((mybuf[i] == ':') && (i + 1 < sizeof(mybuf)))
2057 port_start = &mybuf[i + 1];
2061 if (port_start != NULL)
2062 port = atoi(port_start);
2065 plugin->server_read_task =
2066 GNUNET_SCHEDULER_add_read_file (plugin->env->sched,
2067 GNUNET_TIME_UNIT_FOREVER_REL,
2068 plugin->server_stdout_handle, &tcp_plugin_server_read, plugin);
2073 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
2074 _("nat-server-read read: %s port %d\n"), &mybuf, port);
2078 if (inet_pton(AF_INET, &mybuf[0], &in_addr.sin_addr) != 1)
2081 GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, "tcp",
2082 _("nat-server-read malformed address\n"), &mybuf, port);
2084 plugin->server_read_task =
2085 GNUNET_SCHEDULER_add_read_file (plugin->env->sched,
2086 GNUNET_TIME_UNIT_FOREVER_REL,
2087 plugin->server_stdout_handle, &tcp_plugin_server_read, plugin);
2091 in_addr.sin_family = AF_INET;
2092 in_addr.sin_port = htons(port);
2094 * We have received an ICMP response, ostensibly from a non-NAT'd peer
2095 * that wants to connect to us! Send a message to establish a connection.
2097 sock = GNUNET_CONNECTION_create_from_sockaddr (plugin->env->sched, AF_INET, (struct sockaddr *)&in_addr,
2101 plugin->server_read_task =
2102 GNUNET_SCHEDULER_add_read_file (plugin->env->sched,
2103 GNUNET_TIME_UNIT_FOREVER_REL,
2104 plugin->server_stdout_handle, &tcp_plugin_server_read, plugin);
2109 tcp_probe_ctx = GNUNET_malloc(sizeof(struct TCPProbeContext));
2111 tcp_probe_ctx->message.header.size = htons(sizeof(struct TCP_NAT_ProbeMessage));
2112 tcp_probe_ctx->message.header.type = htons(GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE);
2113 memcpy(&tcp_probe_ctx->message.clientIdentity, plugin->env->my_identity, sizeof(struct GNUNET_PeerIdentity));
2114 tcp_probe_ctx->plugin = plugin;
2115 tcp_probe_ctx->sock = sock;
2116 tcp_probe_ctx->transmit_handle = GNUNET_CONNECTION_notify_transmit_ready (sock,
2117 ntohs(tcp_probe_ctx->message.header.size),
2118 GNUNET_TIME_UNIT_FOREVER_REL,
2119 ¬ify_send_probe, tcp_probe_ctx);
2123 plugin->server_read_task =
2124 GNUNET_SCHEDULER_add_read_file (plugin->env->sched,
2125 GNUNET_TIME_UNIT_FOREVER_REL,
2126 plugin->server_stdout_handle, &tcp_plugin_server_read, plugin);
2130 * Start the gnunet-nat-server process for users behind NAT.
2132 * @param plugin the transport plugin
2134 * @return GNUNET_YES if process was started, GNUNET_SYSERR on error
2137 tcp_transport_start_nat_server(struct Plugin *plugin)
2140 plugin->server_stdout = GNUNET_DISK_pipe(GNUNET_YES);
2141 if (plugin->server_stdout == NULL)
2142 return GNUNET_SYSERR;
2145 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
2147 "Starting gnunet-nat-server process cmd: %s %s\n", "gnunet-nat-server", plugin->internal_address);
2149 /* Start the server process */
2150 plugin->server_pid = GNUNET_OS_start_process(NULL, plugin->server_stdout, "gnunet-nat-server", "gnunet-nat-server", plugin->internal_address, NULL);
2151 if (plugin->server_pid == GNUNET_SYSERR)
2154 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
2156 "Failed to start gnunet-nat-server process\n");
2158 return GNUNET_SYSERR;
2160 /* Close the write end of the read pipe */
2161 GNUNET_DISK_pipe_close_end(plugin->server_stdout, GNUNET_DISK_PIPE_END_WRITE);
2163 plugin->server_stdout_handle = GNUNET_DISK_pipe_handle(plugin->server_stdout, GNUNET_DISK_PIPE_END_READ);
2164 plugin->server_read_task =
2165 GNUNET_SCHEDULER_add_read_file (plugin->env->sched,
2166 GNUNET_TIME_UNIT_FOREVER_REL,
2167 plugin->server_stdout_handle, &tcp_plugin_server_read, plugin);
2172 * Return the actual path to a file found in the current
2173 * PATH environment variable.
2175 * @param binary the name of the file to find
2178 get_path_from_PATH (char *binary)
2186 p = getenv ("PATH");
2189 path = GNUNET_strdup (p); /* because we write on it */
2190 buf = GNUNET_malloc (strlen (path) + 20);
2193 while (NULL != (end = strchr (pos, ':')))
2196 sprintf (buf, "%s/%s", pos, binary);
2197 if (GNUNET_DISK_file_test (buf) == GNUNET_YES)
2204 sprintf (buf, "%s/%s", pos, binary);
2205 if (GNUNET_DISK_file_test (buf) == GNUNET_YES)
2216 * Check whether the suid bit is set on a file.
2217 * Attempts to find the file using the current
2218 * PATH environment variable as a search path.
2220 * @param binary the name of the file to check
2223 check_gnunet_nat_binary(char *binary)
2225 struct stat statbuf;
2228 p = get_path_from_PATH (binary);
2231 if (0 != STAT (p, &statbuf))
2234 return GNUNET_SYSERR;
2237 if ( (0 != (statbuf.st_mode & S_ISUID)) &&
2238 (statbuf.st_uid == 0) )
2244 * Entry point for the plugin.
2246 * @param cls closure, the 'struct GNUNET_TRANSPORT_PluginEnvironment*'
2247 * @return the 'struct GNUNET_TRANSPORT_PluginFunctions*' or NULL on error
2250 libgnunet_plugin_transport_tcp_init (void *cls)
2252 static const struct GNUNET_SERVER_MessageHandler my_handlers[] = {
2253 {&handle_tcp_welcome, NULL, GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME,
2254 sizeof (struct WelcomeMessage)},
2255 {&handle_tcp_nat_probe, NULL, GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE, sizeof (struct TCP_NAT_ProbeMessage)},
2256 {&handle_tcp_data, NULL, GNUNET_MESSAGE_TYPE_ALL, 0},
2259 struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
2260 struct GNUNET_TRANSPORT_PluginFunctions *api;
2261 struct Plugin *plugin;
2262 struct GNUNET_SERVICE_Context *service;
2263 unsigned long long aport;
2264 unsigned long long bport;
2268 int only_nat_addresses;
2269 char *internal_address;
2270 char *external_address;
2271 struct sockaddr_in in_addr;
2272 struct IPv4TcpAddress t4;
2274 service = GNUNET_SERVICE_start ("transport-tcp", env->sched, env->cfg);
2275 if (service == NULL)
2277 GNUNET_log_from (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_from (GNUNET_ERROR_TYPE_WARNING, "tcp", "Configuration specified you are behind a NAT, but gnunet-nat-server is not installed properly (suid bit not set)!\n");
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_from (GNUNET_ERROR_TYPE_WARNING, "tcp", "Configuration specified you want to connect to NAT'd peers, but gnunet-nat-client is not installed properly (suid bit not set)!\n");
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_from (GNUNET_ERROR_TYPE_ERROR,
2336 ("Require EXTERNAL_ADDRESS for service `%s' in configuration (either BEHIND_NAT or ALLOW_NAT set to YES)!\n"),
2338 GNUNET_SERVICE_stop (service);
2342 if ((external_address != NULL) && (inet_pton(AF_INET, external_address, &in_addr.sin_addr) != 1))
2344 GNUNET_log_from(GNUNET_ERROR_TYPE_WARNING, "udp", "Malformed EXTERNAL_ADDRESS %s given in configuration!\n", external_address);
2347 internal_address = NULL;
2348 if ((GNUNET_YES == behind_nat) && (GNUNET_OK !=
2349 GNUNET_CONFIGURATION_get_value_string (env->cfg,
2352 &internal_address)))
2354 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
2357 ("Require INTERNAL_ADDRESS for service `%s' in configuration!\n"),
2359 GNUNET_SERVICE_stop (service);
2360 GNUNET_free_non_null(external_address);
2364 if ((internal_address != NULL) && (inet_pton(AF_INET, internal_address, &in_addr.sin_addr) != 1))
2366 GNUNET_log_from(GNUNET_ERROR_TYPE_WARNING, "udp", "Malformed INTERNAL_ADDRESS %s given in configuration!\n", internal_address);
2371 GNUNET_CONFIGURATION_get_value_number (env->cfg,
2377 GNUNET_CONFIGURATION_get_value_number (env->cfg,
2380 &aport)) && (aport > 65535)))
2382 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
2385 ("Require valid port number for service `%s' in configuration!\n"),
2387 GNUNET_free_non_null(external_address);
2388 GNUNET_free_non_null(internal_address);
2389 GNUNET_SERVICE_stop (service);
2395 plugin = GNUNET_malloc (sizeof (struct Plugin));
2396 plugin->open_port = bport;
2397 plugin->adv_port = aport;
2398 plugin->external_address = external_address;
2399 plugin->internal_address = internal_address;
2400 plugin->behind_nat = behind_nat;
2401 plugin->allow_nat = allow_nat;
2402 plugin->only_nat_addresses = only_nat_addresses;
2404 plugin->lsock = NULL;
2405 api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
2407 api->send = &tcp_plugin_send;
2408 api->disconnect = &tcp_plugin_disconnect;
2409 api->address_pretty_printer = &tcp_plugin_address_pretty_printer;
2410 api->check_address = &tcp_plugin_check_address;
2411 api->address_to_string = &tcp_address_to_string;
2412 plugin->service = service;
2413 plugin->server = GNUNET_SERVICE_get_server (service);
2414 plugin->handlers = GNUNET_malloc (sizeof (my_handlers));
2415 memcpy (plugin->handlers, my_handlers, sizeof (my_handlers));
2418 sizeof (my_handlers) / sizeof (struct GNUNET_SERVER_MessageHandler);
2420 plugin->handlers[i].callback_cls = plugin;
2421 GNUNET_SERVER_add_handlers (plugin->server, plugin->handlers);
2423 if (behind_nat == GNUNET_YES)
2425 if (GNUNET_YES != tcp_transport_start_nat_server(plugin))
2427 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
2430 ("Failed to start %s required for NAT in %s!\n"),
2433 GNUNET_free_non_null(external_address);
2434 GNUNET_free_non_null(internal_address);
2435 GNUNET_SERVICE_stop (service);
2440 if (allow_nat == GNUNET_YES)
2442 plugin->nat_wait_conns = GNUNET_CONTAINER_multihashmap_create(100);
2443 GNUNET_assert(plugin->nat_wait_conns != NULL);
2446 GNUNET_log_from (GNUNET_ERROR_TYPE_INFO,
2447 "tcp", _("TCP transport listening on port %llu\n"), bport);
2449 GNUNET_log_from (GNUNET_ERROR_TYPE_INFO,
2451 _("TCP transport advertises itself as being on port %llu\n"),
2453 GNUNET_SERVER_disconnect_notify (plugin->server,
2456 if (plugin->behind_nat == GNUNET_NO)
2458 GNUNET_OS_network_interfaces_list (&process_interfaces, plugin);
2461 plugin->hostname_dns = GNUNET_RESOLVER_hostname_resolve (env->sched,
2464 HOSTNAME_RESOLVE_TIMEOUT,
2465 &process_hostname_ips,
2468 if ((plugin->behind_nat == GNUNET_YES) && (inet_pton(AF_INET, plugin->external_address, &t4.ipv4_addr) == 1))
2470 t4.t_port = htons(0);
2471 plugin->env->notify_address (plugin->env->cls,
2473 &t4, sizeof(t4), GNUNET_TIME_UNIT_FOREVER_REL);
2475 else if ((plugin->external_address != NULL) && (inet_pton(AF_INET, plugin->external_address, &t4.ipv4_addr) == 1))
2477 t4.t_port = htons(plugin->adv_port);
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,
2514 GNUNET_free (plugin);
2519 /* end of plugin_transport_tcp.c */