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;
174 struct SessionMessageEntry *sme;
176 session = find_session (pid);
179 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Destroying session for peer `%4s'\n",
180 GNUNET_i2s (&session->peer));
181 if (GNUNET_SCHEDULER_NO_TASK != session->cork_task)
183 GNUNET_SCHEDULER_cancel (session->cork_task);
184 session->cork_task = GNUNET_SCHEDULER_NO_TASK;
186 while (NULL != (car = session->active_client_request_head))
188 GNUNET_CONTAINER_DLL_remove (session->active_client_request_head,
189 session->active_client_request_tail, car);
190 GSC_CLIENTS_reject_request (car);
192 while (NULL != (sme = session->sme_head))
194 GNUNET_CONTAINER_DLL_remove (session->sme_head, session->sme_tail, sme);
197 GNUNET_SCHEDULER_cancel (session->typemap_task);
198 GSC_CLIENTS_notify_clients_about_neighbour (&session->peer, NULL,
199 0 /* FIXME: ATSI */ ,
200 session->tmap, NULL);
201 GNUNET_assert (GNUNET_YES ==
202 GNUNET_CONTAINER_multihashmap_remove (sessions,
206 GNUNET_STATISTICS_set (GSC_stats, gettext_noop ("# peers connected"),
207 GNUNET_CONTAINER_multihashmap_size (sessions),
209 GSC_TYPEMAP_destroy (session->tmap);
210 session->tmap = NULL;
211 GNUNET_free (session);
216 * Transmit our current typemap message to the other peer.
217 * (Done periodically in case an update got lost).
219 * @param cls the 'struct Session*'
223 transmit_typemap_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
225 struct Session *session = cls;
226 struct GNUNET_MessageHeader *hdr;
227 struct GNUNET_TIME_Relative delay;
229 delay = TYPEMAP_FREQUENCY;
230 /* randomize a bit to avoid spont. sync */
232 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, 1000);
233 session->typemap_task =
234 GNUNET_SCHEDULER_add_delayed (delay, &transmit_typemap_task, session);
235 GNUNET_STATISTICS_update (GSC_stats,
236 gettext_noop ("# type map refreshes sent"), 1,
238 hdr = GSC_TYPEMAP_compute_type_map_message ();
239 GSC_KX_encrypt_and_transmit (session->kxinfo, hdr, ntohs (hdr->size));
245 * Create a session, a key exchange was just completed.
247 * @param peer peer that is now connected
248 * @param kx key exchange that completed
251 GSC_SESSIONS_create (const struct GNUNET_PeerIdentity *peer,
252 struct GSC_KeyExchangeInfo *kx)
254 struct Session *session;
256 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Creating session for peer `%4s'\n",
258 session = GNUNET_malloc (sizeof (struct Session));
259 session->tmap = GSC_TYPEMAP_create ();
260 session->peer = *peer;
261 session->kxinfo = kx;
262 session->time_established = GNUNET_TIME_absolute_get ();
263 session->typemap_task =
264 GNUNET_SCHEDULER_add_now (&transmit_typemap_task, session);
265 GNUNET_assert (GNUNET_OK ==
266 GNUNET_CONTAINER_multihashmap_put (sessions, &peer->hashPubKey,
268 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
269 GNUNET_STATISTICS_set (GSC_stats, gettext_noop ("# peers connected"),
270 GNUNET_CONTAINER_multihashmap_size (sessions),
272 GSC_CLIENTS_notify_clients_about_neighbour (peer, NULL, 0 /* FIXME: ATSI */ ,
273 NULL, session->tmap);
278 * Notify the given client about the session (client is new).
280 * @param cls the 'struct GSC_Client'
281 * @param key peer identity
282 * @param value the 'struct Session'
283 * @return GNUNET_OK (continue to iterate)
286 notify_client_about_session (void *cls, const GNUNET_HashCode * key,
289 struct GSC_Client *client = cls;
290 struct Session *session = value;
292 GSC_CLIENTS_notify_client_about_neighbour (client, &session->peer, NULL, 0, /* FIXME: ATS!? */
293 NULL, /* old TMAP: none */
300 * We have a new client, notify it about all current sessions.
302 * @param client the new client
305 GSC_SESSIONS_notify_client_about_sessions (struct GSC_Client *client)
307 /* notify new client about existing sessions */
308 GNUNET_CONTAINER_multihashmap_iterate (sessions, ¬ify_client_about_session,
314 * Try to perform a transmission on the given session. Will solicit
315 * additional messages if the 'sme' queue is not full enough.
317 * @param session session to transmit messages from
320 try_transmission (struct Session *session);
324 * Queue a request from a client for transmission to a particular peer.
326 * @param car request to queue; this handle is then shared between
327 * the caller (CLIENTS subsystem) and SESSIONS and must not
328 * be released by either until either 'GNUNET_SESSIONS_dequeue',
329 * 'GNUNET_SESSIONS_transmit' or 'GNUNET_CLIENTS_failed'
330 * have been invoked on it
333 GSC_SESSIONS_queue_request (struct GSC_ClientActiveRequest *car)
335 struct Session *session;
337 session = find_session (&car->target);
340 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
341 "Dropped client request for transmission (am disconnected)\n");
342 GNUNET_break (0); /* should have been rejected earlier */
343 GSC_CLIENTS_reject_request (car);
346 if (car->msize > GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE)
349 GSC_CLIENTS_reject_request (car);
352 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
353 "Received client transmission request. queueing\n");
354 GNUNET_CONTAINER_DLL_insert (session->active_client_request_head,
355 session->active_client_request_tail, car);
356 try_transmission (session);
361 * Dequeue a request from a client from transmission to a particular peer.
363 * @param car request to dequeue; this handle will then be 'owned' by
364 * the caller (CLIENTS sysbsystem)
367 GSC_SESSIONS_dequeue_request (struct GSC_ClientActiveRequest *car)
372 memcmp (&car->target, &GSC_my_identity,
373 sizeof (struct GNUNET_PeerIdentity)))
375 s = find_session (&car->target);
376 GNUNET_assert (NULL != s);
377 GNUNET_CONTAINER_DLL_remove (s->active_client_request_head,
378 s->active_client_request_tail, car);
383 * Discard all expired active transmission requests from clients.
385 * @param session session to clean up
388 discard_expired_requests (struct Session *session)
390 struct GSC_ClientActiveRequest *pos;
391 struct GSC_ClientActiveRequest *nxt;
392 struct GNUNET_TIME_Absolute now;
394 now = GNUNET_TIME_absolute_get ();
396 nxt = session->active_client_request_head;
401 if ((pos->deadline.abs_value < now.abs_value) &&
402 (GNUNET_YES != pos->was_solicited))
404 GNUNET_STATISTICS_update (GSC_stats,
406 ("# messages discarded (expired prior to transmission)"),
408 GNUNET_CONTAINER_DLL_remove (session->active_client_request_head,
409 session->active_client_request_tail, pos);
410 GSC_CLIENTS_reject_request (pos);
417 * Solicit messages for transmission.
419 * @param session session to solict messages for
422 solicit_messages (struct Session *session)
424 struct GSC_ClientActiveRequest *car;
425 struct GSC_ClientActiveRequest *nxt;
428 discard_expired_requests (session);
430 nxt = session->active_client_request_head;
431 while (NULL != (car = nxt))
434 if (so_size + car->msize > GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE)
436 so_size += car->msize;
437 if (car->was_solicited == GNUNET_YES)
439 car->was_solicited = GNUNET_YES;
440 GSC_CLIENTS_solicit_request (car);
446 * Some messages were delayed (corked), but the timeout has now expired.
449 * @param cls 'struct Session' with the messages to transmit now
450 * @param tc scheduler context (unused)
453 pop_cork_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
455 struct Session *session = cls;
457 session->cork_task = GNUNET_SCHEDULER_NO_TASK;
458 try_transmission (session);
463 * Try to perform a transmission on the given session. Will solicit
464 * additional messages if the 'sme' queue is not full enough.
466 * @param session session to transmit messages from
469 try_transmission (struct Session *session)
471 struct SessionMessageEntry *pos;
473 struct GNUNET_TIME_Absolute now;
474 struct GNUNET_TIME_Absolute min_deadline;
476 if (GNUNET_YES != session->ready_to_transmit)
479 min_deadline = GNUNET_TIME_UNIT_FOREVER_ABS;
480 /* check 'ready' messages */
481 pos = session->sme_head;
482 while ((NULL != pos) &&
483 (msize + pos->size <= GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE))
485 GNUNET_assert (pos->size < GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE);
487 min_deadline = GNUNET_TIME_absolute_min (min_deadline, pos->deadline);
490 now = GNUNET_TIME_absolute_get ();
492 ((msize < GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE / 2) &&
493 (min_deadline.abs_value > now.abs_value)))
495 /* not enough ready yet, try to solicit more */
496 solicit_messages (session);
499 /* if there is data to send, just not yet, make sure we do transmit
500 * it once the deadline is reached */
501 if (session->cork_task != GNUNET_SCHEDULER_NO_TASK)
502 GNUNET_SCHEDULER_cancel (session->cork_task);
504 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_absolute_get_remaining
505 (min_deadline), &pop_cork_task,
510 /* create plaintext buffer of all messages, encrypt and transmit */
512 static unsigned long long total_bytes;
513 static unsigned int total_msgs;
514 char pbuf[msize]; /* plaintext */
518 while ((NULL != (pos = session->sme_head)) && (used + pos->size <= msize))
520 memcpy (&pbuf[used], &pos[1], pos->size);
522 GNUNET_CONTAINER_DLL_remove (session->sme_head, session->sme_tail, pos);
525 /* compute average payload size */
530 /* 2^32 messages, wrap around... */
534 GNUNET_STATISTICS_set (GSC_stats, "# avg payload per encrypted message",
535 total_bytes / total_msgs, GNUNET_NO);
536 /* now actually transmit... */
537 session->ready_to_transmit = GNUNET_NO;
538 GSC_KX_encrypt_and_transmit (session->kxinfo, pbuf, used);
544 * Send a message to the neighbour now.
546 * @param cls the message
547 * @param key neighbour's identity
548 * @param value 'struct Neighbour' of the target
549 * @return always GNUNET_OK
552 do_send_message (void *cls, const GNUNET_HashCode * key, void *value)
554 const struct GNUNET_MessageHeader *hdr = cls;
555 struct Session *session = value;
556 struct SessionMessageEntry *m;
559 size = ntohs (hdr->size);
560 m = GNUNET_malloc (sizeof (struct SessionMessageEntry) + size);
561 memcpy (&m[1], hdr, size);
563 GNUNET_CONTAINER_DLL_insert (session->sme_head, session->sme_tail, m);
564 try_transmission (session);
570 * Broadcast a message to all neighbours.
572 * @param msg message to transmit
575 GSC_SESSIONS_broadcast (const struct GNUNET_MessageHeader *msg)
577 if (NULL == sessions)
579 GNUNET_CONTAINER_multihashmap_iterate (sessions, &do_send_message,
585 * Traffic is being solicited for the given peer. This means that the
586 * message queue on the transport-level (NEIGHBOURS subsystem) is now
587 * empty and it is now OK to transmit another (non-control) message.
589 * @param pid identity of peer ready to receive data
592 GSC_SESSIONS_solicit (const struct GNUNET_PeerIdentity *pid)
594 struct Session *session;
596 session = find_session (pid);
599 session->ready_to_transmit = GNUNET_YES;
600 try_transmission (session);
605 * Transmit a message to a particular peer.
607 * @param car original request that was queued and then solicited;
608 * this handle will now be 'owned' by the SESSIONS subsystem
609 * @param msg message to transmit
610 * @param cork is corking allowed?
613 GSC_SESSIONS_transmit (struct GSC_ClientActiveRequest *car,
614 const struct GNUNET_MessageHeader *msg, int cork)
616 struct Session *session;
617 struct SessionMessageEntry *sme;
620 session = find_session (&car->target);
623 msize = ntohs (msg->size);
624 sme = GNUNET_malloc (sizeof (struct SessionMessageEntry) + msize);
625 memcpy (&sme[1], msg, msize);
627 if (GNUNET_YES == cork)
629 GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_MAX_CORK_DELAY);
630 GNUNET_CONTAINER_DLL_insert_tail (session->sme_head, session->sme_tail, sme);
631 try_transmission (session);
636 * Helper function for GSC_SESSIONS_handle_client_iterate_peers.
638 * @param cls the 'struct GNUNET_SERVER_TransmitContext' to queue replies
639 * @param key identity of the connected peer
640 * @param value the 'struct Neighbour' for the peer
641 * @return GNUNET_OK (continue to iterate)
645 queue_connect_message (void *cls, const GNUNET_HashCode * key, void *value)
647 struct GNUNET_SERVER_TransmitContext *tc = cls;
648 struct Session *session = value;
649 struct ConnectNotifyMessage cnm;
651 /* FIXME: code duplication with clients... */
652 cnm.header.size = htons (sizeof (struct ConnectNotifyMessage));
653 cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT);
654 // FIXME: full ats...
655 cnm.ats_count = htonl (0);
656 cnm.peer = session->peer;
657 GNUNET_SERVER_transmit_context_append_message (tc, &cnm.header);
663 * Handle CORE_ITERATE_PEERS request. For this request type, the client
664 * does not have to have transmitted an INIT request. All current peers
665 * are returned, regardless of which message types they accept.
668 * @param client client sending the iteration request
669 * @param message iteration request message
672 GSC_SESSIONS_handle_client_iterate_peers (void *cls,
673 struct GNUNET_SERVER_Client *client,
674 const struct GNUNET_MessageHeader
677 struct GNUNET_MessageHeader done_msg;
678 struct GNUNET_SERVER_TransmitContext *tc;
680 tc = GNUNET_SERVER_transmit_context_create (client);
681 GNUNET_CONTAINER_multihashmap_iterate (sessions, &queue_connect_message, tc);
682 done_msg.size = htons (sizeof (struct GNUNET_MessageHeader));
683 done_msg.type = htons (GNUNET_MESSAGE_TYPE_CORE_ITERATE_PEERS_END);
684 GNUNET_SERVER_transmit_context_append_message (tc, &done_msg);
685 GNUNET_SERVER_transmit_context_run (tc, GNUNET_TIME_UNIT_FOREVER_REL);
690 * Handle CORE_PEER_CONNECTED request. Notify client about connection
691 * to the given neighbour. For this request type, the client does not
692 * have to have transmitted an INIT request. All current peers are
693 * returned, regardless of which message types they accept.
696 * @param client client sending the iteration request
697 * @param message iteration request message
700 GSC_SESSIONS_handle_client_have_peer (void *cls,
701 struct GNUNET_SERVER_Client *client,
702 const struct GNUNET_MessageHeader
705 struct GNUNET_MessageHeader done_msg;
706 struct GNUNET_SERVER_TransmitContext *tc;
707 const struct GNUNET_PeerIdentity *peer;
709 peer = (const struct GNUNET_PeerIdentity *) &message[1]; // YUCK!
710 tc = GNUNET_SERVER_transmit_context_create (client);
711 GNUNET_CONTAINER_multihashmap_get_multiple (sessions, &peer->hashPubKey,
712 &queue_connect_message, tc);
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 * We've received a typemap message from a peer, update ours.
722 * Notifies clients about the session.
724 * @param peer peer this is about
725 * @param msg typemap update message
728 GSC_SESSIONS_set_typemap (const struct GNUNET_PeerIdentity *peer,
729 const struct GNUNET_MessageHeader *msg)
731 struct Session *session;
732 struct GSC_TypeMap *nmap;
734 nmap = GSC_TYPEMAP_get_from_message (msg);
736 return; /* malformed */
737 session = find_session (peer);
743 GSC_CLIENTS_notify_clients_about_neighbour (peer, NULL, 0, /* FIXME: ATS */
744 session->tmap, nmap);
745 GSC_TYPEMAP_destroy (session->tmap);
746 session->tmap = nmap;
751 * The given peer send a message of the specified type. Make sure the
752 * respective bit is set in its type-map and that clients are notified
755 * @param peer peer this is about
756 * @param type type of the message
759 GSC_SESSIONS_add_to_typemap (const struct GNUNET_PeerIdentity *peer,
762 struct Session *session;
763 struct GSC_TypeMap *nmap;
765 if (0 == memcmp (peer, &GSC_my_identity, sizeof (struct GNUNET_PeerIdentity)))
767 session = find_session (peer);
768 GNUNET_assert (NULL != session);
769 if (GNUNET_YES == GSC_TYPEMAP_test_match (session->tmap, &type, 1))
770 return; /* already in it */
771 nmap = GSC_TYPEMAP_extend (session->tmap, &type, 1);
772 GSC_CLIENTS_notify_clients_about_neighbour (peer, NULL, 0, /* FIXME: ATS */
773 session->tmap, nmap);
774 GSC_TYPEMAP_destroy (session->tmap);
775 session->tmap = nmap;
780 * Initialize sessions subsystem.
785 sessions = GNUNET_CONTAINER_multihashmap_create (128);
790 * Helper function for GSC_SESSIONS_handle_client_iterate_peers.
793 * @param key identity of the connected peer
794 * @param value the 'struct Session' for the peer
795 * @return GNUNET_OK (continue to iterate)
798 free_session_helper (void *cls, const GNUNET_HashCode * key, void *value)
800 struct Session *session = value;
802 GSC_SESSIONS_end (&session->peer);
808 * Shutdown sessions subsystem.
813 GNUNET_CONTAINER_multihashmap_iterate (sessions, &free_session_helper, NULL);
814 GNUNET_CONTAINER_multihashmap_destroy (sessions);
818 /* end of gnunet-service-core_sessions.c */