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 GSC_CLIENTS_notify_clients_about_neighbour (&session->peer,
197 NULL, 0 /* FIXME: ATSI */,
200 GNUNET_assert (GNUNET_YES ==
201 GNUNET_CONTAINER_multihashmap_remove (sessions,
202 &session->peer.hashPubKey, session));
203 GNUNET_STATISTICS_set (GSC_stats,
204 gettext_noop ("# entries in session map"),
205 GNUNET_CONTAINER_multihashmap_size (sessions),
207 GSC_TYPEMAP_destroy (session->tmap);
208 session->tmap = NULL;
209 GNUNET_free (session);
214 * Transmit our current typemap message to the other peer.
215 * (Done periodically in case an update got lost).
217 * @param cls the 'struct Session*'
221 transmit_typemap_task (void *cls,
222 const struct GNUNET_SCHEDULER_TaskContext *tc)
224 struct Session *session = cls;
225 struct GNUNET_MessageHeader *hdr;
226 struct GNUNET_TIME_Relative delay;
228 delay = TYPEMAP_FREQUENCY;
229 /* randomize a bit to avoid spont. sync */
230 delay.rel_value += GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
232 session->typemap_task = GNUNET_SCHEDULER_add_delayed (delay,
233 &transmit_typemap_task,
235 GNUNET_STATISTICS_update (GSC_stats,
236 gettext_noop ("# type map refreshes sent"),
239 hdr = GSC_TYPEMAP_compute_type_map_message ();
240 GSC_KX_encrypt_and_transmit (session->kxinfo,
248 * Create a session, a key exchange was just completed.
250 * @param peer peer that is now connected
251 * @param kx key exchange that completed
254 GSC_SESSIONS_create (const struct GNUNET_PeerIdentity *peer,
255 struct GSC_KeyExchangeInfo *kx)
257 struct Session *session;
260 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
261 "Creating session for peer `%4s'\n", GNUNET_i2s (peer));
263 session = GNUNET_malloc (sizeof (struct Session));
264 session->tmap = GSC_TYPEMAP_create ();
265 session->peer = *peer;
266 session->kxinfo = kx;
267 session->time_established = GNUNET_TIME_absolute_get ();
268 session->typemap_task = GNUNET_SCHEDULER_add_now (&transmit_typemap_task,
270 GNUNET_assert (GNUNET_OK ==
271 GNUNET_CONTAINER_multihashmap_put (sessions,
272 &peer->hashPubKey, session,
273 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
274 GNUNET_STATISTICS_set (GSC_stats,
275 gettext_noop ("# entries in session map"),
276 GNUNET_CONTAINER_multihashmap_size (sessions),
278 GSC_CLIENTS_notify_clients_about_neighbour (peer,
279 NULL, 0 /* FIXME: ATSI */,
286 * Notify the given client about the session (client is new).
288 * @param cls the 'struct GSC_Client'
289 * @param key peer identity
290 * @param value the 'struct Session'
291 * @return GNUNET_OK (continue to iterate)
294 notify_client_about_session (void *cls,
295 const GNUNET_HashCode *key,
298 struct GSC_Client *client = cls;
299 struct Session *session = value;
301 GSC_CLIENTS_notify_client_about_neighbour (client,
303 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,
320 ¬ify_client_about_session, client);
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 /* neighbour must have disconnected since request was issued,
352 * ignore (client will realize it once it processes the
353 * disconnect notification) */
355 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
356 "Dropped client request for transmission (am disconnected)\n");
358 GNUNET_STATISTICS_update (GSC_stats,
360 ("# send requests dropped (disconnected)"), 1,
362 GSC_CLIENTS_reject_request (car);
365 if (car->msize > GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE)
368 GSC_CLIENTS_reject_request (car);
372 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
373 "Received client transmission request. queueing\n");
375 GNUNET_CONTAINER_DLL_insert (session->active_client_request_head,
376 session->active_client_request_tail, car);
377 try_transmission (session);
382 * Dequeue a request from a client from transmission to a particular peer.
384 * @param car request to dequeue; this handle will then be 'owned' by
385 * the caller (CLIENTS sysbsystem)
388 GSC_SESSIONS_dequeue_request (struct GSC_ClientActiveRequest *car)
392 if (0 == memcmp (&car->target,
394 sizeof (struct GNUNET_PeerIdentity)))
396 s = find_session (&car->target);
397 GNUNET_assert (NULL != s);
398 GNUNET_CONTAINER_DLL_remove (s->active_client_request_head,
399 s->active_client_request_tail, car);
404 * Discard all expired active transmission requests from clients.
406 * @param session session to clean up
409 discard_expired_requests (struct Session *session)
411 struct GSC_ClientActiveRequest *pos;
412 struct GSC_ClientActiveRequest *nxt;
413 struct GNUNET_TIME_Absolute now;
415 now = GNUNET_TIME_absolute_get ();
417 nxt = session->active_client_request_head;
422 if ( (pos->deadline.abs_value < now.abs_value) &&
423 (GNUNET_YES != pos->was_solicited) )
425 GNUNET_STATISTICS_update (GSC_stats,
427 ("# messages discarded (expired prior to transmission)"),
429 GNUNET_CONTAINER_DLL_remove (session->active_client_request_head,
430 session->active_client_request_tail,
432 GSC_CLIENTS_reject_request (pos);
439 * Solicit messages for transmission.
441 * @param session session to solict messages for
444 solicit_messages (struct Session *session)
446 struct GSC_ClientActiveRequest *car;
449 discard_expired_requests (session);
451 for (car = session->active_client_request_head; NULL != car; car = car->next)
453 if (so_size + car->msize > GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE)
455 so_size += car->msize;
456 if (car->was_solicited == GNUNET_YES)
458 car->was_solicited = GNUNET_YES;
459 GSC_CLIENTS_solicit_request (car);
465 * Some messages were delayed (corked), but the timeout has now expired.
468 * @param cls 'struct Session' with the messages to transmit now
469 * @param tc scheduler context (unused)
472 pop_cork_task (void *cls,
473 const struct GNUNET_SCHEDULER_TaskContext *tc)
475 struct Session *session = cls;
477 session->cork_task = GNUNET_SCHEDULER_NO_TASK;
478 try_transmission (session);
483 * Try to perform a transmission on the given session. Will solicit
484 * additional messages if the 'sme' queue is not full enough.
486 * @param session session to transmit messages from
489 try_transmission (struct Session *session)
491 struct SessionMessageEntry *pos;
493 struct GNUNET_TIME_Absolute now;
494 struct GNUNET_TIME_Absolute min_deadline;
496 if (GNUNET_YES != session->ready_to_transmit)
499 min_deadline = GNUNET_TIME_UNIT_FOREVER_ABS;
500 /* check 'ready' messages */
501 pos = session->sme_head;
502 while ( (NULL != pos) &&
503 (msize + pos->size <= GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE) )
505 GNUNET_assert (pos->size < GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE);
507 min_deadline = GNUNET_TIME_absolute_min (min_deadline,
511 now = GNUNET_TIME_absolute_get ();
513 ( (msize < GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE / 2) &&
514 (min_deadline.abs_value > now.abs_value) ) )
516 /* not enough ready yet, try to solicit more */
517 solicit_messages (session);
520 /* if there is data to send, just not yet, make sure we do transmit
521 it once the deadline is reached */
522 if (session->cork_task != GNUNET_SCHEDULER_NO_TASK)
523 GNUNET_SCHEDULER_cancel (session->cork_task);
524 session->cork_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_absolute_get_remaining (min_deadline),
530 /* create plaintext buffer of all messages, encrypt and transmit */
532 static unsigned long long total_bytes;
533 static unsigned int total_msgs;
534 char pbuf[msize]; /* plaintext */
538 while ( (NULL != (pos = session->sme_head)) &&
539 (used + pos->size <= msize) )
541 memcpy (&pbuf[used], &pos[1], pos->size);
543 GNUNET_CONTAINER_DLL_remove (session->sme_head,
548 /* compute average payload size */
553 /* 2^32 messages, wrap around... */
557 GNUNET_STATISTICS_set (GSC_stats,
558 "# avg payload per encrypted message",
559 total_bytes / total_msgs,
561 /* now actually transmit... */
562 session->ready_to_transmit = GNUNET_NO;
563 GSC_KX_encrypt_and_transmit (session->kxinfo,
571 * Send a message to the neighbour now.
573 * @param cls the message
574 * @param key neighbour's identity
575 * @param value 'struct Neighbour' of the target
576 * @return always GNUNET_OK
579 do_send_message (void *cls, const GNUNET_HashCode * key, void *value)
581 const struct GNUNET_MessageHeader *hdr = cls;
582 struct Session *session = value;
583 struct SessionMessageEntry *m;
586 size = ntohs (hdr->size);
587 m = GNUNET_malloc (sizeof (struct SessionMessageEntry) + size);
588 memcpy (&m[1], hdr, size);
590 GNUNET_CONTAINER_DLL_insert (session->sme_head,
593 try_transmission (session);
599 * Broadcast a message to all neighbours.
601 * @param msg message to transmit
604 GSC_SESSIONS_broadcast (const struct GNUNET_MessageHeader *msg)
606 if (NULL == sessions)
608 GNUNET_CONTAINER_multihashmap_iterate (sessions,
609 &do_send_message, (void*) msg);
614 * Traffic is being solicited for the given peer. This means that the
615 * message queue on the transport-level (NEIGHBOURS subsystem) is now
616 * empty and it is now OK to transmit another (non-control) message.
618 * @param pid identity of peer ready to receive data
621 GSC_SESSIONS_solicit (const struct GNUNET_PeerIdentity *pid)
623 struct Session *session;
625 session = find_session (pid);
628 session->ready_to_transmit = GNUNET_YES;
629 try_transmission (session);
634 * Transmit a message to a particular peer.
636 * @param car original request that was queued and then solicited;
637 * this handle will now be 'owned' by the SESSIONS subsystem
638 * @param msg message to transmit
639 * @param cork is corking allowed?
642 GSC_SESSIONS_transmit (struct GSC_ClientActiveRequest *car,
643 const struct GNUNET_MessageHeader *msg,
646 struct Session *session;
647 struct SessionMessageEntry *sme;
650 session = find_session (&car->target);
653 msize = ntohs (msg->size);
654 sme = GNUNET_malloc (sizeof (struct SessionMessageEntry) + msize);
655 memcpy (&sme[1], msg, msize);
657 if (GNUNET_YES == cork)
658 sme->deadline = GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_MAX_CORK_DELAY);
659 GNUNET_CONTAINER_DLL_insert_tail (session->sme_head,
662 try_transmission (session);
667 * Helper function for GSC_SESSIONS_handle_client_iterate_peers.
669 * @param cls the 'struct GNUNET_SERVER_TransmitContext' to queue replies
670 * @param key identity of the connected peer
671 * @param value the 'struct Neighbour' for the peer
672 * @return GNUNET_OK (continue to iterate)
676 queue_connect_message (void *cls, const GNUNET_HashCode * key, void *value)
678 struct GNUNET_SERVER_TransmitContext *tc = cls;
679 struct Session *session = value;
680 struct ConnectNotifyMessage cnm;
682 /* FIXME: code duplication with clients... */
683 cnm.header.size = htons (sizeof (struct ConnectNotifyMessage));
684 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT);
685 // FIXME: full ats...
686 cnm.ats_count = htonl (0);
687 cnm.peer = session->peer;
688 GNUNET_SERVER_transmit_context_append_message (tc, &cnm.header);
694 * Handle CORE_ITERATE_PEERS request. For this request type, the client
695 * does not have to have transmitted an INIT request. All current peers
696 * are returned, regardless of which message types they accept.
699 * @param client client sending the iteration request
700 * @param message iteration request message
703 GSC_SESSIONS_handle_client_iterate_peers (void *cls, struct GNUNET_SERVER_Client *client,
704 const struct GNUNET_MessageHeader *message)
706 struct GNUNET_MessageHeader done_msg;
707 struct GNUNET_SERVER_TransmitContext *tc;
709 tc = GNUNET_SERVER_transmit_context_create (client);
710 GNUNET_CONTAINER_multihashmap_iterate (sessions,
711 &queue_connect_message,
713 done_msg.size = htons (sizeof (struct GNUNET_MessageHeader));
714 done_msg.type = htons (GNUNET_MESSAGE_TYPE_CORE_ITERATE_PEERS_END);
715 GNUNET_SERVER_transmit_context_append_message (tc, &done_msg);
716 GNUNET_SERVER_transmit_context_run (tc, GNUNET_TIME_UNIT_FOREVER_REL);
721 * Handle CORE_PEER_CONNECTED request. Notify client about connection
722 * to the given neighbour. For this request type, the client does not
723 * have to have transmitted an INIT request. All current peers are
724 * returned, regardless of which message types they accept.
727 * @param client client sending the iteration request
728 * @param message iteration request message
731 GSC_SESSIONS_handle_client_have_peer (void *cls, struct GNUNET_SERVER_Client *client,
732 const struct GNUNET_MessageHeader *message)
734 struct GNUNET_MessageHeader done_msg;
735 struct GNUNET_SERVER_TransmitContext *tc;
736 const struct GNUNET_PeerIdentity *peer;
738 peer = (const struct GNUNET_PeerIdentity *) &message[1]; // YUCK!
739 tc = GNUNET_SERVER_transmit_context_create (client);
740 GNUNET_CONTAINER_multihashmap_get_multiple (sessions, &peer->hashPubKey,
741 &queue_connect_message, tc);
742 done_msg.size = htons (sizeof (struct GNUNET_MessageHeader));
743 done_msg.type = htons (GNUNET_MESSAGE_TYPE_CORE_ITERATE_PEERS_END);
744 GNUNET_SERVER_transmit_context_append_message (tc, &done_msg);
745 GNUNET_SERVER_transmit_context_run (tc, GNUNET_TIME_UNIT_FOREVER_REL);
750 * We've received a typemap message from a peer, update ours.
751 * Notifies clients about the session.
753 * @param peer peer this is about
754 * @param msg typemap update message
757 GSC_SESSIONS_set_typemap (const struct GNUNET_PeerIdentity *peer,
758 const struct GNUNET_MessageHeader *msg)
760 struct Session *session;
761 struct GSC_TypeMap *nmap;
763 nmap = GSC_TYPEMAP_get_from_message (msg);
765 return; /* malformed */
766 session = find_session (peer);
772 GSC_CLIENTS_notify_clients_about_neighbour (peer,
773 NULL, 0, /* FIXME: ATS */
776 GSC_TYPEMAP_destroy (session->tmap);
777 session->tmap = nmap;
782 * The given peer send a message of the specified type. Make sure the
783 * respective bit is set in its type-map and that clients are notified
786 * @param peer peer this is about
787 * @param type type of the message
790 GSC_SESSIONS_add_to_typemap (const struct GNUNET_PeerIdentity *peer,
793 struct Session *session;
794 struct GSC_TypeMap *nmap;
796 if (0 == memcmp (peer, &GSC_my_identity, sizeof (struct GNUNET_PeerIdentity)))
798 session = find_session (peer);
799 GNUNET_assert (NULL != session);
801 GSC_TYPEMAP_test_match (session->tmap,
803 return; /* already in it */
804 nmap = GSC_TYPEMAP_extend (session->tmap,
806 GSC_CLIENTS_notify_clients_about_neighbour (peer,
807 NULL, 0, /* FIXME: ATS */
810 GSC_TYPEMAP_destroy (session->tmap);
811 session->tmap = nmap;
816 * Initialize sessions subsystem.
821 sessions = GNUNET_CONTAINER_multihashmap_create (128);
826 * Helper function for GSC_SESSIONS_handle_client_iterate_peers.
829 * @param key identity of the connected peer
830 * @param value the 'struct Session' for the peer
831 * @return GNUNET_OK (continue to iterate)
834 free_session_helper (void *cls, const GNUNET_HashCode * key, void *value)
836 struct Session *session = value;
838 GSC_SESSIONS_end (&session->peer);
844 * Shutdown sessions subsystem.
849 GNUNET_CONTAINER_multihashmap_iterate (sessions,
850 &free_session_helper,
852 GNUNET_CONTAINER_multihashmap_destroy (sessions);
856 /* end of gnunet-service-core_sessions.c */