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.
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_connection_lib.h"
30 #include "gnunet_container_lib.h"
31 #include "gnunet_os_lib.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_signatures.h"
37 #include "gnunet_statistics_service.h"
38 #include "gnunet_transport_service.h"
39 #include "plugin_transport.h"
40 #include "transport.h"
42 #define DEBUG_TCP GNUNET_NO
45 * How long until we give up on transmitting the welcome message?
47 #define HOSTNAME_RESOLVE_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 5)
51 * Initial handshake message for a session.
56 * Type is GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME.
58 struct GNUNET_MessageHeader header;
61 * Identity of the node connecting (TCP client)
63 struct GNUNET_PeerIdentity clientIdentity;
69 * Encapsulation of all of the state of the plugin.
75 * Information kept for each message that is yet to
82 * This is a doubly-linked list.
84 struct PendingMessage *next;
87 * This is a doubly-linked list.
89 struct PendingMessage *prev;
97 * Continuation function to call once the message
98 * has been sent. Can be NULL if there is no
99 * continuation to call.
101 GNUNET_TRANSPORT_TransmitContinuation transmit_cont;
104 * Closure for transmit_cont.
106 void *transmit_cont_cls;
109 * Timeout value for the pending message.
111 struct GNUNET_TIME_Absolute timeout;
114 * So that the gnunet-service-transport can group messages together,
115 * these pending messages need to accept a message buffer and size
116 * instead of just a GNUNET_MessageHeader.
124 * Session handle for TCP connections.
130 * Stored in a linked list.
132 struct Session *next;
135 * Pointer to the global plugin struct.
137 struct Plugin *plugin;
140 * The client (used to identify this connection)
142 struct GNUNET_SERVER_Client *client;
145 * Messages currently pending for transmission
146 * to this peer, if any.
148 struct PendingMessage *pending_messages_head;
151 * Messages currently pending for transmission
152 * to this peer, if any.
154 struct PendingMessage *pending_messages_tail;
157 * Handle for pending transmission request.
159 struct GNUNET_CONNECTION_TransmitHandle *transmit_handle;
162 * To whom are we talking to (set to our identity
163 * if we are still waiting for the welcome message)
165 struct GNUNET_PeerIdentity target;
168 * At what time did we reset last_received last?
170 struct GNUNET_TIME_Absolute last_quota_update;
173 * Address of the other peer (either based on our 'connect'
174 * call or on our 'accept' call).
179 * How many bytes have we received since the "last_quota_update"
182 uint64_t last_received;
185 * Number of bytes per ms that this peer is allowed
191 * Length of connect_addr.
196 * Are we still expecting the welcome message? (GNUNET_YES/GNUNET_NO)
198 int expecting_welcome;
204 * Encapsulation of all of the state of the plugin.
211 struct GNUNET_TRANSPORT_PluginEnvironment *env;
216 struct GNUNET_CONNECTION_Handle *lsock;
219 * List of open TCP sessions.
221 struct Session *sessions;
224 * Handle for the statistics service.
226 struct GNUNET_STATISTICS_Handle *statistics;
229 * Handle to the network service.
231 struct GNUNET_SERVICE_Context *service;
234 * Handle to the server for this service.
236 struct GNUNET_SERVER_Handle *server;
239 * Copy of the handler array where the closures are
240 * set to this struct's instance.
242 struct GNUNET_SERVER_MessageHandler *handlers;
245 * Handle for request of hostname resolution, non-NULL if pending.
247 struct GNUNET_RESOLVER_RequestHandle *hostname_dns;
250 * ID of task used to update our addresses when one expires.
252 GNUNET_SCHEDULER_TaskIdentifier address_update_task;
255 * Port that we are actually listening on.
260 * Port that the user said we would have visible to the
269 * Find a session handle for the given peer.
270 * FIXME: using a hash map we could do this in O(1).
272 * @return NULL if no matching session exists
274 static struct Session *
275 find_session_by_target (struct Plugin *plugin,
276 const struct GNUNET_PeerIdentity *target)
280 ret = plugin->sessions;
281 while ( (ret != NULL) &&
282 ((GNUNET_SYSERR == ret->expecting_welcome) ||
283 (0 != memcmp (target,
284 &ret->target, sizeof (struct GNUNET_PeerIdentity)))))
291 * Find the session handle for the given client.
293 * @return NULL if no matching session exists
295 static struct Session *
296 find_session_by_client (struct Plugin *plugin,
297 const struct GNUNET_SERVER_Client *client)
301 ret = plugin->sessions;
302 while ((ret != NULL) && (client != ret->client))
309 * Create a new session. Also queues a welcome message.
312 * @param target peer to connect to
313 * @param client client to use
314 * @return new session object
316 static struct Session *
317 create_session (struct Plugin *plugin,
318 const struct GNUNET_PeerIdentity *target,
319 struct GNUNET_SERVER_Client *client)
322 struct PendingMessage *pm;
323 struct WelcomeMessage welcome;
325 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
327 "Creating new session for peer `%4s'\n",
328 GNUNET_i2s (target));
329 ret = GNUNET_malloc (sizeof (struct Session));
330 ret->plugin = plugin;
331 ret->next = plugin->sessions;
332 plugin->sessions = ret;
333 ret->client = client;
334 ret->target = *target;
335 ret->last_quota_update = GNUNET_TIME_absolute_get ();
336 ret->quota_in = plugin->env->default_quota_in;
337 ret->expecting_welcome = GNUNET_YES;
338 pm = GNUNET_malloc (sizeof (struct PendingMessage) + sizeof (struct WelcomeMessage));
339 pm->msg = (const char*) &pm[1];
340 pm->message_size = sizeof (struct WelcomeMessage);
341 welcome.header.size = htons (sizeof (struct WelcomeMessage));
342 welcome.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME);
343 welcome.clientIdentity = *plugin->env->my_identity;
344 memcpy (&pm[1], &welcome, sizeof (welcome));
345 pm->timeout = GNUNET_TIME_UNIT_FOREVER_ABS;
346 GNUNET_CONTAINER_DLL_insert (ret->pending_messages_head,
347 ret->pending_messages_tail,
354 * If we have pending messages, ask the server to
355 * transmit them (schedule the respective tasks, etc.)
357 * @param session for which session should we do this
359 static void process_pending_messages (struct Session *session);
363 * Function called to notify a client about the socket
364 * being ready to queue more data. "buf" will be
365 * NULL and "size" zero if the socket was closed for
366 * writing in the meantime.
369 * @param size number of bytes available in buf
370 * @param buf where the callee should write the message
371 * @return number of bytes written to buf
374 do_transmit (void *cls, size_t size, void *buf)
376 struct Session *session = cls;
377 struct PendingMessage *pm;
382 session->transmit_handle = NULL;
386 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
388 "Timeout trying to transmit to peer `%4s', discarding message queue.\n",
389 GNUNET_i2s (&session->target));
392 while (NULL != (pm = session->pending_messages_head))
394 GNUNET_CONTAINER_DLL_remove (session->pending_messages_head,
395 session->pending_messages_tail,
398 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
400 "Failed to transmit %u byte message to `%4s'.\n",
402 GNUNET_i2s (&session->target));
404 if (pm->transmit_cont != NULL)
405 pm->transmit_cont (pm->transmit_cont_cls,
406 &session->target, GNUNET_SYSERR);
413 while (NULL != (pm = session->pending_messages_head))
415 if (size < pm->message_size)
417 memcpy (cbuf, pm->msg, pm->message_size);
418 cbuf += pm->message_size;
419 ret += pm->message_size;
420 size -= pm->message_size;
421 GNUNET_CONTAINER_DLL_remove (session->pending_messages_head,
422 session->pending_messages_tail,
424 if (pm->transmit_cont != NULL)
425 pm->transmit_cont (pm->transmit_cont_cls,
426 &session->target, GNUNET_OK);
429 if (session->client != NULL)
430 process_pending_messages (session);
432 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
433 "tcp", "Transmitting %u bytes\n", ret);
440 * If we have pending messages, ask the server to
441 * transmit them (schedule the respective tasks, etc.)
443 * @param session for which session should we do this
446 process_pending_messages (struct Session *session)
448 struct PendingMessage *pm;
449 GNUNET_assert (session->client != NULL);
450 if (session->transmit_handle != NULL)
452 if (NULL == (pm = session->pending_messages_head))
454 session->transmit_handle
455 = GNUNET_SERVER_notify_transmit_ready (session->client,
457 GNUNET_TIME_absolute_get_remaining
459 &do_transmit, session);
464 * Functions with this signature are called whenever we need
465 * to close a session due to a disconnect or failure to
466 * establish a connection.
468 * @param session session to close down
471 disconnect_session (struct Session *session)
473 struct Session *prev;
475 struct PendingMessage *pm;
478 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
480 "Disconnecting from `%4s' at %s (session %p).\n",
481 GNUNET_i2s (&session->target),
482 (session->connect_addr != NULL) ?
483 GNUNET_a2s (session->connect_addr,
484 session->connect_alen) : "*", session);
486 /* remove from session list */
488 pos = session->plugin->sessions;
489 while (pos != session)
495 session->plugin->sessions = session->next;
497 prev->next = session->next;
499 if (session->transmit_handle != NULL)
501 GNUNET_CONNECTION_notify_transmit_ready_cancel
502 (session->transmit_handle);
503 session->transmit_handle = NULL;
505 while (NULL != (pm = session->pending_messages_head))
508 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
510 pm->transmit_cont != NULL
511 ? "Could not deliver message to `%4s'.\n"
513 "Could not deliver message to `%4s', notifying.\n",
514 GNUNET_i2s (&session->target));
516 GNUNET_CONTAINER_DLL_remove (session->pending_messages_head,
517 session->pending_messages_tail,
519 if (NULL != pm->transmit_cont)
520 pm->transmit_cont (pm->transmit_cont_cls,
521 &session->target, GNUNET_SYSERR);
524 if (GNUNET_NO == session->expecting_welcome)
527 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
529 "Notifying transport service about loss of connection with `%4s'.\n",
530 GNUNET_i2s (&session->target));
532 /* Data session that actually went past the initial handshake;
533 transport service may know about this one, so we need to
534 notify transport service about disconnect */
535 // FIXME: we should have a very clear connect-disconnect
536 // protocol with gnunet-service-transport!
537 session->plugin->env->receive (session->plugin->env->cls,
538 &session->target, NULL,
540 session->connect_addr,
541 session->connect_alen);
543 if (session->client != NULL)
545 GNUNET_SERVER_client_drop (session->client);
546 session->client = NULL;
548 GNUNET_free_non_null (session->connect_addr);
549 GNUNET_free (session);
554 * Function that can be used by the transport service to transmit
555 * a message using the plugin. Note that in the case of a
556 * peer disconnecting, the continuation MUST be called
557 * prior to the disconnect notification itself. This function
558 * will be called with this peer's HELLO message to initiate
559 * a fresh connection to another peer.
562 * @param target who should receive this message
563 * @param msg the message to transmit
564 * @param msgbuf_size number of bytes in 'msg'
565 * @param priority how important is the message (most plugins will
566 * ignore message priority and just FIFO)
567 * @param timeout how long to wait at most for the transmission (does not
568 * require plugins to discard the message after the timeout,
569 * just advisory for the desired delay; most plugins will ignore
571 * @param addr the address to use (can be NULL if the plugin
572 * is "on its own" (i.e. re-use existing TCP connection))
573 * @param addrlen length of the address in bytes
574 * @param force_address GNUNET_YES if the plugin MUST use the given address,
575 * otherwise the plugin may use other addresses or
576 * existing connections (if available)
577 * @param cont continuation to call once the message has
578 * been transmitted (or if the transport is ready
579 * for the next transmission call; or if the
580 * peer disconnected...); can be NULL
581 * @param cont_cls closure for cont
582 * @return number of bytes used (on the physical network, with overheads);
583 * -1 on hard errors (i.e. address invalid); 0 is a legal value
584 * and does NOT mean that the message was not transmitted (DV)
587 tcp_plugin_send (void *cls,
588 const struct GNUNET_PeerIdentity *target,
592 struct GNUNET_TIME_Relative timeout,
596 GNUNET_TRANSPORT_TransmitContinuation cont, void *cont_cls)
598 struct Plugin *plugin = cls;
599 struct Session *session;
600 struct PendingMessage *pm;
601 struct GNUNET_CONNECTION_Handle *sa;
604 session = plugin->sessions;
605 /* FIXME: we could do this a cheaper with a hash table
606 where we could restrict the iteration to entries that match
607 the target peer... */
608 while ( (session != NULL) &&
609 ( (0 != memcmp (target,
611 sizeof (struct GNUNET_PeerIdentity))) ||
612 ( (GNUNET_YES == force_address) &&
614 ( (addrlen != session->connect_alen) ||
615 (0 != memcmp (session->connect_addr,
618 session = session->next;
619 if ( (session == NULL) &&
623 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
625 "Asked to transmit to `%4s' without address and I have no existing connection (failing).\n",
626 GNUNET_i2s (target));
632 if (sizeof (struct sockaddr_in) == addrlen)
634 else if (sizeof (struct sockaddr_in6) == addrlen)
641 sa = GNUNET_CONNECTION_create_from_sockaddr (plugin->env->sched,
643 GNUNET_SERVER_MAX_MESSAGE_SIZE);
647 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
649 "Failed to create connection to `%4s' at `%s'\n",
651 GNUNET_a2s (addr, addrlen));
657 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
659 "Asked to transmit to `%4s', creating fresh session using address `%s'.\n",
661 GNUNET_a2s (addr, addrlen));
663 session = create_session (plugin,
665 GNUNET_SERVER_connect_socket (plugin->server,
667 session->connect_addr = GNUNET_malloc (addrlen);
668 memcpy (session->connect_addr,
671 session->connect_alen = addrlen;
673 GNUNET_assert (session != NULL);
674 GNUNET_assert (session->client != NULL);
676 /* create new message entry */
677 pm = GNUNET_malloc (sizeof (struct PendingMessage) + msgbuf_size);
678 pm->msg = (const char*) &pm[1];
679 memcpy (&pm[1], msg, msgbuf_size);
680 pm->message_size = msgbuf_size;
681 pm->timeout = GNUNET_TIME_relative_to_absolute (timeout);
682 pm->transmit_cont = cont;
683 pm->transmit_cont_cls = cont_cls;
685 /* append pm to pending_messages list */
686 GNUNET_CONTAINER_DLL_insert_after (session->pending_messages_head,
687 session->pending_messages_tail,
688 session->pending_messages_tail,
691 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
693 "Asked to transmit %u bytes to `%s', added message to list.\n",
695 GNUNET_i2s (target));
697 process_pending_messages (session);
703 * Function that can be called to force a disconnect from the
704 * specified neighbour. This should also cancel all previously
705 * scheduled transmissions. Obviously the transmission may have been
706 * partially completed already, which is OK. The plugin is supposed
707 * to close the connection (if applicable) and no longer call the
708 * transmit continuation(s).
710 * Finally, plugin MUST NOT call the services's receive function to
711 * notify the service that the connection to the specified target was
712 * closed after a getting this call.
715 * @param target peer for which the last transmission is
719 tcp_plugin_disconnect (void *cls, const struct GNUNET_PeerIdentity *target)
721 struct Plugin *plugin = cls;
722 struct Session *session;
723 struct PendingMessage *pm;
726 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
728 "Asked to cancel session with `%4s'\n",
729 GNUNET_i2s (target));
731 session = plugin->sessions;
732 while (NULL != session)
734 if (0 == memcmp (target,
736 sizeof (struct GNUNET_PeerIdentity)))
738 pm = session->pending_messages_head;
741 pm->transmit_cont = NULL;
742 pm->transmit_cont_cls = NULL;
745 if (session->client != NULL)
747 GNUNET_SERVER_client_drop (session->client);
748 session->client = NULL;
750 /* rest of the clean-up of the session will be done as part of
751 disconnect_notify which should be triggered any time now
752 (or which may be triggering this call in the first place) */
754 session = session->next;
759 struct PrettyPrinterContext
761 GNUNET_TRANSPORT_AddressStringCallback asc;
768 * Append our port and forward the result.
771 append_port (void *cls, const char *hostname)
773 struct PrettyPrinterContext *ppc = cls;
776 if (hostname == NULL)
778 ppc->asc (ppc->asc_cls, NULL);
782 GNUNET_asprintf (&ret, "%s:%d", hostname, ppc->port);
783 ppc->asc (ppc->asc_cls, ret);
789 * Convert the transports address to a nice, human-readable
793 * @param type name of the transport that generated the address
794 * @param addr one of the addresses of the host, NULL for the last address
795 * the specific address format depends on the transport
796 * @param addrlen length of the address
797 * @param numeric should (IP) addresses be displayed in numeric form?
798 * @param timeout after how long should we give up?
799 * @param asc function to call on each string
800 * @param asc_cls closure for asc
803 tcp_plugin_address_pretty_printer (void *cls,
808 struct GNUNET_TIME_Relative timeout,
809 GNUNET_TRANSPORT_AddressStringCallback asc,
812 struct Plugin *plugin = cls;
813 const struct sockaddr_in *v4;
814 const struct sockaddr_in6 *v6;
815 struct PrettyPrinterContext *ppc;
817 if ((addrlen != sizeof (struct sockaddr_in)) &&
818 (addrlen != sizeof (struct sockaddr_in6)))
820 /* invalid address */
825 ppc = GNUNET_malloc (sizeof (struct PrettyPrinterContext));
827 ppc->asc_cls = asc_cls;
828 if (addrlen == sizeof (struct sockaddr_in))
830 v4 = (const struct sockaddr_in *) addr;
831 ppc->port = ntohs (v4->sin_port);
835 v6 = (const struct sockaddr_in6 *) addr;
836 ppc->port = ntohs (v6->sin6_port);
839 GNUNET_RESOLVER_hostname_get (plugin->env->sched,
843 !numeric, timeout, &append_port, ppc);
848 * Update the last-received and bandwidth quota values
851 * @param session session to update
852 * @param force set to GNUNET_YES if we should update even
853 * though the minimum refresh time has not yet expired
856 update_quota (struct Session *session, int force)
858 struct GNUNET_TIME_Absolute now;
859 unsigned long long delta;
860 unsigned long long total_allowed;
861 unsigned long long total_remaining;
863 now = GNUNET_TIME_absolute_get ();
864 delta = now.value - session->last_quota_update.value;
865 if ((delta < MIN_QUOTA_REFRESH_TIME) && (!force))
866 return; /* too early, not enough data */
868 total_allowed = session->quota_in * delta;
869 if (total_allowed > session->last_received)
871 /* got less than acceptable */
872 total_remaining = total_allowed - session->last_received;
873 session->last_received = 0;
874 delta = total_remaining / session->quota_in; /* bonus seconds */
875 if (delta > MAX_BANDWIDTH_CARRY)
876 delta = MAX_BANDWIDTH_CARRY; /* limit amount of carry-over */
880 /* got more than acceptable */
881 session->last_received -= total_allowed;
884 session->last_quota_update.value = now.value - delta;
889 * Set a quota for receiving data from the given peer; this is a
890 * per-transport limit. The transport should limit its read/select
891 * calls to stay below the quota (in terms of incoming data).
894 * @param target the peer for whom the quota is given
895 * @param quota_in quota for receiving/sending data in bytes per ms
898 tcp_plugin_set_receive_quota (void *cls,
899 const struct GNUNET_PeerIdentity *target,
902 struct Plugin *plugin = cls;
903 struct Session *session;
905 session = find_session_by_target (plugin, target);
908 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
910 "Could not find session for peer `%4s' to update quota.\n",
911 GNUNET_i2s (target));
912 return; /* peer must have disconnected, ignore */
914 if (session->quota_in != quota_in)
916 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
918 "Changing quota for peer `%4s' from %u to %u\n",
922 update_quota (session, GNUNET_YES);
923 if (session->quota_in > quota_in)
924 session->last_quota_update = GNUNET_TIME_absolute_get ();
925 session->quota_in = quota_in;
931 * Check if the given port is plausible (must be either
932 * our listen port or our advertised port). If it is
933 * neither, we return one of these two ports at random.
935 * @return either in_port or a more plausible port
938 check_port (struct Plugin *plugin, uint16_t in_port)
940 if ((in_port == plugin->adv_port) || (in_port == plugin->open_port))
942 return (GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
944 ? plugin->open_port : plugin->adv_port;
949 * Another peer has suggested an address for this peer and transport
950 * plugin. Check that this could be a valid address.
953 * @param addr pointer to the address
954 * @param addrlen length of addr
955 * @return GNUNET_OK if this is a plausible address for this peer
959 tcp_plugin_check_address (void *cls, void *addr, size_t addrlen)
961 struct Plugin *plugin = cls;
962 char buf[sizeof (struct sockaddr_in6)];
963 struct sockaddr_in *v4;
964 struct sockaddr_in6 *v6;
966 if ((addrlen != sizeof (struct sockaddr_in)) &&
967 (addrlen != sizeof (struct sockaddr_in6)))
970 return GNUNET_SYSERR;
972 memcpy (buf, addr, sizeof (struct sockaddr_in6));
973 if (addrlen == sizeof (struct sockaddr_in))
975 v4 = (struct sockaddr_in *) buf;
976 v4->sin_port = htons (check_port (plugin, ntohs (v4->sin_port)));
980 v6 = (struct sockaddr_in6 *) buf;
981 v6->sin6_port = htons (check_port (plugin, ntohs (v6->sin6_port)));
984 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
986 "Informing transport service about my address `%s'.\n",
987 GNUNET_a2s (addr, addrlen));
994 * We've received a welcome from this peer via TCP. Possibly create a
995 * fresh client record and send back our welcome.
998 * @param client identification of the client
999 * @param message the actual message
1002 handle_tcp_welcome (void *cls,
1003 struct GNUNET_SERVER_Client *client,
1004 const struct GNUNET_MessageHeader *message)
1006 struct Plugin *plugin = cls;
1007 const struct WelcomeMessage *wm = (const struct WelcomeMessage *) message;
1008 struct Session *session;
1013 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1015 "Received %s message from a `%4s/%p'.\n",
1017 GNUNET_i2s (&wm->clientIdentity), client);
1019 session = find_session_by_client (plugin, client);
1020 if (session == NULL)
1022 GNUNET_SERVER_client_keep (client);
1023 session = create_session (plugin,
1024 &wm->clientIdentity, client);
1026 GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
1029 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1031 "Found address `%s' for incoming connection %p\n",
1032 GNUNET_a2s (vaddr, alen),
1035 session->connect_addr = vaddr;
1036 session->connect_alen = alen;
1041 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1043 "Did not obtain TCP socket address for incoming connection\n");
1047 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1049 "Creating new session %p for connection %p\n",
1052 process_pending_messages (session);
1054 if (session->expecting_welcome != GNUNET_YES)
1056 GNUNET_break_op (0);
1057 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1060 session->expecting_welcome = GNUNET_NO;
1061 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1066 * Calculate how long we should delay reading from the TCP socket to
1067 * ensure that we stay within our bandwidth limits (push back).
1069 * @param session for which client should this be calculated
1071 static struct GNUNET_TIME_Relative
1072 calculate_throttle_delay (struct Session *session)
1074 struct GNUNET_TIME_Relative ret;
1075 struct GNUNET_TIME_Absolute now;
1080 now = GNUNET_TIME_absolute_get ();
1081 del = now.value - session->last_quota_update.value;
1082 if (del > MAX_BANDWIDTH_CARRY)
1084 update_quota (session, GNUNET_YES);
1085 del = now.value - session->last_quota_update.value;
1086 GNUNET_assert (del <= MAX_BANDWIDTH_CARRY);
1088 if (session->quota_in == 0)
1089 session->quota_in = 1; /* avoid divison by zero */
1090 avail = del * session->quota_in;
1091 if (avail > session->last_received)
1092 return GNUNET_TIME_UNIT_ZERO; /* can receive right now */
1093 excess = session->last_received - avail;
1094 ret.value = excess / session->quota_in;
1095 GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING,
1097 "Throttling read (%llu bytes excess at %llu b/ms), waiting %llums before reading more.\n",
1098 (unsigned long long) excess,
1099 (unsigned long long) session->quota_in,
1100 (unsigned long long) ret.value);
1106 * Task to signal the server that we can continue
1107 * receiving from the TCP client now.
1110 delayed_done (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1112 struct Session *session = cls;
1113 GNUNET_SERVER_receive_done (session->client, GNUNET_OK);
1118 * We've received data for this peer via TCP. Unbox,
1119 * compute latency and forward.
1121 * @param cls closure
1122 * @param client identification of the client
1123 * @param message the actual message
1126 handle_tcp_data (void *cls,
1127 struct GNUNET_SERVER_Client *client,
1128 const struct GNUNET_MessageHeader *message)
1130 struct Plugin *plugin = cls;
1131 struct Session *session;
1133 struct GNUNET_TIME_Relative delay;
1135 msize = ntohs (message->size);
1136 session = find_session_by_client (plugin, client);
1138 if (GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME == ntohs(message->type))
1140 /* We don't want to propagate WELCOME messages up! */
1141 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1144 if ( (NULL == session) || (GNUNET_NO != session->expecting_welcome))
1146 GNUNET_break_op (0);
1147 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1151 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1153 "Passing %u bytes of type %u from `%4s' to transport service.\n",
1154 (unsigned int) msize,
1155 (unsigned int) ntohs (message->type),
1156 GNUNET_i2s (&session->target));
1158 plugin->env->receive (plugin->env->cls, &session->target, message, 1,
1159 session->connect_addr,
1160 session->connect_alen);
1161 /* update bandwidth used */
1162 session->last_received += msize;
1163 update_quota (session, GNUNET_NO);
1164 delay = calculate_throttle_delay (session);
1165 if (delay.value == 0)
1166 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1168 GNUNET_SCHEDULER_add_delayed (session->plugin->env->sched,
1169 delay, &delayed_done, session);
1174 * Handlers for the various TCP messages.
1176 static struct GNUNET_SERVER_MessageHandler my_handlers[] = {
1177 {&handle_tcp_welcome, NULL, GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME,
1178 sizeof (struct WelcomeMessage)},
1179 {&handle_tcp_data, NULL, GNUNET_MESSAGE_TYPE_ALL, 0},
1185 * Functions with this signature are called whenever a peer
1186 * is disconnected on the network level.
1188 * @param cls closure
1189 * @param client identification of the client
1192 disconnect_notify (void *cls, struct GNUNET_SERVER_Client *client)
1194 struct Plugin *plugin = cls;
1195 struct Session *session;
1199 session = find_session_by_client (plugin, client);
1200 if (session == NULL)
1201 return; /* unknown, nothing to do */
1203 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1205 "Destroying session of `%4s' with %s (%p) due to network-level disconnect.\n",
1206 GNUNET_i2s (&session->target),
1207 (session->connect_addr != NULL) ?
1208 GNUNET_a2s (session->connect_addr,
1209 session->connect_alen) : "*", client);
1211 disconnect_session (session);
1216 * Add the IP of our network interface to the list of
1217 * our external IP addresses.
1220 process_interfaces (void *cls,
1223 const struct sockaddr *addr, socklen_t addrlen)
1225 struct Plugin *plugin = cls;
1227 struct sockaddr_in *v4;
1228 struct sockaddr_in6 *v6;
1230 af = addr->sa_family;
1233 v4 = (struct sockaddr_in *) addr;
1234 v4->sin_port = htons (plugin->adv_port);
1238 GNUNET_assert (af == AF_INET6);
1239 v6 = (struct sockaddr_in6 *) addr;
1240 v6->sin6_port = htons (plugin->adv_port);
1242 GNUNET_log_from (GNUNET_ERROR_TYPE_INFO |
1243 GNUNET_ERROR_TYPE_BULK,
1244 "tcp", _("Found address `%s' (%s)\n"),
1245 GNUNET_a2s (addr, addrlen), name);
1246 plugin->env->notify_address (plugin->env->cls,
1248 addr, addrlen, GNUNET_TIME_UNIT_FOREVER_REL);
1254 * Function called by the resolver for each address obtained from DNS
1255 * for our own hostname. Add the addresses to the list of our
1256 * external IP addresses.
1258 * @param cls closure
1259 * @param addr one of the addresses of the host, NULL for the last address
1260 * @param addrlen length of the address
1263 process_hostname_ips (void *cls,
1264 const struct sockaddr *addr, socklen_t addrlen)
1266 struct Plugin *plugin = cls;
1270 plugin->hostname_dns = NULL;
1273 process_interfaces (plugin, "<hostname>", GNUNET_YES, addr, addrlen);
1278 * Entry point for the plugin.
1281 libgnunet_plugin_transport_tcp_init (void *cls)
1283 struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
1284 struct GNUNET_TRANSPORT_PluginFunctions *api;
1285 struct Plugin *plugin;
1286 struct GNUNET_SERVICE_Context *service;
1287 unsigned long long aport;
1288 unsigned long long bport;
1291 service = GNUNET_SERVICE_start ("transport-tcp", env->sched, env->cfg);
1292 if (service == NULL)
1294 GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING,
1297 ("Failed to start service for `%s' transport plugin.\n"),
1303 GNUNET_CONFIGURATION_get_value_number (env->cfg,
1309 GNUNET_CONFIGURATION_get_value_number (env->cfg,
1312 &aport)) && (aport > 65535)))
1314 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
1317 ("Require valid port number for service `%s' in configuration!\n"),
1319 GNUNET_SERVICE_stop (service);
1324 plugin = GNUNET_malloc (sizeof (struct Plugin));
1325 plugin->open_port = bport;
1326 plugin->adv_port = aport;
1328 plugin->lsock = NULL;
1329 plugin->statistics = NULL;
1330 api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
1332 api->send = &tcp_plugin_send;
1333 api->disconnect = &tcp_plugin_disconnect;
1334 api->address_pretty_printer = &tcp_plugin_address_pretty_printer;
1335 api->set_receive_quota = &tcp_plugin_set_receive_quota;
1336 api->check_address = &tcp_plugin_check_address;
1337 plugin->service = service;
1338 plugin->server = GNUNET_SERVICE_get_server (service);
1339 plugin->handlers = GNUNET_malloc (sizeof (my_handlers));
1340 memcpy (plugin->handlers, my_handlers, sizeof (my_handlers));
1343 sizeof (my_handlers) / sizeof (struct GNUNET_SERVER_MessageHandler);
1345 plugin->handlers[i].callback_cls = plugin;
1346 GNUNET_SERVER_add_handlers (plugin->server, plugin->handlers);
1348 GNUNET_log_from (GNUNET_ERROR_TYPE_INFO,
1349 "tcp", _("TCP transport listening on port %llu\n"), bport);
1351 GNUNET_log_from (GNUNET_ERROR_TYPE_INFO,
1354 ("TCP transport advertises itself as being on port %llu\n"),
1356 GNUNET_SERVER_disconnect_notify (plugin->server, &disconnect_notify,
1358 /* FIXME: do the two calls below periodically again and
1359 not just once (since the info we get might change...) */
1360 GNUNET_OS_network_interfaces_list (&process_interfaces, plugin);
1361 plugin->hostname_dns = GNUNET_RESOLVER_hostname_resolve (env->sched,
1364 HOSTNAME_RESOLVE_TIMEOUT,
1365 &process_hostname_ips,
1372 * Exit point from the plugin.
1375 libgnunet_plugin_transport_tcp_done (void *cls)
1377 struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
1378 struct Plugin *plugin = api->cls;
1379 struct Session *session;
1381 while (NULL != (session = plugin->sessions))
1382 disconnect_session (session);
1383 if (NULL != plugin->hostname_dns)
1385 GNUNET_RESOLVER_request_cancel (plugin->hostname_dns);
1386 plugin->hostname_dns = NULL;
1388 GNUNET_SERVICE_stop (plugin->service);
1389 GNUNET_free (plugin->handlers);
1390 GNUNET_free (plugin);
1395 /* end of plugin_transport_tcp.c */