2 This file is part of GNUnet.
3 (C) 2009-2013 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,
203 session->tmap, NULL);
204 GNUNET_assert (GNUNET_YES ==
205 GNUNET_CONTAINER_multihashmap_remove (sessions,
209 GNUNET_STATISTICS_set (GSC_stats, gettext_noop ("# peers connected"),
210 GNUNET_CONTAINER_multihashmap_size (sessions),
212 GSC_TYPEMAP_destroy (session->tmap);
213 session->tmap = NULL;
214 GNUNET_free (session);
219 * Transmit our current typemap message to the other peer.
220 * (Done periodically in case an update got lost).
222 * @param cls the 'struct Session*'
226 transmit_typemap_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
228 struct Session *session = cls;
229 struct GNUNET_MessageHeader *hdr;
230 struct GNUNET_TIME_Relative delay;
232 if (0 == session->first_typemap)
234 delay = TYPEMAP_FREQUENCY_FIRST;
235 session->first_typemap = 1;
239 delay = TYPEMAP_FREQUENCY;
241 /* randomize a bit to avoid spont. sync */
242 delay.rel_value_us +=
243 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, 1000 * 1000);
244 session->typemap_task =
245 GNUNET_SCHEDULER_add_delayed (delay, &transmit_typemap_task, session);
246 GNUNET_STATISTICS_update (GSC_stats,
247 gettext_noop ("# type map refreshes sent"), 1,
249 hdr = GSC_TYPEMAP_compute_type_map_message ();
250 GSC_KX_encrypt_and_transmit (session->kxinfo, hdr, ntohs (hdr->size));
256 * Create a session, a key exchange was just completed.
258 * @param peer peer that is now connected
259 * @param kx key exchange that completed
262 GSC_SESSIONS_create (const struct GNUNET_PeerIdentity *peer,
263 struct GSC_KeyExchangeInfo *kx)
265 struct Session *session;
267 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Creating session for peer `%4s'\n",
269 session = GNUNET_malloc (sizeof (struct Session));
270 session->tmap = GSC_TYPEMAP_create ();
271 session->peer = *peer;
272 session->kxinfo = kx;
273 session->typemap_task =
274 GNUNET_SCHEDULER_add_now (&transmit_typemap_task, session);
275 GNUNET_assert (GNUNET_OK ==
276 GNUNET_CONTAINER_multihashmap_put (sessions, &peer->hashPubKey,
278 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
279 GNUNET_STATISTICS_set (GSC_stats, gettext_noop ("# peers connected"),
280 GNUNET_CONTAINER_multihashmap_size (sessions),
282 GSC_CLIENTS_notify_clients_about_neighbour (peer,
283 NULL, session->tmap);
288 * Notify the given client about the session (client is new).
290 * @param cls the 'struct GSC_Client'
291 * @param key peer identity
292 * @param value the 'struct Session'
293 * @return GNUNET_OK (continue to iterate)
296 notify_client_about_session (void *cls, const struct GNUNET_HashCode * key,
299 struct GSC_Client *client = cls;
300 struct Session *session = value;
302 GSC_CLIENTS_notify_client_about_neighbour (client, &session->peer,
303 NULL, /* old TMAP: none */
310 * We have a new client, notify it about all current sessions.
312 * @param client the new client
315 GSC_SESSIONS_notify_client_about_sessions (struct GSC_Client *client)
317 /* notify new client about existing sessions */
318 GNUNET_CONTAINER_multihashmap_iterate (sessions, ¬ify_client_about_session,
324 * Try to perform a transmission on the given session. Will solicit
325 * additional messages if the 'sme' queue is not full enough.
327 * @param session session to transmit messages from
330 try_transmission (struct Session *session);
334 * Queue a request from a client for transmission to a particular peer.
336 * @param car request to queue; this handle is then shared between
337 * the caller (CLIENTS subsystem) and SESSIONS and must not
338 * be released by either until either 'GNUNET_SESSIONS_dequeue',
339 * 'GNUNET_SESSIONS_transmit' or 'GNUNET_CLIENTS_failed'
340 * have been invoked on it
343 GSC_SESSIONS_queue_request (struct GSC_ClientActiveRequest *car)
345 struct Session *session;
347 session = find_session (&car->target);
350 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
351 "Dropped client request for transmission (am disconnected)\n");
352 GNUNET_break (0); /* should have been rejected earlier */
353 GSC_CLIENTS_reject_request (car);
356 if (car->msize > GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE)
359 GSC_CLIENTS_reject_request (car);
362 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
363 "Received client transmission request. queueing\n");
364 GNUNET_CONTAINER_DLL_insert (session->active_client_request_head,
365 session->active_client_request_tail, car);
366 try_transmission (session);
371 * Dequeue a request from a client from transmission to a particular peer.
373 * @param car request to dequeue; this handle will then be 'owned' by
374 * the caller (CLIENTS sysbsystem)
377 GSC_SESSIONS_dequeue_request (struct GSC_ClientActiveRequest *car)
382 memcmp (&car->target, &GSC_my_identity,
383 sizeof (struct GNUNET_PeerIdentity)))
385 s = find_session (&car->target);
386 GNUNET_assert (NULL != s);
387 GNUNET_CONTAINER_DLL_remove (s->active_client_request_head,
388 s->active_client_request_tail, car);
393 * Discard all expired active transmission requests from clients.
395 * @param session session to clean up
398 discard_expired_requests (struct Session *session)
400 struct GSC_ClientActiveRequest *pos;
401 struct GSC_ClientActiveRequest *nxt;
402 struct GNUNET_TIME_Absolute now;
404 now = GNUNET_TIME_absolute_get ();
406 nxt = session->active_client_request_head;
411 if ((pos->deadline.abs_value_us < now.abs_value_us) &&
412 (GNUNET_YES != pos->was_solicited))
414 GNUNET_STATISTICS_update (GSC_stats,
416 ("# messages discarded (expired prior to transmission)"),
418 GNUNET_CONTAINER_DLL_remove (session->active_client_request_head,
419 session->active_client_request_tail, pos);
420 GSC_CLIENTS_reject_request (pos);
427 * Solicit messages for transmission.
429 * @param session session to solict messages for
432 solicit_messages (struct Session *session)
434 struct GSC_ClientActiveRequest *car;
435 struct GSC_ClientActiveRequest *nxt;
438 discard_expired_requests (session);
440 nxt = session->active_client_request_head;
441 while (NULL != (car = nxt))
444 if (so_size + car->msize > GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE)
446 so_size += car->msize;
447 if (car->was_solicited == GNUNET_YES)
449 car->was_solicited = GNUNET_YES;
450 GSC_CLIENTS_solicit_request (car);
456 * Some messages were delayed (corked), but the timeout has now expired.
459 * @param cls 'struct Session' with the messages to transmit now
460 * @param tc scheduler context (unused)
463 pop_cork_task (void *cls, 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, pos->deadline);
500 now = GNUNET_TIME_absolute_get ();
502 ((msize < GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE / 2) &&
503 (min_deadline.abs_value_us > now.abs_value_us)))
505 /* not enough ready yet, try to solicit more */
506 solicit_messages (session);
509 /* if there is data to send, just not yet, make sure we do transmit
510 * it once the deadline is reached */
511 if (session->cork_task != GNUNET_SCHEDULER_NO_TASK)
512 GNUNET_SCHEDULER_cancel (session->cork_task);
514 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_absolute_get_remaining
515 (min_deadline), &pop_cork_task,
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)) && (used + pos->size <= msize))
530 memcpy (&pbuf[used], &pos[1], pos->size);
532 GNUNET_CONTAINER_DLL_remove (session->sme_head, session->sme_tail, pos);
535 /* compute average payload size */
540 /* 2^32 messages, wrap around... */
544 GNUNET_STATISTICS_set (GSC_stats, "# avg payload per encrypted message",
545 total_bytes / total_msgs, GNUNET_NO);
546 /* now actually transmit... */
547 session->ready_to_transmit = GNUNET_NO;
548 GSC_KX_encrypt_and_transmit (session->kxinfo, pbuf, used);
554 * Send a message to the neighbour now.
556 * @param cls the message
557 * @param key neighbour's identity
558 * @param value 'struct Neighbour' of the target
559 * @return always GNUNET_OK
562 do_send_message (void *cls, const struct GNUNET_HashCode * key, void *value)
564 const struct GNUNET_MessageHeader *hdr = cls;
565 struct Session *session = value;
566 struct SessionMessageEntry *m;
569 size = ntohs (hdr->size);
570 m = GNUNET_malloc (sizeof (struct SessionMessageEntry) + size);
571 memcpy (&m[1], hdr, size);
573 GNUNET_CONTAINER_DLL_insert (session->sme_head, session->sme_tail, m);
574 try_transmission (session);
580 * Broadcast a message to all neighbours.
582 * @param msg message to transmit
585 GSC_SESSIONS_broadcast (const struct GNUNET_MessageHeader *msg)
587 if (NULL == sessions)
589 GNUNET_CONTAINER_multihashmap_iterate (sessions, &do_send_message,
595 * Traffic is being solicited for the given peer. This means that the
596 * message queue on the transport-level (NEIGHBOURS subsystem) is now
597 * empty and it is now OK to transmit another (non-control) message.
599 * @param pid identity of peer ready to receive data
602 GSC_SESSIONS_solicit (const struct GNUNET_PeerIdentity *pid)
604 struct Session *session;
606 session = find_session (pid);
609 session->ready_to_transmit = GNUNET_YES;
610 try_transmission (session);
615 * Transmit a message to a particular peer.
617 * @param car original request that was queued and then solicited;
618 * this handle will now be 'owned' by the SESSIONS subsystem
619 * @param msg message to transmit
620 * @param cork is corking allowed?
623 GSC_SESSIONS_transmit (struct GSC_ClientActiveRequest *car,
624 const struct GNUNET_MessageHeader *msg, int cork)
626 struct Session *session;
627 struct SessionMessageEntry *sme;
630 session = find_session (&car->target);
633 msize = ntohs (msg->size);
634 sme = GNUNET_malloc (sizeof (struct SessionMessageEntry) + msize);
635 memcpy (&sme[1], msg, msize);
637 if (GNUNET_YES == cork)
639 GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_MAX_CORK_DELAY);
640 GNUNET_CONTAINER_DLL_insert_tail (session->sme_head, session->sme_tail, sme);
641 try_transmission (session);
646 * Helper function for GSC_SESSIONS_handle_client_iterate_peers.
648 * @param cls the 'struct GNUNET_SERVER_TransmitContext' to queue replies
649 * @param key identity of the connected peer
650 * @param value the 'struct Neighbour' for the peer
651 * @return GNUNET_OK (continue to iterate)
655 queue_connect_message (void *cls, const struct GNUNET_HashCode * key, void *value)
657 struct GNUNET_SERVER_TransmitContext *tc = cls;
658 struct Session *session = value;
659 struct ConnectNotifyMessage cnm;
661 /* FIXME: code duplication with clients... */
662 cnm.header.size = htons (sizeof (struct ConnectNotifyMessage));
663 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT);
664 cnm.reserved = htonl (0);
665 cnm.peer = session->peer;
666 GNUNET_SERVER_transmit_context_append_message (tc, &cnm.header);
672 * Handle CORE_ITERATE_PEERS request. For this request type, the client
673 * does not have to have transmitted an INIT request. All current peers
674 * are returned, regardless of which message types they accept.
677 * @param client client sending the iteration request
678 * @param message iteration request message
681 GSC_SESSIONS_handle_client_iterate_peers (void *cls,
682 struct GNUNET_SERVER_Client *client,
683 const struct GNUNET_MessageHeader
686 struct GNUNET_MessageHeader done_msg;
687 struct GNUNET_SERVER_TransmitContext *tc;
689 tc = GNUNET_SERVER_transmit_context_create (client);
690 GNUNET_CONTAINER_multihashmap_iterate (sessions, &queue_connect_message, tc);
691 done_msg.size = htons (sizeof (struct GNUNET_MessageHeader));
692 done_msg.type = htons (GNUNET_MESSAGE_TYPE_CORE_ITERATE_PEERS_END);
693 GNUNET_SERVER_transmit_context_append_message (tc, &done_msg);
694 GNUNET_SERVER_transmit_context_run (tc, GNUNET_TIME_UNIT_FOREVER_REL);
699 * We've received a typemap message from a peer, update ours.
700 * Notifies clients about the session.
702 * @param peer peer this is about
703 * @param msg typemap update message
706 GSC_SESSIONS_set_typemap (const struct GNUNET_PeerIdentity *peer,
707 const struct GNUNET_MessageHeader *msg)
709 struct Session *session;
710 struct GSC_TypeMap *nmap;
712 nmap = GSC_TYPEMAP_get_from_message (msg);
714 return; /* malformed */
715 session = find_session (peer);
721 GSC_CLIENTS_notify_clients_about_neighbour (peer,
722 session->tmap, nmap);
723 GSC_TYPEMAP_destroy (session->tmap);
724 session->tmap = nmap;
729 * The given peer send a message of the specified type. Make sure the
730 * respective bit is set in its type-map and that clients are notified
733 * @param peer peer this is about
734 * @param type type of the message
737 GSC_SESSIONS_add_to_typemap (const struct GNUNET_PeerIdentity *peer,
740 struct Session *session;
741 struct GSC_TypeMap *nmap;
743 if (0 == memcmp (peer, &GSC_my_identity, sizeof (struct GNUNET_PeerIdentity)))
745 session = find_session (peer);
746 GNUNET_assert (NULL != session);
747 if (GNUNET_YES == GSC_TYPEMAP_test_match (session->tmap, &type, 1))
748 return; /* already in it */
749 nmap = GSC_TYPEMAP_extend (session->tmap, &type, 1);
750 GSC_CLIENTS_notify_clients_about_neighbour (peer,
751 session->tmap, nmap);
752 GSC_TYPEMAP_destroy (session->tmap);
753 session->tmap = nmap;
758 * Initialize sessions subsystem.
763 sessions = GNUNET_CONTAINER_multihashmap_create (128, GNUNET_NO);
768 * Helper function for GSC_SESSIONS_handle_client_iterate_peers.
771 * @param key identity of the connected peer
772 * @param value the 'struct Session' for the peer
773 * @return GNUNET_OK (continue to iterate)
776 free_session_helper (void *cls, const struct GNUNET_HashCode * key, void *value)
778 struct Session *session = value;
780 GSC_SESSIONS_end (&session->peer);
786 * Shutdown sessions subsystem.
791 if (NULL != sessions)
793 GNUNET_CONTAINER_multihashmap_iterate (sessions, &free_session_helper, NULL);
794 GNUNET_CONTAINER_multihashmap_destroy (sessions);
799 /* end of gnunet-service-core_sessions.c */