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 // FIXME: This is simply wrong...
337 ret->quota_in = plugin->env->default_quota_in;
338 ret->expecting_welcome = GNUNET_YES;
339 pm = GNUNET_malloc (sizeof (struct PendingMessage) + sizeof (struct WelcomeMessage));
340 pm->msg = (const char*) &pm[1];
341 pm->message_size = sizeof (struct WelcomeMessage);
342 welcome.header.size = htons (sizeof (struct WelcomeMessage));
343 welcome.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME);
344 welcome.clientIdentity = *plugin->env->my_identity;
345 memcpy (&pm[1], &welcome, sizeof (welcome));
346 pm->timeout = GNUNET_TIME_UNIT_FOREVER_ABS;
347 GNUNET_CONTAINER_DLL_insert (ret->pending_messages_head,
348 ret->pending_messages_tail,
355 * If we have pending messages, ask the server to
356 * transmit them (schedule the respective tasks, etc.)
358 * @param session for which session should we do this
360 static void process_pending_messages (struct Session *session);
364 * Function called to notify a client about the socket
365 * being ready to queue more data. "buf" will be
366 * NULL and "size" zero if the socket was closed for
367 * writing in the meantime.
370 * @param size number of bytes available in buf
371 * @param buf where the callee should write the message
372 * @return number of bytes written to buf
375 do_transmit (void *cls, size_t size, void *buf)
377 struct Session *session = cls;
378 struct PendingMessage *pm;
383 session->transmit_handle = NULL;
387 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
389 "Timeout trying to transmit to peer `%4s', discarding message queue.\n",
390 GNUNET_i2s (&session->target));
393 while (NULL != (pm = session->pending_messages_head))
395 GNUNET_CONTAINER_DLL_remove (session->pending_messages_head,
396 session->pending_messages_tail,
399 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
401 "Failed to transmit %u byte message to `%4s'.\n",
403 GNUNET_i2s (&session->target));
405 if (pm->transmit_cont != NULL)
406 pm->transmit_cont (pm->transmit_cont_cls,
407 &session->target, GNUNET_SYSERR);
414 while (NULL != (pm = session->pending_messages_head))
416 if (size < pm->message_size)
418 memcpy (cbuf, pm->msg, pm->message_size);
419 cbuf += pm->message_size;
420 ret += pm->message_size;
421 size -= pm->message_size;
422 GNUNET_CONTAINER_DLL_remove (session->pending_messages_head,
423 session->pending_messages_tail,
425 if (pm->transmit_cont != NULL)
426 pm->transmit_cont (pm->transmit_cont_cls,
427 &session->target, GNUNET_OK);
430 if (session->client != NULL)
431 process_pending_messages (session);
433 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
434 "tcp", "Transmitting %u bytes\n", ret);
441 * If we have pending messages, ask the server to
442 * transmit them (schedule the respective tasks, etc.)
444 * @param session for which session should we do this
447 process_pending_messages (struct Session *session)
449 struct PendingMessage *pm;
450 GNUNET_assert (session->client != NULL);
451 if (session->transmit_handle != NULL)
453 if (NULL == (pm = session->pending_messages_head))
455 session->transmit_handle
456 = GNUNET_SERVER_notify_transmit_ready (session->client,
458 GNUNET_TIME_absolute_get_remaining
460 &do_transmit, session);
465 * Functions with this signature are called whenever we need
466 * to close a session due to a disconnect or failure to
467 * establish a connection.
469 * @param session session to close down
472 disconnect_session (struct Session *session)
474 struct Session *prev;
476 struct PendingMessage *pm;
479 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
481 "Disconnecting from `%4s' at %s (session %p).\n",
482 GNUNET_i2s (&session->target),
483 (session->connect_addr != NULL) ?
484 GNUNET_a2s (session->connect_addr,
485 session->connect_alen) : "*", session);
487 /* remove from session list */
489 pos = session->plugin->sessions;
490 while (pos != session)
496 session->plugin->sessions = session->next;
498 prev->next = session->next;
500 if (session->transmit_handle != NULL)
502 GNUNET_CONNECTION_notify_transmit_ready_cancel
503 (session->transmit_handle);
504 session->transmit_handle = NULL;
506 while (NULL != (pm = session->pending_messages_head))
509 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
511 pm->transmit_cont != NULL
512 ? "Could not deliver message to `%4s'.\n"
514 "Could not deliver message to `%4s', notifying.\n",
515 GNUNET_i2s (&session->target));
517 GNUNET_CONTAINER_DLL_remove (session->pending_messages_head,
518 session->pending_messages_tail,
520 if (NULL != pm->transmit_cont)
521 pm->transmit_cont (pm->transmit_cont_cls,
522 &session->target, GNUNET_SYSERR);
525 if (GNUNET_NO == session->expecting_welcome)
528 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
530 "Notifying transport service about loss of connection with `%4s'.\n",
531 GNUNET_i2s (&session->target));
533 /* Data session that actually went past the initial handshake;
534 transport service may know about this one, so we need to
535 notify transport service about disconnect */
536 // FIXME: we should have a very clear connect-disconnect
537 // protocol with gnunet-service-transport!
538 session->plugin->env->receive (session->plugin->env->cls,
539 &session->target, NULL,
541 session->connect_addr,
542 session->connect_alen);
544 if (session->client != NULL)
546 GNUNET_SERVER_client_drop (session->client);
547 session->client = NULL;
549 GNUNET_free_non_null (session->connect_addr);
550 GNUNET_free (session);
555 * Function that can be used by the transport service to transmit
556 * a message using the plugin. Note that in the case of a
557 * peer disconnecting, the continuation MUST be called
558 * prior to the disconnect notification itself. This function
559 * will be called with this peer's HELLO message to initiate
560 * a fresh connection to another peer.
563 * @param target who should receive this message
564 * @param msg the message to transmit
565 * @param msgbuf_size number of bytes in 'msg'
566 * @param priority how important is the message (most plugins will
567 * ignore message priority and just FIFO)
568 * @param timeout how long to wait at most for the transmission (does not
569 * require plugins to discard the message after the timeout,
570 * just advisory for the desired delay; most plugins will ignore
572 * @param addr the address to use (can be NULL if the plugin
573 * is "on its own" (i.e. re-use existing TCP connection))
574 * @param addrlen length of the address in bytes
575 * @param force_address GNUNET_YES if the plugin MUST use the given address,
576 * otherwise the plugin may use other addresses or
577 * existing connections (if available)
578 * @param cont continuation to call once the message has
579 * been transmitted (or if the transport is ready
580 * for the next transmission call; or if the
581 * peer disconnected...); can be NULL
582 * @param cont_cls closure for cont
583 * @return number of bytes used (on the physical network, with overheads);
584 * -1 on hard errors (i.e. address invalid); 0 is a legal value
585 * and does NOT mean that the message was not transmitted (DV)
588 tcp_plugin_send (void *cls,
589 const struct GNUNET_PeerIdentity *target,
593 struct GNUNET_TIME_Relative timeout,
597 GNUNET_TRANSPORT_TransmitContinuation cont, void *cont_cls)
599 struct Plugin *plugin = cls;
600 struct Session *session;
601 struct PendingMessage *pm;
602 struct GNUNET_CONNECTION_Handle *sa;
605 session = plugin->sessions;
606 /* FIXME: we could do this a cheaper with a hash table
607 where we could restrict the iteration to entries that match
608 the target peer... */
609 while ( (session != NULL) &&
610 ( (0 != memcmp (target,
612 sizeof (struct GNUNET_PeerIdentity))) ||
613 ( (GNUNET_YES == force_address) &&
615 ( (addrlen != session->connect_alen) ||
616 (0 != memcmp (session->connect_addr,
619 session = session->next;
620 if ( (session == NULL) &&
624 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
626 "Asked to transmit to `%4s' without address and I have no existing connection (failing).\n",
627 GNUNET_i2s (target));
633 if (sizeof (struct sockaddr_in) == addrlen)
635 else if (sizeof (struct sockaddr_in6) == addrlen)
642 sa = GNUNET_CONNECTION_create_from_sockaddr (plugin->env->sched,
644 GNUNET_SERVER_MAX_MESSAGE_SIZE);
648 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
650 "Failed to create connection to `%4s' at `%s'\n",
652 GNUNET_a2s (addr, addrlen));
658 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
660 "Asked to transmit to `%4s', creating fresh session using address `%s'.\n",
662 GNUNET_a2s (addr, addrlen));
664 session = create_session (plugin,
666 GNUNET_SERVER_connect_socket (plugin->server,
668 session->connect_addr = GNUNET_malloc (addrlen);
669 memcpy (session->connect_addr,
672 session->connect_alen = addrlen;
674 GNUNET_assert (session != NULL);
675 GNUNET_assert (session->client != NULL);
677 /* create new message entry */
678 pm = GNUNET_malloc (sizeof (struct PendingMessage) + msgbuf_size);
679 pm->msg = (const char*) &pm[1];
680 memcpy (&pm[1], msg, msgbuf_size);
681 pm->message_size = msgbuf_size;
682 pm->timeout = GNUNET_TIME_relative_to_absolute (timeout);
683 pm->transmit_cont = cont;
684 pm->transmit_cont_cls = cont_cls;
686 /* append pm to pending_messages list */
687 GNUNET_CONTAINER_DLL_insert_after (session->pending_messages_head,
688 session->pending_messages_tail,
689 session->pending_messages_tail,
692 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
694 "Asked to transmit %u bytes to `%s', added message to list.\n",
696 GNUNET_i2s (target));
698 process_pending_messages (session);
704 * Function that can be called to force a disconnect from the
705 * specified neighbour. This should also cancel all previously
706 * scheduled transmissions. Obviously the transmission may have been
707 * partially completed already, which is OK. The plugin is supposed
708 * to close the connection (if applicable) and no longer call the
709 * transmit continuation(s).
711 * Finally, plugin MUST NOT call the services's receive function to
712 * notify the service that the connection to the specified target was
713 * closed after a getting this call.
716 * @param target peer for which the last transmission is
720 tcp_plugin_disconnect (void *cls, const struct GNUNET_PeerIdentity *target)
722 struct Plugin *plugin = cls;
723 struct Session *session;
724 struct PendingMessage *pm;
727 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
729 "Asked to cancel session with `%4s'\n",
730 GNUNET_i2s (target));
732 session = plugin->sessions;
733 while (NULL != session)
735 if (0 == memcmp (target,
737 sizeof (struct GNUNET_PeerIdentity)))
739 pm = session->pending_messages_head;
742 pm->transmit_cont = NULL;
743 pm->transmit_cont_cls = NULL;
746 if (session->client != NULL)
748 GNUNET_SERVER_client_drop (session->client);
749 session->client = NULL;
751 /* rest of the clean-up of the session will be done as part of
752 disconnect_notify which should be triggered any time now
753 (or which may be triggering this call in the first place) */
755 session = session->next;
760 struct PrettyPrinterContext
762 GNUNET_TRANSPORT_AddressStringCallback asc;
769 * Append our port and forward the result.
772 append_port (void *cls, const char *hostname)
774 struct PrettyPrinterContext *ppc = cls;
777 if (hostname == NULL)
779 ppc->asc (ppc->asc_cls, NULL);
783 GNUNET_asprintf (&ret, "%s:%d", hostname, ppc->port);
784 ppc->asc (ppc->asc_cls, ret);
790 * Convert the transports address to a nice, human-readable
794 * @param type name of the transport that generated the address
795 * @param addr one of the addresses of the host, NULL for the last address
796 * the specific address format depends on the transport
797 * @param addrlen length of the address
798 * @param numeric should (IP) addresses be displayed in numeric form?
799 * @param timeout after how long should we give up?
800 * @param asc function to call on each string
801 * @param asc_cls closure for asc
804 tcp_plugin_address_pretty_printer (void *cls,
809 struct GNUNET_TIME_Relative timeout,
810 GNUNET_TRANSPORT_AddressStringCallback asc,
813 struct Plugin *plugin = cls;
814 const struct sockaddr_in *v4;
815 const struct sockaddr_in6 *v6;
816 struct PrettyPrinterContext *ppc;
818 if ((addrlen != sizeof (struct sockaddr_in)) &&
819 (addrlen != sizeof (struct sockaddr_in6)))
821 /* invalid address */
826 ppc = GNUNET_malloc (sizeof (struct PrettyPrinterContext));
828 ppc->asc_cls = asc_cls;
829 if (addrlen == sizeof (struct sockaddr_in))
831 v4 = (const struct sockaddr_in *) addr;
832 ppc->port = ntohs (v4->sin_port);
836 v6 = (const struct sockaddr_in6 *) addr;
837 ppc->port = ntohs (v6->sin6_port);
840 GNUNET_RESOLVER_hostname_get (plugin->env->sched,
844 !numeric, timeout, &append_port, ppc);
849 * Update the last-received and bandwidth quota values
852 * @param session session to update
853 * @param force set to GNUNET_YES if we should update even
854 * though the minimum refresh time has not yet expired
857 update_quota (struct Session *session, int force)
859 struct GNUNET_TIME_Absolute now;
860 unsigned long long delta;
861 unsigned long long total_allowed;
862 unsigned long long total_remaining;
864 now = GNUNET_TIME_absolute_get ();
865 delta = now.value - session->last_quota_update.value;
866 if ((delta < MIN_QUOTA_REFRESH_TIME) && (!force))
867 return; /* too early, not enough data */
869 total_allowed = session->quota_in * delta;
870 if (total_allowed > session->last_received)
872 /* got less than acceptable */
873 total_remaining = total_allowed - session->last_received;
874 session->last_received = 0;
875 delta = total_remaining / session->quota_in; /* bonus seconds */
876 if (delta > MAX_BANDWIDTH_CARRY)
877 delta = MAX_BANDWIDTH_CARRY; /* limit amount of carry-over */
881 /* got more than acceptable */
882 session->last_received -= total_allowed;
885 session->last_quota_update.value = now.value - delta;
890 * Set a quota for receiving data from the given peer; this is a
891 * per-transport limit. The transport should limit its read/select
892 * calls to stay below the quota (in terms of incoming data).
895 * @param target the peer for whom the quota is given
896 * @param quota_in quota for receiving/sending data in bytes per ms
899 tcp_plugin_set_receive_quota (void *cls,
900 const struct GNUNET_PeerIdentity *target,
903 struct Plugin *plugin = cls;
904 struct Session *session;
906 // FIXME: This is simply wrong:
907 // We may have multiple sessions for the target,
908 // and some OTHER session might be the one to
909 // survive; not to mention the inbound-quota should
910 // be enforced across transports!
911 // => keep quota-related states in the service (globally, per peer)
912 // and update/query the information when it is needed!
913 // => we can likely get rid of this entire function and
914 // replace it with a query/update API!
915 session = find_session_by_target (plugin, target);
918 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
920 "Could not find session for peer `%4s' to update quota.\n",
921 GNUNET_i2s (target));
922 return; /* peer must have disconnected, ignore */
924 if (session->quota_in != quota_in)
926 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
928 "Changing quota for peer `%4s' from %u to %u\n",
932 update_quota (session, GNUNET_YES);
933 if (session->quota_in > quota_in)
934 session->last_quota_update = GNUNET_TIME_absolute_get ();
935 session->quota_in = quota_in;
941 * Check if the given port is plausible (must be either
942 * our listen port or our advertised port). If it is
943 * neither, we return one of these two ports at random.
945 * @return either in_port or a more plausible port
948 check_port (struct Plugin *plugin, uint16_t in_port)
950 if ((in_port == plugin->adv_port) || (in_port == plugin->open_port))
952 return (GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
954 ? plugin->open_port : plugin->adv_port;
959 * Another peer has suggested an address for this peer and transport
960 * plugin. Check that this could be a valid address.
963 * @param addr pointer to the address
964 * @param addrlen length of addr
965 * @return GNUNET_OK if this is a plausible address for this peer
969 tcp_plugin_check_address (void *cls, void *addr, size_t addrlen)
971 struct Plugin *plugin = cls;
972 char buf[sizeof (struct sockaddr_in6)];
973 struct sockaddr_in *v4;
974 struct sockaddr_in6 *v6;
976 if ((addrlen != sizeof (struct sockaddr_in)) &&
977 (addrlen != sizeof (struct sockaddr_in6)))
980 return GNUNET_SYSERR;
982 memcpy (buf, addr, sizeof (struct sockaddr_in6));
983 if (addrlen == sizeof (struct sockaddr_in))
985 v4 = (struct sockaddr_in *) buf;
986 v4->sin_port = htons (check_port (plugin, ntohs (v4->sin_port)));
990 v6 = (struct sockaddr_in6 *) buf;
991 v6->sin6_port = htons (check_port (plugin, ntohs (v6->sin6_port)));
994 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
996 "Informing transport service about my address `%s'.\n",
997 GNUNET_a2s (addr, addrlen));
1004 * We've received a welcome from this peer via TCP. Possibly create a
1005 * fresh client record and send back our welcome.
1007 * @param cls closure
1008 * @param client identification of the client
1009 * @param message the actual message
1012 handle_tcp_welcome (void *cls,
1013 struct GNUNET_SERVER_Client *client,
1014 const struct GNUNET_MessageHeader *message)
1016 struct Plugin *plugin = cls;
1017 const struct WelcomeMessage *wm = (const struct WelcomeMessage *) message;
1018 struct Session *session;
1023 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1025 "Received %s message from a `%4s/%p'.\n",
1027 GNUNET_i2s (&wm->clientIdentity), client);
1029 session = find_session_by_client (plugin, client);
1030 if (session == NULL)
1032 GNUNET_SERVER_client_keep (client);
1033 session = create_session (plugin,
1034 &wm->clientIdentity, client);
1036 GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
1039 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1041 "Found address `%s' for incoming connection %p\n",
1042 GNUNET_a2s (vaddr, alen),
1045 session->connect_addr = vaddr;
1046 session->connect_alen = alen;
1051 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1053 "Did not obtain TCP socket address for incoming connection\n");
1057 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1059 "Creating new session %p for connection %p\n",
1062 process_pending_messages (session);
1064 if (session->expecting_welcome != GNUNET_YES)
1066 GNUNET_break_op (0);
1067 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1070 session->expecting_welcome = GNUNET_NO;
1071 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1076 * Calculate how long we should delay reading from the TCP socket to
1077 * ensure that we stay within our bandwidth limits (push back).
1079 * @param session for which client should this be calculated
1081 static struct GNUNET_TIME_Relative
1082 calculate_throttle_delay (struct Session *session)
1084 struct GNUNET_TIME_Relative ret;
1085 struct GNUNET_TIME_Absolute now;
1090 now = GNUNET_TIME_absolute_get ();
1091 del = now.value - session->last_quota_update.value;
1092 if (del > MAX_BANDWIDTH_CARRY)
1094 update_quota (session, GNUNET_YES);
1095 del = now.value - session->last_quota_update.value;
1096 GNUNET_assert (del <= MAX_BANDWIDTH_CARRY);
1098 if (session->quota_in == 0)
1099 session->quota_in = 1; /* avoid divison by zero */
1100 avail = del * session->quota_in;
1101 if (avail > session->last_received)
1102 return GNUNET_TIME_UNIT_ZERO; /* can receive right now */
1103 excess = session->last_received - avail;
1104 ret.value = excess / session->quota_in;
1105 GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING,
1107 "Throttling read (%llu bytes excess at %llu b/ms), waiting %llums before reading more.\n",
1108 (unsigned long long) excess,
1109 (unsigned long long) session->quota_in,
1110 (unsigned long long) ret.value);
1116 * Task to signal the server that we can continue
1117 * receiving from the TCP client now.
1120 delayed_done (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1122 struct Session *session = cls;
1123 GNUNET_SERVER_receive_done (session->client, GNUNET_OK);
1128 * We've received data for this peer via TCP. Unbox,
1129 * compute latency and forward.
1131 * @param cls closure
1132 * @param client identification of the client
1133 * @param message the actual message
1136 handle_tcp_data (void *cls,
1137 struct GNUNET_SERVER_Client *client,
1138 const struct GNUNET_MessageHeader *message)
1140 struct Plugin *plugin = cls;
1141 struct Session *session;
1143 struct GNUNET_TIME_Relative delay;
1145 msize = ntohs (message->size);
1146 session = find_session_by_client (plugin, client);
1148 if (GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME == ntohs(message->type))
1150 /* We don't want to propagate WELCOME messages up! */
1151 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1154 if ( (NULL == session) || (GNUNET_NO != session->expecting_welcome))
1156 GNUNET_break_op (0);
1157 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1161 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1163 "Passing %u bytes of type %u from `%4s' to transport service.\n",
1164 (unsigned int) msize,
1165 (unsigned int) ntohs (message->type),
1166 GNUNET_i2s (&session->target));
1168 plugin->env->receive (plugin->env->cls, &session->target, message, 1,
1169 session->connect_addr,
1170 session->connect_alen);
1171 /* update bandwidth used */
1172 session->last_received += msize;
1173 update_quota (session, GNUNET_NO);
1174 delay = calculate_throttle_delay (session);
1175 if (delay.value == 0)
1176 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1178 GNUNET_SCHEDULER_add_delayed (session->plugin->env->sched,
1179 delay, &delayed_done, session);
1184 * Handlers for the various TCP messages.
1186 static struct GNUNET_SERVER_MessageHandler my_handlers[] = {
1187 {&handle_tcp_welcome, NULL, GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME,
1188 sizeof (struct WelcomeMessage)},
1189 {&handle_tcp_data, NULL, GNUNET_MESSAGE_TYPE_ALL, 0},
1195 * Functions with this signature are called whenever a peer
1196 * is disconnected on the network level.
1198 * @param cls closure
1199 * @param client identification of the client
1202 disconnect_notify (void *cls, struct GNUNET_SERVER_Client *client)
1204 struct Plugin *plugin = cls;
1205 struct Session *session;
1209 session = find_session_by_client (plugin, client);
1210 if (session == NULL)
1211 return; /* unknown, nothing to do */
1213 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1215 "Destroying session of `%4s' with %s (%p) due to network-level disconnect.\n",
1216 GNUNET_i2s (&session->target),
1217 (session->connect_addr != NULL) ?
1218 GNUNET_a2s (session->connect_addr,
1219 session->connect_alen) : "*", client);
1221 disconnect_session (session);
1226 * Add the IP of our network interface to the list of
1227 * our external IP addresses.
1230 process_interfaces (void *cls,
1233 const struct sockaddr *addr, socklen_t addrlen)
1235 struct Plugin *plugin = cls;
1237 struct sockaddr_in *v4;
1238 struct sockaddr_in6 *v6;
1240 af = addr->sa_family;
1243 v4 = (struct sockaddr_in *) addr;
1244 v4->sin_port = htons (plugin->adv_port);
1248 GNUNET_assert (af == AF_INET6);
1249 v6 = (struct sockaddr_in6 *) addr;
1250 v6->sin6_port = htons (plugin->adv_port);
1252 GNUNET_log_from (GNUNET_ERROR_TYPE_INFO |
1253 GNUNET_ERROR_TYPE_BULK,
1254 "tcp", _("Found address `%s' (%s)\n"),
1255 GNUNET_a2s (addr, addrlen), name);
1256 plugin->env->notify_address (plugin->env->cls,
1258 addr, addrlen, GNUNET_TIME_UNIT_FOREVER_REL);
1264 * Function called by the resolver for each address obtained from DNS
1265 * for our own hostname. Add the addresses to the list of our
1266 * external IP addresses.
1268 * @param cls closure
1269 * @param addr one of the addresses of the host, NULL for the last address
1270 * @param addrlen length of the address
1273 process_hostname_ips (void *cls,
1274 const struct sockaddr *addr, socklen_t addrlen)
1276 struct Plugin *plugin = cls;
1280 plugin->hostname_dns = NULL;
1283 process_interfaces (plugin, "<hostname>", GNUNET_YES, addr, addrlen);
1288 * Entry point for the plugin.
1291 libgnunet_plugin_transport_tcp_init (void *cls)
1293 struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
1294 struct GNUNET_TRANSPORT_PluginFunctions *api;
1295 struct Plugin *plugin;
1296 struct GNUNET_SERVICE_Context *service;
1297 unsigned long long aport;
1298 unsigned long long bport;
1301 service = GNUNET_SERVICE_start ("transport-tcp", env->sched, env->cfg);
1302 if (service == NULL)
1304 GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING,
1307 ("Failed to start service for `%s' transport plugin.\n"),
1313 GNUNET_CONFIGURATION_get_value_number (env->cfg,
1319 GNUNET_CONFIGURATION_get_value_number (env->cfg,
1322 &aport)) && (aport > 65535)))
1324 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
1327 ("Require valid port number for service `%s' in configuration!\n"),
1329 GNUNET_SERVICE_stop (service);
1334 plugin = GNUNET_malloc (sizeof (struct Plugin));
1335 plugin->open_port = bport;
1336 plugin->adv_port = aport;
1338 plugin->lsock = NULL;
1339 plugin->statistics = NULL;
1340 api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
1342 api->send = &tcp_plugin_send;
1343 api->disconnect = &tcp_plugin_disconnect;
1344 api->address_pretty_printer = &tcp_plugin_address_pretty_printer;
1345 api->set_receive_quota = &tcp_plugin_set_receive_quota;
1346 api->check_address = &tcp_plugin_check_address;
1347 plugin->service = service;
1348 plugin->server = GNUNET_SERVICE_get_server (service);
1349 plugin->handlers = GNUNET_malloc (sizeof (my_handlers));
1350 memcpy (plugin->handlers, my_handlers, sizeof (my_handlers));
1353 sizeof (my_handlers) / sizeof (struct GNUNET_SERVER_MessageHandler);
1355 plugin->handlers[i].callback_cls = plugin;
1356 GNUNET_SERVER_add_handlers (plugin->server, plugin->handlers);
1358 GNUNET_log_from (GNUNET_ERROR_TYPE_INFO,
1359 "tcp", _("TCP transport listening on port %llu\n"), bport);
1361 GNUNET_log_from (GNUNET_ERROR_TYPE_INFO,
1364 ("TCP transport advertises itself as being on port %llu\n"),
1366 GNUNET_SERVER_disconnect_notify (plugin->server, &disconnect_notify,
1368 /* FIXME: do the two calls below periodically again and
1369 not just once (since the info we get might change...) */
1370 GNUNET_OS_network_interfaces_list (&process_interfaces, plugin);
1371 plugin->hostname_dns = GNUNET_RESOLVER_hostname_resolve (env->sched,
1374 HOSTNAME_RESOLVE_TIMEOUT,
1375 &process_hostname_ips,
1382 * Exit point from the plugin.
1385 libgnunet_plugin_transport_tcp_done (void *cls)
1387 struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
1388 struct Plugin *plugin = api->cls;
1389 struct Session *session;
1391 while (NULL != (session = plugin->sessions))
1392 disconnect_session (session);
1393 if (NULL != plugin->hostname_dns)
1395 GNUNET_RESOLVER_request_cancel (plugin->hostname_dns);
1396 plugin->hostname_dns = NULL;
1398 GNUNET_SERVICE_stop (plugin->service);
1399 GNUNET_free (plugin->handlers);
1400 GNUNET_free (plugin);
1405 /* end of plugin_transport_tcp.c */