2 This file is part of GNUnet
3 (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009 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.
22 * @file transport/plugin_transport_tcp.c
23 * @brief Implementation of the TCP transport service
24 * @author Christian Grothoff
28 #include "gnunet_hello_lib.h"
29 #include "gnunet_network_lib.h"
30 #include "gnunet_os_lib.h"
31 #include "gnunet_peerinfo_service.h"
32 #include "gnunet_protocols.h"
33 #include "gnunet_resolver_service.h"
34 #include "gnunet_server_lib.h"
35 #include "gnunet_service_lib.h"
36 #include "gnunet_statistics_service.h"
37 #include "gnunet_transport_service.h"
38 #include "plugin_transport.h"
39 #include "transport.h"
41 #define DEBUG_TCP GNUNET_YES
44 * After how long do we expire an address that we
45 * learned from another peer if it is not reconfirmed
48 #define LEARNED_ADDRESS_EXPIRATION GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_HOURS, 6)
51 * How long until we give up on transmitting the welcome message?
53 #define WELCOME_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 30)
56 * How long until we give up on transmitting the welcome message?
58 #define HOSTNAME_RESOLVE_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 5)
61 * For how many messages back to we keep transmission times?
63 #define ACK_LOG_SIZE 32
66 * Initial handshake message for a session. This header
67 * is followed by the address that the other peer used to
68 * connect to us (so that we may learn it) or the address
69 * that the other peer got from the accept call.
73 struct GNUNET_MessageHeader header;
76 * Identity of the node connecting (TCP client)
78 struct GNUNET_PeerIdentity clientIdentity;
84 * Encapsulation for normal TCP traffic.
88 struct GNUNET_MessageHeader header;
93 uint32_t reserved GNUNET_PACKED;
96 * Number of the last message that was received from the other peer.
98 uint64_t ack_in GNUNET_PACKED;
101 * Number of this outgoing message.
103 uint64_t ack_out GNUNET_PACKED;
106 * How long was sending this ack delayed by the other peer
107 * (estimate). The receiver of this message can use the delay
108 * between sending his message number 'ack' and receiving this ack
109 * minus the delay as an estimate of the round-trip time.
111 struct GNUNET_TIME_RelativeNBO delay;
117 * Encapsulation of all of the state of the plugin.
123 * Information kept for each message that is yet to
126 struct PendingMessage
130 * This is a linked list.
132 struct PendingMessage *next;
135 * The pending message, pointer to the end
136 * of this struct, do not free!
138 struct GNUNET_MessageHeader *msg;
142 * Continuation function to call once the message
143 * has been sent. Can be NULL if there is no
144 * continuation to call.
146 GNUNET_TRANSPORT_TransmitContinuation transmit_cont;
149 * Closure for transmit_cont.
151 void *transmit_cont_cls;
154 * Timeout value for the pending message.
156 struct GNUNET_TIME_Absolute timeout;
159 * GNUNET_YES if this is a welcome message;
160 * otherwise this should be a DATA message.
168 * Session handle for TCP connections.
174 * Stored in a linked list.
176 struct Session *next;
179 * Pointer to the global plugin struct.
181 struct Plugin *plugin;
184 * The client (used to identify this connection)
186 struct GNUNET_SERVER_Client *client;
189 * gnunet-service-transport context for this connection.
191 struct ReadyList *service_context;
194 * Messages currently pending for transmission
195 * to this peer, if any.
197 struct PendingMessage *pending_messages;
200 * Handle for pending transmission request.
202 struct GNUNET_NETWORK_TransmitHandle *transmit_handle;
205 * To whom are we talking to (set to our identity
206 * if we are still waiting for the welcome message)
208 struct GNUNET_PeerIdentity target;
211 * At what time did we reset last_received last?
213 struct GNUNET_TIME_Absolute last_quota_update;
216 * Address of the other peer if WE initiated the connection
217 * (and hence can be sure what it is), otherwise NULL.
222 * How many bytes have we received since the "last_quota_update"
225 uint64_t last_received;
228 * Our current latency estimate (in ms).
230 double latency_estimate;
233 * Time when we generated the last ACK_LOG_SIZE acks.
234 * (the "last" refers to the "out_msg_counter" here)
236 struct GNUNET_TIME_Absolute gen_time[ACK_LOG_SIZE];
239 * Our current sequence number.
241 uint64_t out_msg_counter;
244 * Highest received incoming sequence number.
246 uint64_t max_in_msg_counter;
249 * Number of bytes per ms that this peer is allowed
255 * Length of connect_addr, can be 0.
260 * Are we still expecting the welcome message? (GNUNET_YES/GNUNET_NO)
262 int expecting_welcome;
265 * Are we still trying to connect?
267 int still_connecting;
273 * Encapsulation of all of the state of the plugin.
280 struct GNUNET_TRANSPORT_PluginEnvironment *env;
285 struct GNUNET_NETWORK_SocketHandle *lsock;
288 * List of open TCP sessions.
290 struct Session *sessions;
293 * Handle for the statistics service.
295 struct GNUNET_STATISTICS_Handle *statistics;
298 * Handle to the network service.
300 struct GNUNET_SERVICE_Context *service;
303 * Handle to the server for this service.
305 struct GNUNET_SERVER_Handle *server;
308 * Copy of the handler array where the closures are
309 * set to this struct's instance.
311 struct GNUNET_SERVER_MessageHandler *handlers;
314 * ID of task used to update our addresses when one expires.
316 GNUNET_SCHEDULER_TaskIdentifier address_update_task;
319 * Port that we are actually listening on.
324 * Port that the user said we would have visible to the
333 * Find the session handle for the given peer.
335 static struct Session *
336 find_session_by_target (struct Plugin *plugin,
337 const struct GNUNET_PeerIdentity *target)
341 ret = plugin->sessions;
342 while ((ret != NULL) &&
343 (0 != memcmp (target,
344 &ret->target, sizeof (struct GNUNET_PeerIdentity))))
351 * Find the session handle for the given peer.
353 static struct Session *
354 find_session_by_client (struct Plugin *plugin,
355 const struct GNUNET_SERVER_Client *client)
359 ret = plugin->sessions;
360 while ((ret != NULL) && (client != ret->client))
367 * Create a welcome message.
369 static struct PendingMessage *
370 create_welcome (size_t addrlen, const void *addr, struct Plugin *plugin)
372 struct PendingMessage *pm;
373 struct WelcomeMessage *welcome;
375 pm = GNUNET_malloc (sizeof (struct PendingMessage) +
376 sizeof (struct WelcomeMessage) + addrlen);
377 pm->msg = (struct GNUNET_MessageHeader *) &pm[1];
378 welcome = (struct WelcomeMessage *) &pm[1];
379 welcome->header.size = htons (sizeof (struct WelcomeMessage) + addrlen);
380 welcome->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME);
381 GNUNET_CRYPTO_hash (plugin->env->my_public_key,
382 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
383 &welcome->clientIdentity.hashPubKey);
384 memcpy (&welcome[1], addr, addrlen);
385 pm->timeout = GNUNET_TIME_relative_to_absolute (WELCOME_TIMEOUT);
386 pm->is_welcome = GNUNET_YES;
392 * Create a new session using the specified address
393 * for the welcome message.
396 * @param target peer to connect to
397 * @param client client to use
398 * @param addrlen IPv4 or IPv6
399 * @param addr either struct sockaddr_in or struct sockaddr_in6
400 * @return NULL connection failed / invalid address
402 static struct Session *
403 create_session (struct Plugin *plugin,
404 const struct GNUNET_PeerIdentity *target,
405 struct GNUNET_SERVER_Client *client,
406 const void *addr, size_t addrlen)
410 ret = GNUNET_malloc (sizeof (struct Session));
411 ret->plugin = plugin;
412 ret->next = plugin->sessions;
413 plugin->sessions = ret;
414 ret->client = client;
415 ret->target = *target;
416 ret->last_quota_update = GNUNET_TIME_absolute_get ();
417 ret->quota_in = plugin->env->default_quota_in;
418 ret->expecting_welcome = GNUNET_YES;
419 ret->pending_messages = create_welcome (addrlen, addr, plugin);
425 * Create a new session connecting to the specified
426 * target at the specified address.
429 * @param target peer to connect to
430 * @param addrlen IPv4 or IPv6
431 * @param addr either struct sockaddr_in or struct sockaddr_in6
432 * @return NULL connection failed / invalid address
434 static struct Session *
435 connect_and_create_session (struct Plugin *plugin,
436 const struct GNUNET_PeerIdentity *target,
437 const void *addr, size_t addrlen)
439 struct GNUNET_SERVER_Client *client;
440 struct GNUNET_NETWORK_SocketHandle *conn;
441 struct Session *session;
444 session = plugin->sessions;
445 while (session != NULL)
447 if ((0 == memcmp (target,
449 sizeof (struct GNUNET_PeerIdentity))) &&
450 (session->connect_alen == addrlen) &&
451 (0 == memcmp (session->connect_addr, addr, addrlen)))
452 return session; /* already exists! */
453 session = session->next;
456 if (addrlen == sizeof (struct sockaddr_in))
458 else if (addrlen == sizeof (struct sockaddr_in6))
463 return NULL; /* invalid address */
465 conn = GNUNET_NETWORK_socket_create_from_sockaddr (plugin->env->sched,
469 GNUNET_SERVER_MAX_MESSAGE_SIZE);
473 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
475 "Failed to create connection to peer at `%s'.\n",
476 GNUNET_a2s(addr, addrlen));
480 client = GNUNET_SERVER_connect_socket (plugin->server, conn);
481 GNUNET_assert (client != NULL);
482 session = create_session (plugin, target, client, addr, addrlen);
483 session->connect_alen = addrlen;
484 session->connect_addr = GNUNET_malloc (addrlen);
485 memcpy (session->connect_addr, addr, addrlen);
487 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
489 "Creating new session %p with `%s' based on `%s' request.\n",
491 GNUNET_a2s(addr, addrlen),
499 * If we have pending messages, ask the server to
500 * transmit them (schedule the respective tasks, etc.)
502 * @param session for which session should we do this
504 static void process_pending_messages (struct Session *session);
508 * Function called to notify a client about the socket
509 * begin ready to queue more data. "buf" will be
510 * NULL and "size" zero if the socket was closed for
511 * writing in the meantime.
514 * @param size number of bytes available in buf
515 * @param buf where the callee should write the message
516 * @return number of bytes written to buf
519 do_transmit (void *cls, size_t size, void *buf)
521 struct Session *session = cls;
522 struct PendingMessage *pm;
526 struct DataMessage *dm;
528 session->transmit_handle = NULL;
532 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
534 "Timeout trying to transmit to peer `%4s', discarding message queue.\n",
535 GNUNET_i2s(&session->target));
538 while (NULL != (pm = session->pending_messages))
540 session->pending_messages = pm->next;
541 if (pm->transmit_cont != NULL)
542 pm->transmit_cont (pm->transmit_cont_cls,
543 session->service_context,
544 &session->target, GNUNET_SYSERR);
551 while (NULL != (pm = session->pending_messages))
555 if (size < (msize = htons (pm->msg->size)))
557 memcpy (cbuf, pm->msg, msize);
565 sizeof (struct DataMessage) + (msize = htons (pm->msg->size)))
567 dm = (struct DataMessage *) cbuf;
568 dm->header.size = htons (sizeof (struct DataMessage) + msize);
569 dm->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_DATA);
570 dm->ack_out = GNUNET_htonll (++session->out_msg_counter);
571 dm->ack_in = GNUNET_htonll (session->max_in_msg_counter);
572 cbuf += sizeof (struct DataMessage);
573 ret += sizeof (struct DataMessage);
574 size -= sizeof (struct DataMessage);
575 memcpy (cbuf, pm->msg, msize);
580 session->pending_messages = pm->next;
581 if (pm->transmit_cont != NULL)
582 pm->transmit_cont (pm->transmit_cont_cls,
583 session->service_context,
584 &session->target, GNUNET_OK);
586 session->gen_time[session->out_msg_counter % ACK_LOG_SIZE]
587 = GNUNET_TIME_absolute_get ();
589 process_pending_messages (session);
591 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
592 "tcp", "Transmitting %u bytes\n", ret);
599 * If we have pending messages, ask the server to
600 * transmit them (schedule the respective tasks, etc.)
602 * @param session for which session should we do this
605 process_pending_messages (struct Session *session)
607 GNUNET_assert (session->client != NULL);
608 if (session->pending_messages == NULL)
610 if (session->transmit_handle != NULL)
612 session->transmit_handle
613 = GNUNET_SERVER_notify_transmit_ready (session->client,
615 pending_messages->msg->
618 pending_messages->is_welcome ? 0 :
619 sizeof (struct DataMessage)),
620 GNUNET_TIME_absolute_get_remaining
622 pending_messages[0].timeout),
623 &do_transmit, session);
628 * Function that can be used by the transport service to transmit
629 * a message using the plugin using a fresh connection (even if
630 * we already have a connection to this peer, this function is
631 * required to establish a new one).
634 * @param target who should receive this message
635 * @param priority how important is the message
636 * @param msg1 first message to transmit
637 * @param msg2 second message to transmit (can be NULL)
638 * @param timeout how long should we try to transmit these?
639 * @param addrlen length of the address
640 * @param addr the address
641 * @return session if the transmission has been scheduled
642 * NULL if the address format is invalid
645 tcp_plugin_send_to (void *cls,
646 const struct GNUNET_PeerIdentity *target,
647 unsigned int priority,
648 const struct GNUNET_MessageHeader *msg1,
649 const struct GNUNET_MessageHeader *msg2,
650 struct GNUNET_TIME_Relative timeout,
651 const void *addr, size_t addrlen)
653 struct Plugin *plugin = cls;
654 struct Session *session;
655 struct PendingMessage *pl;
656 struct PendingMessage *pm;
658 session = connect_and_create_session (plugin, target, addr, addrlen);
662 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
663 "tcp", "Failed to create fresh session.\n");
670 pm = GNUNET_malloc (sizeof (struct PendingMessage) +
672 pm->msg = (struct GNUNET_MessageHeader *) &pm[1];
673 memcpy (pm->msg, msg2, ntohs (msg2->size));
674 pm->timeout = GNUNET_TIME_relative_to_absolute (timeout);
675 pm->is_welcome = GNUNET_NO;
680 pm = GNUNET_malloc (sizeof (struct PendingMessage) +
682 pm->msg = (struct GNUNET_MessageHeader *) &pm[1];
683 memcpy (pm->msg, msg1, ntohs (msg1->size));
684 pm->timeout = GNUNET_TIME_relative_to_absolute (timeout);
685 pm->is_welcome = GNUNET_NO;
690 if (session->pending_messages != NULL)
692 pm = session->pending_messages;
693 while (pm->next != NULL)
699 session->pending_messages = pl;
701 process_pending_messages (session);
707 * Functions with this signature are called whenever we need
708 * to close a session due to a disconnect or failure to
709 * establish a connection.
711 * @param session session to close down
714 disconnect_session (struct Session *session)
716 struct Session *prev;
718 struct PendingMessage *pm;
721 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
723 "Disconnecting from other peer (session %p).\n", session);
725 /* remove from session list */
727 pos = session->plugin->sessions;
728 while (pos != session)
734 session->plugin->sessions = session->next;
736 prev->next = session->next;
738 if (session->client != NULL)
741 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
742 "Disconnecting from client address %p\n", session->client);
744 GNUNET_SERVER_client_drop (session->client);
745 session->client = NULL;
747 if (session->transmit_handle != NULL)
749 GNUNET_NETWORK_notify_transmit_ready_cancel (session->transmit_handle);
750 session->transmit_handle = NULL;
752 while (NULL != (pm = session->pending_messages))
754 session->pending_messages = pm->next;
755 if (NULL != pm->transmit_cont)
756 pm->transmit_cont (pm->transmit_cont_cls,
757 session->service_context,
758 &session->target, GNUNET_SYSERR);
761 /* notify transport service about disconnect */
762 session->plugin->env->receive (session->plugin->env->cls,
764 session->service_context,
765 GNUNET_TIME_UNIT_ZERO,
766 &session->target, NULL);
767 GNUNET_free_non_null (session->connect_addr);
768 GNUNET_free (session);
773 * Iterator callback to go over all addresses. If we get
774 * a TCP address, increment the counter
776 * @param cls closure, points to the counter
777 * @param tname name of the transport
778 * @param expiration expiration time
779 * @param addr the address
780 * @param addrlen length of the address
781 * @return GNUNET_OK to keep the address,
782 * GNUNET_NO to delete it from the HELLO
783 * GNUNET_SYSERR to stop iterating (but keep current address)
786 count_tcp_addresses (void *cls,
788 struct GNUNET_TIME_Absolute expiration,
789 const void *addr, size_t addrlen)
791 unsigned int *counter = cls;
793 if (0 != strcmp (tname, "tcp"))
794 return GNUNET_OK; /* not one of ours */
796 return GNUNET_OK; /* failed to connect */
800 struct ConnectContext
802 struct Plugin *plugin;
804 struct GNUNET_NETWORK_SocketHandle *sa;
806 struct PendingMessage *welcome;
813 * Iterator callback to go over all addresses. If we get
814 * the "pos" TCP address, try to connect to it.
817 * @param tname name of the transport
818 * @param expiration expiration time
819 * @param addrlen length of the address
820 * @param addr the address
821 * @return GNUNET_OK to keep the address,
822 * GNUNET_NO to delete it from the HELLO
823 * GNUNET_SYSERR to stop iterating (but keep current address)
826 try_connect_to_address (void *cls,
828 struct GNUNET_TIME_Absolute expiration,
829 const void *addr, size_t addrlen)
831 struct ConnectContext *cc = cls;
834 if (0 != strcmp (tname, "tcp"))
835 return GNUNET_OK; /* not one of ours */
836 if (sizeof (struct sockaddr_in) == addrlen)
838 else if (sizeof (struct sockaddr_in6) == addrlen)
842 /* not a valid address */
848 cc->welcome = create_welcome (addrlen, addr, cc->plugin);
850 GNUNET_NETWORK_socket_create_from_sockaddr (cc->plugin->env->sched,
852 GNUNET_SERVER_MAX_MESSAGE_SIZE);
854 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
855 "tcp", "Connected to other peer.\n");
857 return GNUNET_SYSERR;
859 return GNUNET_OK; /* failed to connect */
864 * Type of an iterator over the hosts. Note that each
865 * host will be called with each available protocol.
868 * @param peer id of the peer, NULL for last call
869 * @param hello hello message for the peer (can be NULL)
870 * @param trust amount of trust we have in the peer
873 session_try_connect (void *cls,
874 const struct GNUNET_PeerIdentity *peer,
875 const struct GNUNET_HELLO_Message *hello, uint32_t trust)
877 struct Session *session = cls;
879 struct ConnectContext cctx;
880 struct PendingMessage *pm;
884 /* last call, destroy session if we are still not
886 if (session->still_connecting == GNUNET_NO)
889 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
891 "Connected to other peer, now processing messages.\n");
893 process_pending_messages (session);
898 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
900 "Failed to connect to other peer, now closing session.\n");
902 disconnect_session (session);
906 if ((hello == NULL) || (session->client != NULL))
908 GNUNET_break (0); /* should this ever happen!? */
912 GNUNET_HELLO_iterate_addresses (hello,
913 GNUNET_NO, &count_tcp_addresses, &count);
917 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
919 "Asked to connect, but have no addresses to try.\n");
923 cctx.plugin = session->plugin;
926 cctx.pos = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, count);
927 GNUNET_HELLO_iterate_addresses (hello,
928 GNUNET_NO, &try_connect_to_address, &cctx);
932 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
934 "Asked to connect, but all addresses failed.\n");
936 GNUNET_free_non_null (cctx.welcome);
939 session->client = GNUNET_SERVER_connect_socket (session->plugin->server,
942 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
943 "Connected getting client address %p\n", session->client);
945 if (session->client == NULL)
947 GNUNET_break (0); /* how could this happen? */
948 GNUNET_free_non_null (cctx.welcome);
953 pm->next = session->pending_messages;
954 session->pending_messages = pm;
955 session->still_connecting = GNUNET_NO;
957 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
959 "Connected to other peer, now sending `%s' message.\n",
966 * Function that can be used by the transport service to transmit
967 * a message using the plugin.
970 * @param plugin_context value we were asked to pass to this plugin
971 * to respond to the given peer (use is optional,
972 * but may speed up processing), can be NULL
973 * @param service_context value passed to the transport-service
974 * to identify the neighbour
975 * @param target who should receive this message
976 * @param priority how important is the message
977 * @param msg the message to transmit
978 * @param cont continuation to call once the message has
979 * been transmitted (or if the transport is ready
980 * for the next transmission call; or if the
981 * peer disconnected...)
982 * @param cont_cls closure for cont
983 * @return plugin_context that should be used next time for
984 * sending messages to the specified peer
987 tcp_plugin_send (void *cls,
988 void *plugin_context,
989 struct ReadyList *service_context,
990 const struct GNUNET_PeerIdentity *target,
991 unsigned int priority,
992 const struct GNUNET_MessageHeader *msg,
993 struct GNUNET_TIME_Relative timeout,
994 GNUNET_TRANSPORT_TransmitContinuation cont, void *cont_cls)
996 struct Plugin *plugin = cls;
997 struct Session *session = plugin_context;
998 struct PendingMessage *pm;
999 struct PendingMessage *pme;
1001 if (session == NULL)
1002 session = find_session_by_target (plugin, target);
1003 pm = GNUNET_malloc (sizeof (struct PendingMessage) + ntohs (msg->size));
1004 pm->msg = (struct GNUNET_MessageHeader *) &pm[1];
1005 memcpy (pm->msg, msg, ntohs (msg->size));
1006 pm->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1007 pm->transmit_cont = cont;
1008 pm->transmit_cont_cls = cont_cls;
1009 if (session == NULL)
1011 session = GNUNET_malloc (sizeof (struct Session));
1013 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1015 "Asked to transmit, creating fresh session %p.\n",
1018 session->next = plugin->sessions;
1019 plugin->sessions = session;
1020 session->plugin = plugin;
1021 session->target = *target;
1022 session->last_quota_update = GNUNET_TIME_absolute_get ();
1023 session->quota_in = plugin->env->default_quota_in;
1024 session->expecting_welcome = GNUNET_YES;
1025 session->still_connecting = GNUNET_YES;
1026 session->pending_messages = pm;
1027 session->service_context = service_context;
1028 GNUNET_PEERINFO_for_all (plugin->env->cfg,
1031 0, timeout, &session_try_connect, session);
1034 GNUNET_assert (session != NULL);
1035 GNUNET_assert (session->still_connecting == GNUNET_NO);
1036 session->service_context = service_context;
1037 /* append pm to pending_messages list */
1038 pme = session->pending_messages;
1041 session->pending_messages = pm;
1045 while (NULL != pme->next)
1050 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1051 "tcp", "Asked to transmit, added message to list.\n");
1053 process_pending_messages (session);
1060 * Function that can be called to force a disconnect from the
1061 * specified neighbour. This should also cancel all previously
1062 * scheduled transmissions. Obviously the transmission may have been
1063 * partially completed already, which is OK. The plugin is supposed
1064 * to close the connection (if applicable) and no longer call the
1065 * transmit continuation(s).
1067 * Finally, plugin MUST NOT call the services's receive function to
1068 * notify the service that the connection to the specified target was
1069 * closed after a getting this call.
1071 * @param cls closure
1072 * @param plugin_context value we were asked to pass to this plugin
1073 * to respond to the given peer (use is optional,
1074 * but may speed up processing), can be NULL (if
1075 * NULL was returned from the transmit function)
1076 * @param service_context must correspond to the service context
1077 * of the corresponding Transmit call; the plugin should
1078 * not cancel a send call made with a different service
1079 * context pointer! Never NULL.
1080 * @param target peer for which the last transmission is
1084 tcp_plugin_cancel (void *cls,
1085 void *plugin_context,
1086 struct ReadyList *service_context,
1087 const struct GNUNET_PeerIdentity *target)
1089 struct Plugin *plugin = cls;
1090 struct PendingMessage *pm;
1091 struct Session *session;
1092 struct Session *next;
1094 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1096 "Asked to close session with `%4s'\n",
1097 GNUNET_i2s(target));
1098 session = plugin->sessions;
1099 while (session != NULL)
1101 next = session->next;
1102 if (0 == memcmp (target,
1103 &session->target, sizeof (struct GNUNET_PeerIdentity)))
1105 pm = session->pending_messages;
1108 pm->transmit_cont = NULL;
1109 pm->transmit_cont_cls = NULL;
1112 session->service_context = NULL;
1113 GNUNET_SERVER_client_disconnect (session->client);
1114 /* rest of the clean-up of the session will be done as part of
1115 disconnect_notify which should be triggered any time now */
1122 struct PrettyPrinterContext
1124 GNUNET_TRANSPORT_AddressStringCallback asc;
1131 * Append our port and forward the result.
1134 append_port (void *cls, const char *hostname)
1136 struct PrettyPrinterContext *ppc = cls;
1139 if (hostname == NULL)
1141 ppc->asc (ppc->asc_cls, NULL);
1145 GNUNET_asprintf (&ret, "%s:%d", hostname, ppc->port);
1146 ppc->asc (ppc->asc_cls, ret);
1152 * Convert the transports address to a nice, human-readable
1155 * @param cls closure
1156 * @param name name of the transport that generated the address
1157 * @param addr one of the addresses of the host, NULL for the last address
1158 * the specific address format depends on the transport
1159 * @param addrlen length of the address
1160 * @param numeric should (IP) addresses be displayed in numeric form?
1161 * @param timeout after how long should we give up?
1162 * @param asc function to call on each string
1163 * @param asc_cls closure for asc
1166 tcp_plugin_address_pretty_printer (void *cls,
1171 struct GNUNET_TIME_Relative timeout,
1172 GNUNET_TRANSPORT_AddressStringCallback asc,
1175 struct Plugin *plugin = cls;
1176 const struct sockaddr_in *v4;
1177 const struct sockaddr_in6 *v6;
1178 struct PrettyPrinterContext *ppc;
1180 if ((addrlen != sizeof (struct sockaddr_in)) &&
1181 (addrlen != sizeof (struct sockaddr_in6)))
1183 /* invalid address */
1184 GNUNET_break_op (0);
1185 asc (asc_cls, NULL);
1188 ppc = GNUNET_malloc (sizeof (struct PrettyPrinterContext));
1190 ppc->asc_cls = asc_cls;
1191 if (addrlen == sizeof (struct sockaddr_in))
1193 v4 = (const struct sockaddr_in *) addr;
1194 ppc->port = ntohs (v4->sin_port);
1198 v6 = (const struct sockaddr_in6 *) addr;
1199 ppc->port = ntohs (v6->sin6_port);
1202 GNUNET_RESOLVER_hostname_get (plugin->env->sched,
1206 !numeric, timeout, &append_port, ppc);
1211 * Update the last-received and bandwidth quota values
1214 * @param session session to update
1215 * @param force set to GNUNET_YES if we should update even
1216 * though the minimum refresh time has not yet expired
1219 update_quota (struct Session *session, int force)
1221 struct GNUNET_TIME_Absolute now;
1222 unsigned long long delta;
1223 unsigned long long total_allowed;
1224 unsigned long long total_remaining;
1226 now = GNUNET_TIME_absolute_get ();
1227 delta = now.value - session->last_quota_update.value;
1228 if ((delta < MIN_QUOTA_REFRESH_TIME) && (!force))
1229 return; /* too early, not enough data */
1231 total_allowed = session->quota_in * delta;
1232 if (total_allowed > session->last_received)
1234 /* got less than acceptable */
1235 total_remaining = total_allowed - session->last_received;
1236 session->last_received = 0;
1237 delta = total_remaining / session->quota_in; /* bonus seconds */
1238 if (delta > MAX_BANDWIDTH_CARRY)
1239 delta = MAX_BANDWIDTH_CARRY; /* limit amount of carry-over */
1243 /* got more than acceptable */
1244 total_remaining = 0;
1245 session->last_received -= total_allowed;
1248 session->last_quota_update.value = now.value - delta;
1253 * Set a quota for receiving data from the given peer; this is a
1254 * per-transport limit. The transport should limit its read/select
1255 * calls to stay below the quota (in terms of incoming data).
1257 * @param cls closure
1258 * @param peer the peer for whom the quota is given
1259 * @param quota_in quota for receiving/sending data in bytes per ms
1262 tcp_plugin_set_receive_quota (void *cls,
1263 const struct GNUNET_PeerIdentity *target,
1266 struct Plugin *plugin = cls;
1267 struct Session *session;
1269 session = find_session_by_target (plugin, target);
1270 if (session->quota_in != quota_in)
1272 update_quota (session, GNUNET_YES);
1273 if (session->quota_in > quota_in)
1274 session->last_quota_update = GNUNET_TIME_absolute_get ();
1275 session->quota_in = quota_in;
1281 * Check if the given port is plausible (must be either
1282 * our listen port or our advertised port). If it is
1283 * neither, we return one of these two ports at random.
1285 * @return either in_port or a more plausible port
1288 check_port (struct Plugin *plugin, uint16_t in_port)
1290 if ((in_port == plugin->adv_port) || (in_port == plugin->open_port))
1292 return (GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
1294 ? plugin->open_port : plugin->adv_port;
1299 * Another peer has suggested an address for this
1300 * peer and transport plugin. Check that this could be a valid
1301 * address. If so, consider adding it to the list
1304 * @param cls closure
1305 * @param addr pointer to the address
1306 * @param addrlen length of addr
1307 * @return GNUNET_OK if this is a plausible address for this peer
1311 tcp_plugin_address_suggested (void *cls, const void *addr, size_t addrlen)
1313 struct Plugin *plugin = cls;
1314 char buf[sizeof (struct sockaddr_in6)];
1315 struct sockaddr_in *v4;
1316 struct sockaddr_in6 *v6;
1318 if ((addrlen != sizeof (struct sockaddr_in)) &&
1319 (addrlen != sizeof (struct sockaddr_in6)))
1321 GNUNET_break_op (0);
1322 return GNUNET_SYSERR;
1324 memcpy (buf, addr, sizeof (struct sockaddr_in6));
1325 if (addrlen == sizeof (struct sockaddr_in))
1327 v4 = (struct sockaddr_in *) buf;
1328 v4->sin_port = htons (check_port (plugin, ntohs (v4->sin_port)));
1332 v6 = (struct sockaddr_in6 *) buf;
1333 v6->sin6_port = htons (check_port (plugin, ntohs (v6->sin6_port)));
1336 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1338 "Informing transport service about my address `%s'.\n",
1339 GNUNET_a2s(addr, addrlen));
1341 plugin->env->notify_address (plugin->env->cls,
1343 buf, addrlen, LEARNED_ADDRESS_EXPIRATION);
1349 * We've received a welcome from this peer via TCP.
1350 * Possibly create a fresh client record and send back
1353 * @param cls closure
1354 * @param client identification of the client
1355 * @param message the actual message
1358 handle_tcp_welcome (void *cls,
1359 struct GNUNET_SERVER_Client *client,
1360 const struct GNUNET_MessageHeader *message)
1362 struct Plugin *plugin = cls;
1363 struct Session *session_c;
1364 const struct WelcomeMessage *wm;
1369 const struct sockaddr *addr;
1371 msize = ntohs (message->size);
1372 if (msize < sizeof (struct WelcomeMessage))
1374 GNUNET_break_op (0);
1375 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1378 wm = (const struct WelcomeMessage *) message;
1380 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1382 "Received `%s' message from `%4s/%p'.\n", "WELCOME",
1383 GNUNET_i2s(&wm->clientIdentity),
1386 session_c = find_session_by_client (plugin, client);
1387 if (session_c == NULL)
1390 GNUNET_SERVER_client_get_address (client, &vaddr, &alen);
1391 GNUNET_SERVER_client_keep (client);
1392 session_c = create_session (plugin,
1393 &wm->clientIdentity, client, vaddr, alen);
1395 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1397 "Creating new session %p for incoming `%s' message.\n",
1398 session_c, "WELCOME");
1400 GNUNET_free_non_null (vaddr);
1401 process_pending_messages (session_c);
1403 session_c->expecting_welcome = GNUNET_NO;
1404 if (0 < (addrlen = msize - sizeof (struct WelcomeMessage)))
1406 addr = (const struct sockaddr *) &wm[1];
1407 tcp_plugin_address_suggested (plugin, addr, addrlen);
1409 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1414 * Calculate how long we should delay reading from the TCP socket to
1415 * ensure that we stay within our bandwidth limits (push back).
1417 * @param session for which client should this be calculated
1419 static struct GNUNET_TIME_Relative
1420 calculate_throttle_delay (struct Session *session)
1422 struct GNUNET_TIME_Relative ret;
1423 struct GNUNET_TIME_Absolute now;
1428 now = GNUNET_TIME_absolute_get ();
1429 del = now.value - session->last_quota_update.value;
1430 if (del > MAX_BANDWIDTH_CARRY)
1432 update_quota (session, GNUNET_YES);
1433 del = now.value - session->last_quota_update.value;
1434 GNUNET_assert (del <= MAX_BANDWIDTH_CARRY);
1436 if (session->quota_in == 0)
1437 session->quota_in = 1; /* avoid divison by zero */
1438 avail = del * session->quota_in;
1439 if (avail > session->last_received)
1440 return GNUNET_TIME_UNIT_ZERO; /* can receive right now */
1441 excess = session->last_received - avail;
1442 ret.value = excess / session->quota_in;
1448 * Task to signal the server that we can continue
1449 * receiving from the TCP client now.
1452 delayed_done (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1454 struct Session *session = cls;
1455 GNUNET_SERVER_receive_done (session->client, GNUNET_OK);
1460 * We've received data for this peer via TCP. Unbox,
1461 * compute latency and forward.
1463 * @param cls closure
1464 * @param client identification of the client
1465 * @param message the actual message
1468 handle_tcp_data (void *cls,
1469 struct GNUNET_SERVER_Client *client,
1470 const struct GNUNET_MessageHeader *message)
1472 struct Plugin *plugin = cls;
1473 struct Session *session;
1474 const struct DataMessage *dm;
1476 const struct GNUNET_MessageHeader *msg;
1477 struct GNUNET_TIME_Relative latency;
1478 struct GNUNET_TIME_Absolute ttime;
1479 struct GNUNET_TIME_Absolute now;
1480 struct GNUNET_TIME_Relative delay;
1483 msize = ntohs (message->size);
1485 sizeof (struct DataMessage) + sizeof (struct GNUNET_MessageHeader)))
1487 GNUNET_break_op (0);
1488 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1491 session = find_session_by_client (plugin, client);
1492 if ((NULL == session) || (GNUNET_YES == session->expecting_welcome))
1494 GNUNET_break_op (0);
1495 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1499 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1500 "tcp", "Receiving %u bytes from `%4s'.\n",
1502 GNUNET_i2s(&session->target));
1504 dm = (const struct DataMessage *) message;
1505 session->max_in_msg_counter = GNUNET_MAX (session->max_in_msg_counter,
1506 GNUNET_ntohll (dm->ack_out));
1507 msg = (const struct GNUNET_MessageHeader *) &dm[1];
1508 if (msize != sizeof (struct DataMessage) + ntohs (msg->size))
1510 GNUNET_break_op (0);
1511 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1514 /* estimate latency */
1515 ack_in = GNUNET_ntohll (dm->ack_in);
1516 if ((ack_in <= session->out_msg_counter) &&
1517 (session->out_msg_counter - ack_in < ACK_LOG_SIZE))
1519 delay = GNUNET_TIME_relative_ntoh (dm->delay);
1520 ttime = session->gen_time[ack_in % ACK_LOG_SIZE];
1521 now = GNUNET_TIME_absolute_get ();
1522 if (delay.value > now.value - ttime.value)
1523 delay.value = 0; /* not plausible */
1524 /* update (round-trip) latency using ageing; we
1525 use 7:1 so that we can reasonably quickly react
1526 to changes, but not so fast that latency is largely
1528 session->latency_estimate
1529 = ((7 * session->latency_estimate) +
1530 (now.value - ttime.value - delay.value)) / 8;
1532 latency.value = (uint64_t) session->latency_estimate;
1535 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1537 "Forwarding data of type %u to transport service.\n",
1540 session->service_context
1541 = plugin->env->receive (plugin->env->cls,
1543 session->service_context,
1544 latency, &session->target, msg);
1545 /* update bandwidth used */
1546 session->last_received += msize;
1547 update_quota (session, GNUNET_NO);
1549 delay = calculate_throttle_delay (session);
1550 if (delay.value == 0)
1551 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1553 GNUNET_SCHEDULER_add_delayed (session->plugin->env->sched,
1555 GNUNET_SCHEDULER_PRIORITY_HIGH,
1556 GNUNET_SCHEDULER_NO_PREREQUISITE_TASK,
1557 delay, &delayed_done, session);
1562 * Handlers for the various TCP messages.
1564 static struct GNUNET_SERVER_MessageHandler my_handlers[] = {
1565 {&handle_tcp_welcome, NULL, GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME, 0},
1566 {&handle_tcp_data, NULL, GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_DATA, 0},
1572 create_tcp_handlers (struct Plugin *plugin)
1575 plugin->handlers = GNUNET_malloc (sizeof (my_handlers));
1576 memcpy (plugin->handlers, my_handlers, sizeof (my_handlers));
1579 sizeof (my_handlers) / sizeof (struct GNUNET_SERVER_MessageHandler);
1581 plugin->handlers[i].callback_cls = plugin;
1582 GNUNET_SERVER_add_handlers (plugin->server, plugin->handlers);
1587 * Functions with this signature are called whenever a peer
1588 * is disconnected on the network level.
1590 * @param cls closure
1591 * @param client identification of the client
1594 disconnect_notify (void *cls, struct GNUNET_SERVER_Client *client)
1596 struct Plugin *plugin = cls;
1597 struct Session *session;
1600 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1602 "Notified about network-level disconnect of client %p.\n",
1605 session = find_session_by_client (plugin, client);
1606 if (session == NULL)
1607 return; /* unknown, nothing to do */
1609 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1610 "tcp", "Will now destroy session %p.\n", session);
1612 disconnect_session (session);
1617 * Add the IP of our network interface to the list of
1618 * our external IP addresses.
1621 process_interfaces (void *cls,
1624 const struct sockaddr *addr, socklen_t addrlen)
1626 struct Plugin *plugin = cls;
1628 struct sockaddr_in *v4;
1629 struct sockaddr_in6 *v6;
1631 af = addr->sa_family;
1634 v4 = (struct sockaddr_in *) addr;
1635 v4->sin_port = htons (plugin->adv_port);
1639 GNUNET_assert (af == AF_INET6);
1640 v6 = (struct sockaddr_in6 *) addr;
1641 v6->sin6_port = htons (plugin->adv_port);
1643 GNUNET_log_from (GNUNET_ERROR_TYPE_INFO |
1644 GNUNET_ERROR_TYPE_BULK,
1645 "tcp", _("Found address `%s' (%s)\n"),
1646 GNUNET_a2s(addr, addrlen), name);
1647 plugin->env->notify_address (plugin->env->cls,
1649 addr, addrlen, GNUNET_TIME_UNIT_FOREVER_REL);
1655 * Function called by the resolver for each address obtained from DNS
1656 * for our own hostname. Add the addresses to the list of our
1657 * external IP addresses.
1659 * @param cls closure
1660 * @param addr one of the addresses of the host, NULL for the last address
1661 * @param addrlen length of the address
1664 process_hostname_ips (void *cls,
1665 const struct sockaddr *addr, socklen_t addrlen)
1667 struct Plugin *plugin = cls;
1671 plugin->env->notify_address (plugin->env->cls,
1673 addr, addrlen, GNUNET_TIME_UNIT_FOREVER_REL);
1678 * Entry point for the plugin.
1681 libgnunet_plugin_transport_tcp_init (void *cls)
1683 struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
1684 struct GNUNET_TRANSPORT_PluginFunctions *api;
1685 struct Plugin *plugin;
1686 struct GNUNET_SERVICE_Context *service;
1687 unsigned long long aport;
1688 unsigned long long bport;
1690 service = GNUNET_SERVICE_start ("transport-tcp", env->sched, env->cfg);
1691 if (service == NULL)
1693 GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING,
1696 ("Failed to start service for `%s' transport plugin.\n"),
1702 GNUNET_CONFIGURATION_get_value_number (env->cfg,
1708 GNUNET_CONFIGURATION_get_value_number (env->cfg,
1711 &aport)) && (aport > 65535)))
1713 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
1716 ("Require valid port number for service `%s' in configuration!\n"),
1718 GNUNET_SERVICE_stop (service);
1723 plugin = GNUNET_malloc (sizeof (struct Plugin));
1724 plugin->open_port = bport;
1725 plugin->adv_port = aport;
1727 plugin->lsock = NULL;
1728 plugin->statistics = NULL;
1729 api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
1731 api->send_to = &tcp_plugin_send_to;
1732 api->send = &tcp_plugin_send;
1733 api->cancel = &tcp_plugin_cancel;
1734 api->address_pretty_printer = &tcp_plugin_address_pretty_printer;
1735 api->set_receive_quota = &tcp_plugin_set_receive_quota;
1736 api->address_suggested = &tcp_plugin_address_suggested;
1737 api->cost_estimate = 42; /* TODO: ATS */
1738 plugin->service = service;
1739 plugin->server = GNUNET_SERVICE_get_server (service);
1740 create_tcp_handlers (plugin);
1741 GNUNET_log_from (GNUNET_ERROR_TYPE_INFO,
1742 "tcp", _("TCP transport listening on port %u\n"), bport);
1744 GNUNET_log_from (GNUNET_ERROR_TYPE_INFO,
1747 ("TCP transport advertises itself as being on port %u\n"),
1749 GNUNET_SERVER_disconnect_notify (plugin->server, &disconnect_notify,
1751 GNUNET_OS_network_interfaces_list (&process_interfaces, plugin);
1752 GNUNET_RESOLVER_hostname_resolve (env->sched,
1755 HOSTNAME_RESOLVE_TIMEOUT,
1756 &process_hostname_ips, plugin);
1762 * Exit point from the plugin.
1765 libgnunet_plugin_transport_tcp_done (void *cls)
1767 struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
1768 struct Plugin *plugin = api->cls;
1770 GNUNET_SERVICE_stop (plugin->service);
1771 GNUNET_free (plugin->handlers);
1772 GNUNET_free (plugin);
1777 /* end of plugin_transport_tcp.c */