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)
42 * Message ready for encryption. This struct is followed by the
43 * actual content of the message.
45 struct SessionMessageEntry
49 * We keep messages in a doubly linked list.
51 struct SessionMessageEntry *next;
54 * We keep messages in a doubly linked list.
56 struct SessionMessageEntry *prev;
59 * Deadline for transmission, 1s after we received it (if we
60 * are not corking), otherwise "now". Note that this message
61 * does NOT expire past its deadline.
63 struct GNUNET_TIME_Absolute deadline;
66 * How long is the message? (number of bytes following the "struct
67 * MessageEntry", but not including the size of "struct
68 * MessageEntry" itself!)
76 * Data kept per session.
81 * Identity of the other peer.
83 struct GNUNET_PeerIdentity peer;
86 * Head of list of requests from clients for transmission to
89 struct GSC_ClientActiveRequest *active_client_request_head;
92 * Tail of list of requests from clients for transmission to
95 struct GSC_ClientActiveRequest *active_client_request_tail;
98 * Head of list of messages ready for encryption.
100 struct SessionMessageEntry *sme_head;
103 * Tail of list of messages ready for encryption.
105 struct SessionMessageEntry *sme_tail;
108 * Information about the key exchange with the other peer.
110 struct GSC_KeyExchangeInfo *kxinfo;
113 * Current type map for this peer.
115 struct GSC_TypeMap *tmap;
118 * At what time did we initially establish this session?
119 * (currently unused, should be integrated with ATS in the
122 struct GNUNET_TIME_Absolute time_established;
125 * Task to transmit corked messages with a delay.
127 GNUNET_SCHEDULER_TaskIdentifier cork_task;
130 * Task to transmit our type map.
132 GNUNET_SCHEDULER_TaskIdentifier typemap_task;
135 * Is the neighbour queue empty and thus ready for us
136 * to transmit an encrypted message?
138 int ready_to_transmit;
144 * Map of peer identities to 'struct Session'.
146 static struct GNUNET_CONTAINER_MultiHashMap *sessions;
150 * Find the session for the given peer.
152 * @param peer identity of the peer
153 * @return NULL if we are not connected, otherwise the
156 static struct Session *
157 find_session (const struct GNUNET_PeerIdentity *peer)
159 return GNUNET_CONTAINER_multihashmap_get (sessions, &peer->hashPubKey);
164 * End the session with the given peer (we are no longer
167 * @param pid identity of peer to kill session with
170 GSC_SESSIONS_end (const struct GNUNET_PeerIdentity *pid)
172 struct Session *session;
173 struct GSC_ClientActiveRequest *car;
175 session = find_session (pid);
179 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
180 "Destroying session for peer `%4s'\n",
181 GNUNET_i2s (&session->peer));
183 if (GNUNET_SCHEDULER_NO_TASK != session->cork_task)
185 GNUNET_SCHEDULER_cancel (session->cork_task);
186 session->cork_task = GNUNET_SCHEDULER_NO_TASK;
188 while (NULL != (car = session->active_client_request_head))
190 GNUNET_CONTAINER_DLL_remove (session->active_client_request_head,
191 session->active_client_request_tail,
193 GSC_CLIENTS_reject_request (car);
195 GNUNET_SCHEDULER_cancel (session->typemap_task);
196 GNUNET_assert (GNUNET_YES ==
197 GNUNET_CONTAINER_multihashmap_remove (sessions,
198 &session->peer.hashPubKey, session));
199 GNUNET_STATISTICS_set (GSC_stats,
200 gettext_noop ("# entries in session map"),
201 GNUNET_CONTAINER_multihashmap_size (sessions),
203 if (NULL != session->tmap)
205 GSC_TYPEMAP_destroy (session->tmap);
206 session->tmap = NULL;
208 GNUNET_free (session);
213 * Transmit our current typemap message to the other peer.
214 * (Done periodically in case an update got lost).
216 * @param cls the 'struct Session*'
220 transmit_typemap_task (void *cls,
221 const struct GNUNET_SCHEDULER_TaskContext *tc)
223 struct Session *session = cls;
224 struct GNUNET_MessageHeader *hdr;
225 struct GNUNET_TIME_Relative delay;
227 delay = TYPEMAP_FREQUENCY;
228 /* randomize a bit to avoid spont. sync */
229 delay.rel_value += GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
231 session->typemap_task = GNUNET_SCHEDULER_add_delayed (delay,
232 &transmit_typemap_task,
234 hdr = GSC_TYPEMAP_compute_type_map_message ();
235 GSC_KX_encrypt_and_transmit (session->kxinfo,
243 * Create a session, a key exchange was just completed.
245 * @param peer peer that is now connected
246 * @param kx key exchange that completed
249 GSC_SESSIONS_create (const struct GNUNET_PeerIdentity *peer,
250 struct GSC_KeyExchangeInfo *kx)
252 struct Session *session;
255 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
256 "Creating session for peer `%4s'\n", GNUNET_i2s (peer));
258 session = GNUNET_malloc (sizeof (struct Session));
259 session->peer = *peer;
260 session->kxinfo = kx;
261 session->time_established = GNUNET_TIME_absolute_get ();
262 session->typemap_task = GNUNET_SCHEDULER_add_now (&transmit_typemap_task,
264 GNUNET_assert (GNUNET_OK ==
265 GNUNET_CONTAINER_multihashmap_put (sessions,
266 &peer->hashPubKey, session,
267 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
268 GNUNET_STATISTICS_update (GSC_stats,
269 gettext_noop ("# entries in session map"),
270 GNUNET_CONTAINER_multihashmap_size (sessions),
276 * Notify the given client about the session (client is new).
278 * @param cls the 'struct GSC_Client'
279 * @param key peer identity
280 * @param value the 'struct Session'
281 * @return GNUNET_OK (continue to iterate)
284 notify_client_about_session (void *cls,
285 const GNUNET_HashCode *key,
288 struct GSC_Client *client = cls;
289 struct Session *session = value;
291 GSC_CLIENTS_notify_client_about_neighbour (client,
293 NULL, 0, /* FIXME: ATS!? */
294 NULL, /* old TMAP: none */
301 * We have a new client, notify it about all current sessions.
303 * @param client the new client
306 GSC_SESSIONS_notify_client_about_sessions (struct GSC_Client *client)
308 /* notify new client about existing sessions */
309 GNUNET_CONTAINER_multihashmap_iterate (sessions,
310 ¬ify_client_about_session, client);
315 * Try to perform a transmission on the given session. Will solicit
316 * additional messages if the 'sme' queue is not full enough.
318 * @param session session to transmit messages from
321 try_transmission (struct Session *session);
325 * Queue a request from a client for transmission to a particular peer.
327 * @param car request to queue; this handle is then shared between
328 * the caller (CLIENTS subsystem) and SESSIONS and must not
329 * be released by either until either 'GNUNET_SESSIONS_dequeue',
330 * 'GNUNET_SESSIONS_transmit' or 'GNUNET_CLIENTS_failed'
331 * have been invoked on it
334 GSC_SESSIONS_queue_request (struct GSC_ClientActiveRequest *car)
336 struct Session *session;
338 session = find_session (&car->target);
341 /* neighbour must have disconnected since request was issued,
342 * ignore (client will realize it once it processes the
343 * disconnect notification) */
345 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
346 "Dropped client request for transmission (am disconnected)\n");
348 GNUNET_STATISTICS_update (GSC_stats,
350 ("# send requests dropped (disconnected)"), 1,
352 GSC_CLIENTS_reject_request (car);
355 if (car->msize > GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE)
358 GSC_CLIENTS_reject_request (car);
362 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
363 "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)
382 if (0 == memcmp (&car->target,
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,
422 GSC_CLIENTS_reject_request (pos);
429 * Solicit messages for transmission.
431 * @param session session to solict messages for
434 solicit_messages (struct Session *session)
436 struct GSC_ClientActiveRequest *car;
439 discard_expired_requests (session);
441 for (car = session->active_client_request_head; NULL != car; car = car->next)
443 if (so_size + car->msize > GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE)
445 so_size += car->msize;
446 if (car->was_solicited == GNUNET_YES)
448 car->was_solicited = GNUNET_YES;
449 GSC_CLIENTS_solicit_request (car);
455 * Some messages were delayed (corked), but the timeout has now expired.
458 * @param cls 'struct Session' with the messages to transmit now
459 * @param tc scheduler context (unused)
462 pop_cork_task (void *cls,
463 const struct GNUNET_SCHEDULER_TaskContext *tc)
465 struct Session *session = cls;
467 session->cork_task = GNUNET_SCHEDULER_NO_TASK;
468 try_transmission (session);
473 * Try to perform a transmission on the given session. Will solicit
474 * additional messages if the 'sme' queue is not full enough.
476 * @param session session to transmit messages from
479 try_transmission (struct Session *session)
481 struct SessionMessageEntry *pos;
483 struct GNUNET_TIME_Absolute now;
484 struct GNUNET_TIME_Absolute min_deadline;
486 if (GNUNET_YES != session->ready_to_transmit)
489 min_deadline = GNUNET_TIME_UNIT_FOREVER_ABS;
490 /* check 'ready' messages */
491 pos = session->sme_head;
492 while ( (NULL != pos) &&
493 (msize + pos->size <= GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE) )
495 GNUNET_assert (pos->size < GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE);
497 min_deadline = GNUNET_TIME_absolute_min (min_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);
514 session->cork_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_absolute_get_remaining (min_deadline),
520 /* create plaintext buffer of all messages, encrypt and transmit */
522 static unsigned long long total_bytes;
523 static unsigned int total_msgs;
524 char pbuf[msize]; /* plaintext */
528 while ( (NULL != (pos = session->sme_head)) &&
529 (used + pos->size <= msize) )
531 memcpy (&pbuf[used], &pos[1], pos->size);
533 GNUNET_CONTAINER_DLL_remove (session->sme_head,
538 /* compute average payload size */
543 /* 2^32 messages, wrap around... */
547 GNUNET_STATISTICS_set (GSC_stats,
548 "# avg payload per encrypted message",
549 total_bytes / total_msgs,
551 /* now actually transmit... */
552 session->ready_to_transmit = GNUNET_NO;
553 GSC_KX_encrypt_and_transmit (session->kxinfo,
561 * Send a message to the neighbour now.
563 * @param cls the message
564 * @param key neighbour's identity
565 * @param value 'struct Neighbour' of the target
566 * @return always GNUNET_OK
569 do_send_message (void *cls, const GNUNET_HashCode * key, void *value)
571 const struct GNUNET_MessageHeader *hdr = cls;
572 struct Session *session = value;
573 struct SessionMessageEntry *m;
576 size = ntohs (hdr->size);
577 m = GNUNET_malloc (sizeof (struct SessionMessageEntry) + size);
578 memcpy (&m[1], hdr, size);
580 GNUNET_CONTAINER_DLL_insert (session->sme_head,
583 try_transmission (session);
589 * Broadcast a message to all neighbours.
591 * @param msg message to transmit
594 GSC_SESSIONS_broadcast (const struct GNUNET_MessageHeader *msg)
596 if (NULL == sessions)
598 GNUNET_CONTAINER_multihashmap_iterate (sessions,
599 &do_send_message, (void*) msg);
604 * Traffic is being solicited for the given peer. This means that the
605 * message queue on the transport-level (NEIGHBOURS subsystem) is now
606 * empty and it is now OK to transmit another (non-control) message.
608 * @param pid identity of peer ready to receive data
611 GSC_SESSIONS_solicit (const struct GNUNET_PeerIdentity *pid)
613 struct Session *session;
615 session = find_session (pid);
618 session->ready_to_transmit = GNUNET_YES;
619 try_transmission (session);
624 * Transmit a message to a particular peer.
626 * @param car original request that was queued and then solicited;
627 * this handle will now be 'owned' by the SESSIONS subsystem
628 * @param msg message to transmit
629 * @param cork is corking allowed?
632 GSC_SESSIONS_transmit (struct GSC_ClientActiveRequest *car,
633 const struct GNUNET_MessageHeader *msg,
636 struct Session *session;
637 struct SessionMessageEntry *sme;
640 session = find_session (&car->target);
643 msize = ntohs (msg->size);
644 sme = GNUNET_malloc (sizeof (struct SessionMessageEntry) + msize);
645 memcpy (&sme[1], msg, msize);
647 if (GNUNET_YES == cork)
648 sme->deadline = GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_MAX_CORK_DELAY);
649 GNUNET_CONTAINER_DLL_insert_tail (session->sme_head,
652 try_transmission (session);
657 * Helper function for GSC_SESSIONS_handle_client_iterate_peers.
659 * @param cls the 'struct GNUNET_SERVER_TransmitContext' to queue replies
660 * @param key identity of the connected peer
661 * @param value the 'struct Neighbour' for the peer
662 * @return GNUNET_OK (continue to iterate)
666 queue_connect_message (void *cls, const GNUNET_HashCode * key, void *value)
668 struct GNUNET_SERVER_TransmitContext *tc = cls;
669 struct Session *session = value;
670 struct ConnectNotifyMessage cnm;
671 struct GNUNET_ATS_Information *a;
673 /* FIXME: code duplication with clients... */
674 cnm.header.size = htons (sizeof (struct ConnectNotifyMessage));
675 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT);
676 cnm.ats_count = htonl (0);
677 cnm.peer = session->peer;
679 // FIXME: full ats...
680 a[0].type = htonl (GNUNET_ATS_ARRAY_TERMINATOR);
681 a[0].value = htonl (0);
682 GNUNET_SERVER_transmit_context_append_message (tc, &cnm.header);
688 * Handle CORE_ITERATE_PEERS request. For this request type, the client
689 * does not have to have transmitted an INIT request. All current peers
690 * are returned, regardless of which message types they accept.
693 * @param client client sending the iteration request
694 * @param message iteration request message
697 GSC_SESSIONS_handle_client_iterate_peers (void *cls, struct GNUNET_SERVER_Client *client,
698 const struct GNUNET_MessageHeader *message)
700 struct GNUNET_MessageHeader done_msg;
701 struct GNUNET_SERVER_TransmitContext *tc;
703 tc = GNUNET_SERVER_transmit_context_create (client);
704 GNUNET_CONTAINER_multihashmap_iterate (sessions,
705 &queue_connect_message,
707 done_msg.size = htons (sizeof (struct GNUNET_MessageHeader));
708 done_msg.type = htons (GNUNET_MESSAGE_TYPE_CORE_ITERATE_PEERS_END);
709 GNUNET_SERVER_transmit_context_append_message (tc, &done_msg);
710 GNUNET_SERVER_transmit_context_run (tc, GNUNET_TIME_UNIT_FOREVER_REL);
715 * Handle CORE_PEER_CONNECTED request. Notify client about connection
716 * to the given neighbour. For this request type, the client does not
717 * have to have transmitted an INIT request. All current peers are
718 * returned, regardless of which message types they accept.
721 * @param client client sending the iteration request
722 * @param message iteration request message
725 GSC_SESSIONS_handle_client_have_peer (void *cls, struct GNUNET_SERVER_Client *client,
726 const struct GNUNET_MessageHeader *message)
728 struct GNUNET_MessageHeader done_msg;
729 struct GNUNET_SERVER_TransmitContext *tc;
730 const struct GNUNET_PeerIdentity *peer;
732 peer = (const struct GNUNET_PeerIdentity *) &message[1]; // YUCK!
733 tc = GNUNET_SERVER_transmit_context_create (client);
734 GNUNET_CONTAINER_multihashmap_get_multiple (sessions, &peer->hashPubKey,
735 &queue_connect_message, tc);
736 done_msg.size = htons (sizeof (struct GNUNET_MessageHeader));
737 done_msg.type = htons (GNUNET_MESSAGE_TYPE_CORE_ITERATE_PEERS_END);
738 GNUNET_SERVER_transmit_context_append_message (tc, &done_msg);
739 GNUNET_SERVER_transmit_context_run (tc, GNUNET_TIME_UNIT_FOREVER_REL);
744 * We've received a typemap message from a peer, update ours.
745 * Notifies clients about the session.
747 * @param peer peer this is about
748 * @param msg typemap update message
751 GSC_SESSIONS_set_typemap (const struct GNUNET_PeerIdentity *peer,
752 const struct GNUNET_MessageHeader *msg)
754 struct Session *session;
755 struct GSC_TypeMap *nmap;
757 nmap = GSC_TYPEMAP_get_from_message (msg);
759 return; /* malformed */
760 session = find_session (peer);
766 GSC_CLIENTS_notify_clients_about_neighbour (peer,
767 NULL, 0, /* FIXME: ATS */
770 if (NULL != session->tmap)
771 GSC_TYPEMAP_destroy (session->tmap);
772 session->tmap = nmap;
777 * The given peer send a message of the specified type. Make sure the
778 * respective bit is set in its type-map and that clients are notified
781 * @param peer peer this is about
782 * @param type type of the message
785 GSC_SESSIONS_add_to_typemap (const struct GNUNET_PeerIdentity *peer,
788 struct Session *session;
789 struct GSC_TypeMap *nmap;
791 if (0 == memcmp (peer, &GSC_my_identity, sizeof (struct GNUNET_PeerIdentity)))
793 session = find_session (peer);
794 GNUNET_assert (NULL != session);
796 GSC_TYPEMAP_test_match (session->tmap,
798 return; /* already in it */
799 nmap = GSC_TYPEMAP_extend (session->tmap,
801 GSC_CLIENTS_notify_clients_about_neighbour (peer,
802 NULL, 0, /* FIXME: ATS */
805 if (NULL != session->tmap)
806 GSC_TYPEMAP_destroy (session->tmap);
807 session->tmap = nmap;
812 * Initialize sessions subsystem.
817 sessions = GNUNET_CONTAINER_multihashmap_create (128);
822 * Helper function for GSC_SESSIONS_handle_client_iterate_peers.
825 * @param key identity of the connected peer
826 * @param value the 'struct Session' for the peer
827 * @return GNUNET_OK (continue to iterate)
830 free_session_helper (void *cls, const GNUNET_HashCode * key, void *value)
832 struct Session *session = value;
834 GSC_SESSIONS_end (&session->peer);
840 * Shutdown sessions subsystem.
845 GNUNET_CONTAINER_multihashmap_iterate (sessions,
846 &free_session_helper,
848 GNUNET_CONTAINER_multihashmap_destroy (sessions);
852 /* end of gnunet-service-core_sessions.c */