2 This file is part of GNUnet.
3 (C) 2009-2014 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"
38 * How often do we transmit our typemap?
40 #define TYPEMAP_FREQUENCY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 5)
43 * How often do we transmit our typemap on first attempt?
45 #define TYPEMAP_FREQUENCY_FIRST GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 5)
49 * Message ready for encryption. This struct is followed by the
50 * actual content of the message.
52 struct SessionMessageEntry
56 * We keep messages in a doubly linked list.
58 struct SessionMessageEntry *next;
61 * We keep messages in a doubly linked list.
63 struct SessionMessageEntry *prev;
66 * Deadline for transmission, 1s after we received it (if we
67 * are not corking), otherwise "now". Note that this message
68 * does NOT expire past its deadline.
70 struct GNUNET_TIME_Absolute deadline;
73 * How long is the message? (number of bytes following the "struct
74 * MessageEntry", but not including the size of "struct
75 * MessageEntry" itself!)
80 * How important is this message.
82 enum GNUNET_CORE_Priority priority;
88 * Data kept per session.
93 * Identity of the other peer.
95 struct GNUNET_PeerIdentity peer;
98 * Head of list of requests from clients for transmission to
101 struct GSC_ClientActiveRequest *active_client_request_head;
104 * Tail of list of requests from clients for transmission to
107 struct GSC_ClientActiveRequest *active_client_request_tail;
110 * Head of list of messages ready for encryption.
112 struct SessionMessageEntry *sme_head;
115 * Tail of list of messages ready for encryption.
117 struct SessionMessageEntry *sme_tail;
120 * Information about the key exchange with the other peer.
122 struct GSC_KeyExchangeInfo *kxinfo;
125 * Current type map for this peer.
127 struct GSC_TypeMap *tmap;
130 * Task to transmit corked messages with a delay.
132 GNUNET_SCHEDULER_TaskIdentifier cork_task;
135 * Task to transmit our type map.
137 GNUNET_SCHEDULER_TaskIdentifier typemap_task;
140 * Is the neighbour queue empty and thus ready for us
141 * to transmit an encrypted message?
143 int ready_to_transmit;
146 * Is this the first time we're sending the typemap? If so,
147 * we want to send it a bit faster the second time. 0 if
148 * we are sending for the first time, 1 if not.
155 * Map of peer identities to `struct Session`.
157 static struct GNUNET_CONTAINER_MultiPeerMap *sessions;
161 * Find the session for the given peer.
163 * @param peer identity of the peer
164 * @return NULL if we are not connected, otherwise the
167 static struct Session *
168 find_session (const struct GNUNET_PeerIdentity *peer)
170 return GNUNET_CONTAINER_multipeermap_get (sessions, peer);
175 * End the session with the given peer (we are no longer
178 * @param pid identity of peer to kill session with
181 GSC_SESSIONS_end (const struct GNUNET_PeerIdentity *pid)
183 struct Session *session;
184 struct GSC_ClientActiveRequest *car;
185 struct SessionMessageEntry *sme;
187 session = find_session (pid);
190 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
191 "Destroying session for peer `%4s'\n",
192 GNUNET_i2s (&session->peer));
193 if (GNUNET_SCHEDULER_NO_TASK != session->cork_task)
195 GNUNET_SCHEDULER_cancel (session->cork_task);
196 session->cork_task = GNUNET_SCHEDULER_NO_TASK;
198 while (NULL != (car = session->active_client_request_head))
200 GNUNET_CONTAINER_DLL_remove (session->active_client_request_head,
201 session->active_client_request_tail, car);
202 GSC_CLIENTS_reject_request (car);
204 while (NULL != (sme = session->sme_head))
206 GNUNET_CONTAINER_DLL_remove (session->sme_head, session->sme_tail, sme);
209 GNUNET_SCHEDULER_cancel (session->typemap_task);
210 GSC_CLIENTS_notify_clients_about_neighbour (&session->peer,
211 session->tmap, NULL);
212 GNUNET_assert (GNUNET_YES ==
213 GNUNET_CONTAINER_multipeermap_remove (sessions,
216 GNUNET_STATISTICS_set (GSC_stats, gettext_noop ("# peers connected"),
217 GNUNET_CONTAINER_multipeermap_size (sessions),
219 GSC_TYPEMAP_destroy (session->tmap);
220 session->tmap = NULL;
221 GNUNET_free (session);
226 * Transmit our current typemap message to the other peer.
227 * (Done periodically in case an update got lost).
229 * @param cls the `struct Session *`
233 transmit_typemap_task (void *cls,
234 const struct GNUNET_SCHEDULER_TaskContext *tc)
236 struct Session *session = cls;
237 struct GNUNET_MessageHeader *hdr;
238 struct GNUNET_TIME_Relative delay;
240 if (0 == session->first_typemap)
242 delay = TYPEMAP_FREQUENCY_FIRST;
243 session->first_typemap = 1;
247 delay = TYPEMAP_FREQUENCY;
249 /* randomize a bit to avoid spont. sync */
250 delay.rel_value_us +=
251 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, 1000 * 1000);
252 session->typemap_task =
253 GNUNET_SCHEDULER_add_delayed (delay, &transmit_typemap_task, session);
254 GNUNET_STATISTICS_update (GSC_stats,
255 gettext_noop ("# type map refreshes sent"), 1,
257 hdr = GSC_TYPEMAP_compute_type_map_message ();
258 GSC_KX_encrypt_and_transmit (session->kxinfo, hdr, ntohs (hdr->size));
264 * Create a session, a key exchange was just completed.
266 * @param peer peer that is now connected
267 * @param kx key exchange that completed
270 GSC_SESSIONS_create (const struct GNUNET_PeerIdentity *peer,
271 struct GSC_KeyExchangeInfo *kx)
273 struct Session *session;
275 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
276 "Creating session for peer `%4s'\n",
278 session = GNUNET_new (struct Session);
279 session->tmap = GSC_TYPEMAP_create ();
280 session->peer = *peer;
281 session->kxinfo = kx;
282 session->typemap_task =
283 GNUNET_SCHEDULER_add_now (&transmit_typemap_task, session);
284 GNUNET_assert (GNUNET_OK ==
285 GNUNET_CONTAINER_multipeermap_put (sessions, peer,
287 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
288 GNUNET_STATISTICS_set (GSC_stats, gettext_noop ("# peers connected"),
289 GNUNET_CONTAINER_multipeermap_size (sessions),
291 GSC_CLIENTS_notify_clients_about_neighbour (peer,
292 NULL, session->tmap);
297 * Notify the given client about the session (client is new).
299 * @param cls the `struct GSC_Client`
300 * @param key peer identity
301 * @param value the `struct Session`
302 * @return #GNUNET_OK (continue to iterate)
305 notify_client_about_session (void *cls,
306 const struct GNUNET_PeerIdentity *key,
309 struct GSC_Client *client = cls;
310 struct Session *session = value;
312 GSC_CLIENTS_notify_client_about_neighbour (client, &session->peer,
313 NULL, /* old TMAP: none */
320 * We have a new client, notify it about all current sessions.
322 * @param client the new client
325 GSC_SESSIONS_notify_client_about_sessions (struct GSC_Client *client)
327 /* notify new client about existing sessions */
328 GNUNET_CONTAINER_multipeermap_iterate (sessions, ¬ify_client_about_session,
334 * Try to perform a transmission on the given session. Will solicit
335 * additional messages if the 'sme' queue is not full enough.
337 * @param session session to transmit messages from
340 try_transmission (struct Session *session);
344 * Queue a request from a client for transmission to a particular peer.
346 * @param car request to queue; this handle is then shared between
347 * the caller (CLIENTS subsystem) and SESSIONS and must not
348 * be released by either until either #GSC_SESSIONS_dequeue(),
349 * #GSC_SESSIONS_transmit() or #GSC_CLIENTS_failed()
350 * have been invoked on it
353 GSC_SESSIONS_queue_request (struct GSC_ClientActiveRequest *car)
355 struct Session *session;
357 session = find_session (&car->target);
360 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
361 "Dropped client request for transmission (am disconnected)\n");
362 GNUNET_break (0); /* should have been rejected earlier */
363 GSC_CLIENTS_reject_request (car);
366 if (car->msize > GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE)
369 GSC_CLIENTS_reject_request (car);
372 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
373 "Received client transmission request. queueing\n");
374 GNUNET_CONTAINER_DLL_insert (session->active_client_request_head,
375 session->active_client_request_tail, car);
376 try_transmission (session);
381 * Dequeue a request from a client from transmission to a particular peer.
383 * @param car request to dequeue; this handle will then be 'owned' by
384 * the caller (CLIENTS sysbsystem)
387 GSC_SESSIONS_dequeue_request (struct GSC_ClientActiveRequest *car)
392 memcmp (&car->target, &GSC_my_identity,
393 sizeof (struct GNUNET_PeerIdentity)))
395 s = find_session (&car->target);
396 GNUNET_assert (NULL != s);
397 GNUNET_CONTAINER_DLL_remove (s->active_client_request_head,
398 s->active_client_request_tail, car);
403 * Discard all expired active transmission requests from clients.
405 * @param session session to clean up
408 discard_expired_requests (struct Session *session)
410 struct GSC_ClientActiveRequest *pos;
411 struct GSC_ClientActiveRequest *nxt;
412 struct GNUNET_TIME_Absolute now;
414 now = GNUNET_TIME_absolute_get ();
416 nxt = session->active_client_request_head;
421 if ((pos->deadline.abs_value_us < now.abs_value_us) &&
422 (GNUNET_YES != pos->was_solicited))
424 GNUNET_STATISTICS_update (GSC_stats,
426 ("# messages discarded (expired prior to transmission)"),
428 GNUNET_CONTAINER_DLL_remove (session->active_client_request_head,
429 session->active_client_request_tail, pos);
430 GSC_CLIENTS_reject_request (pos);
437 * Solicit messages for transmission, starting with those of the highest
440 * @param session session to solict messages for
441 * @param msize how many bytes do we have already
444 solicit_messages (struct Session *session,
447 struct GSC_ClientActiveRequest *car;
448 struct GSC_ClientActiveRequest *nxt;
450 enum GNUNET_CORE_Priority pmax;
452 discard_expired_requests (session);
454 pmax = GNUNET_CORE_PRIO_BACKGROUND;
455 for (car = session->active_client_request_head; NULL != car; car = car->next)
457 if (GNUNET_YES == car->was_solicited)
459 pmax = GNUNET_MAX (pmax, car->priority);
461 nxt = session->active_client_request_head;
462 while (NULL != (car = nxt))
465 if (car->priority < pmax)
467 if (so_size + car->msize > GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE)
469 so_size += car->msize;
470 if (GNUNET_YES == car->was_solicited)
472 car->was_solicited = GNUNET_YES;
473 GSC_CLIENTS_solicit_request (car);
479 * Some messages were delayed (corked), but the timeout has now expired.
482 * @param cls `struct Session` with the messages to transmit now
483 * @param tc scheduler context (unused)
486 pop_cork_task (void *cls,
487 const struct GNUNET_SCHEDULER_TaskContext *tc)
489 struct Session *session = cls;
491 session->cork_task = GNUNET_SCHEDULER_NO_TASK;
492 try_transmission (session);
497 * Try to perform a transmission on the given session. Will solicit
498 * additional messages if the 'sme' queue is not full enough or has
499 * only low-priority messages.
501 * @param session session to transmit messages from
504 try_transmission (struct Session *session)
506 struct SessionMessageEntry *pos;
508 struct GNUNET_TIME_Absolute now;
509 struct GNUNET_TIME_Absolute min_deadline;
510 enum GNUNET_CORE_Priority maxp;
511 enum GNUNET_CORE_Priority maxpc;
512 struct GSC_ClientActiveRequest *car;
515 if (GNUNET_YES != session->ready_to_transmit)
518 min_deadline = GNUNET_TIME_UNIT_FOREVER_ABS;
519 /* if the peer has excess bandwidth, background traffic is allowed,
521 excess = GSC_NEIGHBOURS_check_excess_bandwidth (&session->peer);
522 if (GNUNET_YES == excess)
523 maxp = GNUNET_CORE_PRIO_BACKGROUND;
525 maxp = GNUNET_CORE_PRIO_BEST_EFFORT;
526 /* determine highest priority of 'ready' messages we already solicited from clients */
527 pos = session->sme_head;
528 while ((NULL != pos) &&
529 (msize + pos->size <= GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE))
531 GNUNET_assert (pos->size < GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE);
533 maxp = GNUNET_MAX (maxp, pos->priority);
534 min_deadline = GNUNET_TIME_absolute_min (min_deadline, pos->deadline);
537 if (maxp < GNUNET_CORE_PRIO_CRITICAL_CONTROL)
539 /* if highest already solicited priority from clients is not critical,
540 check if there are higher-priority messages to be solicited from clients */
541 if (GNUNET_YES == excess)
542 maxpc = GNUNET_CORE_PRIO_BACKGROUND;
544 maxpc = GNUNET_CORE_PRIO_BEST_EFFORT;
545 for (car = session->active_client_request_head; NULL != car; car = car->next)
547 if (GNUNET_YES == car->was_solicited)
549 maxpc = GNUNET_MAX (maxpc, car->priority);
553 /* we have messages waiting for solicitation that have a higher
554 priority than those that we already accepted; solicit the
555 high-priority messages first */
556 solicit_messages (session, 0);
561 now = GNUNET_TIME_absolute_get ();
562 if ( ( (GNUNET_YES == excess) ||
563 (maxpc >= GNUNET_CORE_PRIO_BEST_EFFORT) ) &&
565 ( (msize < GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE / 2) &&
566 (min_deadline.abs_value_us > now.abs_value_us))) )
568 /* not enough ready yet (tiny message & cork possible), or no messages at all,
569 and either excess bandwidth or best-effort or higher message waiting at
570 client; in this case, we try to solicit more */
571 solicit_messages (session,
575 /* if there is data to send, just not yet, make sure we do transmit
576 * it once the deadline is reached */
577 if (GNUNET_SCHEDULER_NO_TASK != session->cork_task)
578 GNUNET_SCHEDULER_cancel (session->cork_task);
580 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_absolute_get_remaining
581 (min_deadline), &pop_cork_task,
586 /* create plaintext buffer of all messages (that fit), encrypt and
589 static unsigned long long total_bytes;
590 static unsigned int total_msgs;
591 char pbuf[msize]; /* plaintext */
595 while ((NULL != (pos = session->sme_head)) && (used + pos->size <= msize))
597 memcpy (&pbuf[used], &pos[1], pos->size);
599 GNUNET_CONTAINER_DLL_remove (session->sme_head, session->sme_tail, pos);
602 /* compute average payload size */
607 /* 2^32 messages, wrap around... */
611 GNUNET_STATISTICS_set (GSC_stats,
612 "# avg payload per encrypted message",
613 total_bytes / total_msgs, GNUNET_NO);
614 /* now actually transmit... */
615 session->ready_to_transmit = GNUNET_NO;
616 GSC_KX_encrypt_and_transmit (session->kxinfo, pbuf, used);
622 * Send a message to the neighbour now.
624 * @param cls the message
625 * @param key neighbour's identity
626 * @param value `struct Neighbour` of the target
627 * @return always #GNUNET_OK
630 do_send_message (void *cls,
631 const struct GNUNET_PeerIdentity *key,
634 const struct GNUNET_MessageHeader *hdr = cls;
635 struct Session *session = value;
636 struct SessionMessageEntry *m;
639 size = ntohs (hdr->size);
640 m = GNUNET_malloc (sizeof (struct SessionMessageEntry) + size);
641 memcpy (&m[1], hdr, size);
643 m->priority = GNUNET_CORE_PRIO_CRITICAL_CONTROL;
644 GNUNET_CONTAINER_DLL_insert_tail (session->sme_head, session->sme_tail, m);
645 try_transmission (session);
651 * Broadcast a message to all neighbours.
653 * @param msg message to transmit
656 GSC_SESSIONS_broadcast (const struct GNUNET_MessageHeader *msg)
658 if (NULL == sessions)
660 GNUNET_CONTAINER_multipeermap_iterate (sessions,
667 * Traffic is being solicited for the given peer. This means that the
668 * message queue on the transport-level (NEIGHBOURS subsystem) is now
669 * empty and it is now OK to transmit another (non-control) message.
671 * @param pid identity of peer ready to receive data
674 GSC_SESSIONS_solicit (const struct GNUNET_PeerIdentity *pid)
676 struct Session *session;
678 session = find_session (pid);
681 session->ready_to_transmit = GNUNET_YES;
682 try_transmission (session);
687 * Transmit a message to a particular peer.
689 * @param car original request that was queued and then solicited;
690 * this handle will now be 'owned' by the SESSIONS subsystem
691 * @param msg message to transmit
692 * @param cork is corking allowed?
693 * @param priority how important is this message
696 GSC_SESSIONS_transmit (struct GSC_ClientActiveRequest *car,
697 const struct GNUNET_MessageHeader *msg,
699 enum GNUNET_CORE_Priority priority)
701 struct Session *session;
702 struct SessionMessageEntry *sme;
703 struct SessionMessageEntry *pos;
706 session = find_session (&car->target);
709 msize = ntohs (msg->size);
710 sme = GNUNET_malloc (sizeof (struct SessionMessageEntry) + msize);
711 memcpy (&sme[1], msg, msize);
713 sme->priority = priority;
714 if (GNUNET_YES == cork)
716 GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_MAX_CORK_DELAY);
717 pos = session->sme_head;
718 while ( (NULL != pos) &&
719 (pos->priority > sme->priority) )
722 GNUNET_CONTAINER_DLL_insert_tail (session->sme_head,
726 GNUNET_CONTAINER_DLL_insert_after (session->sme_head,
730 try_transmission (session);
735 * We've received a typemap message from a peer, update ours.
736 * Notifies clients about the session.
738 * @param peer peer this is about
739 * @param msg typemap update message
742 GSC_SESSIONS_set_typemap (const struct GNUNET_PeerIdentity *peer,
743 const struct GNUNET_MessageHeader *msg)
745 struct Session *session;
746 struct GSC_TypeMap *nmap;
748 nmap = GSC_TYPEMAP_get_from_message (msg);
750 return; /* malformed */
751 session = find_session (peer);
757 GSC_CLIENTS_notify_clients_about_neighbour (peer,
758 session->tmap, nmap);
759 GSC_TYPEMAP_destroy (session->tmap);
760 session->tmap = nmap;
765 * The given peer send a message of the specified type. Make sure the
766 * respective bit is set in its type-map and that clients are notified
769 * @param peer peer this is about
770 * @param type type of the message
773 GSC_SESSIONS_add_to_typemap (const struct GNUNET_PeerIdentity *peer,
776 struct Session *session;
777 struct GSC_TypeMap *nmap;
779 if (0 == memcmp (peer, &GSC_my_identity, sizeof (struct GNUNET_PeerIdentity)))
781 session = find_session (peer);
782 GNUNET_assert (NULL != session);
783 if (GNUNET_YES == GSC_TYPEMAP_test_match (session->tmap, &type, 1))
784 return; /* already in it */
785 nmap = GSC_TYPEMAP_extend (session->tmap, &type, 1);
786 GSC_CLIENTS_notify_clients_about_neighbour (peer,
787 session->tmap, nmap);
788 GSC_TYPEMAP_destroy (session->tmap);
789 session->tmap = nmap;
794 * Initialize sessions subsystem.
799 sessions = GNUNET_CONTAINER_multipeermap_create (128, GNUNET_NO);
804 * Helper function for GSC_SESSIONS_handle_client_iterate_peers.
807 * @param key identity of the connected peer
808 * @param value the `struct Session` for the peer
809 * @return #GNUNET_OK (continue to iterate)
812 free_session_helper (void *cls,
813 const struct GNUNET_PeerIdentity *key,
816 struct Session *session = value;
818 GSC_SESSIONS_end (&session->peer);
824 * Shutdown sessions subsystem.
829 if (NULL != sessions)
831 GNUNET_CONTAINER_multipeermap_iterate (sessions, &free_session_helper, NULL);
832 GNUNET_CONTAINER_multipeermap_destroy (sessions);
837 /* end of gnunet-service-core_sessions.c */