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 * Is the neighbour queue empty and thus ready for us
126 * to transmit an encrypted message?
128 int ready_to_transmit;
134 * Map of peer identities to 'struct Session'.
136 static struct GNUNET_CONTAINER_MultiHashMap *sessions;
140 * Find the session for the given peer.
142 * @param peer identity of the peer
143 * @return NULL if we are not connected, otherwise the
146 static struct Session *
147 find_session (const struct GNUNET_PeerIdentity *peer)
149 return GNUNET_CONTAINER_multihashmap_get (sessions, &peer->hashPubKey);
154 * End the session with the given peer (we are no longer
157 * @param pid identity of peer to kill session with
160 GSC_SESSIONS_end (const struct GNUNET_PeerIdentity *pid)
162 struct Session *session;
163 struct GSC_ClientActiveRequest *car;
165 session = find_session (pid);
169 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
170 "Destroying session for peer `%4s'\n",
171 GNUNET_i2s (&session->peer));
173 if (GNUNET_SCHEDULER_NO_TASK != session->cork_task)
175 GNUNET_SCHEDULER_cancel (session->cork_task);
176 session->cork_task = GNUNET_SCHEDULER_NO_TASK;
178 GNUNET_assert (GNUNET_YES ==
179 GNUNET_CONTAINER_multihashmap_remove (sessions,
180 &session->peer.hashPubKey, session));
181 while (NULL != (car = session->active_client_request_head))
183 GNUNET_CONTAINER_DLL_remove (session->active_client_request_head,
184 session->active_client_request_tail,
186 GSC_CLIENTS_reject_request (car);
188 GNUNET_STATISTICS_set (GSC_stats,
189 gettext_noop ("# established sessions"),
190 GNUNET_CONTAINER_multihashmap_size (sessions),
192 GNUNET_free (session);
197 * Create a session, a key exchange was just completed.
199 * @param peer peer that is now connected
200 * @param kx key exchange that completed
203 GSC_SESSIONS_create (const struct GNUNET_PeerIdentity *peer,
204 struct GSC_KeyExchangeInfo *kx)
206 struct GNUNET_MessageHeader *hdr;
207 struct Session *session;
210 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
211 "Creating session for peer `%4s'\n", GNUNET_i2s (pid));
213 session = GNUNET_malloc (sizeof (struct Session));
214 session->peer = *peer;
215 session->kxinfo = kx;
216 session->time_established = GNUNET_TIME_absolute_get ();
217 GNUNET_assert (GNUNET_OK ==
218 GNUNET_CONTAINER_multihashmap_put (sessions,
219 &peer->hashPubKey, session,
220 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
221 GNUNET_STATISTICS_update (GSC_stats,
222 gettext_noop ("# established sessions"),
223 GNUNET_CONTAINER_multihashmap_size (sessions),
226 /* FIXME: integration with ATS for quota calculations... */
227 /* FIXME: who should do this? Neighbours!? */
228 GNUNET_TRANSPORT_set_quota (transport,
230 GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT,
231 GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT);
233 /* FIXME: we should probably do this periodically (in case
234 type map message is lost...) */
235 hdr = GSC_TYPEMAP_compute_type_map_message ();
236 GSC_KX_encrypt_and_transmit (kx,
237 GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT,
245 * Notify the given client about the session (client is new).
247 * @param cls the 'struct GSC_Client'
248 * @param key peer identity
249 * @param value the 'struct Session'
250 * @return GNUNET_OK (continue to iterate)
253 notify_client_about_session (void *cls,
254 const GNUNET_HashCode *key,
257 struct GSC_Client *client = cls;
258 struct Session *session = value;
260 GDS_CLIENTS_notify_client_about_neighbour (client,
262 NULL, 0, /* FIXME: ATS!? */
263 NULL, /* old TMAP: none */
270 * We have a new client, notify it about all current sessions.
272 * @param client the new client
275 GSC_SESSIONS_notify_client_about_sessions (struct GSC_Client *client)
277 /* notify new client about existing sessions */
278 GNUNET_CONTAINER_multihashmap_iterate (sessions,
279 ¬ify_client_about_session, client);
284 * Try to perform a transmission on the given session. Will solicit
285 * additional messages if the 'sme' queue is not full enough.
287 * @param session session to transmit messages from
290 try_transmission (struct Session *session);
294 * Queue a request from a client for transmission to a particular peer.
296 * @param car request to queue; this handle is then shared between
297 * the caller (CLIENTS subsystem) and SESSIONS and must not
298 * be released by either until either 'GNUNET_SESSIONS_dequeue',
299 * 'GNUNET_SESSIONS_transmit' or 'GNUNET_CLIENTS_failed'
300 * have been invoked on it
303 GSC_SESSIONS_queue_request (struct GSC_ClientActiveRequest *car)
305 struct Session *session;
307 session = find_session (&car->target);
310 /* neighbour must have disconnected since request was issued,
311 * ignore (client will realize it once it processes the
312 * disconnect notification) */
313 #if DEBUG_CORE_CLIENT
314 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
315 "Dropped client request for transmission (am disconnected)\n");
317 GNUNET_STATISTICS_update (GSC_stats,
319 ("# send requests dropped (disconnected)"), 1,
321 GSC_CLIENTS_reject_request (car);
324 if (car->msize > GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE)
327 GSC_CLIENTS_reject_request (car);
330 #if DEBUG_CORE_CLIENT
331 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
332 "Received client transmission request. queueing\n");
334 GNUNET_CONTAINER_DLL_insert (session->active_client_request_head,
335 session->active_client_request_tail, car);
336 try_transmission (session);
341 * Dequeue a request from a client from transmission to a particular peer.
343 * @param car request to dequeue; this handle will then be 'owned' by
344 * the caller (CLIENTS sysbsystem)
347 GSC_SESSIONS_dequeue_request (struct GSC_ClientActiveRequest *car)
351 s = find_session (&car->target);
352 GNUNET_CONTAINER_DLL_remove (s->active_client_request_head,
353 s->active_client_request_tail, car);
358 * Discard all expired active transmission requests from clients.
360 * @param session session to clean up
363 discard_expired_requests (struct Session *session)
365 struct GSC_ClientActiveRequest *pos;
366 struct GSC_ClientActiveRequest *nxt;
367 struct GNUNET_TIME_Absolute now;
369 now = GNUNET_TIME_absolute_get ();
371 nxt = session->active_client_request_head;
376 if ( (pos->deadline.abs_value < now.abs_value) &&
377 (GNUNET_YES != pos->was_solicited) )
379 GNUNET_STATISTICS_update (GSC_stats,
381 ("# messages discarded (expired prior to transmission)"),
383 GNUNET_CONTAINER_DLL_remove (session->active_client_request_head,
384 session->active_client_request_tail,
386 GSC_CLIENTS_reject_request (pos);
393 * Solicit messages for transmission.
395 * @param session session to solict messages for
398 solicit_messages (struct Session *session)
400 struct GSC_ClientActiveRequest *car;
403 discard_expired_requests (session);
405 for (car = session->active_client_request_head; NULL != car; car = car->next)
407 if (so_size + car->msize > GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE)
409 so_size += car->msize;
410 if (car->was_solicited == GNUNET_YES)
412 car->was_solicited = GNUNET_YES;
413 GSC_CLIENTS_solicit_request (car);
419 * Some messages were delayed (corked), but the timeout has now expired.
422 * @param cls 'struct Session' with the messages to transmit now
423 * @param tc scheduler context (unused)
426 pop_cork_task (void *cls,
427 const struct GNUNET_SCHEDULER_TaskContext *tc)
429 struct Session *session = session;
431 session->cork_task = GNUNET_SCHEDULER_NO_TASK;
432 try_transmission (session);
437 * Try to perform a transmission on the given session. Will solicit
438 * additional messages if the 'sme' queue is not full enough.
440 * @param session session to transmit messages from
443 try_transmission (struct Session *session)
445 struct SessionMessageEntry *pos;
447 struct GNUNET_TIME_Absolute now;
448 struct GNUNET_TIME_Absolute min_deadline;
450 if (GNUNET_YES != session->ready_to_transmit)
453 min_deadline = GNUNET_TIME_UNIT_FOREVER_ABS;
454 /* check 'ready' messages */
455 pos = session->sme_head;
456 GNUNET_assert (pos->size < GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE);
457 while ( (NULL != pos) &&
458 (msize + pos->size <= GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE) )
461 min_deadline = GNUNET_TIME_absolute_min (min_deadline,
465 now = GNUNET_TIME_absolute_get ();
467 ( (msize < GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE / 2) &&
468 (min_deadline.abs_value > now.abs_value) ) )
470 /* not enough ready yet, try to solicit more */
471 solicit_messages (session);
474 /* if there is data to send, just not yet, make sure we do transmit
475 it once the deadline is reached */
476 if (session->cork_task != GNUNET_SCHEDULER_NO_TASK)
477 GNUNET_SCHEDULER_cancel (session->cork_task);
478 session->cork_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_absolute_get_remaining (min_deadline),
484 /* create plaintext buffer of all messages, encrypt and transmit */
486 static unsigned long long total_bytes;
487 static unsigned int total_msgs;
488 char pbuf[msize]; /* plaintext */
492 pos = session->sme_head;
493 while ( (NULL != pos) &&
494 (used + pos->size <= msize) )
496 memcpy (&pbuf[used], &pos[1], pos->size);
499 /* compute average payload size */
504 /* 2^32 messages, wrap around... */
508 GNUNET_STATISTICS_set (GSC_stats,
509 "# avg payload per encrypted message",
510 total_bytes / total_msgs,
512 /* now actually transmit... */
513 session->ready_to_transmit = GNUNET_NO;
514 GSC_KX_encrypt_and_transmit (session->kxinfo,
515 GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT /* FIXME! */,
523 * Send a message to the neighbour now.
525 * @param cls the message
526 * @param key neighbour's identity
527 * @param value 'struct Neighbour' of the target
528 * @return always GNUNET_OK
531 do_send_message (void *cls, const GNUNET_HashCode * key, void *value)
533 const struct GNUNET_MessageHeader *hdr = cls;
534 struct Session *session = value;
535 struct SessionMessageEntry *m;
538 size = ntohs (hdr->size);
539 m = GNUNET_malloc (sizeof (struct SessionMessageEntry) + size);
540 memcpy (&m[1], hdr, size);
542 GNUNET_CONTAINER_DLL_insert (session->sme_head,
545 try_transmission (session);
551 * Broadcast a message to all neighbours.
553 * @param msg message to transmit
556 GSC_SESSIONS_broadcast (const struct GNUNET_MessageHeader *msg)
558 if (NULL == sessions)
560 GNUNET_CONTAINER_multihashmap_iterate (sessions,
561 &do_send_message, (void*) msg);
566 * Traffic is being solicited for the given peer. This means that the
567 * message queue on the transport-level (NEIGHBOURS subsystem) is now
568 * empty and it is now OK to transmit another (non-control) message.
570 * @param pid identity of peer ready to receive data
573 GSC_SESSIONS_solicit (const struct GNUNET_PeerIdentity *pid)
575 struct Session *session;
577 session = find_session (pid);
578 session->ready_to_transmit = GNUNET_YES;
579 try_transmission (session);
584 * Transmit a message to a particular peer.
586 * @param car original request that was queued and then solicited;
587 * this handle will now be 'owned' by the SESSIONS subsystem
588 * @param msg message to transmit
589 * @param cork is corking allowed?
592 GSC_SESSIONS_transmit (struct GSC_ClientActiveRequest *car,
593 const struct GNUNET_MessageHeader *msg,
596 struct Session *session;
597 struct SessionMessageEntry *sme;
600 session = find_session (&car->target);
601 msize = ntohs (msg->size);
602 sme = GNUNET_malloc (sizeof (struct SessionMessageEntry) + msize);
603 memcpy (&sme[1], msg, msize);
605 if (GNUNET_YES == cork)
606 sme->deadline = GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_MAX_CORK_DELAY);
607 GNUNET_CONTAINER_DLL_insert_tail (session->sme_head,
610 try_transmission (session);
615 * Helper function for GSC_SESSIONS_handle_client_iterate_peers.
617 * @param cls the 'struct GNUNET_SERVER_TransmitContext' to queue replies
618 * @param key identity of the connected peer
619 * @param value the 'struct Neighbour' for the peer
620 * @return GNUNET_OK (continue to iterate)
624 queue_connect_message (void *cls, const GNUNET_HashCode * key, void *value)
626 struct GNUNET_SERVER_TransmitContext *tc = cls;
627 struct Session *session = value;
628 struct ConnectNotifyMessage cnm;
629 struct GNUNET_TRANSPORT_ATS_Information *a;
631 /* FIXME: code duplication with clients... */
632 cnm.header.size = htons (sizeof (struct ConnectNotifyMessage));
633 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT);
634 cnm.ats_count = htonl (0);
635 cnm.peer = session->peer;
637 // FIXME: full ats...
638 a[0].type = htonl (GNUNET_TRANSPORT_ATS_ARRAY_TERMINATOR);
639 a[0].value = htonl (0);
640 GNUNET_SERVER_transmit_context_append_message (tc, &cnm.header);
646 * Handle CORE_ITERATE_PEERS request. For this request type, the client
647 * does not have to have transmitted an INIT request. All current peers
648 * are returned, regardless of which message types they accept.
651 * @param client client sending the iteration request
652 * @param message iteration request message
655 GSC_SESSIONS_handle_client_iterate_peers (void *cls, struct GNUNET_SERVER_Client *client,
656 const struct GNUNET_MessageHeader *message)
658 struct GNUNET_MessageHeader done_msg;
659 struct GNUNET_SERVER_TransmitContext *tc;
661 tc = GNUNET_SERVER_transmit_context_create (client);
662 GNUNET_CONTAINER_multihashmap_iterate (sessions,
663 &queue_connect_message,
665 done_msg.size = htons (sizeof (struct GNUNET_MessageHeader));
666 done_msg.type = htons (GNUNET_MESSAGE_TYPE_CORE_ITERATE_PEERS_END);
667 GNUNET_SERVER_transmit_context_append_message (tc, &done_msg);
668 GNUNET_SERVER_transmit_context_run (tc, GNUNET_TIME_UNIT_FOREVER_REL);
673 * Handle CORE_PEER_CONNECTED request. Notify client about connection
674 * to the given neighbour. For this request type, the client does not
675 * have to have transmitted an INIT request. All current peers are
676 * returned, regardless of which message types they accept.
679 * @param client client sending the iteration request
680 * @param message iteration request message
683 GSC_SESSIONS_handle_client_have_peer (void *cls, struct GNUNET_SERVER_Client *client,
684 const struct GNUNET_MessageHeader *message)
686 struct GNUNET_MessageHeader done_msg;
687 struct GNUNET_SERVER_TransmitContext *tc;
688 const struct GNUNET_PeerIdentity *peer;
690 peer = (const struct GNUNET_PeerIdentity *) &message[1]; // YUCK!
691 tc = GNUNET_SERVER_transmit_context_create (client);
692 GNUNET_CONTAINER_multihashmap_get_multiple (sessions, &peer->hashPubKey,
693 &queue_connect_message, tc);
694 done_msg.size = htons (sizeof (struct GNUNET_MessageHeader));
695 done_msg.type = htons (GNUNET_MESSAGE_TYPE_CORE_ITERATE_PEERS_END);
696 GNUNET_SERVER_transmit_context_append_message (tc, &done_msg);
697 GNUNET_SERVER_transmit_context_run (tc, GNUNET_TIME_UNIT_FOREVER_REL);
702 * Handle REQUEST_INFO request. For this request type, the client must
703 * have transmitted an INIT first.
706 * @param client client sending the request
707 * @param message iteration request message
710 GSC_SESSIONS_handle_client_request_info (void *cls, struct GNUNET_SERVER_Client *client,
711 const struct GNUNET_MessageHeader *message)
713 const struct RequestInfoMessage *rcm;
714 struct Session *session;
715 struct ConfigurationInfoMessage cim;
718 struct GNUNET_TIME_Relative rdelay;
720 rdelay = GNUNET_TIME_UNIT_ZERO;
721 #if DEBUG_CORE_CLIENT
722 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
723 "Core service receives `%s' request.\n",
726 rcm = (const struct RequestInfoMessage *) message;
727 session = find_session (&rcm->peer);
730 /* Technically, this COULD happen (due to asynchronous behavior),
731 * but it should be rare, so we should generate an info event
732 * to help diagnosis of serious errors that might be masked by this */
733 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
734 _("Client asked for preference change with peer `%s', which is not connected!\n"),
735 GNUNET_i2s (&rcm->peer));
736 GNUNET_SERVER_receive_done (client, GNUNET_OK);
740 want_reserv = ntohl (rcm->reserve_inbound);
741 if (session->bw_out_internal_limit.value__ != rcm->limit_outbound.value__)
743 session->bw_out_internal_limit = rcm->limit_outbound;
744 if (session->bw_out.value__ !=
745 GNUNET_BANDWIDTH_value_min (session->bw_out_internal_limit,
746 session->bw_out_external_limit).value__)
749 GNUNET_BANDWIDTH_value_min (session->bw_out_internal_limit,
750 session->bw_out_external_limit);
751 GNUNET_BANDWIDTH_tracker_update_quota (&session->available_recv_window,
754 // FIXME: who does this?
755 GNUNET_TRANSPORT_set_quota (transport, &session->peer,
763 got_reserv = want_reserv;
765 else if (want_reserv > 0)
768 GNUNET_BANDWIDTH_tracker_get_delay (&session->available_recv_window,
770 if (rdelay.rel_value == 0)
771 got_reserv = want_reserv;
773 got_reserv = 0; /* all or nothing */
777 GNUNET_BANDWIDTH_tracker_consume (&session->available_recv_window, got_reserv);
779 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
780 "Received reservation request for %d bytes for peer `%4s', reserved %d bytes, suggesting delay of %llu ms\n",
781 (int) want_reserv, GNUNET_i2s (&rcm->peer), (int) got_reserv,
782 (unsigned long long) rdelay.rel_value);
784 cim.header.size = htons (sizeof (struct ConfigurationInfoMessage));
785 cim.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_CONFIGURATION_INFO);
786 cim.reserved_amount = htonl (got_reserv);
787 cim.reserve_delay = GNUNET_TIME_relative_hton (rdelay);
788 cim.rim_id = rcm->rim_id;
789 cim.bw_out = session->bw_out;
790 cim.preference = 0; /* FIXME: remove */
791 cim.peer = rcm->peer;
792 GSC_CLIENTS_send_to_client (client, &cim.header, GNUNET_NO);
793 GNUNET_SERVER_receive_done (client, GNUNET_OK);
798 * Update information about a session.
800 * @param peer peer who's session should be updated
801 * @param bw_out new outbound bandwidth limit for the peer
802 * @param atsi performance information
803 * @param atsi_count number of performance records supplied
806 GSC_SESSIONS_update (const struct GNUNET_PeerIdentity *peer,
807 struct GNUNET_BANDWIDTH_Value32NBO bw_out)
810 /* not implemented */
815 * Initialize sessions subsystem.
820 sessions = GNUNET_CONTAINER_multihashmap_create (128);
825 * Helper function for GSC_SESSIONS_handle_client_iterate_peers.
828 * @param key identity of the connected peer
829 * @param value the 'struct Session' for the peer
830 * @return GNUNET_OK (continue to iterate)
833 free_session_helper (void *cls, const GNUNET_HashCode * key, void *value)
835 struct Session *session = value;
837 GSC_SESSIONS_end (&session->peer);
843 * Shutdown sessions subsystem.
848 GNUNET_CONTAINER_multihashmap_iterate (sessions,
849 &free_session_helper,
851 GNUNET_CONTAINER_multihashmap_destroy (sessions);
853 GNUNET_STATISTICS_set (GSC_stats,
854 gettext_noop ("# established sessions"),
858 /* end of gnunet-service-core_sessions.c */