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_MultiPeerMap *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_multipeermap_get (sessions, peer);
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_multipeermap_remove (sessions,
208 GNUNET_STATISTICS_set (GSC_stats, gettext_noop ("# peers connected"),
209 GNUNET_CONTAINER_multipeermap_size (sessions),
211 GSC_TYPEMAP_destroy (session->tmap);
212 session->tmap = NULL;
213 GNUNET_free (session);
218 * Transmit our current typemap message to the other peer.
219 * (Done periodically in case an update got lost).
221 * @param cls the 'struct Session*'
225 transmit_typemap_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
227 struct Session *session = cls;
228 struct GNUNET_MessageHeader *hdr;
229 struct GNUNET_TIME_Relative delay;
231 if (0 == session->first_typemap)
233 delay = TYPEMAP_FREQUENCY_FIRST;
234 session->first_typemap = 1;
238 delay = TYPEMAP_FREQUENCY;
240 /* randomize a bit to avoid spont. sync */
241 delay.rel_value_us +=
242 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, 1000 * 1000);
243 session->typemap_task =
244 GNUNET_SCHEDULER_add_delayed (delay, &transmit_typemap_task, session);
245 GNUNET_STATISTICS_update (GSC_stats,
246 gettext_noop ("# type map refreshes sent"), 1,
248 hdr = GSC_TYPEMAP_compute_type_map_message ();
249 GSC_KX_encrypt_and_transmit (session->kxinfo, hdr, ntohs (hdr->size));
255 * Create a session, a key exchange was just completed.
257 * @param peer peer that is now connected
258 * @param kx key exchange that completed
261 GSC_SESSIONS_create (const struct GNUNET_PeerIdentity *peer,
262 struct GSC_KeyExchangeInfo *kx)
264 struct Session *session;
266 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Creating session for peer `%4s'\n",
268 session = GNUNET_new (struct Session);
269 session->tmap = GSC_TYPEMAP_create ();
270 session->peer = *peer;
271 session->kxinfo = kx;
272 session->typemap_task =
273 GNUNET_SCHEDULER_add_now (&transmit_typemap_task, session);
274 GNUNET_assert (GNUNET_OK ==
275 GNUNET_CONTAINER_multipeermap_put (sessions, peer,
277 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
278 GNUNET_STATISTICS_set (GSC_stats, gettext_noop ("# peers connected"),
279 GNUNET_CONTAINER_multipeermap_size (sessions),
281 GSC_CLIENTS_notify_clients_about_neighbour (peer,
282 NULL, session->tmap);
287 * Notify the given client about the session (client is new).
289 * @param cls the 'struct GSC_Client'
290 * @param key peer identity
291 * @param value the 'struct Session'
292 * @return GNUNET_OK (continue to iterate)
295 notify_client_about_session (void *cls, const struct GNUNET_PeerIdentity * key,
298 struct GSC_Client *client = cls;
299 struct Session *session = value;
301 GSC_CLIENTS_notify_client_about_neighbour (client, &session->peer,
302 NULL, /* old TMAP: none */
309 * We have a new client, notify it about all current sessions.
311 * @param client the new client
314 GSC_SESSIONS_notify_client_about_sessions (struct GSC_Client *client)
316 /* notify new client about existing sessions */
317 GNUNET_CONTAINER_multipeermap_iterate (sessions, ¬ify_client_about_session,
323 * Try to perform a transmission on the given session. Will solicit
324 * additional messages if the 'sme' queue is not full enough.
326 * @param session session to transmit messages from
329 try_transmission (struct Session *session);
333 * Queue a request from a client for transmission to a particular peer.
335 * @param car request to queue; this handle is then shared between
336 * the caller (CLIENTS subsystem) and SESSIONS and must not
337 * be released by either until either 'GNUNET_SESSIONS_dequeue',
338 * 'GNUNET_SESSIONS_transmit' or 'GNUNET_CLIENTS_failed'
339 * have been invoked on it
342 GSC_SESSIONS_queue_request (struct GSC_ClientActiveRequest *car)
344 struct Session *session;
346 session = find_session (&car->target);
349 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
350 "Dropped client request for transmission (am disconnected)\n");
351 GNUNET_break (0); /* should have been rejected earlier */
352 GSC_CLIENTS_reject_request (car);
355 if (car->msize > GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE)
358 GSC_CLIENTS_reject_request (car);
361 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
362 "Received client transmission request. queueing\n");
363 GNUNET_CONTAINER_DLL_insert (session->active_client_request_head,
364 session->active_client_request_tail, car);
365 try_transmission (session);
370 * Dequeue a request from a client from transmission to a particular peer.
372 * @param car request to dequeue; this handle will then be 'owned' by
373 * the caller (CLIENTS sysbsystem)
376 GSC_SESSIONS_dequeue_request (struct GSC_ClientActiveRequest *car)
381 memcmp (&car->target, &GSC_my_identity,
382 sizeof (struct GNUNET_PeerIdentity)))
384 s = find_session (&car->target);
385 GNUNET_assert (NULL != s);
386 GNUNET_CONTAINER_DLL_remove (s->active_client_request_head,
387 s->active_client_request_tail, car);
392 * Discard all expired active transmission requests from clients.
394 * @param session session to clean up
397 discard_expired_requests (struct Session *session)
399 struct GSC_ClientActiveRequest *pos;
400 struct GSC_ClientActiveRequest *nxt;
401 struct GNUNET_TIME_Absolute now;
403 now = GNUNET_TIME_absolute_get ();
405 nxt = session->active_client_request_head;
410 if ((pos->deadline.abs_value_us < now.abs_value_us) &&
411 (GNUNET_YES != pos->was_solicited))
413 GNUNET_STATISTICS_update (GSC_stats,
415 ("# messages discarded (expired prior to transmission)"),
417 GNUNET_CONTAINER_DLL_remove (session->active_client_request_head,
418 session->active_client_request_tail, pos);
419 GSC_CLIENTS_reject_request (pos);
426 * Solicit messages for transmission.
428 * @param session session to solict messages for
431 solicit_messages (struct Session *session)
433 struct GSC_ClientActiveRequest *car;
434 struct GSC_ClientActiveRequest *nxt;
437 discard_expired_requests (session);
439 nxt = session->active_client_request_head;
440 while (NULL != (car = nxt))
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, const struct GNUNET_SCHEDULER_TaskContext *tc)
464 struct Session *session = cls;
466 session->cork_task = GNUNET_SCHEDULER_NO_TASK;
467 try_transmission (session);
472 * Try to perform a transmission on the given session. Will solicit
473 * additional messages if the 'sme' queue is not full enough.
475 * @param session session to transmit messages from
478 try_transmission (struct Session *session)
480 struct SessionMessageEntry *pos;
482 struct GNUNET_TIME_Absolute now;
483 struct GNUNET_TIME_Absolute min_deadline;
485 if (GNUNET_YES != session->ready_to_transmit)
488 min_deadline = GNUNET_TIME_UNIT_FOREVER_ABS;
489 /* check 'ready' messages */
490 pos = session->sme_head;
491 while ((NULL != pos) &&
492 (msize + pos->size <= GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE))
494 GNUNET_assert (pos->size < GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE);
496 min_deadline = GNUNET_TIME_absolute_min (min_deadline, pos->deadline);
499 now = GNUNET_TIME_absolute_get ();
501 ((msize < GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE / 2) &&
502 (min_deadline.abs_value_us > now.abs_value_us)))
504 /* not enough ready yet, try to solicit more */
505 solicit_messages (session);
508 /* if there is data to send, just not yet, make sure we do transmit
509 * it once the deadline is reached */
510 if (session->cork_task != GNUNET_SCHEDULER_NO_TASK)
511 GNUNET_SCHEDULER_cancel (session->cork_task);
513 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_absolute_get_remaining
514 (min_deadline), &pop_cork_task,
519 /* create plaintext buffer of all messages, encrypt and transmit */
521 static unsigned long long total_bytes;
522 static unsigned int total_msgs;
523 char pbuf[msize]; /* plaintext */
527 while ((NULL != (pos = session->sme_head)) && (used + pos->size <= msize))
529 memcpy (&pbuf[used], &pos[1], pos->size);
531 GNUNET_CONTAINER_DLL_remove (session->sme_head, session->sme_tail, pos);
534 /* compute average payload size */
539 /* 2^32 messages, wrap around... */
543 GNUNET_STATISTICS_set (GSC_stats, "# avg payload per encrypted message",
544 total_bytes / total_msgs, GNUNET_NO);
545 /* now actually transmit... */
546 session->ready_to_transmit = GNUNET_NO;
547 GSC_KX_encrypt_and_transmit (session->kxinfo, pbuf, used);
553 * Send a message to the neighbour now.
555 * @param cls the message
556 * @param key neighbour's identity
557 * @param value 'struct Neighbour' of the target
558 * @return always GNUNET_OK
561 do_send_message (void *cls, const struct GNUNET_PeerIdentity * key, void *value)
563 const struct GNUNET_MessageHeader *hdr = cls;
564 struct Session *session = value;
565 struct SessionMessageEntry *m;
568 size = ntohs (hdr->size);
569 m = GNUNET_malloc (sizeof (struct SessionMessageEntry) + size);
570 memcpy (&m[1], hdr, size);
572 GNUNET_CONTAINER_DLL_insert (session->sme_head, session->sme_tail, m);
573 try_transmission (session);
579 * Broadcast a message to all neighbours.
581 * @param msg message to transmit
584 GSC_SESSIONS_broadcast (const struct GNUNET_MessageHeader *msg)
586 if (NULL == sessions)
588 GNUNET_CONTAINER_multipeermap_iterate (sessions, &do_send_message,
594 * Traffic is being solicited for the given peer. This means that the
595 * message queue on the transport-level (NEIGHBOURS subsystem) is now
596 * empty and it is now OK to transmit another (non-control) message.
598 * @param pid identity of peer ready to receive data
601 GSC_SESSIONS_solicit (const struct GNUNET_PeerIdentity *pid)
603 struct Session *session;
605 session = find_session (pid);
608 session->ready_to_transmit = GNUNET_YES;
609 try_transmission (session);
614 * Transmit a message to a particular peer.
616 * @param car original request that was queued and then solicited;
617 * this handle will now be 'owned' by the SESSIONS subsystem
618 * @param msg message to transmit
619 * @param cork is corking allowed?
622 GSC_SESSIONS_transmit (struct GSC_ClientActiveRequest *car,
623 const struct GNUNET_MessageHeader *msg, int cork)
625 struct Session *session;
626 struct SessionMessageEntry *sme;
629 session = find_session (&car->target);
632 msize = ntohs (msg->size);
633 sme = GNUNET_malloc (sizeof (struct SessionMessageEntry) + msize);
634 memcpy (&sme[1], msg, msize);
636 if (GNUNET_YES == cork)
638 GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_MAX_CORK_DELAY);
639 GNUNET_CONTAINER_DLL_insert_tail (session->sme_head, session->sme_tail, sme);
640 try_transmission (session);
645 * Helper function for GSC_SESSIONS_handle_client_iterate_peers.
647 * @param cls the 'struct GNUNET_SERVER_TransmitContext' to queue replies
648 * @param key identity of the connected peer
649 * @param value the 'struct Neighbour' for the peer
650 * @return GNUNET_OK (continue to iterate)
654 queue_connect_message (void *cls, const struct GNUNET_PeerIdentity * key, void *value)
656 struct GNUNET_SERVER_TransmitContext *tc = cls;
657 struct Session *session = value;
658 struct ConnectNotifyMessage cnm;
660 /* FIXME: code duplication with clients... */
661 cnm.header.size = htons (sizeof (struct ConnectNotifyMessage));
662 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT);
663 cnm.reserved = htonl (0);
664 cnm.peer = session->peer;
665 GNUNET_SERVER_transmit_context_append_message (tc, &cnm.header);
671 * Handle CORE_ITERATE_PEERS request. For this request type, the client
672 * does not have to have transmitted an INIT request. All current peers
673 * are returned, regardless of which message types they accept.
676 * @param client client sending the iteration request
677 * @param message iteration request message
680 GSC_SESSIONS_handle_client_iterate_peers (void *cls,
681 struct GNUNET_SERVER_Client *client,
682 const struct GNUNET_MessageHeader
685 struct GNUNET_MessageHeader done_msg;
686 struct GNUNET_SERVER_TransmitContext *tc;
688 tc = GNUNET_SERVER_transmit_context_create (client);
689 GNUNET_CONTAINER_multipeermap_iterate (sessions, &queue_connect_message, tc);
690 done_msg.size = htons (sizeof (struct GNUNET_MessageHeader));
691 done_msg.type = htons (GNUNET_MESSAGE_TYPE_CORE_ITERATE_PEERS_END);
692 GNUNET_SERVER_transmit_context_append_message (tc, &done_msg);
693 GNUNET_SERVER_transmit_context_run (tc, GNUNET_TIME_UNIT_FOREVER_REL);
698 * We've received a typemap message from a peer, update ours.
699 * Notifies clients about the session.
701 * @param peer peer this is about
702 * @param msg typemap update message
705 GSC_SESSIONS_set_typemap (const struct GNUNET_PeerIdentity *peer,
706 const struct GNUNET_MessageHeader *msg)
708 struct Session *session;
709 struct GSC_TypeMap *nmap;
711 nmap = GSC_TYPEMAP_get_from_message (msg);
713 return; /* malformed */
714 session = find_session (peer);
720 GSC_CLIENTS_notify_clients_about_neighbour (peer,
721 session->tmap, nmap);
722 GSC_TYPEMAP_destroy (session->tmap);
723 session->tmap = nmap;
728 * The given peer send a message of the specified type. Make sure the
729 * respective bit is set in its type-map and that clients are notified
732 * @param peer peer this is about
733 * @param type type of the message
736 GSC_SESSIONS_add_to_typemap (const struct GNUNET_PeerIdentity *peer,
739 struct Session *session;
740 struct GSC_TypeMap *nmap;
742 if (0 == memcmp (peer, &GSC_my_identity, sizeof (struct GNUNET_PeerIdentity)))
744 session = find_session (peer);
745 GNUNET_assert (NULL != session);
746 if (GNUNET_YES == GSC_TYPEMAP_test_match (session->tmap, &type, 1))
747 return; /* already in it */
748 nmap = GSC_TYPEMAP_extend (session->tmap, &type, 1);
749 GSC_CLIENTS_notify_clients_about_neighbour (peer,
750 session->tmap, nmap);
751 GSC_TYPEMAP_destroy (session->tmap);
752 session->tmap = nmap;
757 * Initialize sessions subsystem.
762 sessions = GNUNET_CONTAINER_multipeermap_create (128, GNUNET_NO);
767 * Helper function for GSC_SESSIONS_handle_client_iterate_peers.
770 * @param key identity of the connected peer
771 * @param value the 'struct Session' for the peer
772 * @return GNUNET_OK (continue to iterate)
775 free_session_helper (void *cls, const struct GNUNET_PeerIdentity * key, void *value)
777 struct Session *session = value;
779 GSC_SESSIONS_end (&session->peer);
785 * Shutdown sessions subsystem.
790 if (NULL != sessions)
792 GNUNET_CONTAINER_multipeermap_iterate (sessions, &free_session_helper, NULL);
793 GNUNET_CONTAINER_multipeermap_destroy (sessions);
798 /* end of gnunet-service-core_sessions.c */