2 This file is part of GNUnet.
3 (C) 2009, 2010, 2011 Christian Grothoff (and other contributing authors)
5 GNUnet is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published
7 by the Free Software Foundation; either version 3, or (at your
8 option) any later version.
10 GNUnet is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with GNUnet; see the file COPYING. If not, write to the
17 Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18 Boston, MA 02111-1307, USA.
22 * @file core/gnunet-service-core_sessions.c
23 * @brief code for managing of 'encrypted' sessions (key exchange done)
24 * @author Christian Grothoff
27 #include "gnunet-service-core.h"
28 #include "gnunet-service-core_neighbours.h"
29 #include "gnunet-service-core_kx.h"
30 #include "gnunet-service-core_typemap.h"
31 #include "gnunet-service-core_sessions.h"
32 #include "gnunet-service-core_clients.h"
33 #include "gnunet_constants.h"
37 * Message ready for encryption. This struct is followed by the
38 * actual content of the message.
40 struct SessionMessageEntry
44 * We keep messages in a doubly linked list.
46 struct SessionMessageEntry *next;
49 * We keep messages in a doubly linked list.
51 struct SessionMessageEntry *prev;
54 * Deadline for transmission, 1s after we received it (if we
55 * are not corking), otherwise "now". Note that this message
56 * does NOT expire past its deadline.
58 struct GNUNET_TIME_Absolute deadline;
61 * How long is the message? (number of bytes following the "struct
62 * MessageEntry", but not including the size of "struct
63 * MessageEntry" itself!)
71 * Data kept per session.
76 * Identity of the other peer.
78 struct GNUNET_PeerIdentity peer;
81 * Head of list of requests from clients for transmission to
84 struct GSC_ClientActiveRequest *active_client_request_head;
87 * Tail of list of requests from clients for transmission to
90 struct GSC_ClientActiveRequest *active_client_request_tail;
93 * Head of list of messages ready for encryption.
95 struct SessionMessageEntry *sme_head;
98 * Tail of list of messages ready for encryption.
100 struct SessionMessageEntry *sme_tail;
103 * Information about the key exchange with the other peer.
105 struct GSC_KeyExchangeInfo *kxinfo;
108 * Current type map for this peer.
110 struct GSC_TypeMap *tmap;
113 * At what time did we initially establish this session?
114 * (currently unused, should be integrated with ATS in the
117 struct GNUNET_TIME_Absolute time_established;
120 * Task to transmit corked messages with a delay.
122 GNUNET_SCHEDULER_TaskIdentifier cork_task;
125 * Tracking bandwidth for receiving from this peer.
126 * // FIXME: need to set it!
128 struct GNUNET_BANDWIDTH_Tracker available_recv_window;
131 * Available bandwidth out for this peer (current target). This
132 * value should be the 'MIN' of 'bw_out_internal_limit' and
133 * 'bw_out_external_limit'.
135 struct GNUNET_BANDWIDTH_Value32NBO bw_out;
138 * Internal bandwidth limit set for this peer (initially typically
139 * set to "MAX_INT"). Actual "bw_out" is MIN of
140 * "bpm_out_internal_limit" and "bw_out_external_limit".
144 * // FIXME: check usage
146 struct GNUNET_BANDWIDTH_Value32NBO bw_out_internal_limit;
149 * External bandwidth limit set for this peer by the
150 * peer that we are communicating with. "bw_out" is MIN of
151 * "bw_out_internal_limit" and "bw_out_external_limit".
152 * // FIXME: check usage
154 struct GNUNET_BANDWIDTH_Value32NBO bw_out_external_limit;
158 * Is the neighbour queue empty and thus ready for us
159 * to transmit an encrypted message?
161 int ready_to_transmit;
167 * Map of peer identities to 'struct Session'.
169 static struct GNUNET_CONTAINER_MultiHashMap *sessions;
173 * Find the session for the given peer.
175 * @param peer identity of the peer
176 * @return NULL if we are not connected, otherwise the
179 static struct Session *
180 find_session (const struct GNUNET_PeerIdentity *peer)
182 return GNUNET_CONTAINER_multihashmap_get (sessions, &peer->hashPubKey);
187 * End the session with the given peer (we are no longer
190 * @param pid identity of peer to kill session with
193 GSC_SESSIONS_end (const struct GNUNET_PeerIdentity *pid)
195 struct Session *session;
196 struct GSC_ClientActiveRequest *car;
198 session = find_session (pid);
202 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
203 "Destroying session for peer `%4s'\n",
204 GNUNET_i2s (&session->peer));
206 if (GNUNET_SCHEDULER_NO_TASK != session->cork_task)
208 GNUNET_SCHEDULER_cancel (session->cork_task);
209 session->cork_task = GNUNET_SCHEDULER_NO_TASK;
211 GNUNET_assert (GNUNET_YES ==
212 GNUNET_CONTAINER_multihashmap_remove (sessions,
213 &session->peer.hashPubKey, session));
214 while (NULL != (car = session->active_client_request_head))
216 GNUNET_CONTAINER_DLL_remove (session->active_client_request_head,
217 session->active_client_request_tail,
219 GSC_CLIENTS_reject_request (car);
221 GNUNET_STATISTICS_set (GSC_stats,
222 gettext_noop ("# established sessions"),
223 GNUNET_CONTAINER_multihashmap_size (sessions),
225 GNUNET_free (session);
230 * Create a session, a key exchange was just completed.
232 * @param peer peer that is now connected
233 * @param kx key exchange that completed
236 GSC_SESSIONS_create (const struct GNUNET_PeerIdentity *peer,
237 struct GSC_KeyExchangeInfo *kx)
239 struct GNUNET_MessageHeader *hdr;
240 struct Session *session;
243 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
244 "Creating session for peer `%4s'\n", GNUNET_i2s (pid));
246 session = GNUNET_malloc (sizeof (struct Session));
247 session->peer = *peer;
248 session->kxinfo = kx;
249 session->time_established = GNUNET_TIME_absolute_get ();
250 GNUNET_assert (GNUNET_OK ==
251 GNUNET_CONTAINER_multihashmap_put (sessions,
252 &peer->hashPubKey, session,
253 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
254 GNUNET_STATISTICS_update (GSC_stats,
255 gettext_noop ("# established sessions"),
256 GNUNET_CONTAINER_multihashmap_size (sessions),
259 /* FIXME: integration with ATS for quota calculations... */
260 /* FIXME: who should do this? Neighbours!? */
261 GNUNET_TRANSPORT_set_quota (transport,
263 GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT,
264 GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT);
266 /* FIXME: we should probably do this periodically (in case
267 type map message is lost...) */
268 hdr = GSC_TYPEMAP_compute_type_map_message ();
269 GSC_KX_encrypt_and_transmit (kx,
270 GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT,
278 * Notify the given client about the session (client is new).
280 * @param cls the 'struct GSC_Client'
281 * @param key peer identity
282 * @param value the 'struct Session'
283 * @return GNUNET_OK (continue to iterate)
286 notify_client_about_session (void *cls,
287 const GNUNET_HashCode *key,
290 struct GSC_Client *client = cls;
291 struct Session *session = value;
293 GDS_CLIENTS_notify_client_about_neighbour (client,
295 NULL, 0, /* FIXME: ATS!? */
296 NULL, /* old TMAP: none */
303 * We have a new client, notify it about all current sessions.
305 * @param client the new client
308 GSC_SESSIONS_notify_client_about_sessions (struct GSC_Client *client)
310 /* notify new client about existing sessions */
311 GNUNET_CONTAINER_multihashmap_iterate (sessions,
312 ¬ify_client_about_session, client);
317 * Try to perform a transmission on the given session. Will solicit
318 * additional messages if the 'sme' queue is not full enough.
320 * @param session session to transmit messages from
323 try_transmission (struct Session *session);
327 * Queue a request from a client for transmission to a particular peer.
329 * @param car request to queue; this handle is then shared between
330 * the caller (CLIENTS subsystem) and SESSIONS and must not
331 * be released by either until either 'GNUNET_SESSIONS_dequeue',
332 * 'GNUNET_SESSIONS_transmit' or 'GNUNET_CLIENTS_failed'
333 * have been invoked on it
336 GSC_SESSIONS_queue_request (struct GSC_ClientActiveRequest *car)
338 struct Session *session;
340 session = find_session (&car->target);
343 /* neighbour must have disconnected since request was issued,
344 * ignore (client will realize it once it processes the
345 * disconnect notification) */
346 #if DEBUG_CORE_CLIENT
347 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
348 "Dropped client request for transmission (am disconnected)\n");
350 GNUNET_STATISTICS_update (GSC_stats,
352 ("# send requests dropped (disconnected)"), 1,
354 GSC_CLIENTS_reject_request (car);
357 if (car->msize > GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE)
360 GSC_CLIENTS_reject_request (car);
363 #if DEBUG_CORE_CLIENT
364 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
365 "Received client transmission request. queueing\n");
367 GNUNET_CONTAINER_DLL_insert (session->active_client_request_head,
368 session->active_client_request_tail, car);
369 try_transmission (session);
374 * Dequeue a request from a client from transmission to a particular peer.
376 * @param car request to dequeue; this handle will then be 'owned' by
377 * the caller (CLIENTS sysbsystem)
380 GSC_SESSIONS_dequeue_request (struct GSC_ClientActiveRequest *car)
384 s = find_session (&car->target);
385 GNUNET_CONTAINER_DLL_remove (s->active_client_request_head,
386 s->active_client_request_tail, car);
391 * Discard all expired active transmission requests from clients.
393 * @param session session to clean up
396 discard_expired_requests (struct Session *session)
398 struct GSC_ClientActiveRequest *pos;
399 struct GSC_ClientActiveRequest *nxt;
400 struct GNUNET_TIME_Absolute now;
402 now = GNUNET_TIME_absolute_get ();
404 nxt = session->active_client_request_head;
409 if ( (pos->deadline.abs_value < now.abs_value) &&
410 (GNUNET_YES != pos->was_solicited) )
412 GNUNET_STATISTICS_update (GSC_stats,
414 ("# messages discarded (expired prior to transmission)"),
416 GNUNET_CONTAINER_DLL_remove (session->active_client_request_head,
417 session->active_client_request_tail,
419 GSC_CLIENTS_reject_request (pos);
426 * Solicit messages for transmission.
428 * @param session session to solict messages for
431 solicit_messages (struct Session *session)
433 struct GSC_ClientActiveRequest *car;
436 discard_expired_requests (session);
438 for (car = session->active_client_request_head; NULL != car; car = car->next)
440 if (so_size + car->msize > GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE)
442 so_size += car->msize;
443 if (car->was_solicited == GNUNET_YES)
445 car->was_solicited = GNUNET_YES;
446 GSC_CLIENTS_solicit_request (car);
452 * Some messages were delayed (corked), but the timeout has now expired.
455 * @param cls 'struct Session' with the messages to transmit now
456 * @param tc scheduler context (unused)
459 pop_cork_task (void *cls,
460 const struct GNUNET_SCHEDULER_TaskContext *tc)
462 struct Session *session = session;
464 session->cork_task = GNUNET_SCHEDULER_NO_TASK;
465 try_transmission (session);
470 * Try to perform a transmission on the given session. Will solicit
471 * additional messages if the 'sme' queue is not full enough.
473 * @param session session to transmit messages from
476 try_transmission (struct Session *session)
478 struct SessionMessageEntry *pos;
480 struct GNUNET_TIME_Absolute now;
481 struct GNUNET_TIME_Absolute min_deadline;
483 if (GNUNET_YES != session->ready_to_transmit)
486 min_deadline = GNUNET_TIME_UNIT_FOREVER_ABS;
487 /* check 'ready' messages */
488 pos = session->sme_head;
489 GNUNET_assert (pos->size < GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE);
490 while ( (NULL != pos) &&
491 (msize + pos->size <= GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE) )
494 min_deadline = GNUNET_TIME_absolute_min (min_deadline,
498 now = GNUNET_TIME_absolute_get ();
500 ( (msize < GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE / 2) &&
501 (min_deadline.abs_value > now.abs_value) ) )
503 /* not enough ready yet, try to solicit more */
504 solicit_messages (session);
507 /* if there is data to send, just not yet, make sure we do transmit
508 it once the deadline is reached */
509 if (session->cork_task != GNUNET_SCHEDULER_NO_TASK)
510 GNUNET_SCHEDULER_cancel (session->cork_task);
511 session->cork_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_absolute_get_remaining (min_deadline),
517 /* create plaintext buffer of all messages, encrypt and transmit */
519 static unsigned long long total_bytes;
520 static unsigned int total_msgs;
521 char pbuf[msize]; /* plaintext */
525 pos = session->sme_head;
526 while ( (NULL != pos) &&
527 (used + pos->size <= msize) )
529 memcpy (&pbuf[used], &pos[1], pos->size);
532 /* compute average payload size */
537 /* 2^32 messages, wrap around... */
541 GNUNET_STATISTICS_set (GSC_stats,
542 "# avg payload per encrypted message",
543 total_bytes / total_msgs,
545 /* now actually transmit... */
546 session->ready_to_transmit = GNUNET_NO;
547 GSC_KX_encrypt_and_transmit (session->kxinfo,
548 GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT /* FIXME! */,
556 * Send a message to the neighbour now.
558 * @param cls the message
559 * @param key neighbour's identity
560 * @param value 'struct Neighbour' of the target
561 * @return always GNUNET_OK
564 do_send_message (void *cls, const GNUNET_HashCode * key, void *value)
566 const struct GNUNET_MessageHeader *hdr = cls;
567 struct Session *session = value;
568 struct SessionMessageEntry *m;
571 size = ntohs (hdr->size);
572 m = GNUNET_malloc (sizeof (struct SessionMessageEntry) + size);
573 memcpy (&m[1], hdr, size);
575 GNUNET_CONTAINER_DLL_insert (session->sme_head,
578 try_transmission (session);
584 * Broadcast a message to all neighbours.
586 * @param msg message to transmit
589 GSC_SESSIONS_broadcast (const struct GNUNET_MessageHeader *msg)
591 if (NULL == sessions)
593 GNUNET_CONTAINER_multihashmap_iterate (sessions,
594 &do_send_message, (void*) msg);
599 * Traffic is being solicited for the given peer. This means that the
600 * message queue on the transport-level (NEIGHBOURS subsystem) is now
601 * empty and it is now OK to transmit another (non-control) message.
603 * @param pid identity of peer ready to receive data
606 GSC_SESSIONS_solicit (const struct GNUNET_PeerIdentity *pid)
608 struct Session *session;
610 session = find_session (pid);
611 session->ready_to_transmit = GNUNET_YES;
612 try_transmission (session);
617 * Transmit a message to a particular peer.
619 * @param car original request that was queued and then solicited;
620 * this handle will now be 'owned' by the SESSIONS subsystem
621 * @param msg message to transmit
622 * @param cork is corking allowed?
625 GSC_SESSIONS_transmit (struct GSC_ClientActiveRequest *car,
626 const struct GNUNET_MessageHeader *msg,
629 struct Session *session;
630 struct SessionMessageEntry *sme;
633 session = find_session (&car->target);
634 msize = ntohs (msg->size);
635 sme = GNUNET_malloc (sizeof (struct SessionMessageEntry) + msize);
636 memcpy (&sme[1], msg, msize);
638 if (GNUNET_YES == cork)
639 sme->deadline = GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_MAX_CORK_DELAY);
640 GNUNET_CONTAINER_DLL_insert_tail (session->sme_head,
643 try_transmission (session);
648 * Helper function for GSC_SESSIONS_handle_client_iterate_peers.
650 * @param cls the 'struct GNUNET_SERVER_TransmitContext' to queue replies
651 * @param key identity of the connected peer
652 * @param value the 'struct Neighbour' for the peer
653 * @return GNUNET_OK (continue to iterate)
657 queue_connect_message (void *cls, const GNUNET_HashCode * key, void *value)
659 struct GNUNET_SERVER_TransmitContext *tc = cls;
660 struct Session *session = value;
661 struct ConnectNotifyMessage cnm;
662 struct GNUNET_TRANSPORT_ATS_Information *a;
664 /* FIXME: code duplication with clients... */
665 cnm.header.size = htons (sizeof (struct ConnectNotifyMessage));
666 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT);
667 cnm.ats_count = htonl (0);
668 cnm.peer = session->peer;
670 // FIXME: full ats...
671 a[0].type = htonl (GNUNET_TRANSPORT_ATS_ARRAY_TERMINATOR);
672 a[0].value = htonl (0);
673 GNUNET_SERVER_transmit_context_append_message (tc, &cnm.header);
679 * Handle CORE_ITERATE_PEERS request. For this request type, the client
680 * does not have to have transmitted an INIT request. All current peers
681 * are returned, regardless of which message types they accept.
684 * @param client client sending the iteration request
685 * @param message iteration request message
688 GSC_SESSIONS_handle_client_iterate_peers (void *cls, struct GNUNET_SERVER_Client *client,
689 const struct GNUNET_MessageHeader *message)
691 struct GNUNET_MessageHeader done_msg;
692 struct GNUNET_SERVER_TransmitContext *tc;
694 tc = GNUNET_SERVER_transmit_context_create (client);
695 GNUNET_CONTAINER_multihashmap_iterate (sessions,
696 &queue_connect_message,
698 done_msg.size = htons (sizeof (struct GNUNET_MessageHeader));
699 done_msg.type = htons (GNUNET_MESSAGE_TYPE_CORE_ITERATE_PEERS_END);
700 GNUNET_SERVER_transmit_context_append_message (tc, &done_msg);
701 GNUNET_SERVER_transmit_context_run (tc, GNUNET_TIME_UNIT_FOREVER_REL);
706 * Handle CORE_PEER_CONNECTED request. Notify client about connection
707 * to the given neighbour. For this request type, the client does not
708 * have to have transmitted an INIT request. All current peers are
709 * returned, regardless of which message types they accept.
712 * @param client client sending the iteration request
713 * @param message iteration request message
716 GSC_SESSIONS_handle_client_have_peer (void *cls, struct GNUNET_SERVER_Client *client,
717 const struct GNUNET_MessageHeader *message)
719 struct GNUNET_MessageHeader done_msg;
720 struct GNUNET_SERVER_TransmitContext *tc;
721 const struct GNUNET_PeerIdentity *peer;
723 peer = (const struct GNUNET_PeerIdentity *) &message[1]; // YUCK!
724 tc = GNUNET_SERVER_transmit_context_create (client);
725 GNUNET_CONTAINER_multihashmap_get_multiple (sessions, &peer->hashPubKey,
726 &queue_connect_message, tc);
727 done_msg.size = htons (sizeof (struct GNUNET_MessageHeader));
728 done_msg.type = htons (GNUNET_MESSAGE_TYPE_CORE_ITERATE_PEERS_END);
729 GNUNET_SERVER_transmit_context_append_message (tc, &done_msg);
730 GNUNET_SERVER_transmit_context_run (tc, GNUNET_TIME_UNIT_FOREVER_REL);
735 * Handle REQUEST_INFO request. For this request type, the client must
736 * have transmitted an INIT first.
739 * @param client client sending the request
740 * @param message iteration request message
743 GSC_SESSIONS_handle_client_request_info (void *cls, struct GNUNET_SERVER_Client *client,
744 const struct GNUNET_MessageHeader *message)
746 const struct RequestInfoMessage *rcm;
747 struct Session *session;
748 struct ConfigurationInfoMessage cim;
751 struct GNUNET_TIME_Relative rdelay;
753 rdelay = GNUNET_TIME_UNIT_ZERO;
754 #if DEBUG_CORE_CLIENT
755 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
756 "Core service receives `%s' request.\n",
759 rcm = (const struct RequestInfoMessage *) message;
760 session = find_session (&rcm->peer);
763 /* Technically, this COULD happen (due to asynchronous behavior),
764 * but it should be rare, so we should generate an info event
765 * to help diagnosis of serious errors that might be masked by this */
766 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
767 _("Client asked for preference change with peer `%s', which is not connected!\n"),
768 GNUNET_i2s (&rcm->peer));
769 GNUNET_SERVER_receive_done (client, GNUNET_OK);
773 want_reserv = ntohl (rcm->reserve_inbound);
776 got_reserv = want_reserv;
778 else if (want_reserv > 0)
781 GNUNET_BANDWIDTH_tracker_get_delay (&session->available_recv_window,
783 if (rdelay.rel_value == 0)
784 got_reserv = want_reserv;
786 got_reserv = 0; /* all or nothing */
790 GNUNET_BANDWIDTH_tracker_consume (&session->available_recv_window, got_reserv);
792 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
793 "Received reservation request for %d bytes for peer `%4s', reserved %d bytes, suggesting delay of %llu ms\n",
794 (int) want_reserv, GNUNET_i2s (&rcm->peer), (int) got_reserv,
795 (unsigned long long) rdelay.rel_value);
797 cim.header.size = htons (sizeof (struct ConfigurationInfoMessage));
798 cim.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_CONFIGURATION_INFO);
799 cim.reserved_amount = htonl (got_reserv);
800 cim.reserve_delay = GNUNET_TIME_relative_hton (rdelay);
801 cim.rim_id = rcm->rim_id;
802 cim.bw_out = session->bw_out;
803 cim.preference = 0; /* FIXME: remove */
804 cim.peer = rcm->peer;
805 GSC_CLIENTS_send_to_client (client, &cim.header, GNUNET_NO);
806 GNUNET_SERVER_receive_done (client, GNUNET_OK);
811 * Update information about a session.
813 * @param peer peer who's session should be updated
814 * @param bw_out new outbound bandwidth limit for the peer
815 * @param atsi performance information
816 * @param atsi_count number of performance records supplied
819 GSC_SESSIONS_update (const struct GNUNET_PeerIdentity *peer,
820 struct GNUNET_BANDWIDTH_Value32NBO bw_out)
823 /* not implemented */
828 * Initialize sessions subsystem.
833 sessions = GNUNET_CONTAINER_multihashmap_create (128);
838 * Helper function for GSC_SESSIONS_handle_client_iterate_peers.
841 * @param key identity of the connected peer
842 * @param value the 'struct Session' for the peer
843 * @return GNUNET_OK (continue to iterate)
846 free_session_helper (void *cls, const GNUNET_HashCode * key, void *value)
848 struct Session *session = value;
850 GSC_SESSIONS_end (&session->peer);
856 * Shutdown sessions subsystem.
861 GNUNET_CONTAINER_multihashmap_iterate (sessions,
862 &free_session_helper,
864 GNUNET_CONTAINER_multihashmap_destroy (sessions);
866 GNUNET_STATISTICS_set (GSC_stats,
867 gettext_noop ("# established sessions"),
871 /* end of gnunet-service-core_sessions.c */