2 This file is part of GNUnet
3 (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 Christian Grothoff (and other contributing authors)
5 GNUnet is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published
7 by the Free Software Foundation; either version 2, or (at your
8 option) any later version.
10 GNUnet is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with GNUnet; see the file COPYING. If not, write to the
17 Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18 Boston, MA 02111-1307, USA.
21 * @file transport/plugin_transport_tcp.c
22 * @brief Implementation of the TCP transport service
23 * @author Christian Grothoff
26 #include "gnunet_hello_lib.h"
27 #include "gnunet_connection_lib.h"
28 #include "gnunet_container_lib.h"
29 #include "gnunet_os_lib.h"
30 #include "gnunet_protocols.h"
31 #include "gnunet_resolver_service.h"
32 #include "gnunet_server_lib.h"
33 #include "gnunet_service_lib.h"
34 #include "gnunet_signatures.h"
35 #include "gnunet_statistics_service.h"
36 #include "gnunet_transport_service.h"
37 #include "plugin_transport.h"
38 #include "transport.h"
40 #define DEBUG_TCP GNUNET_NO
41 #define DEBUG_TCP_NAT GNUNET_NO
44 * How long until we give up on transmitting the welcome message?
46 #define HOSTNAME_RESOLVE_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 5)
50 * Initial handshake message for a session.
55 * Type is GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME.
57 struct GNUNET_MessageHeader header;
60 * Identity of the node connecting (TCP client)
62 struct GNUNET_PeerIdentity clientIdentity;
67 * Basically a WELCOME message, but with the purpose
68 * of giving the waiting peer a client handle to use
70 struct TCP_NAT_ProbeMessage
73 * Type is GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE.
75 struct GNUNET_MessageHeader header;
78 * Identity of the sender of the message.
80 struct GNUNET_PeerIdentity clientIdentity;
85 * Context for sending a NAT probe via TCP.
87 struct TCPProbeContext
92 struct GNUNET_CONNECTION_Handle *sock;
97 struct TCP_NAT_ProbeMessage message;
100 * Handle to the transmission.
102 struct GNUNET_CONNECTION_TransmitHandle *transmit_handle;
105 * Transport plugin handle.
107 struct Plugin *plugin;
112 * Network format for IPv4 addresses.
114 struct IPv4TcpAddress
117 * IPv4 address, in network byte order.
122 * Port number, in network byte order.
130 * Network format for IPv6 addresses.
132 struct IPv6TcpAddress
137 struct in6_addr ipv6_addr;
140 * Port number, in network byte order.
147 * Encapsulation of all of the state of the plugin.
153 * Information kept for each message that is yet to
156 struct PendingMessage
160 * This is a doubly-linked list.
162 struct PendingMessage *next;
165 * This is a doubly-linked list.
167 struct PendingMessage *prev;
170 * The pending message
175 * Continuation function to call once the message
176 * has been sent. Can be NULL if there is no
177 * continuation to call.
179 GNUNET_TRANSPORT_TransmitContinuation transmit_cont;
182 * Closure for transmit_cont.
184 void *transmit_cont_cls;
187 * Timeout value for the pending message.
189 struct GNUNET_TIME_Absolute timeout;
192 * So that the gnunet-service-transport can group messages together,
193 * these pending messages need to accept a message buffer and size
194 * instead of just a GNUNET_MessageHeader.
202 * Session handle for TCP connections.
208 * Stored in a linked list.
210 struct Session *next;
213 * Pointer to the global plugin struct.
215 struct Plugin *plugin;
218 * The client (used to identify this connection)
220 struct GNUNET_SERVER_Client *client;
223 * Messages currently pending for transmission
224 * to this peer, if any.
226 struct PendingMessage *pending_messages_head;
229 * Messages currently pending for transmission
230 * to this peer, if any.
232 struct PendingMessage *pending_messages_tail;
235 * Handle for pending transmission request.
237 struct GNUNET_CONNECTION_TransmitHandle *transmit_handle;
240 * To whom are we talking to (set to our identity
241 * if we are still waiting for the welcome message)
243 struct GNUNET_PeerIdentity target;
246 * ID of task used to delay receiving more to throttle sender.
248 GNUNET_SCHEDULER_TaskIdentifier receive_delay_task;
251 * Address of the other peer (either based on our 'connect'
252 * call or on our 'accept' call).
257 * Last activity on this connection. Used to select preferred
260 struct GNUNET_TIME_Absolute last_activity;
263 * Length of connect_addr.
268 * Are we still expecting the welcome message? (GNUNET_YES/GNUNET_NO)
270 int expecting_welcome;
273 * Was this a connection that was inbound (we accepted)? (GNUNET_YES/GNUNET_NO)
281 * Encapsulation of all of the state of the plugin.
288 struct GNUNET_TRANSPORT_PluginEnvironment *env;
293 struct GNUNET_CONNECTION_Handle *lsock;
296 * stdout pipe handle for the gnunet-nat-server process
298 struct GNUNET_DISK_PipeHandle *server_stdout;
301 * stdout file handle (for reading) for the gnunet-nat-server process
303 const struct GNUNET_DISK_FileHandle *server_stdout_handle;
306 * ID of select gnunet-nat-server stdout read task
308 GNUNET_SCHEDULER_TaskIdentifier server_read_task;
311 * The process id of the server process (if behind NAT)
316 * List of open TCP sessions.
318 struct Session *sessions;
321 * Handle to the network service.
323 struct GNUNET_SERVICE_Context *service;
326 * Handle to the server for this service.
328 struct GNUNET_SERVER_Handle *server;
331 * Copy of the handler array where the closures are
332 * set to this struct's instance.
334 struct GNUNET_SERVER_MessageHandler *handlers;
337 * Handle for request of hostname resolution, non-NULL if pending.
339 struct GNUNET_RESOLVER_RequestHandle *hostname_dns;
342 * Map of peers we have tried to contact behind a NAT
344 struct GNUNET_CONTAINER_MultiHashMap *nat_wait_conns;
347 * The external address given to us by the user. Must be actual
348 * outside visible address for NAT punching to work.
350 char *external_address;
353 * The internal address given to us by the user (or discovered).
355 char *internal_address;
358 * ID of task used to update our addresses when one expires.
360 GNUNET_SCHEDULER_TaskIdentifier address_update_task;
363 * Port that we are actually listening on.
368 * Port that the user said we would have visible to the
374 * Is this transport configured to be behind a NAT?
379 * Is this transport configured to allow connections to NAT'd peers?
384 * Should this transport advertise only NAT addresses (port set to 0)?
385 * If not, all addresses will be duplicated for NAT punching and regular
388 int only_nat_addresses;
396 * Function called for a quick conversion of the binary address to
397 * a numeric address. Note that the caller must not free the
398 * address and that the next call to this function is allowed
399 * to override the address again.
401 * @param cls closure ('struct Plugin*')
402 * @param addr binary address
403 * @param addrlen length of the address
404 * @return string representing the same address
407 tcp_address_to_string (void *cls,
411 static char rbuf[INET6_ADDRSTRLEN + 12];
412 char buf[INET6_ADDRSTRLEN];
416 const struct IPv4TcpAddress *t4;
417 const struct IPv6TcpAddress *t6;
421 if (addrlen == sizeof (struct IPv6TcpAddress))
425 port = ntohs (t6->t6_port);
426 memcpy (&a6, &t6->ipv6_addr, sizeof (a6));
429 else if (addrlen == sizeof (struct IPv4TcpAddress))
433 port = ntohs (t4->t_port);
434 memcpy (&a4, &t4->ipv4_addr, sizeof (a4));
439 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
441 _("Unexected address length: %u\n"),
446 if (NULL == inet_ntop (af, sb, buf, INET6_ADDRSTRLEN))
448 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "inet_ntop");
451 GNUNET_snprintf (rbuf,
453 (af == AF_INET6) ? "[%s]:%u" : "%s:%u",
461 * Find the session handle for the given client.
463 * @return NULL if no matching session exists
465 static struct Session *
466 find_session_by_client (struct Plugin *plugin,
467 const struct GNUNET_SERVER_Client *client)
471 ret = plugin->sessions;
472 while ((ret != NULL) && (client != ret->client))
478 * Create a new session. Also queues a welcome message.
481 * @param target peer to connect to
482 * @param client client to use
483 * @param is_nat this a NAT session, we should wait for a client to
484 * connect to us from an address, then assign that to
486 * @return new session object
488 static struct Session *
489 create_session (struct Plugin *plugin,
490 const struct GNUNET_PeerIdentity *target,
491 struct GNUNET_SERVER_Client *client, int is_nat)
494 struct PendingMessage *pm;
495 struct WelcomeMessage welcome;
497 if (is_nat != GNUNET_YES)
498 GNUNET_assert (client != NULL);
500 GNUNET_assert (client == NULL);
503 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
505 "Creating new session for peer `%4s'\n",
506 GNUNET_i2s (target));
508 ret = GNUNET_malloc (sizeof (struct Session));
509 ret->last_activity = GNUNET_TIME_absolute_get ();
510 ret->plugin = plugin;
511 if (is_nat != GNUNET_YES) /* If not a NAT WAIT conn, add it to global list */
513 ret->next = plugin->sessions;
514 plugin->sessions = ret;
516 ret->client = client;
517 ret->target = *target;
518 ret->expecting_welcome = GNUNET_YES;
519 pm = GNUNET_malloc (sizeof (struct PendingMessage) + sizeof (struct WelcomeMessage));
520 pm->msg = (const char*) &pm[1];
521 pm->message_size = sizeof (struct WelcomeMessage);
522 welcome.header.size = htons (sizeof (struct WelcomeMessage));
523 welcome.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME);
524 welcome.clientIdentity = *plugin->env->my_identity;
525 memcpy (&pm[1], &welcome, sizeof (welcome));
526 pm->timeout = GNUNET_TIME_UNIT_FOREVER_ABS;
527 GNUNET_STATISTICS_update (plugin->env->stats,
528 gettext_noop ("# bytes currently in TCP buffers"),
531 GNUNET_CONTAINER_DLL_insert (ret->pending_messages_head,
532 ret->pending_messages_tail,
534 if (is_nat != GNUNET_YES)
535 GNUNET_STATISTICS_update (plugin->env->stats,
536 gettext_noop ("# TCP sessions active"),
544 * If we have pending messages, ask the server to
545 * transmit them (schedule the respective tasks, etc.)
547 * @param session for which session should we do this
549 static void process_pending_messages (struct Session *session);
553 * Function called to notify a client about the socket
554 * being ready to queue more data. "buf" will be
555 * NULL and "size" zero if the socket was closed for
556 * writing in the meantime.
559 * @param size number of bytes available in buf
560 * @param buf where the callee should write the message
561 * @return number of bytes written to buf
564 do_transmit (void *cls, size_t size, void *buf)
566 struct Session *session = cls;
567 struct GNUNET_PeerIdentity pid;
568 struct Plugin *plugin;
569 struct PendingMessage *pos;
570 struct PendingMessage *hd;
571 struct PendingMessage *tl;
572 struct GNUNET_TIME_Absolute now;
576 session->transmit_handle = NULL;
577 plugin = session->plugin;
581 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
583 "Timeout trying to transmit to peer `%4s', discarding message queue.\n",
584 GNUNET_i2s (&session->target));
586 /* timeout; cancel all messages that have already expired */
590 now = GNUNET_TIME_absolute_get ();
591 while ( (NULL != (pos = session->pending_messages_head)) &&
592 (pos->timeout.value <= now.value) )
594 GNUNET_CONTAINER_DLL_remove (session->pending_messages_head,
595 session->pending_messages_tail,
598 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
600 "Failed to transmit %u byte message to `%4s'.\n",
602 GNUNET_i2s (&session->target));
604 ret += pos->message_size;
605 GNUNET_CONTAINER_DLL_insert_after (hd, tl, tl, pos);
607 /* do this call before callbacks (so that if callbacks destroy
608 session, they have a chance to cancel actions done by this
610 process_pending_messages (session);
611 pid = session->target;
612 /* no do callbacks and do not use session again since
613 the callbacks may abort the session */
614 while (NULL != (pos = hd))
616 GNUNET_CONTAINER_DLL_remove (hd, tl, pos);
617 if (pos->transmit_cont != NULL)
618 pos->transmit_cont (pos->transmit_cont_cls,
619 &pid, GNUNET_SYSERR);
622 GNUNET_STATISTICS_update (plugin->env->stats,
623 gettext_noop ("# bytes currently in TCP buffers"),
626 GNUNET_STATISTICS_update (plugin->env->stats,
627 gettext_noop ("# bytes discarded by TCP (timeout)"),
632 /* copy all pending messages that would fit */
637 while (NULL != (pos = session->pending_messages_head))
639 if (ret + pos->message_size > size)
641 GNUNET_CONTAINER_DLL_remove (session->pending_messages_head,
642 session->pending_messages_tail,
644 GNUNET_assert (size >= pos->message_size);
645 memcpy (cbuf, pos->msg, pos->message_size);
646 cbuf += pos->message_size;
647 ret += pos->message_size;
648 size -= pos->message_size;
649 GNUNET_CONTAINER_DLL_insert_after (hd, tl, tl, pos);
651 /* schedule 'continuation' before callbacks so that callbacks that
652 cancel everything don't cause us to use a session that no longer
654 process_pending_messages (session);
655 session->last_activity = GNUNET_TIME_absolute_get ();
656 pid = session->target;
657 /* we'll now call callbacks that may cancel the session; hence
658 we should not use 'session' after this point */
659 while (NULL != (pos = hd))
661 GNUNET_CONTAINER_DLL_remove (hd, tl, pos);
662 if (pos->transmit_cont != NULL)
663 pos->transmit_cont (pos->transmit_cont_cls,
667 GNUNET_assert (hd == NULL);
668 GNUNET_assert (tl == NULL);
670 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
671 "tcp", "Transmitting %u bytes\n", ret);
673 GNUNET_STATISTICS_update (plugin->env->stats,
674 gettext_noop ("# bytes currently in TCP buffers"),
677 GNUNET_STATISTICS_update (plugin->env->stats,
678 gettext_noop ("# bytes transmitted via TCP"),
686 * If we have pending messages, ask the server to
687 * transmit them (schedule the respective tasks, etc.)
689 * @param session for which session should we do this
692 process_pending_messages (struct Session *session)
694 struct PendingMessage *pm;
696 GNUNET_assert (session->client != NULL);
697 if (session->transmit_handle != NULL)
699 if (NULL == (pm = session->pending_messages_head))
701 session->transmit_handle
702 = GNUNET_SERVER_notify_transmit_ready (session->client,
704 GNUNET_TIME_absolute_get_remaining
706 &do_transmit, session);
711 * Functions with this signature are called whenever we need
712 * to close a session due to a disconnect or failure to
713 * establish a connection.
715 * @param session session to close down
718 disconnect_session (struct Session *session)
720 struct Session *prev;
722 struct PendingMessage *pm;
725 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
727 "Disconnecting from `%4s' at %s (session %p).\n",
728 GNUNET_i2s (&session->target),
729 (session->connect_addr != NULL) ?
730 tcp_address_to_string (session->plugin,
731 session->connect_addr,
732 session->connect_alen) : "*",
735 /* remove from session list */
737 pos = session->plugin->sessions;
738 while (pos != session)
744 session->plugin->sessions = session->next;
746 prev->next = session->next;
747 session->plugin->env->session_end (session->plugin->env->cls,
751 if (session->transmit_handle != NULL)
753 GNUNET_CONNECTION_notify_transmit_ready_cancel
754 (session->transmit_handle);
755 session->transmit_handle = NULL;
757 while (NULL != (pm = session->pending_messages_head))
760 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
762 pm->transmit_cont != NULL
763 ? "Could not deliver message to `%4s'.\n"
765 "Could not deliver message to `%4s', notifying.\n",
766 GNUNET_i2s (&session->target));
768 GNUNET_STATISTICS_update (session->plugin->env->stats,
769 gettext_noop ("# bytes currently in TCP buffers"),
770 - (int64_t) pm->message_size,
772 GNUNET_STATISTICS_update (session->plugin->env->stats,
773 gettext_noop ("# bytes discarded by TCP (disconnect)"),
776 GNUNET_CONTAINER_DLL_remove (session->pending_messages_head,
777 session->pending_messages_tail,
779 if (NULL != pm->transmit_cont)
780 pm->transmit_cont (pm->transmit_cont_cls,
781 &session->target, GNUNET_SYSERR);
784 GNUNET_break (session->client != NULL);
785 if (session->receive_delay_task != GNUNET_SCHEDULER_NO_TASK)
787 GNUNET_SCHEDULER_cancel (session->plugin->env->sched,
788 session->receive_delay_task);
789 GNUNET_SERVER_receive_done (session->client,
792 GNUNET_SERVER_client_drop (session->client);
793 GNUNET_STATISTICS_update (session->plugin->env->stats,
794 gettext_noop ("# TCP sessions active"),
797 GNUNET_free_non_null (session->connect_addr);
798 GNUNET_free (session);
803 * Given two otherwise equivalent sessions, pick the better one.
805 * @param s1 one session (also default)
806 * @param s2 other session
807 * @return "better" session (more active)
809 static struct Session *
810 select_better_session (struct Session *s1,
817 if ( (s1->expecting_welcome == GNUNET_NO) &&
818 (s2->expecting_welcome == GNUNET_YES) )
820 if ( (s1->expecting_welcome == GNUNET_YES) &&
821 (s2->expecting_welcome == GNUNET_NO) )
823 if (s1->last_activity.value < s2->last_activity.value)
825 if (s1->last_activity.value > s2->last_activity.value)
827 if ( (GNUNET_YES == s1->inbound) &&
828 (GNUNET_NO == s2->inbound) )
830 if ( (GNUNET_NO == s1->inbound) &&
831 (GNUNET_YES == s2->inbound) )
838 * We learned about a peer (possibly behind NAT) so run the
839 * gnunet-nat-client to send dummy ICMP responses
841 * @param plugin the plugin for this transport
842 * @param addr the address of the peer
843 * @param addrlen the length of the address
846 run_gnunet_nat_client (struct Plugin *plugin, const char *addr, size_t addrlen)
848 char inet4[INET_ADDRSTRLEN];
849 char *address_as_string;
850 char *port_as_string;
852 const struct sockaddr *sa = (const struct sockaddr *)addr;
854 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
855 _("called run_gnunet_nat_client addrlen %d others are %d and %d\n"), addrlen, sizeof (struct sockaddr), sizeof (struct sockaddr_in));
858 if (addrlen < sizeof (struct sockaddr))
861 switch (sa->sa_family)
864 if (addrlen != sizeof (struct sockaddr_in))
866 if (NULL == inet_ntop (AF_INET,
867 &((struct sockaddr_in *) sa)->sin_addr,
868 inet4, INET_ADDRSTRLEN))
870 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "inet_ntop");
873 address_as_string = GNUNET_strdup (inet4);
880 GNUNET_asprintf(&port_as_string, "%d", plugin->adv_port);
882 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
883 _("Running gnunet-nat-client with arguments: %s %s %d\n"), plugin->external_address, address_as_string, plugin->adv_port);
886 /* Start the client process */
887 pid = GNUNET_OS_start_process(NULL, NULL, "gnunet-nat-client", "gnunet-nat-client", plugin->external_address, address_as_string, port_as_string, NULL);
888 GNUNET_free(address_as_string);
889 GNUNET_free(port_as_string);
890 GNUNET_OS_process_wait (pid);
895 * Function that can be used by the transport service to transmit
896 * a message using the plugin. Note that in the case of a
897 * peer disconnecting, the continuation MUST be called
898 * prior to the disconnect notification itself. This function
899 * will be called with this peer's HELLO message to initiate
900 * a fresh connection to another peer.
903 * @param target who should receive this message
904 * @param msg the message to transmit
905 * @param msgbuf_size number of bytes in 'msg'
906 * @param priority how important is the message (most plugins will
907 * ignore message priority and just FIFO)
908 * @param timeout how long to wait at most for the transmission (does not
909 * require plugins to discard the message after the timeout,
910 * just advisory for the desired delay; most plugins will ignore
912 * @param session which session must be used (or NULL for "any")
913 * @param addr the address to use (can be NULL if the plugin
914 * is "on its own" (i.e. re-use existing TCP connection))
915 * @param addrlen length of the address in bytes
916 * @param force_address GNUNET_YES if the plugin MUST use the given address,
917 * GNUNET_NO means the plugin may use any other address and
918 * GNUNET_SYSERR means that only reliable existing
919 * bi-directional connections should be used (regardless
921 * @param cont continuation to call once the message has
922 * been transmitted (or if the transport is ready
923 * for the next transmission call; or if the
924 * peer disconnected...); can be NULL
925 * @param cont_cls closure for cont
926 * @return number of bytes used (on the physical network, with overheads);
927 * -1 on hard errors (i.e. address invalid); 0 is a legal value
928 * and does NOT mean that the message was not transmitted (DV and NAT)
931 tcp_plugin_send (void *cls,
932 const struct GNUNET_PeerIdentity *target,
936 struct GNUNET_TIME_Relative timeout,
937 struct Session *session,
941 GNUNET_TRANSPORT_TransmitContinuation cont, void *cont_cls)
943 struct Plugin *plugin = cls;
944 struct Session *cand_session;
945 struct Session *next;
946 struct PendingMessage *pm;
947 struct GNUNET_CONNECTION_Handle *sa;
951 struct sockaddr_in a4;
952 struct sockaddr_in6 a6;
953 const struct IPv4TcpAddress *t4;
954 const struct IPv6TcpAddress *t6;
955 unsigned int is_natd;
957 GNUNET_STATISTICS_update (plugin->env->stats,
958 gettext_noop ("# bytes TCP was asked to transmit"),
961 /* FIXME: we could do this cheaper with a hash table
962 where we could restrict the iteration to entries that match
963 the target peer... */
968 next = plugin->sessions;
969 while (NULL != (session = next))
971 next = session->next;
972 GNUNET_assert (session->client != NULL);
973 if (0 != memcmp (target,
975 sizeof (struct GNUNET_PeerIdentity)))
977 if ( ( (GNUNET_SYSERR == force_address) &&
978 (session->expecting_welcome == GNUNET_NO) ) ||
979 (GNUNET_NO == force_address) )
981 cand_session = select_better_session (cand_session,
985 if (GNUNET_SYSERR == force_address)
987 GNUNET_break (GNUNET_YES == force_address);
993 if (session->inbound == GNUNET_YES)
995 if (addrlen != session->connect_alen)
997 if (0 != memcmp (session->connect_addr,
1001 cand_session = select_better_session (cand_session,
1004 session = cand_session;
1006 if ( (session == NULL) &&
1010 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1012 "Asked to transmit to `%4s' without address and I have no existing connection (failing).\n",
1013 GNUNET_i2s (target));
1015 GNUNET_STATISTICS_update (plugin->env->stats,
1016 gettext_noop ("# bytes discarded by TCP (no address and no connection)"),
1021 if (session == NULL)
1023 if (addrlen == sizeof (struct IPv6TcpAddress))
1027 memset (&a6, 0, sizeof (a6));
1028 #if HAVE_SOCKADDR_IN_SIN_LEN
1029 a6.sin6_len = sizeof (a6);
1031 a6.sin6_family = AF_INET6;
1032 a6.sin6_port = t6->t6_port;
1033 if (t6->t6_port == 0)
1034 is_natd = GNUNET_YES;
1035 memcpy (&a6.sin6_addr,
1037 sizeof (struct in6_addr));
1041 else if (addrlen == sizeof (struct IPv4TcpAddress))
1045 memset (&a4, 0, sizeof (a4));
1046 #if HAVE_SOCKADDR_IN_SIN_LEN
1047 a4.sin_len = sizeof (a4);
1049 a4.sin_family = AF_INET;
1050 a4.sin_port = t4->t_port;
1051 if (t4->t_port == 0)
1052 is_natd = GNUNET_YES;
1053 a4.sin_addr.s_addr = t4->ipv4_addr;
1059 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
1061 _("Address of unexpected length: %u\n"),
1067 if ((is_natd == GNUNET_YES) && (addrlen == sizeof (struct IPv6TcpAddress)))
1068 return -1; /* NAT client only works with IPv4 addresses */
1071 if ( (plugin->allow_nat == GNUNET_YES) && (is_natd == GNUNET_YES) &&
1072 (GNUNET_NO == GNUNET_CONTAINER_multihashmap_contains(plugin->nat_wait_conns, &target->hashPubKey)))
1075 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1077 _("Found valid IPv4 NAT address!\n"));
1079 session = create_session (plugin,
1083 /* create new message entry */
1084 pm = GNUNET_malloc (sizeof (struct PendingMessage) + msgbuf_size);
1085 pm->msg = (const char*) &pm[1];
1086 memcpy (&pm[1], msg, msgbuf_size);
1087 pm->message_size = msgbuf_size;
1088 pm->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1089 pm->transmit_cont = cont;
1090 pm->transmit_cont_cls = cont_cls;
1092 /* append pm to pending_messages list */
1093 GNUNET_CONTAINER_DLL_insert_after (session->pending_messages_head,
1094 session->pending_messages_tail,
1095 session->pending_messages_tail,
1098 GNUNET_assert(GNUNET_CONTAINER_multihashmap_put(plugin->nat_wait_conns, &target->hashPubKey, session, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY) == GNUNET_OK);
1100 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1102 "Created NAT WAIT connection to `%4s' at `%s'\n",
1103 GNUNET_i2s (target),
1104 GNUNET_a2s (sb, sbs));
1106 run_gnunet_nat_client(plugin, sb, sbs);
1109 else if ((plugin->allow_nat == GNUNET_YES) && (is_natd == GNUNET_YES) && (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains(plugin->nat_wait_conns, &target->hashPubKey)))
1111 /* Only do one NAT punch attempt per peer identity */
1114 sa = GNUNET_CONNECTION_create_from_sockaddr (plugin->env->sched,
1116 GNUNET_SERVER_MAX_MESSAGE_SIZE);
1120 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1122 "Failed to create connection to `%4s' at `%s'\n",
1123 GNUNET_i2s (target),
1124 GNUNET_a2s (sb, sbs));
1126 GNUNET_STATISTICS_update (plugin->env->stats,
1127 gettext_noop ("# bytes discarded by TCP (failed to connect)"),
1133 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1135 "Asked to transmit to `%4s', creating fresh session using address `%s'.\n",
1136 GNUNET_i2s (target),
1137 GNUNET_a2s (sb, sbs));
1139 session = create_session (plugin,
1141 GNUNET_SERVER_connect_socket (plugin->server,
1143 session->connect_addr = GNUNET_malloc (addrlen);
1144 memcpy (session->connect_addr,
1147 session->connect_alen = addrlen;
1149 GNUNET_assert (session != NULL);
1150 GNUNET_assert (session->client != NULL);
1151 GNUNET_STATISTICS_update (plugin->env->stats,
1152 gettext_noop ("# bytes currently in TCP buffers"),
1155 /* create new message entry */
1156 pm = GNUNET_malloc (sizeof (struct PendingMessage) + msgbuf_size);
1157 pm->msg = (const char*) &pm[1];
1158 memcpy (&pm[1], msg, msgbuf_size);
1159 pm->message_size = msgbuf_size;
1160 pm->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1161 pm->transmit_cont = cont;
1162 pm->transmit_cont_cls = cont_cls;
1164 /* append pm to pending_messages list */
1165 GNUNET_CONTAINER_DLL_insert_after (session->pending_messages_head,
1166 session->pending_messages_tail,
1167 session->pending_messages_tail,
1170 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1172 "Asked to transmit %u bytes to `%s', added message to list.\n",
1174 GNUNET_i2s (target));
1176 process_pending_messages (session);
1182 * Function that can be called to force a disconnect from the
1183 * specified neighbour. This should also cancel all previously
1184 * scheduled transmissions. Obviously the transmission may have been
1185 * partially completed already, which is OK. The plugin is supposed
1186 * to close the connection (if applicable) and no longer call the
1187 * transmit continuation(s).
1189 * Finally, plugin MUST NOT call the services's receive function to
1190 * notify the service that the connection to the specified target was
1191 * closed after a getting this call.
1193 * @param cls closure
1194 * @param target peer for which the last transmission is
1198 tcp_plugin_disconnect (void *cls,
1199 const struct GNUNET_PeerIdentity *target)
1201 struct Plugin *plugin = cls;
1202 struct Session *session;
1203 struct Session *next;
1204 struct PendingMessage *pm;
1207 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1209 "Asked to cancel session with `%4s'\n",
1210 GNUNET_i2s (target));
1212 next = plugin->sessions;
1213 while (NULL != (session = next))
1215 next = session->next;
1216 if (0 != memcmp (target,
1218 sizeof (struct GNUNET_PeerIdentity)))
1220 pm = session->pending_messages_head;
1223 pm->transmit_cont = NULL;
1224 pm->transmit_cont_cls = NULL;
1227 disconnect_session (session);
1233 * Context for address to string conversion.
1235 struct PrettyPrinterContext
1238 * Function to call with the result.
1240 GNUNET_TRANSPORT_AddressStringCallback asc;
1243 * Clsoure for 'asc'.
1248 * Port to add after the IP address.
1255 * Append our port and forward the result.
1257 * @param cls the 'struct PrettyPrinterContext*'
1258 * @param hostname hostname part of the address
1261 append_port (void *cls, const char *hostname)
1263 struct PrettyPrinterContext *ppc = cls;
1266 if (hostname == NULL)
1268 ppc->asc (ppc->asc_cls, NULL);
1272 GNUNET_asprintf (&ret, "%s:%d", hostname, ppc->port);
1273 ppc->asc (ppc->asc_cls, ret);
1279 * Convert the transports address to a nice, human-readable
1282 * @param cls closure
1283 * @param type name of the transport that generated the address
1284 * @param addr one of the addresses of the host, NULL for the last address
1285 * the specific address format depends on the transport
1286 * @param addrlen length of the address
1287 * @param numeric should (IP) addresses be displayed in numeric form?
1288 * @param timeout after how long should we give up?
1289 * @param asc function to call on each string
1290 * @param asc_cls closure for asc
1293 tcp_plugin_address_pretty_printer (void *cls,
1298 struct GNUNET_TIME_Relative timeout,
1299 GNUNET_TRANSPORT_AddressStringCallback asc,
1302 struct Plugin *plugin = cls;
1303 struct PrettyPrinterContext *ppc;
1306 struct sockaddr_in a4;
1307 struct sockaddr_in6 a6;
1308 const struct IPv4TcpAddress *t4;
1309 const struct IPv6TcpAddress *t6;
1312 if (addrlen == sizeof (struct IPv6TcpAddress))
1315 memset (&a6, 0, sizeof (a6));
1316 a6.sin6_family = AF_INET6;
1317 a6.sin6_port = t6->t6_port;
1318 memcpy (&a6.sin6_addr,
1320 sizeof (struct in6_addr));
1321 port = ntohs (t6->t6_port);
1325 else if (addrlen == sizeof (struct IPv4TcpAddress))
1328 memset (&a4, 0, sizeof (a4));
1329 a4.sin_family = AF_INET;
1330 a4.sin_port = t4->t_port;
1331 a4.sin_addr.s_addr = t4->ipv4_addr;
1332 port = ntohs (t4->t_port);
1338 /* invalid address */
1339 GNUNET_break_op (0);
1340 asc (asc_cls, NULL);
1343 ppc = GNUNET_malloc (sizeof (struct PrettyPrinterContext));
1345 ppc->asc_cls = asc_cls;
1347 GNUNET_RESOLVER_hostname_get (plugin->env->sched,
1351 !numeric, timeout, &append_port, ppc);
1356 * Check if the given port is plausible (must be either
1357 * our listen port or our advertised port). If it is
1358 * neither, we return one of these two ports at random.
1360 * @param plugin global variables
1361 * @param in_port port number to check
1362 * @return either in_port or a more plausible port
1365 check_port (struct Plugin *plugin, uint16_t in_port)
1367 if ((in_port == plugin->adv_port) || (in_port == plugin->open_port))
1369 return (GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
1371 ? plugin->open_port : plugin->adv_port;
1376 * Another peer has suggested an address for this peer and transport
1377 * plugin. Check that this could be a valid address. This function
1378 * is not expected to 'validate' the address in the sense of trying to
1379 * connect to it but simply to see if the binary format is technically
1380 * legal for establishing a connection.
1382 * @param cls closure, our 'struct Plugin*'
1383 * @param addr pointer to the address
1384 * @param addrlen length of addr
1385 * @return GNUNET_OK if this is a plausible address for this peer
1386 * and transport, GNUNET_SYSERR if not
1389 tcp_plugin_check_address (void *cls, void *addr, size_t addrlen)
1391 struct Plugin *plugin = cls;
1392 struct IPv4TcpAddress *v4;
1393 struct IPv6TcpAddress *v6;
1395 if ((addrlen != sizeof (struct IPv4TcpAddress)) &&
1396 (addrlen != sizeof (struct IPv6TcpAddress)))
1398 GNUNET_break_op (0);
1399 return GNUNET_SYSERR;
1401 if (addrlen == sizeof (struct IPv4TcpAddress))
1403 v4 = (struct IPv4TcpAddress *) addr;
1404 v4->t_port = htons (check_port (plugin, ntohs (v4->t_port)));
1408 v6 = (struct IPv6TcpAddress *) addr;
1409 if (IN6_IS_ADDR_LINKLOCAL (&v6->ipv6_addr))
1411 GNUNET_break_op (0);
1412 return GNUNET_SYSERR;
1414 v6->t6_port = htons (check_port (plugin, ntohs (v6->t6_port)));
1420 * We've received a nat probe from this peer via TCP. Finish
1421 * creating the client session and resume sending of queued
1424 * @param cls closure
1425 * @param client identification of the client
1426 * @param message the actual message
1429 handle_tcp_nat_probe (void *cls,
1430 struct GNUNET_SERVER_Client *client,
1431 const struct GNUNET_MessageHeader *message)
1433 struct Plugin *plugin = cls;
1434 struct Session *session;
1435 struct TCP_NAT_ProbeMessage *tcp_nat_probe;
1438 struct IPv4TcpAddress *t4;
1439 struct IPv6TcpAddress *t6;
1440 const struct sockaddr_in *s4;
1441 const struct sockaddr_in6 *s6;
1444 GNUNET_log_from(GNUNET_ERROR_TYPE_DEBUG, "tcp", "received tcp NAT probe\n");
1446 /* We have received a TCP NAT probe, meaning we (hopefully) initiated
1447 * a connection to this peer by running gnunet-nat-client. This peer
1448 * received the punch message and now wants us to use the new connection
1449 * as the default for that peer. Do so and then send a WELCOME message
1450 * so we can really be connected!
1452 if (ntohs(message->size) != sizeof(struct TCP_NAT_ProbeMessage))
1455 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));
1460 tcp_nat_probe = (struct TCP_NAT_ProbeMessage *)message;
1462 if (GNUNET_CONTAINER_multihashmap_contains(plugin->nat_wait_conns, &tcp_nat_probe->clientIdentity.hashPubKey) == GNUNET_YES)
1465 GNUNET_log_from(GNUNET_ERROR_TYPE_DEBUG, "tcp", "Found session for NAT probe!\n");
1467 session = GNUNET_CONTAINER_multihashmap_get(plugin->nat_wait_conns, &tcp_nat_probe->clientIdentity.hashPubKey);
1468 GNUNET_assert(session != NULL);
1469 GNUNET_assert(GNUNET_CONTAINER_multihashmap_remove(plugin->nat_wait_conns, &tcp_nat_probe->clientIdentity.hashPubKey, session) == GNUNET_YES);
1470 GNUNET_SERVER_client_keep (client);
1471 session->client = client;
1472 session->last_activity = GNUNET_TIME_absolute_get ();
1475 GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
1478 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1480 "Found address `%s' for incoming connection %p\n",
1481 GNUNET_a2s (vaddr, alen),
1484 if (alen == sizeof (struct sockaddr_in))
1487 t4 = GNUNET_malloc (sizeof (struct IPv4TcpAddress));
1488 t4->t_port = s4->sin_port;
1489 t4->ipv4_addr = s4->sin_addr.s_addr;
1490 session->connect_addr = t4;
1491 session->connect_alen = sizeof (struct IPv4TcpAddress);
1493 else if (alen == sizeof (struct sockaddr_in6))
1496 t6 = GNUNET_malloc (sizeof (struct IPv6TcpAddress));
1497 t6->t6_port = s6->sin6_port;
1498 memcpy (&t6->ipv6_addr,
1500 sizeof (struct in6_addr));
1501 session->connect_addr = t6;
1502 session->connect_alen = sizeof (struct IPv6TcpAddress);
1505 session->connect_addr = GNUNET_malloc (alen);
1506 memcpy (session->connect_addr,
1509 session->connect_alen = alen;
1510 GNUNET_free (vaddr);
1513 session->next = plugin->sessions;
1514 plugin->sessions = session;
1515 GNUNET_STATISTICS_update (plugin->env->stats,
1516 gettext_noop ("# TCP sessions active"),
1519 process_pending_messages (session);
1524 GNUNET_log_from(GNUNET_ERROR_TYPE_DEBUG, "tcp", "Did NOT find session for NAT probe!\n");
1530 * We've received a welcome from this peer via TCP. Possibly create a
1531 * fresh client record and send back our welcome.
1533 * @param cls closure
1534 * @param client identification of the client
1535 * @param message the actual message
1538 handle_tcp_welcome (void *cls,
1539 struct GNUNET_SERVER_Client *client,
1540 const struct GNUNET_MessageHeader *message)
1542 struct Plugin *plugin = cls;
1543 const struct WelcomeMessage *wm = (const struct WelcomeMessage *) message;
1544 struct Session *session;
1547 struct IPv4TcpAddress *t4;
1548 struct IPv6TcpAddress *t6;
1549 const struct sockaddr_in *s4;
1550 const struct sockaddr_in6 *s6;
1554 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1556 "Received %s message from a `%4s/%p'.\n",
1558 GNUNET_i2s (&wm->clientIdentity), client);
1560 GNUNET_STATISTICS_update (plugin->env->stats,
1561 gettext_noop ("# TCP WELCOME messages received"),
1564 session = find_session_by_client (plugin, client);
1565 if (session == NULL)
1567 GNUNET_SERVER_client_keep (client);
1568 session = create_session (plugin,
1569 &wm->clientIdentity, client, GNUNET_NO);
1570 session->inbound = GNUNET_YES;
1572 GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
1575 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1577 "Found address `%s' for incoming connection %p\n",
1578 GNUNET_a2s (vaddr, alen),
1581 if (alen == sizeof (struct sockaddr_in))
1584 t4 = GNUNET_malloc (sizeof (struct IPv4TcpAddress));
1585 t4->t_port = s4->sin_port;
1586 t4->ipv4_addr = s4->sin_addr.s_addr;
1587 session->connect_addr = t4;
1588 session->connect_alen = sizeof (struct IPv4TcpAddress);
1590 else if (alen == sizeof (struct sockaddr_in6))
1593 t6 = GNUNET_malloc (sizeof (struct IPv6TcpAddress));
1594 t6->t6_port = s6->sin6_port;
1595 memcpy (&t6->ipv6_addr,
1597 sizeof (struct in6_addr));
1598 session->connect_addr = t6;
1599 session->connect_alen = sizeof (struct IPv6TcpAddress);
1601 GNUNET_free (vaddr);
1606 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1608 "Did not obtain TCP socket address for incoming connection\n");
1612 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1614 "Creating new session %p for connection %p\n",
1617 process_pending_messages (session);
1619 if (session->expecting_welcome != GNUNET_YES)
1621 GNUNET_break_op (0);
1622 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1625 session->last_activity = GNUNET_TIME_absolute_get ();
1626 session->expecting_welcome = GNUNET_NO;
1627 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1632 * Task to signal the server that we can continue
1633 * receiving from the TCP client now.
1635 * @param cls the 'struct Session*'
1636 * @param tc task context (unused)
1639 delayed_done (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1641 struct Session *session = cls;
1642 struct GNUNET_TIME_Relative delay;
1644 session->receive_delay_task = GNUNET_SCHEDULER_NO_TASK;
1645 delay = session->plugin->env->receive (session->plugin->env->cls,
1650 if (delay.value == 0)
1651 GNUNET_SERVER_receive_done (session->client, GNUNET_OK);
1653 session->receive_delay_task =
1654 GNUNET_SCHEDULER_add_delayed (session->plugin->env->sched,
1655 delay, &delayed_done, session);
1660 * We've received data for this peer via TCP. Unbox,
1661 * compute latency and forward.
1663 * @param cls closure
1664 * @param client identification of the client
1665 * @param message the actual message
1668 handle_tcp_data (void *cls,
1669 struct GNUNET_SERVER_Client *client,
1670 const struct GNUNET_MessageHeader *message)
1672 struct Plugin *plugin = cls;
1673 struct Session *session;
1674 struct GNUNET_TIME_Relative delay;
1676 if ((GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME == ntohs(message->type)) || (ntohs(message->type) == GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE))
1678 /* We don't want to propagate WELCOME and NAT Probe messages up! */
1679 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1682 session = find_session_by_client (plugin, client);
1683 if ( (NULL == session) || (GNUNET_YES == session->expecting_welcome))
1685 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1688 session->last_activity = GNUNET_TIME_absolute_get ();
1690 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1692 "Passing %u bytes of type %u from `%4s' to transport service.\n",
1693 (unsigned int) ntohs (message->size),
1694 (unsigned int) ntohs (message->type),
1695 GNUNET_i2s (&session->target));
1697 GNUNET_STATISTICS_update (plugin->env->stats,
1698 gettext_noop ("# bytes received via TCP"),
1699 ntohs (message->size),
1701 delay = plugin->env->receive (plugin->env->cls, &session->target, message, 1,
1703 (GNUNET_YES == session->inbound) ? NULL : session->connect_addr,
1704 (GNUNET_YES == session->inbound) ? 0 : session->connect_alen);
1705 if (delay.value == 0)
1706 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1708 session->receive_delay_task =
1709 GNUNET_SCHEDULER_add_delayed (session->plugin->env->sched,
1710 delay, &delayed_done, session);
1715 * Handlers for the various TCP messages.
1717 static struct GNUNET_SERVER_MessageHandler my_handlers[] = {
1718 {&handle_tcp_welcome, NULL, GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME,
1719 sizeof (struct WelcomeMessage)},
1720 {&handle_tcp_nat_probe, NULL, GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE, sizeof (struct TCP_NAT_ProbeMessage)},
1721 {&handle_tcp_data, NULL, GNUNET_MESSAGE_TYPE_ALL, 0},
1727 * Functions with this signature are called whenever a peer
1728 * is disconnected on the network level.
1730 * @param cls closure
1731 * @param client identification of the client
1734 disconnect_notify (void *cls,
1735 struct GNUNET_SERVER_Client *client)
1737 struct Plugin *plugin = cls;
1738 struct Session *session;
1742 session = find_session_by_client (plugin, client);
1743 if (session == NULL)
1744 return; /* unknown, nothing to do */
1746 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1748 "Destroying session of `%4s' with %s (%p) due to network-level disconnect.\n",
1749 GNUNET_i2s (&session->target),
1750 (session->connect_addr != NULL) ?
1751 tcp_address_to_string (session->plugin,
1752 session->connect_addr,
1753 session->connect_alen) : "*",
1756 disconnect_session (session);
1761 * Add the IP of our network interface to the list of
1762 * our external IP addresses.
1764 * @param cls the 'struct Plugin*'
1765 * @param name name of the interface
1766 * @param isDefault do we think this may be our default interface
1767 * @param addr address of the interface
1768 * @param addrlen number of bytes in addr
1769 * @return GNUNET_OK to continue iterating
1772 process_interfaces (void *cls,
1775 const struct sockaddr *addr, socklen_t addrlen)
1777 struct Plugin *plugin = cls;
1779 struct IPv4TcpAddress t4;
1780 struct IPv6TcpAddress t6;
1781 struct IPv4TcpAddress t4_nat;
1782 struct IPv6TcpAddress t6_nat;
1787 af = addr->sa_family;
1791 t4.ipv4_addr = ((struct sockaddr_in *) addr)->sin_addr.s_addr;
1792 if ((plugin->behind_nat == GNUNET_YES) && (plugin->only_nat_addresses == GNUNET_YES))
1793 t4.t_port = htons(0);
1794 else if (plugin->behind_nat == GNUNET_YES) /* We are behind NAT, but will advertise NAT and normal addresses */
1796 t4_nat.ipv4_addr = ((struct sockaddr_in *) addr)->sin_addr.s_addr;
1797 t4_nat.t_port = htons(plugin->adv_port);
1801 t4.t_port = htons (plugin->adv_port);
1805 else if (af == AF_INET6)
1807 if (IN6_IS_ADDR_LINKLOCAL (&((struct sockaddr_in6 *) addr)->sin6_addr))
1809 /* skip link local addresses */
1812 memcpy (&t6.ipv6_addr,
1813 &((struct sockaddr_in6 *) addr)->sin6_addr,
1814 sizeof (struct in6_addr));
1815 if ((plugin->behind_nat == GNUNET_YES) && (plugin->only_nat_addresses == GNUNET_YES))
1816 t6.t6_port = htons(0);
1817 else if (plugin->behind_nat == GNUNET_YES) /* We are behind NAT, but will advertise NAT and normal addresses */
1819 memcpy (&t6_nat.ipv6_addr,
1820 &((struct sockaddr_in6 *) addr)->sin6_addr,
1821 sizeof (struct in6_addr));
1822 t6_nat.t6_port = htons(plugin->adv_port);
1826 t6.t6_port = htons (plugin->adv_port);
1835 GNUNET_log_from (GNUNET_ERROR_TYPE_INFO |
1836 GNUNET_ERROR_TYPE_BULK,
1838 _("Found address `%s' (%s)\n"),
1839 GNUNET_a2s (addr, addrlen), name);
1841 plugin->env->notify_address (plugin->env->cls,
1843 arg, args, GNUNET_TIME_UNIT_FOREVER_REL);
1845 if (arg_nat != NULL)
1847 GNUNET_log_from (GNUNET_ERROR_TYPE_INFO |
1848 GNUNET_ERROR_TYPE_BULK,
1850 _("Found address `%s' (%s)\n"),
1851 GNUNET_a2s (addr, addrlen), name);
1852 plugin->env->notify_address (plugin->env->cls,
1854 arg_nat, args, GNUNET_TIME_UNIT_FOREVER_REL);
1862 * Function called by the resolver for each address obtained from DNS
1863 * for our own hostname. Add the addresses to the list of our
1864 * external IP addresses.
1866 * @param cls closure
1867 * @param addr one of the addresses of the host, NULL for the last address
1868 * @param addrlen length of the address
1871 process_hostname_ips (void *cls,
1872 const struct sockaddr *addr, socklen_t addrlen)
1874 struct Plugin *plugin = cls;
1878 plugin->hostname_dns = NULL;
1881 /* FIXME: Can we figure out our external address here so it doesn't need to be user specified? */
1882 process_interfaces (plugin, "<hostname>", GNUNET_YES, addr, addrlen);
1886 * We can now send a probe message, copy into buffer to really send.
1888 * @param cls closure, a struct TCPProbeContext
1889 * @param size max size to copy
1890 * @param buf buffer to copy message to
1892 static size_t notify_send_probe (void *cls,
1893 size_t size, void *buf)
1895 struct TCPProbeContext *tcp_probe_ctx = cls;
1902 GNUNET_assert(size >= sizeof(tcp_probe_ctx->message));
1903 memcpy(buf, &tcp_probe_ctx->message, sizeof(tcp_probe_ctx->message));
1904 GNUNET_SERVER_connect_socket (tcp_probe_ctx->plugin->server,
1905 tcp_probe_ctx->sock);
1907 GNUNET_free(tcp_probe_ctx);
1908 return sizeof(tcp_probe_ctx->message);
1912 * @param cls the plugin handle
1913 * @param tc the scheduling context (for rescheduling this function again)
1915 * We have been notified that gnunet-nat-server has written something to stdout.
1916 * Handle the output, then reschedule this function to be called again once
1917 * more is available.
1921 tcp_plugin_server_read (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1923 struct Plugin *plugin = cls;
1926 memset(&mybuf, 0, sizeof(mybuf));
1930 struct sockaddr_in in_addr;
1931 struct TCPProbeContext *tcp_probe_ctx;
1932 struct GNUNET_CONNECTION_Handle *sock;
1934 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
1937 bytes = GNUNET_DISK_file_read(plugin->server_stdout_handle, &mybuf, sizeof(mybuf));
1942 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1943 _("Finished reading from server stdout with code: %d\n"), bytes);
1950 for (i = 0; i < sizeof(mybuf); i++)
1952 if (mybuf[i] == '\n')
1955 if ((mybuf[i] == ':') && (i + 1 < sizeof(mybuf)))
1958 port_start = &mybuf[i + 1];
1962 if (port_start != NULL)
1963 port = atoi(port_start);
1966 plugin->server_read_task =
1967 GNUNET_SCHEDULER_add_read_file (plugin->env->sched,
1968 GNUNET_TIME_UNIT_FOREVER_REL,
1969 plugin->server_stdout_handle, &tcp_plugin_server_read, plugin);
1974 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1975 _("nat-server-read read: %s port %d\n"), &mybuf, port);
1979 if (inet_pton(AF_INET, &mybuf[0], &in_addr.sin_addr) != 1)
1982 GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, "tcp",
1983 _("nat-server-read malformed address\n"), &mybuf, port);
1985 plugin->server_read_task =
1986 GNUNET_SCHEDULER_add_read_file (plugin->env->sched,
1987 GNUNET_TIME_UNIT_FOREVER_REL,
1988 plugin->server_stdout_handle, &tcp_plugin_server_read, plugin);
1992 in_addr.sin_family = AF_INET;
1993 in_addr.sin_port = htons(port);
1995 * We have received an ICMP response, ostensibly from a non-NAT'd peer
1996 * that wants to connect to us! Send a message to establish a connection.
1998 sock = GNUNET_CONNECTION_create_from_sockaddr (plugin->env->sched, AF_INET, (struct sockaddr *)&in_addr,
1999 sizeof(in_addr), GNUNET_SERVER_MAX_MESSAGE_SIZE);
2002 plugin->server_read_task =
2003 GNUNET_SCHEDULER_add_read_file (plugin->env->sched,
2004 GNUNET_TIME_UNIT_FOREVER_REL,
2005 plugin->server_stdout_handle, &tcp_plugin_server_read, plugin);
2010 tcp_probe_ctx = GNUNET_malloc(sizeof(struct TCPProbeContext));
2012 tcp_probe_ctx->message.header.size = htons(sizeof(struct TCP_NAT_ProbeMessage));
2013 tcp_probe_ctx->message.header.type = htons(GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE);
2014 memcpy(&tcp_probe_ctx->message.clientIdentity, plugin->env->my_identity, sizeof(struct GNUNET_PeerIdentity));
2015 tcp_probe_ctx->plugin = plugin;
2016 tcp_probe_ctx->sock = sock;
2017 tcp_probe_ctx->transmit_handle = GNUNET_CONNECTION_notify_transmit_ready (sock,
2018 ntohs(tcp_probe_ctx->message.header.size),
2019 GNUNET_TIME_UNIT_FOREVER_REL,
2020 ¬ify_send_probe, tcp_probe_ctx);
2024 plugin->server_read_task =
2025 GNUNET_SCHEDULER_add_read_file (plugin->env->sched,
2026 GNUNET_TIME_UNIT_FOREVER_REL,
2027 plugin->server_stdout_handle, &tcp_plugin_server_read, plugin);
2031 * Start the gnunet-nat-server process for users behind NAT.
2033 * @param plugin the transport plugin
2035 * @return GNUNET_YES if process was started, GNUNET_SYSERR on error
2038 tcp_transport_start_nat_server(struct Plugin *plugin)
2041 plugin->server_stdout = GNUNET_DISK_pipe(GNUNET_YES);
2042 if (plugin->server_stdout == NULL)
2043 return GNUNET_SYSERR;
2046 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
2048 "Starting gnunet-nat-server process cmd: %s %s\n", "gnunet-nat-server", plugin->internal_address);
2050 /* Start the server process */
2051 plugin->server_pid = GNUNET_OS_start_process(NULL, plugin->server_stdout, "gnunet-nat-server", "gnunet-nat-server", plugin->internal_address, NULL);
2052 if (plugin->server_pid == GNUNET_SYSERR)
2055 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
2057 "Failed to start gnunet-nat-server process\n");
2059 return GNUNET_SYSERR;
2061 /* Close the write end of the read pipe */
2062 GNUNET_DISK_pipe_close_end(plugin->server_stdout, GNUNET_DISK_PIPE_END_WRITE);
2064 plugin->server_stdout_handle = GNUNET_DISK_pipe_handle(plugin->server_stdout, GNUNET_DISK_PIPE_END_READ);
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 * Return the actual path to a file found in the current
2074 * PATH environment variable.
2076 * @param binary the name of the file to find
2079 get_path_from_PATH (char *binary)
2087 p = getenv ("PATH");
2090 path = GNUNET_strdup (p); /* because we write on it */
2091 buf = GNUNET_malloc (strlen (path) + 20);
2094 while (NULL != (end = strchr (pos, ':')))
2097 sprintf (buf, "%s/%s", pos, binary);
2098 if (GNUNET_DISK_file_test (buf) == GNUNET_YES)
2105 sprintf (buf, "%s/%s", pos, binary);
2106 if (GNUNET_DISK_file_test (buf) == GNUNET_YES)
2117 * Check whether the suid bit is set on a file.
2118 * Attempts to find the file using the current
2119 * PATH environment variable as a search path.
2121 * @param binary the name of the file to check
2124 check_gnunet_nat_binary(char *binary)
2126 struct stat statbuf;
2129 p = get_path_from_PATH (binary);
2132 if (0 != STAT (p, &statbuf))
2135 return GNUNET_SYSERR;
2138 if ( (0 != (statbuf.st_mode & S_ISUID)) &&
2139 (statbuf.st_uid == 0) )
2145 * Entry point for the plugin.
2147 * @param cls closure, the 'struct GNUNET_TRANSPORT_PluginEnvironment*'
2148 * @return the 'struct GNUNET_TRANSPORT_PluginFunctions*' or NULL on error
2151 libgnunet_plugin_transport_tcp_init (void *cls)
2153 struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
2154 struct GNUNET_TRANSPORT_PluginFunctions *api;
2155 struct Plugin *plugin;
2156 struct GNUNET_SERVICE_Context *service;
2157 unsigned long long aport;
2158 unsigned long long bport;
2162 int only_nat_addresses;
2163 char *internal_address;
2164 char *external_address;
2165 struct sockaddr_in in_addr;
2166 struct IPv4TcpAddress t4;
2168 service = GNUNET_SERVICE_start ("transport-tcp", env->sched, env->cfg);
2169 if (service == NULL)
2171 GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING,
2174 ("Failed to start service for `%s' transport plugin.\n"),
2179 if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno (env->cfg,
2183 /* We are behind nat (according to the user) */
2184 if (check_gnunet_nat_binary("gnunet-nat-server") == GNUNET_YES)
2186 behind_nat = GNUNET_YES;
2190 behind_nat = GNUNET_NO;
2191 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");
2195 behind_nat = GNUNET_NO; /* We are not behind nat! */
2197 if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno (env->cfg,
2201 if (check_gnunet_nat_binary("gnunet-nat-client") == GNUNET_YES)
2202 allow_nat = GNUNET_YES; /* We will try to connect to NAT'd peers */
2205 allow_nat = GNUNET_NO;
2206 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");
2210 allow_nat = GNUNET_NO; /* We don't want to try to help NAT'd peers */
2213 if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno (env->cfg,
2215 "ONLY_NAT_ADDRESSES"))
2216 only_nat_addresses = GNUNET_YES; /* We will only report our addresses as NAT'd */
2218 only_nat_addresses = GNUNET_NO; /* We will report our addresses as NAT'd and non-NAT'd */
2220 external_address = NULL;
2221 if (((GNUNET_YES == behind_nat) || (GNUNET_YES == allow_nat)) && (GNUNET_OK !=
2222 GNUNET_CONFIGURATION_get_value_string (env->cfg,
2225 &external_address)))
2227 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
2230 ("Require EXTERNAL_ADDRESS for service `%s' in configuration (either BEHIND_NAT or ALLOW_NAT set to YES)!\n"),
2232 GNUNET_SERVICE_stop (service);
2236 if ((external_address != NULL) && (inet_pton(AF_INET, external_address, &in_addr.sin_addr) != 1))
2238 GNUNET_log_from(GNUNET_ERROR_TYPE_WARNING, "udp", "Malformed EXTERNAL_ADDRESS %s given in configuration!\n", external_address);
2241 internal_address = NULL;
2242 if ((GNUNET_YES == behind_nat) && (GNUNET_OK !=
2243 GNUNET_CONFIGURATION_get_value_string (env->cfg,
2246 &internal_address)))
2248 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
2251 ("Require INTERNAL_ADDRESS for service `%s' in configuration!\n"),
2253 GNUNET_SERVICE_stop (service);
2254 GNUNET_free_non_null(external_address);
2258 if ((internal_address != NULL) && (inet_pton(AF_INET, internal_address, &in_addr.sin_addr) != 1))
2260 GNUNET_log_from(GNUNET_ERROR_TYPE_WARNING, "udp", "Malformed INTERNAL_ADDRESS %s given in configuration!\n", internal_address);
2265 GNUNET_CONFIGURATION_get_value_number (env->cfg,
2271 GNUNET_CONFIGURATION_get_value_number (env->cfg,
2274 &aport)) && (aport > 65535)))
2276 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
2279 ("Require valid port number for service `%s' in configuration!\n"),
2281 GNUNET_free_non_null(external_address);
2282 GNUNET_free_non_null(internal_address);
2283 GNUNET_SERVICE_stop (service);
2289 plugin = GNUNET_malloc (sizeof (struct Plugin));
2290 plugin->open_port = bport;
2291 plugin->adv_port = aport;
2292 plugin->external_address = external_address;
2293 plugin->internal_address = internal_address;
2294 plugin->behind_nat = behind_nat;
2295 plugin->allow_nat = allow_nat;
2296 plugin->only_nat_addresses = only_nat_addresses;
2298 plugin->lsock = NULL;
2299 api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
2301 api->send = &tcp_plugin_send;
2302 api->disconnect = &tcp_plugin_disconnect;
2303 api->address_pretty_printer = &tcp_plugin_address_pretty_printer;
2304 api->check_address = &tcp_plugin_check_address;
2305 api->address_to_string = &tcp_address_to_string;
2306 plugin->service = service;
2307 plugin->server = GNUNET_SERVICE_get_server (service);
2308 plugin->handlers = GNUNET_malloc (sizeof (my_handlers));
2309 memcpy (plugin->handlers, my_handlers, sizeof (my_handlers));
2312 sizeof (my_handlers) / sizeof (struct GNUNET_SERVER_MessageHandler);
2314 plugin->handlers[i].callback_cls = plugin;
2315 GNUNET_SERVER_add_handlers (plugin->server, plugin->handlers);
2317 if (behind_nat == GNUNET_YES)
2319 if (GNUNET_YES != tcp_transport_start_nat_server(plugin))
2321 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
2324 ("Failed to start %s required for NAT in %s!\n"),
2327 GNUNET_free_non_null(external_address);
2328 GNUNET_free_non_null(internal_address);
2329 GNUNET_SERVICE_stop (service);
2334 if (allow_nat == GNUNET_YES)
2336 plugin->nat_wait_conns = GNUNET_CONTAINER_multihashmap_create(100);
2337 GNUNET_assert(plugin->nat_wait_conns != NULL);
2340 GNUNET_log_from (GNUNET_ERROR_TYPE_INFO,
2341 "tcp", _("TCP transport listening on port %llu\n"), bport);
2343 GNUNET_log_from (GNUNET_ERROR_TYPE_INFO,
2345 _("TCP transport advertises itself as being on port %llu\n"),
2347 GNUNET_SERVER_disconnect_notify (plugin->server,
2350 if (plugin->behind_nat == GNUNET_NO)
2352 GNUNET_OS_network_interfaces_list (&process_interfaces, plugin);
2355 plugin->hostname_dns = GNUNET_RESOLVER_hostname_resolve (env->sched,
2358 HOSTNAME_RESOLVE_TIMEOUT,
2359 &process_hostname_ips,
2362 if ((plugin->behind_nat == GNUNET_YES) && (inet_pton(AF_INET, plugin->external_address, &t4.ipv4_addr) == 1))
2364 t4.t_port = htons(0);
2365 plugin->env->notify_address (plugin->env->cls,
2367 &t4, sizeof(t4), GNUNET_TIME_UNIT_FOREVER_REL);
2369 else if ((plugin->external_address != NULL) && (inet_pton(AF_INET, plugin->external_address, &t4.ipv4_addr) == 1))
2371 t4.t_port = htons(plugin->adv_port);
2372 plugin->env->notify_address (plugin->env->cls,
2374 &t4, sizeof(t4), GNUNET_TIME_UNIT_FOREVER_REL);
2382 * Exit point from the plugin.
2385 libgnunet_plugin_transport_tcp_done (void *cls)
2387 struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
2388 struct Plugin *plugin = api->cls;
2389 struct Session *session;
2391 while (NULL != (session = plugin->sessions))
2392 disconnect_session (session);
2393 if (NULL != plugin->hostname_dns)
2395 GNUNET_RESOLVER_request_cancel (plugin->hostname_dns);
2396 plugin->hostname_dns = NULL;
2398 GNUNET_SERVICE_stop (plugin->service);
2399 GNUNET_free (plugin->handlers);
2400 GNUNET_free (plugin);
2405 /* end of plugin_transport_tcp.c */