advanced logging
[oweals/gnunet.git] / src / core / gnunet-service-core_sessions.c
1 /*
2      This file is part of GNUnet.
3      (C) 2009-2014 Christian Grothoff (and other contributing authors)
4
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.
9
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.
14
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.
19 */
20
21 /**
22  * @file core/gnunet-service-core_sessions.c
23  * @brief code for managing of 'encrypted' sessions (key exchange done)
24  * @author Christian Grothoff
25  */
26 #include "platform.h"
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"
34 #include "core.h"
35
36
37 /**
38  * How often do we transmit our typemap?
39  */
40 #define TYPEMAP_FREQUENCY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 5)
41
42 /**
43  * How often do we transmit our typemap on first attempt?
44  */
45 #define TYPEMAP_FREQUENCY_FIRST GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 5)
46
47
48 /**
49  * Message ready for encryption.  This struct is followed by the
50  * actual content of the message.
51  */
52 struct SessionMessageEntry
53 {
54
55   /**
56    * We keep messages in a doubly linked list.
57    */
58   struct SessionMessageEntry *next;
59
60   /**
61    * We keep messages in a doubly linked list.
62    */
63   struct SessionMessageEntry *prev;
64
65   /**
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.
69    */
70   struct GNUNET_TIME_Absolute deadline;
71
72   /**
73    * How long is the message? (number of bytes following the "struct
74    * MessageEntry", but not including the size of "struct
75    * MessageEntry" itself!)
76    */
77   size_t size;
78
79   /**
80    * How important is this message.
81    */
82   enum GNUNET_CORE_Priority priority;
83
84 };
85
86
87 /**
88  * Data kept per session.
89  */
90 struct Session
91 {
92   /**
93    * Identity of the other peer.
94    */
95   struct GNUNET_PeerIdentity peer;
96
97   /**
98    * Head of list of requests from clients for transmission to
99    * this peer.
100    */
101   struct GSC_ClientActiveRequest *active_client_request_head;
102
103   /**
104    * Tail of list of requests from clients for transmission to
105    * this peer.
106    */
107   struct GSC_ClientActiveRequest *active_client_request_tail;
108
109   /**
110    * Head of list of messages ready for encryption.
111    */
112   struct SessionMessageEntry *sme_head;
113
114   /**
115    * Tail of list of messages ready for encryption.
116    */
117   struct SessionMessageEntry *sme_tail;
118
119   /**
120    * Information about the key exchange with the other peer.
121    */
122   struct GSC_KeyExchangeInfo *kxinfo;
123
124   /**
125    * Current type map for this peer.
126    */
127   struct GSC_TypeMap *tmap;
128
129   /**
130    * Task to transmit corked messages with a delay.
131    */
132   GNUNET_SCHEDULER_TaskIdentifier cork_task;
133
134   /**
135    * Task to transmit our type map.
136    */
137   GNUNET_SCHEDULER_TaskIdentifier typemap_task;
138
139   /**
140    * Is the neighbour queue empty and thus ready for us
141    * to transmit an encrypted message?
142    */
143   int ready_to_transmit;
144
145   /**
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.
149    */
150   int first_typemap;
151 };
152
153
154 /**
155  * Map of peer identities to `struct Session`.
156  */
157 static struct GNUNET_CONTAINER_MultiPeerMap *sessions;
158
159
160 /**
161  * Find the session for the given peer.
162  *
163  * @param peer identity of the peer
164  * @return NULL if we are not connected, otherwise the
165  *         session handle
166  */
167 static struct Session *
168 find_session (const struct GNUNET_PeerIdentity *peer)
169 {
170   return GNUNET_CONTAINER_multipeermap_get (sessions, peer);
171 }
172
173
174 /**
175  * End the session with the given peer (we are no longer
176  * connected).
177  *
178  * @param pid identity of peer to kill session with
179  */
180 void
181 GSC_SESSIONS_end (const struct GNUNET_PeerIdentity *pid)
182 {
183   struct Session *session;
184   struct GSC_ClientActiveRequest *car;
185   struct SessionMessageEntry *sme;
186
187   session = find_session (pid);
188   if (NULL == session)
189     return;
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)
194   {
195     GNUNET_SCHEDULER_cancel (session->cork_task);
196     session->cork_task = GNUNET_SCHEDULER_NO_TASK;
197   }
198   while (NULL != (car = session->active_client_request_head))
199   {
200     GNUNET_CONTAINER_DLL_remove (session->active_client_request_head,
201                                  session->active_client_request_tail, car);
202     GSC_CLIENTS_reject_request (car);
203   }
204   while (NULL != (sme = session->sme_head))
205   {
206     GNUNET_CONTAINER_DLL_remove (session->sme_head, session->sme_tail, sme);
207     GNUNET_free (sme);
208   }
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,
214                                                        &session->peer,
215                                                        session));
216   GNUNET_STATISTICS_set (GSC_stats, gettext_noop ("# peers connected"),
217                          GNUNET_CONTAINER_multipeermap_size (sessions),
218                          GNUNET_NO);
219   GSC_TYPEMAP_destroy (session->tmap);
220   session->tmap = NULL;
221   GNUNET_free (session);
222 }
223
224
225 /**
226  * Transmit our current typemap message to the other peer.
227  * (Done periodically in case an update got lost).
228  *
229  * @param cls the `struct Session *`
230  * @param tc unused
231  */
232 static void
233 transmit_typemap_task (void *cls,
234                        const struct GNUNET_SCHEDULER_TaskContext *tc)
235 {
236   struct Session *session = cls;
237   struct GNUNET_MessageHeader *hdr;
238   struct GNUNET_TIME_Relative delay;
239
240   if (0 == session->first_typemap)
241   {
242     delay = TYPEMAP_FREQUENCY_FIRST;
243     session->first_typemap = 1;
244   }
245   else
246   {
247     delay = TYPEMAP_FREQUENCY;
248   }
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,
256                             GNUNET_NO);
257   hdr = GSC_TYPEMAP_compute_type_map_message ();
258   GSC_KX_encrypt_and_transmit (session->kxinfo, hdr, ntohs (hdr->size));
259   GNUNET_free (hdr);
260 }
261
262
263 /**
264  * Create a session, a key exchange was just completed.
265  *
266  * @param peer peer that is now connected
267  * @param kx key exchange that completed
268  */
269 void
270 GSC_SESSIONS_create (const struct GNUNET_PeerIdentity *peer,
271                      struct GSC_KeyExchangeInfo *kx)
272 {
273   struct Session *session;
274
275   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
276               "Creating session for peer `%4s'\n",
277               GNUNET_i2s (peer));
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,
286                                                     session,
287                                                     GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
288   GNUNET_STATISTICS_set (GSC_stats, gettext_noop ("# peers connected"),
289                          GNUNET_CONTAINER_multipeermap_size (sessions),
290                          GNUNET_NO);
291   GSC_CLIENTS_notify_clients_about_neighbour (peer,
292                                               NULL, session->tmap);
293 }
294
295
296 /**
297  * Notify the given client about the session (client is new).
298  *
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)
303  */
304 static int
305 notify_client_about_session (void *cls,
306                              const struct GNUNET_PeerIdentity *key,
307                              void *value)
308 {
309   struct GSC_Client *client = cls;
310   struct Session *session = value;
311
312   GSC_CLIENTS_notify_client_about_neighbour (client, &session->peer,
313                                              NULL,      /* old TMAP: none */
314                                              session->tmap);
315   return GNUNET_OK;
316 }
317
318
319 /**
320  * We have a new client, notify it about all current sessions.
321  *
322  * @param client the new client
323  */
324 void
325 GSC_SESSIONS_notify_client_about_sessions (struct GSC_Client *client)
326 {
327   /* notify new client about existing sessions */
328   GNUNET_CONTAINER_multipeermap_iterate (sessions, &notify_client_about_session,
329                                          client);
330 }
331
332
333 /**
334  * Try to perform a transmission on the given session.  Will solicit
335  * additional messages if the 'sme' queue is not full enough.
336  *
337  * @param session session to transmit messages from
338  */
339 static void
340 try_transmission (struct Session *session);
341
342
343 /**
344  * Queue a request from a client for transmission to a particular peer.
345  *
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
351  */
352 void
353 GSC_SESSIONS_queue_request (struct GSC_ClientActiveRequest *car)
354 {
355   struct Session *session;
356
357   session = find_session (&car->target);
358   if (NULL == session)
359   {
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);
364     return;
365   }
366   if (car->msize > GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE)
367   {
368     GNUNET_break (0);
369     GSC_CLIENTS_reject_request (car);
370     return;
371   }
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);
377 }
378
379
380 /**
381  * Dequeue a request from a client from transmission to a particular peer.
382  *
383  * @param car request to dequeue; this handle will then be 'owned' by
384  *        the caller (CLIENTS sysbsystem)
385  */
386 void
387 GSC_SESSIONS_dequeue_request (struct GSC_ClientActiveRequest *car)
388 {
389   struct Session *s;
390
391   if (0 ==
392       memcmp (&car->target, &GSC_my_identity,
393               sizeof (struct GNUNET_PeerIdentity)))
394     return;
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);
399 }
400
401
402 /**
403  * Discard all expired active transmission requests from clients.
404  *
405  * @param session session to clean up
406  */
407 static void
408 discard_expired_requests (struct Session *session)
409 {
410   struct GSC_ClientActiveRequest *pos;
411   struct GSC_ClientActiveRequest *nxt;
412   struct GNUNET_TIME_Absolute now;
413
414   now = GNUNET_TIME_absolute_get ();
415   pos = NULL;
416   nxt = session->active_client_request_head;
417   while (NULL != nxt)
418   {
419     pos = nxt;
420     nxt = pos->next;
421     if ((pos->deadline.abs_value_us < now.abs_value_us) &&
422         (GNUNET_YES != pos->was_solicited))
423     {
424       GNUNET_STATISTICS_update (GSC_stats,
425                                 gettext_noop
426                                 ("# messages discarded (expired prior to transmission)"),
427                                 1, GNUNET_NO);
428       GNUNET_CONTAINER_DLL_remove (session->active_client_request_head,
429                                    session->active_client_request_tail, pos);
430       GSC_CLIENTS_reject_request (pos);
431     }
432   }
433 }
434
435
436 /**
437  * Solicit messages for transmission, starting with those of the highest
438  * priority.
439  *
440  * @param session session to solict messages for
441  * @param msize how many bytes do we have already
442  */
443 static void
444 solicit_messages (struct Session *session,
445                   size_t msize)
446 {
447   struct GSC_ClientActiveRequest *car;
448   struct GSC_ClientActiveRequest *nxt;
449   size_t so_size;
450   enum GNUNET_CORE_Priority pmax;
451
452   discard_expired_requests (session);
453   so_size = msize;
454   pmax = GNUNET_CORE_PRIO_BACKGROUND;
455   for (car = session->active_client_request_head; NULL != car; car = car->next)
456   {
457     if (GNUNET_YES == car->was_solicited)
458       continue;
459     pmax = GNUNET_MAX (pmax, car->priority);
460   }
461   nxt = session->active_client_request_head;
462   while (NULL != (car = nxt))
463   {
464     nxt = car->next;
465     if (car->priority < pmax)
466       continue;
467     if (so_size + car->msize > GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE)
468       break;
469     so_size += car->msize;
470     if (GNUNET_YES == car->was_solicited)
471       continue;
472     car->was_solicited = GNUNET_YES;
473     GSC_CLIENTS_solicit_request (car);
474   }
475 }
476
477
478 /**
479  * Some messages were delayed (corked), but the timeout has now expired.
480  * Send them now.
481  *
482  * @param cls `struct Session` with the messages to transmit now
483  * @param tc scheduler context (unused)
484  */
485 static void
486 pop_cork_task (void *cls,
487                const struct GNUNET_SCHEDULER_TaskContext *tc)
488 {
489   struct Session *session = cls;
490
491   session->cork_task = GNUNET_SCHEDULER_NO_TASK;
492   try_transmission (session);
493 }
494
495
496 /**
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.
500  *
501  * @param session session to transmit messages from
502  */
503 static void
504 try_transmission (struct Session *session)
505 {
506   struct SessionMessageEntry *pos;
507   size_t msize;
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;
513   int excess;
514
515   if (GNUNET_YES != session->ready_to_transmit)
516     return;
517   msize = 0;
518   min_deadline = GNUNET_TIME_UNIT_FOREVER_ABS;
519   /* if the peer has excess bandwidth, background traffic is allowed,
520      otherwise not */
521   excess = GSC_NEIGHBOURS_check_excess_bandwidth (&session->peer);
522   if (GNUNET_YES == excess)
523     maxp = GNUNET_CORE_PRIO_BACKGROUND;
524   else
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))
530   {
531     GNUNET_assert (pos->size < GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE);
532     msize += pos->size;
533     maxp = GNUNET_MAX (maxp, pos->priority);
534     min_deadline = GNUNET_TIME_absolute_min (min_deadline, pos->deadline);
535     pos = pos->next;
536   }
537   if (maxp < GNUNET_CORE_PRIO_CRITICAL_CONTROL)
538   {
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;
543     else
544       maxpc = GNUNET_CORE_PRIO_BEST_EFFORT;
545     for (car = session->active_client_request_head; NULL != car; car = car->next)
546     {
547       if (GNUNET_YES == car->was_solicited)
548         continue;
549       maxpc = GNUNET_MAX (maxpc, car->priority);
550     }
551     if (maxpc > maxp)
552     {
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);
557       return;
558     }
559   }
560
561   now = GNUNET_TIME_absolute_get ();
562   if ( ( (GNUNET_YES == excess) ||
563          (maxpc >= GNUNET_CORE_PRIO_BEST_EFFORT) ) &&
564        ( (0 == msize) ||
565          ( (msize < GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE / 2) &&
566            (min_deadline.abs_value_us > now.abs_value_us))) )
567   {
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,
572                       msize);
573     if (msize > 0)
574     {
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);
579       session->cork_task =
580           GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_absolute_get_remaining
581                                         (min_deadline), &pop_cork_task,
582                                         session);
583     }
584     return;
585   }
586   /* create plaintext buffer of all messages (that fit), encrypt and
587      transmit */
588   {
589     static unsigned long long total_bytes;
590     static unsigned int total_msgs;
591     char pbuf[msize];           /* plaintext */
592     size_t used;
593
594     used = 0;
595     while ((NULL != (pos = session->sme_head)) && (used + pos->size <= msize))
596     {
597       memcpy (&pbuf[used], &pos[1], pos->size);
598       used += pos->size;
599       GNUNET_CONTAINER_DLL_remove (session->sme_head, session->sme_tail, pos);
600       GNUNET_free (pos);
601     }
602     /* compute average payload size */
603     total_bytes += used;
604     total_msgs++;
605     if (0 == total_msgs)
606     {
607       /* 2^32 messages, wrap around... */
608       total_msgs = 1;
609       total_bytes = used;
610     }
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);
617   }
618 }
619
620
621 /**
622  * Send a message to the neighbour now.
623  *
624  * @param cls the message
625  * @param key neighbour's identity
626  * @param value `struct Neighbour` of the target
627  * @return always #GNUNET_OK
628  */
629 static int
630 do_send_message (void *cls,
631                  const struct GNUNET_PeerIdentity *key,
632                  void *value)
633 {
634   const struct GNUNET_MessageHeader *hdr = cls;
635   struct Session *session = value;
636   struct SessionMessageEntry *m;
637   uint16_t size;
638
639   size = ntohs (hdr->size);
640   m = GNUNET_malloc (sizeof (struct SessionMessageEntry) + size);
641   memcpy (&m[1], hdr, size);
642   m->size = 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);
646   return GNUNET_OK;
647 }
648
649
650 /**
651  * Broadcast a message to all neighbours.
652  *
653  * @param msg message to transmit
654  */
655 void
656 GSC_SESSIONS_broadcast (const struct GNUNET_MessageHeader *msg)
657 {
658   if (NULL == sessions)
659     return;
660   GNUNET_CONTAINER_multipeermap_iterate (sessions,
661                                          &do_send_message,
662                                          (void *) msg);
663 }
664
665
666 /**
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.
670  *
671  * @param pid identity of peer ready to receive data
672  */
673 void
674 GSC_SESSIONS_solicit (const struct GNUNET_PeerIdentity *pid)
675 {
676   struct Session *session;
677
678   session = find_session (pid);
679   if (NULL == session)
680     return;
681   session->ready_to_transmit = GNUNET_YES;
682   try_transmission (session);
683 }
684
685
686 /**
687  * Transmit a message to a particular peer.
688  *
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
694  */
695 void
696 GSC_SESSIONS_transmit (struct GSC_ClientActiveRequest *car,
697                        const struct GNUNET_MessageHeader *msg,
698                        int cork,
699                        enum GNUNET_CORE_Priority priority)
700 {
701   struct Session *session;
702   struct SessionMessageEntry *sme;
703   struct SessionMessageEntry *pos;
704   size_t msize;
705
706   session = find_session (&car->target);
707   if (NULL == session)
708     return;
709   msize = ntohs (msg->size);
710   sme = GNUNET_malloc (sizeof (struct SessionMessageEntry) + msize);
711   memcpy (&sme[1], msg, msize);
712   sme->size = msize;
713   sme->priority = priority;
714   if (GNUNET_YES == cork)
715     sme->deadline =
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) )
720     pos = pos->next;
721   if (NULL == pos)
722     GNUNET_CONTAINER_DLL_insert_tail (session->sme_head,
723                                       session->sme_tail,
724                                       sme);
725   else
726     GNUNET_CONTAINER_DLL_insert_after (session->sme_head,
727                                        session->sme_tail,
728                                        pos->prev,
729                                        sme);
730   try_transmission (session);
731 }
732
733
734 /**
735  * We've received a typemap message from a peer, update ours.
736  * Notifies clients about the session.
737  *
738  * @param peer peer this is about
739  * @param msg typemap update message
740  */
741 void
742 GSC_SESSIONS_set_typemap (const struct GNUNET_PeerIdentity *peer,
743                           const struct GNUNET_MessageHeader *msg)
744 {
745   struct Session *session;
746   struct GSC_TypeMap *nmap;
747
748   nmap = GSC_TYPEMAP_get_from_message (msg);
749   if (NULL == nmap)
750     return;                     /* malformed */
751   session = find_session (peer);
752   if (NULL == session)
753   {
754     GNUNET_break (0);
755     return;
756   }
757   GSC_CLIENTS_notify_clients_about_neighbour (peer,
758                                               session->tmap, nmap);
759   GSC_TYPEMAP_destroy (session->tmap);
760   session->tmap = nmap;
761 }
762
763
764 /**
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
767  * about the session.
768  *
769  * @param peer peer this is about
770  * @param type type of the message
771  */
772 void
773 GSC_SESSIONS_add_to_typemap (const struct GNUNET_PeerIdentity *peer,
774                              uint16_t type)
775 {
776   struct Session *session;
777   struct GSC_TypeMap *nmap;
778
779   if (0 == memcmp (peer, &GSC_my_identity, sizeof (struct GNUNET_PeerIdentity)))
780     return;
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;
790 }
791
792
793 /**
794  * Initialize sessions subsystem.
795  */
796 void
797 GSC_SESSIONS_init ()
798 {
799   sessions = GNUNET_CONTAINER_multipeermap_create (128, GNUNET_NO);
800 }
801
802
803 /**
804  * Helper function for GSC_SESSIONS_handle_client_iterate_peers.
805  *
806  * @param cls NULL
807  * @param key identity of the connected peer
808  * @param value the `struct Session` for the peer
809  * @return #GNUNET_OK (continue to iterate)
810  */
811 static int
812 free_session_helper (void *cls,
813                      const struct GNUNET_PeerIdentity *key,
814                      void *value)
815 {
816   struct Session *session = value;
817
818   GSC_SESSIONS_end (&session->peer);
819   return GNUNET_OK;
820 }
821
822
823 /**
824  * Shutdown sessions subsystem.
825  */
826 void
827 GSC_SESSIONS_done ()
828 {
829   if (NULL != sessions)
830   {
831     GNUNET_CONTAINER_multipeermap_iterate (sessions, &free_session_helper, NULL);
832     GNUNET_CONTAINER_multipeermap_destroy (sessions);
833     sessions = NULL;
834   }
835 }
836
837 /* end of gnunet-service-core_sessions.c */