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"
36 * How often do we transmit our typemap?
38 #define TYPEMAP_FREQUENCY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 5)
41 * How often do we transmit our typemap on first attempt?
43 #define TYPEMAP_FREQUENCY_FIRST GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 5)
47 * Message ready for encryption. This struct is followed by the
48 * actual content of the message.
50 struct SessionMessageEntry
54 * We keep messages in a doubly linked list.
56 struct SessionMessageEntry *next;
59 * We keep messages in a doubly linked list.
61 struct SessionMessageEntry *prev;
64 * Deadline for transmission, 1s after we received it (if we
65 * are not corking), otherwise "now". Note that this message
66 * does NOT expire past its deadline.
68 struct GNUNET_TIME_Absolute deadline;
71 * How long is the message? (number of bytes following the "struct
72 * MessageEntry", but not including the size of "struct
73 * MessageEntry" itself!)
81 * Data kept per session.
86 * Identity of the other peer.
88 struct GNUNET_PeerIdentity peer;
91 * Head of list of requests from clients for transmission to
94 struct GSC_ClientActiveRequest *active_client_request_head;
97 * Tail of list of requests from clients for transmission to
100 struct GSC_ClientActiveRequest *active_client_request_tail;
103 * Head of list of messages ready for encryption.
105 struct SessionMessageEntry *sme_head;
108 * Tail of list of messages ready for encryption.
110 struct SessionMessageEntry *sme_tail;
113 * Information about the key exchange with the other peer.
115 struct GSC_KeyExchangeInfo *kxinfo;
118 * Current type map for this peer.
120 struct GSC_TypeMap *tmap;
123 * Task to transmit corked messages with a delay.
125 GNUNET_SCHEDULER_TaskIdentifier cork_task;
128 * Task to transmit our type map.
130 GNUNET_SCHEDULER_TaskIdentifier typemap_task;
133 * Is the neighbour queue empty and thus ready for us
134 * to transmit an encrypted message?
136 int ready_to_transmit;
139 * Is this the first time we're sending the typemap? If so,
140 * we want to send it a bit faster the second time. 0 if
141 * we are sending for the first time, 1 if not.
148 * Map of peer identities to 'struct Session'.
150 static struct GNUNET_CONTAINER_MultiHashMap *sessions;
154 * Find the session for the given peer.
156 * @param peer identity of the peer
157 * @return NULL if we are not connected, otherwise the
160 static struct Session *
161 find_session (const struct GNUNET_PeerIdentity *peer)
163 return GNUNET_CONTAINER_multihashmap_get (sessions, &peer->hashPubKey);
168 * End the session with the given peer (we are no longer
171 * @param pid identity of peer to kill session with
174 GSC_SESSIONS_end (const struct GNUNET_PeerIdentity *pid)
176 struct Session *session;
177 struct GSC_ClientActiveRequest *car;
178 struct SessionMessageEntry *sme;
180 session = find_session (pid);
183 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Destroying session for peer `%4s'\n",
184 GNUNET_i2s (&session->peer));
185 if (GNUNET_SCHEDULER_NO_TASK != session->cork_task)
187 GNUNET_SCHEDULER_cancel (session->cork_task);
188 session->cork_task = GNUNET_SCHEDULER_NO_TASK;
190 while (NULL != (car = session->active_client_request_head))
192 GNUNET_CONTAINER_DLL_remove (session->active_client_request_head,
193 session->active_client_request_tail, car);
194 GSC_CLIENTS_reject_request (car);
196 while (NULL != (sme = session->sme_head))
198 GNUNET_CONTAINER_DLL_remove (session->sme_head, session->sme_tail, sme);
201 GNUNET_SCHEDULER_cancel (session->typemap_task);
202 GSC_CLIENTS_notify_clients_about_neighbour (&session->peer, NULL,
203 0 /* FIXME: ATSI */ ,
204 session->tmap, NULL);
205 GNUNET_assert (GNUNET_YES ==
206 GNUNET_CONTAINER_multihashmap_remove (sessions,
210 GNUNET_STATISTICS_set (GSC_stats, gettext_noop ("# peers connected"),
211 GNUNET_CONTAINER_multihashmap_size (sessions),
213 GSC_TYPEMAP_destroy (session->tmap);
214 session->tmap = NULL;
215 GNUNET_free (session);
220 * Transmit our current typemap message to the other peer.
221 * (Done periodically in case an update got lost).
223 * @param cls the 'struct Session*'
227 transmit_typemap_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
229 struct Session *session = cls;
230 struct GNUNET_MessageHeader *hdr;
231 struct GNUNET_TIME_Relative delay;
233 if (0 == session->first_typemap)
235 delay = TYPEMAP_FREQUENCY_FIRST;
236 session->first_typemap = 1;
240 delay = TYPEMAP_FREQUENCY;
242 /* randomize a bit to avoid spont. sync */
244 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, 1000);
245 session->typemap_task =
246 GNUNET_SCHEDULER_add_delayed (delay, &transmit_typemap_task, session);
247 GNUNET_STATISTICS_update (GSC_stats,
248 gettext_noop ("# type map refreshes sent"), 1,
250 hdr = GSC_TYPEMAP_compute_type_map_message ();
251 GSC_KX_encrypt_and_transmit (session->kxinfo, hdr, ntohs (hdr->size));
257 * Create a session, a key exchange was just completed.
259 * @param peer peer that is now connected
260 * @param kx key exchange that completed
263 GSC_SESSIONS_create (const struct GNUNET_PeerIdentity *peer,
264 struct GSC_KeyExchangeInfo *kx)
266 struct Session *session;
268 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Creating session for peer `%4s'\n",
270 session = GNUNET_malloc (sizeof (struct Session));
271 session->tmap = GSC_TYPEMAP_create ();
272 session->peer = *peer;
273 session->kxinfo = kx;
274 session->typemap_task =
275 GNUNET_SCHEDULER_add_now (&transmit_typemap_task, session);
276 GNUNET_assert (GNUNET_OK ==
277 GNUNET_CONTAINER_multihashmap_put (sessions, &peer->hashPubKey,
279 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
280 GNUNET_STATISTICS_set (GSC_stats, gettext_noop ("# peers connected"),
281 GNUNET_CONTAINER_multihashmap_size (sessions),
283 GSC_CLIENTS_notify_clients_about_neighbour (peer, NULL, 0 /* FIXME: ATSI */ ,
284 NULL, session->tmap);
289 * Notify the given client about the session (client is new).
291 * @param cls the 'struct GSC_Client'
292 * @param key peer identity
293 * @param value the 'struct Session'
294 * @return GNUNET_OK (continue to iterate)
297 notify_client_about_session (void *cls, const struct GNUNET_HashCode * key,
300 struct GSC_Client *client = cls;
301 struct Session *session = value;
303 GSC_CLIENTS_notify_client_about_neighbour (client, &session->peer, NULL, 0, /* FIXME: ATS!? */
304 NULL, /* old TMAP: none */
311 * We have a new client, notify it about all current sessions.
313 * @param client the new client
316 GSC_SESSIONS_notify_client_about_sessions (struct GSC_Client *client)
318 /* notify new client about existing sessions */
319 GNUNET_CONTAINER_multihashmap_iterate (sessions, ¬ify_client_about_session,
325 * Try to perform a transmission on the given session. Will solicit
326 * additional messages if the 'sme' queue is not full enough.
328 * @param session session to transmit messages from
331 try_transmission (struct Session *session);
335 * Queue a request from a client for transmission to a particular peer.
337 * @param car request to queue; this handle is then shared between
338 * the caller (CLIENTS subsystem) and SESSIONS and must not
339 * be released by either until either 'GNUNET_SESSIONS_dequeue',
340 * 'GNUNET_SESSIONS_transmit' or 'GNUNET_CLIENTS_failed'
341 * have been invoked on it
344 GSC_SESSIONS_queue_request (struct GSC_ClientActiveRequest *car)
346 struct Session *session;
348 session = find_session (&car->target);
351 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
352 "Dropped client request for transmission (am disconnected)\n");
353 GNUNET_break (0); /* should have been rejected earlier */
354 GSC_CLIENTS_reject_request (car);
357 if (car->msize > GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE)
360 GSC_CLIENTS_reject_request (car);
363 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
364 "Received client transmission request. queueing\n");
365 GNUNET_CONTAINER_DLL_insert (session->active_client_request_head,
366 session->active_client_request_tail, car);
367 try_transmission (session);
372 * Dequeue a request from a client from transmission to a particular peer.
374 * @param car request to dequeue; this handle will then be 'owned' by
375 * the caller (CLIENTS sysbsystem)
378 GSC_SESSIONS_dequeue_request (struct GSC_ClientActiveRequest *car)
383 memcmp (&car->target, &GSC_my_identity,
384 sizeof (struct GNUNET_PeerIdentity)))
386 s = find_session (&car->target);
387 GNUNET_assert (NULL != s);
388 GNUNET_CONTAINER_DLL_remove (s->active_client_request_head,
389 s->active_client_request_tail, car);
394 * Discard all expired active transmission requests from clients.
396 * @param session session to clean up
399 discard_expired_requests (struct Session *session)
401 struct GSC_ClientActiveRequest *pos;
402 struct GSC_ClientActiveRequest *nxt;
403 struct GNUNET_TIME_Absolute now;
405 now = GNUNET_TIME_absolute_get ();
407 nxt = session->active_client_request_head;
412 if ((pos->deadline.abs_value < now.abs_value) &&
413 (GNUNET_YES != pos->was_solicited))
415 GNUNET_STATISTICS_update (GSC_stats,
417 ("# messages discarded (expired prior to transmission)"),
419 GNUNET_CONTAINER_DLL_remove (session->active_client_request_head,
420 session->active_client_request_tail, pos);
421 GSC_CLIENTS_reject_request (pos);
428 * Solicit messages for transmission.
430 * @param session session to solict messages for
433 solicit_messages (struct Session *session)
435 struct GSC_ClientActiveRequest *car;
436 struct GSC_ClientActiveRequest *nxt;
439 discard_expired_requests (session);
441 nxt = session->active_client_request_head;
442 while (NULL != (car = nxt))
445 if (so_size + car->msize > GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE)
447 so_size += car->msize;
448 if (car->was_solicited == GNUNET_YES)
450 car->was_solicited = GNUNET_YES;
451 GSC_CLIENTS_solicit_request (car);
457 * Some messages were delayed (corked), but the timeout has now expired.
460 * @param cls 'struct Session' with the messages to transmit now
461 * @param tc scheduler context (unused)
464 pop_cork_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
466 struct Session *session = cls;
468 session->cork_task = GNUNET_SCHEDULER_NO_TASK;
469 try_transmission (session);
474 * Try to perform a transmission on the given session. Will solicit
475 * additional messages if the 'sme' queue is not full enough.
477 * @param session session to transmit messages from
480 try_transmission (struct Session *session)
482 struct SessionMessageEntry *pos;
484 struct GNUNET_TIME_Absolute now;
485 struct GNUNET_TIME_Absolute min_deadline;
487 if (GNUNET_YES != session->ready_to_transmit)
490 min_deadline = GNUNET_TIME_UNIT_FOREVER_ABS;
491 /* check 'ready' messages */
492 pos = session->sme_head;
493 while ((NULL != pos) &&
494 (msize + pos->size <= GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE))
496 GNUNET_assert (pos->size < GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE);
498 min_deadline = GNUNET_TIME_absolute_min (min_deadline, pos->deadline);
501 now = GNUNET_TIME_absolute_get ();
503 ((msize < GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE / 2) &&
504 (min_deadline.abs_value > now.abs_value)))
506 /* not enough ready yet, try to solicit more */
507 solicit_messages (session);
510 /* if there is data to send, just not yet, make sure we do transmit
511 * it once the deadline is reached */
512 if (session->cork_task != GNUNET_SCHEDULER_NO_TASK)
513 GNUNET_SCHEDULER_cancel (session->cork_task);
515 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_absolute_get_remaining
516 (min_deadline), &pop_cork_task,
521 /* create plaintext buffer of all messages, encrypt and transmit */
523 static unsigned long long total_bytes;
524 static unsigned int total_msgs;
525 char pbuf[msize]; /* plaintext */
529 while ((NULL != (pos = session->sme_head)) && (used + pos->size <= msize))
531 memcpy (&pbuf[used], &pos[1], pos->size);
533 GNUNET_CONTAINER_DLL_remove (session->sme_head, session->sme_tail, pos);
536 /* compute average payload size */
541 /* 2^32 messages, wrap around... */
545 GNUNET_STATISTICS_set (GSC_stats, "# avg payload per encrypted message",
546 total_bytes / total_msgs, GNUNET_NO);
547 /* now actually transmit... */
548 session->ready_to_transmit = GNUNET_NO;
549 GSC_KX_encrypt_and_transmit (session->kxinfo, pbuf, used);
555 * Send a message to the neighbour now.
557 * @param cls the message
558 * @param key neighbour's identity
559 * @param value 'struct Neighbour' of the target
560 * @return always GNUNET_OK
563 do_send_message (void *cls, const struct GNUNET_HashCode * key, void *value)
565 const struct GNUNET_MessageHeader *hdr = cls;
566 struct Session *session = value;
567 struct SessionMessageEntry *m;
570 size = ntohs (hdr->size);
571 m = GNUNET_malloc (sizeof (struct SessionMessageEntry) + size);
572 memcpy (&m[1], hdr, size);
574 GNUNET_CONTAINER_DLL_insert (session->sme_head, session->sme_tail, m);
575 try_transmission (session);
581 * Broadcast a message to all neighbours.
583 * @param msg message to transmit
586 GSC_SESSIONS_broadcast (const struct GNUNET_MessageHeader *msg)
588 if (NULL == sessions)
590 GNUNET_CONTAINER_multihashmap_iterate (sessions, &do_send_message,
596 * Traffic is being solicited for the given peer. This means that the
597 * message queue on the transport-level (NEIGHBOURS subsystem) is now
598 * empty and it is now OK to transmit another (non-control) message.
600 * @param pid identity of peer ready to receive data
603 GSC_SESSIONS_solicit (const struct GNUNET_PeerIdentity *pid)
605 struct Session *session;
607 session = find_session (pid);
610 session->ready_to_transmit = GNUNET_YES;
611 try_transmission (session);
616 * Transmit a message to a particular peer.
618 * @param car original request that was queued and then solicited;
619 * this handle will now be 'owned' by the SESSIONS subsystem
620 * @param msg message to transmit
621 * @param cork is corking allowed?
624 GSC_SESSIONS_transmit (struct GSC_ClientActiveRequest *car,
625 const struct GNUNET_MessageHeader *msg, int cork)
627 struct Session *session;
628 struct SessionMessageEntry *sme;
631 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)
640 GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_MAX_CORK_DELAY);
641 GNUNET_CONTAINER_DLL_insert_tail (session->sme_head, session->sme_tail, sme);
642 try_transmission (session);
647 * Helper function for GSC_SESSIONS_handle_client_iterate_peers.
649 * @param cls the 'struct GNUNET_SERVER_TransmitContext' to queue replies
650 * @param key identity of the connected peer
651 * @param value the 'struct Neighbour' for the peer
652 * @return GNUNET_OK (continue to iterate)
656 queue_connect_message (void *cls, const struct GNUNET_HashCode * key, void *value)
658 struct GNUNET_SERVER_TransmitContext *tc = cls;
659 struct Session *session = value;
660 struct ConnectNotifyMessage cnm;
662 /* FIXME: code duplication with clients... */
663 cnm.header.size = htons (sizeof (struct ConnectNotifyMessage));
664 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT);
665 // FIXME: full ats...
666 cnm.ats_count = htonl (0);
667 cnm.peer = session->peer;
668 GNUNET_SERVER_transmit_context_append_message (tc, &cnm.header);
674 * Handle CORE_ITERATE_PEERS request. For this request type, the client
675 * does not have to have transmitted an INIT request. All current peers
676 * are 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_iterate_peers (void *cls,
684 struct GNUNET_SERVER_Client *client,
685 const struct GNUNET_MessageHeader
688 struct GNUNET_MessageHeader done_msg;
689 struct GNUNET_SERVER_TransmitContext *tc;
691 tc = GNUNET_SERVER_transmit_context_create (client);
692 GNUNET_CONTAINER_multihashmap_iterate (sessions, &queue_connect_message, tc);
693 done_msg.size = htons (sizeof (struct GNUNET_MessageHeader));
694 done_msg.type = htons (GNUNET_MESSAGE_TYPE_CORE_ITERATE_PEERS_END);
695 GNUNET_SERVER_transmit_context_append_message (tc, &done_msg);
696 GNUNET_SERVER_transmit_context_run (tc, GNUNET_TIME_UNIT_FOREVER_REL);
701 * Handle CORE_PEER_CONNECTED request. Notify client about connection
702 * to the given neighbour. For this request type, the client does not
703 * have to have transmitted an INIT request. All current peers are
704 * returned, regardless of which message types they accept.
707 * @param client client sending the iteration request
708 * @param message iteration request message
711 GSC_SESSIONS_handle_client_have_peer (void *cls,
712 struct GNUNET_SERVER_Client *client,
713 const struct GNUNET_MessageHeader
716 struct GNUNET_MessageHeader done_msg;
717 struct GNUNET_SERVER_TransmitContext *tc;
718 const struct GNUNET_PeerIdentity *peer;
720 peer = (const struct GNUNET_PeerIdentity *) &message[1]; // YUCK!
721 tc = GNUNET_SERVER_transmit_context_create (client);
722 GNUNET_CONTAINER_multihashmap_get_multiple (sessions, &peer->hashPubKey,
723 &queue_connect_message, tc);
724 done_msg.size = htons (sizeof (struct GNUNET_MessageHeader));
725 done_msg.type = htons (GNUNET_MESSAGE_TYPE_CORE_ITERATE_PEERS_END);
726 GNUNET_SERVER_transmit_context_append_message (tc, &done_msg);
727 GNUNET_SERVER_transmit_context_run (tc, GNUNET_TIME_UNIT_FOREVER_REL);
732 * We've received a typemap message from a peer, update ours.
733 * Notifies clients about the session.
735 * @param peer peer this is about
736 * @param msg typemap update message
739 GSC_SESSIONS_set_typemap (const struct GNUNET_PeerIdentity *peer,
740 const struct GNUNET_MessageHeader *msg)
742 struct Session *session;
743 struct GSC_TypeMap *nmap;
745 nmap = GSC_TYPEMAP_get_from_message (msg);
747 return; /* malformed */
748 session = find_session (peer);
754 GSC_CLIENTS_notify_clients_about_neighbour (peer, NULL, 0, /* FIXME: ATS */
755 session->tmap, nmap);
756 GSC_TYPEMAP_destroy (session->tmap);
757 session->tmap = nmap;
762 * The given peer send a message of the specified type. Make sure the
763 * respective bit is set in its type-map and that clients are notified
766 * @param peer peer this is about
767 * @param type type of the message
770 GSC_SESSIONS_add_to_typemap (const struct GNUNET_PeerIdentity *peer,
773 struct Session *session;
774 struct GSC_TypeMap *nmap;
776 if (0 == memcmp (peer, &GSC_my_identity, sizeof (struct GNUNET_PeerIdentity)))
778 session = find_session (peer);
779 GNUNET_assert (NULL != session);
780 if (GNUNET_YES == GSC_TYPEMAP_test_match (session->tmap, &type, 1))
781 return; /* already in it */
782 nmap = GSC_TYPEMAP_extend (session->tmap, &type, 1);
783 GSC_CLIENTS_notify_clients_about_neighbour (peer, NULL, 0, /* FIXME: ATS */
784 session->tmap, nmap);
785 GSC_TYPEMAP_destroy (session->tmap);
786 session->tmap = nmap;
791 * Initialize sessions subsystem.
796 sessions = GNUNET_CONTAINER_multihashmap_create (128, GNUNET_NO);
801 * Helper function for GSC_SESSIONS_handle_client_iterate_peers.
804 * @param key identity of the connected peer
805 * @param value the 'struct Session' for the peer
806 * @return GNUNET_OK (continue to iterate)
809 free_session_helper (void *cls, const struct GNUNET_HashCode * key, void *value)
811 struct Session *session = value;
813 GSC_SESSIONS_end (&session->peer);
819 * Shutdown sessions subsystem.
824 if (NULL != sessions)
826 GNUNET_CONTAINER_multihashmap_iterate (sessions, &free_session_helper, NULL);
827 GNUNET_CONTAINER_multihashmap_destroy (sessions);
832 /* end of gnunet-service-core_sessions.c */