cbbc1b850db744548206fd8f92707c4fe91efcda
[oweals/gnunet.git] / src / core / gnunet-service-core_sessions.c
1 /*
2      This file is part of GNUnet.
3      (C) 2009, 2010, 2011 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
35 /**
36  * Message ready for encryption.  This struct is followed by the
37  * actual content of the message.
38  */
39 struct SessionMessageEntry
40 {
41
42   /**
43    * We keep messages in a doubly linked list.
44    */
45   struct SessionMessageEntry *next;
46
47   /**
48    * We keep messages in a doubly linked list.
49    */
50   struct SessionMessageEntry *prev;
51
52   /**
53    * Deadline for transmission, 1s after we received it (if we
54    * are not corking), otherwise "now".  Note that this message
55    * does NOT expire past its deadline.
56    */
57   struct GNUNET_TIME_Absolute deadline;
58
59   /**
60    * How long is the message? (number of bytes following the "struct
61    * MessageEntry", but not including the size of "struct
62    * MessageEntry" itself!)
63    */
64   size_t size;
65
66 };
67
68
69 /**
70  * Data kept per session.
71  */
72 struct Session
73 {
74   /**
75    * Identity of the other peer.
76    */
77   struct GNUNET_PeerIdentity peer;
78
79   /**
80    * Head of list of requests from clients for transmission to
81    * this peer.
82    */
83   struct GSC_ClientActiveRequest *active_client_request_head;
84
85   /**
86    * Tail of list of requests from clients for transmission to
87    * this peer.
88    */
89   struct GSC_ClientActiveRequest *active_client_request_tail;
90
91   /**
92    * Head of list of messages ready for encryption.
93    */
94   struct SessionMessageEntry *sme_head;
95
96   /**
97    * Tail of list of messages ready for encryption.
98    */
99   struct SessionMessageEntry *sme_tail;
100
101   /**
102    * Information about the key exchange with the other peer.
103    */
104   struct GSC_KeyExchangeInfo *kxinfo;
105
106   /**
107    * Current type map for this peer.
108    */
109   struct GSC_TypeMap *tmap;
110
111   /**
112    * At what time did we initially establish this session?
113    * (currently unused, should be integrated with ATS in the
114    * future...).
115    */
116   struct GNUNET_TIME_Absolute time_established;
117
118   /**
119    * Task to transmit corked messages with a delay.
120    */
121   GNUNET_SCHEDULER_TaskIdentifier cork_task;
122
123   /**
124    * Is the neighbour queue empty and thus ready for us
125    * to transmit an encrypted message?  
126    */
127   int ready_to_transmit;
128
129 };
130
131
132 /**
133  * Map of peer identities to 'struct Session'.
134  */
135 static struct GNUNET_CONTAINER_MultiHashMap *sessions;
136
137
138 /**
139  * Find the session for the given peer.
140  *
141  * @param peer identity of the peer
142  * @return NULL if we are not connected, otherwise the
143  *         session handle
144  */
145 static struct Session *
146 find_session (const struct GNUNET_PeerIdentity *peer)
147 {
148   return GNUNET_CONTAINER_multihashmap_get (sessions, &peer->hashPubKey);
149 }
150
151
152 /**
153  * End the session with the given peer (we are no longer
154  * connected). 
155  *
156  * @param pid identity of peer to kill session with
157  */
158 void
159 GSC_SESSIONS_end (const struct GNUNET_PeerIdentity *pid)
160 {
161   struct Session *session;
162   struct GSC_ClientActiveRequest *car;
163
164   session = find_session (pid);
165   if (NULL == session)
166     return;
167 #if DEBUG_CORE
168   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
169               "Destroying session for peer `%4s'\n",
170               GNUNET_i2s (&session->peer));
171 #endif
172   if (GNUNET_SCHEDULER_NO_TASK != session->cork_task)
173   {
174     GNUNET_SCHEDULER_cancel (session->cork_task);
175     session->cork_task = GNUNET_SCHEDULER_NO_TASK;
176   }
177   GNUNET_assert (GNUNET_YES ==
178                  GNUNET_CONTAINER_multihashmap_remove (sessions,
179                                                        &session->peer.hashPubKey, session));
180   while (NULL != (car = session->active_client_request_head))
181   {
182     GNUNET_CONTAINER_DLL_remove (session->active_client_request_head,
183                                  session->active_client_request_tail,
184                                  car);
185     GSC_CLIENTS_reject_request (car);
186   }
187   GNUNET_STATISTICS_set (GSC_stats, 
188                          gettext_noop ("# established sessions"),
189                          GNUNET_CONTAINER_multihashmap_size (sessions), 
190                          GNUNET_NO);
191   if (NULL != session->tmap)
192   {
193     GSC_TYPEMAP_destroy (session->tmap);
194     session->tmap = NULL;
195   }
196   GNUNET_free (session);
197 }
198
199
200 /**
201  * Create a session, a key exchange was just completed.
202  *
203  * @param peer peer that is now connected
204  * @param kx key exchange that completed
205  */
206 void
207 GSC_SESSIONS_create (const struct GNUNET_PeerIdentity *peer,
208                      struct GSC_KeyExchangeInfo *kx)
209 {
210   struct GNUNET_MessageHeader *hdr;
211   struct Session *session;
212
213 #if DEBUG_CORE
214   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
215               "Creating session for peer `%4s'\n", GNUNET_i2s (peer));
216 #endif
217   session = GNUNET_malloc (sizeof (struct Session));
218   session->peer = *peer;
219   session->kxinfo = kx;
220   session->time_established = GNUNET_TIME_absolute_get ();
221   GNUNET_assert (GNUNET_OK ==
222                  GNUNET_CONTAINER_multihashmap_put (sessions,
223                                                     &peer->hashPubKey, session,
224                                                     GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
225   GNUNET_STATISTICS_update (GSC_stats, 
226                             gettext_noop ("# established sessions"),
227                             GNUNET_CONTAINER_multihashmap_size (sessions), 
228                             GNUNET_NO);
229   /* FIXME: we should probably do this periodically (in case
230      type map message is lost...) */
231   hdr = GSC_TYPEMAP_compute_type_map_message ();
232   GSC_KX_encrypt_and_transmit (kx, 
233                                hdr,
234                                ntohs (hdr->size));
235   GNUNET_free (hdr);
236 }
237
238
239 /**
240  * Notify the given client about the session (client is new).
241  *
242  * @param cls the 'struct GSC_Client'
243  * @param key peer identity 
244  * @param value the 'struct Session'
245  * @return GNUNET_OK (continue to iterate)
246  */
247 static int
248 notify_client_about_session (void *cls,
249                              const GNUNET_HashCode *key,
250                              void *value)
251 {
252   struct GSC_Client *client = cls;
253   struct Session *session = value;
254
255   GSC_CLIENTS_notify_client_about_neighbour (client,
256                                              &session->peer,
257                                              NULL, 0, /* FIXME: ATS!? */
258                                              NULL, /* old TMAP: none */
259                                              session->tmap);
260   return GNUNET_OK;
261 }
262
263
264 /**
265  * We have a new client, notify it about all current sessions.
266  *
267  * @param client the new client
268  */
269 void
270 GSC_SESSIONS_notify_client_about_sessions (struct GSC_Client *client)
271 {
272   /* notify new client about existing sessions */
273   GNUNET_CONTAINER_multihashmap_iterate (sessions,
274                                          &notify_client_about_session, client);
275 }
276
277
278 /**
279  * Try to perform a transmission on the given session.  Will solicit
280  * additional messages if the 'sme' queue is not full enough.
281  *
282  * @param session session to transmit messages from
283  */
284 static void
285 try_transmission (struct Session *session);
286
287
288 /**
289  * Queue a request from a client for transmission to a particular peer.
290  *
291  * @param car request to queue; this handle is then shared between
292  *         the caller (CLIENTS subsystem) and SESSIONS and must not
293  *         be released by either until either 'GNUNET_SESSIONS_dequeue',
294  *         'GNUNET_SESSIONS_transmit' or 'GNUNET_CLIENTS_failed'
295  *         have been invoked on it
296  */
297 void
298 GSC_SESSIONS_queue_request (struct GSC_ClientActiveRequest *car)
299 {
300   struct Session *session;
301
302   session = find_session (&car->target);
303   if (session == NULL)
304   {
305     /* neighbour must have disconnected since request was issued,
306      * ignore (client will realize it once it processes the
307      * disconnect notification) */
308 #if DEBUG_CORE
309     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
310                 "Dropped client request for transmission (am disconnected)\n");
311 #endif
312     GNUNET_STATISTICS_update (GSC_stats,
313                               gettext_noop
314                               ("# send requests dropped (disconnected)"), 1,
315                               GNUNET_NO);
316     GSC_CLIENTS_reject_request (car);
317     return;
318   }
319   if (car->msize > GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE)
320   {
321     GNUNET_break (0);
322     GSC_CLIENTS_reject_request (car);
323     return;
324   }
325 #if DEBUG_CORE
326   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
327               "Received client transmission request. queueing\n");
328 #endif
329   GNUNET_CONTAINER_DLL_insert (session->active_client_request_head,
330                                session->active_client_request_tail, car);
331   try_transmission (session);
332 }
333
334
335 /**
336  * Dequeue a request from a client from transmission to a particular peer.
337  *
338  * @param car request to dequeue; this handle will then be 'owned' by
339  *        the caller (CLIENTS sysbsystem)
340  */
341 void
342 GSC_SESSIONS_dequeue_request (struct GSC_ClientActiveRequest *car)
343 {
344   struct Session *s;
345
346   s = find_session (&car->target);
347   GNUNET_CONTAINER_DLL_remove (s->active_client_request_head,
348                                s->active_client_request_tail, car);
349 }
350
351
352 /**
353  * Discard all expired active transmission requests from clients.
354  *
355  * @param session session to clean up
356  */
357 static void
358 discard_expired_requests (struct Session *session)
359 {
360   struct GSC_ClientActiveRequest *pos;
361   struct GSC_ClientActiveRequest *nxt;
362   struct GNUNET_TIME_Absolute now;
363   
364   now = GNUNET_TIME_absolute_get ();
365   pos = NULL;
366   nxt = session->active_client_request_head;
367   while (NULL != nxt)
368   {
369     pos = nxt;
370     nxt = pos->next;
371     if ( (pos->deadline.abs_value < now.abs_value) &&
372          (GNUNET_YES != pos->was_solicited) )
373     {
374       GNUNET_STATISTICS_update (GSC_stats,
375                                 gettext_noop
376                                 ("# messages discarded (expired prior to transmission)"),
377                                 1, GNUNET_NO);
378       GNUNET_CONTAINER_DLL_remove (session->active_client_request_head,
379                                    session->active_client_request_tail,
380                                    pos);
381       GSC_CLIENTS_reject_request (pos);
382     }
383   }
384 }
385
386
387 /**
388  * Solicit messages for transmission.
389  *
390  * @param session session to solict messages for
391  */
392 static void
393 solicit_messages (struct Session *session)
394 {
395   struct GSC_ClientActiveRequest *car;
396   size_t so_size;
397
398   discard_expired_requests (session); 
399   so_size = 0;
400   for (car = session->active_client_request_head; NULL != car; car = car->next)
401   {
402     if (so_size + car->msize > GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE)
403       break;
404     so_size += car->msize;
405     if (car->was_solicited == GNUNET_YES)
406       continue;
407     car->was_solicited = GNUNET_YES;
408     GSC_CLIENTS_solicit_request (car);
409   }
410 }
411
412
413 /**
414  * Some messages were delayed (corked), but the timeout has now expired.  
415  * Send them now.
416  *
417  * @param cls 'struct Session' with the messages to transmit now
418  * @param tc scheduler context (unused)
419  */
420 static void
421 pop_cork_task (void *cls,
422                const struct GNUNET_SCHEDULER_TaskContext *tc)
423 {
424   struct Session *session = cls;
425
426   session->cork_task = GNUNET_SCHEDULER_NO_TASK;
427   try_transmission (session);
428 }
429
430
431 /**
432  * Try to perform a transmission on the given session. Will solicit
433  * additional messages if the 'sme' queue is not full enough.
434  *
435  * @param session session to transmit messages from
436  */
437 static void
438 try_transmission (struct Session *session)
439 {
440   struct SessionMessageEntry *pos;
441   size_t msize;
442   struct GNUNET_TIME_Absolute now;
443   struct GNUNET_TIME_Absolute min_deadline;
444
445   if (GNUNET_YES != session->ready_to_transmit)
446     return;
447   msize = 0;
448   min_deadline = GNUNET_TIME_UNIT_FOREVER_ABS;
449   /* check 'ready' messages */
450   pos = session->sme_head;
451   while ( (NULL != pos) &&
452           (msize + pos->size <= GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE) )
453   {
454     GNUNET_assert (pos->size < GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE);
455     msize += pos->size;
456     min_deadline = GNUNET_TIME_absolute_min (min_deadline,
457                                              pos->deadline);
458     pos = pos->next;
459   }
460   now = GNUNET_TIME_absolute_get ();
461   if ( (msize == 0) ||
462        ( (msize < GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE / 2) &&
463          (min_deadline.abs_value > now.abs_value) ) )
464   {
465     /* not enough ready yet, try to solicit more */
466     solicit_messages (session);
467     if (msize > 0)
468     {
469       /* if there is data to send, just not yet, make sure we do transmit
470          it once the deadline is reached */
471       if (session->cork_task != GNUNET_SCHEDULER_NO_TASK)
472         GNUNET_SCHEDULER_cancel (session->cork_task);
473       session->cork_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_absolute_get_remaining (min_deadline),
474                                                          &pop_cork_task,
475                                                          session);
476     }
477     return;
478   }
479   /* create plaintext buffer of all messages, encrypt and transmit */
480   {
481     static unsigned long long total_bytes;
482     static unsigned int total_msgs;
483     char pbuf[msize];    /* plaintext */
484     size_t used;
485
486     used = 0;
487     while ( (NULL != (pos = session->sme_head)) &&
488             (used + pos->size <= msize) )
489     {
490       memcpy (&pbuf[used], &pos[1], pos->size);
491       used += pos->size;
492       GNUNET_CONTAINER_DLL_remove (session->sme_head,
493                                    session->sme_tail,
494                                    pos);      
495       GNUNET_free (pos);
496     }
497     /* compute average payload size */
498     total_bytes += used;
499     total_msgs++;
500     if (0 == total_msgs)
501     {
502       /* 2^32 messages, wrap around... */
503       total_msgs = 1;
504       total_bytes = used;
505     }
506     GNUNET_STATISTICS_set (GSC_stats, 
507                            "# avg payload per encrypted message",
508                            total_bytes / total_msgs,
509                            GNUNET_NO);
510     /* now actually transmit... */
511     session->ready_to_transmit = GNUNET_NO;
512     GSC_KX_encrypt_and_transmit (session->kxinfo,
513                                  pbuf,
514                                  used);
515   }
516 }
517
518
519 /**
520  * Send a message to the neighbour now.
521  *
522  * @param cls the message
523  * @param key neighbour's identity
524  * @param value 'struct Neighbour' of the target
525  * @return always GNUNET_OK
526  */
527 static int
528 do_send_message (void *cls, const GNUNET_HashCode * key, void *value)
529 {
530   const struct GNUNET_MessageHeader *hdr = cls;
531   struct Session *session = value;
532   struct SessionMessageEntry *m;
533   uint16_t size;
534
535   size = ntohs (hdr->size);
536   m = GNUNET_malloc (sizeof (struct SessionMessageEntry) + size);
537   memcpy (&m[1], hdr, size);
538   m->size = size;
539   GNUNET_CONTAINER_DLL_insert (session->sme_head,
540                                session->sme_tail,
541                                m);
542   try_transmission (session);
543   return GNUNET_OK;
544 }
545
546
547 /**
548  * Broadcast a message to all neighbours.
549  *
550  * @param msg message to transmit
551  */
552 void
553 GSC_SESSIONS_broadcast (const struct GNUNET_MessageHeader *msg)
554 {
555   if (NULL == sessions)
556     return;
557   GNUNET_CONTAINER_multihashmap_iterate (sessions,
558                                          &do_send_message, (void*) msg);
559 }
560
561
562 /**
563  * Traffic is being solicited for the given peer.  This means that the
564  * message queue on the transport-level (NEIGHBOURS subsystem) is now
565  * empty and it is now OK to transmit another (non-control) message.
566  *
567  * @param pid identity of peer ready to receive data
568  */
569 void
570 GSC_SESSIONS_solicit (const struct GNUNET_PeerIdentity *pid)
571 {
572   struct Session *session;
573
574   session = find_session (pid);
575   if (NULL == session)
576     return;
577   session->ready_to_transmit = GNUNET_YES;
578   try_transmission (session);
579 }
580
581
582 /**
583  * Transmit a message to a particular peer.
584  *
585  * @param car original request that was queued and then solicited;
586  *            this handle will now be 'owned' by the SESSIONS subsystem
587  * @param msg message to transmit
588  * @param cork is corking allowed?
589  */
590 void
591 GSC_SESSIONS_transmit (struct GSC_ClientActiveRequest *car,
592                        const struct GNUNET_MessageHeader *msg,
593                        int cork)
594 {
595   struct Session *session;
596   struct SessionMessageEntry *sme;
597   size_t msize;
598
599   session = find_session (&car->target);
600   msize = ntohs (msg->size);
601   sme = GNUNET_malloc (sizeof (struct SessionMessageEntry) + msize);
602   memcpy (&sme[1], msg, msize);
603   sme->size = msize;
604   if (GNUNET_YES == cork)
605     sme->deadline = GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_MAX_CORK_DELAY);
606   GNUNET_CONTAINER_DLL_insert_tail (session->sme_head,
607                                     session->sme_tail,
608                                     sme);
609   try_transmission (session);
610 }
611
612
613 /**
614  * Helper function for GSC_SESSIONS_handle_client_iterate_peers.
615  *
616  * @param cls the 'struct GNUNET_SERVER_TransmitContext' to queue replies
617  * @param key identity of the connected peer
618  * @param value the 'struct Neighbour' for the peer
619  * @return GNUNET_OK (continue to iterate)
620  */
621 #include "core.h"
622 static int
623 queue_connect_message (void *cls, const GNUNET_HashCode * key, void *value)
624 {
625   struct GNUNET_SERVER_TransmitContext *tc = cls;
626   struct Session *session = value;
627   struct ConnectNotifyMessage cnm;
628   struct GNUNET_TRANSPORT_ATS_Information *a;
629  
630   /* FIXME: code duplication with clients... */
631   cnm.header.size = htons (sizeof (struct ConnectNotifyMessage));
632   cnm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT);
633   cnm.ats_count = htonl (0);
634   cnm.peer = session->peer;
635   a = &cnm.ats;
636   // FIXME: full ats...
637   a[0].type = htonl (GNUNET_TRANSPORT_ATS_ARRAY_TERMINATOR);
638   a[0].value = htonl (0);
639   GNUNET_SERVER_transmit_context_append_message (tc, &cnm.header);
640   return GNUNET_OK;
641 }
642
643
644 /**
645  * Handle CORE_ITERATE_PEERS request. For this request type, the client
646  * does not have to have transmitted an INIT request.  All current peers
647  * are returned, regardless of which message types they accept. 
648  *
649  * @param cls unused
650  * @param client client sending the iteration request
651  * @param message iteration request message
652  */
653 void
654 GSC_SESSIONS_handle_client_iterate_peers (void *cls, struct GNUNET_SERVER_Client *client,
655                                           const struct GNUNET_MessageHeader *message)
656 {
657   struct GNUNET_MessageHeader done_msg;
658   struct GNUNET_SERVER_TransmitContext *tc;
659
660   tc = GNUNET_SERVER_transmit_context_create (client);
661   GNUNET_CONTAINER_multihashmap_iterate (sessions, 
662                                          &queue_connect_message,
663                                          tc);
664   done_msg.size = htons (sizeof (struct GNUNET_MessageHeader));
665   done_msg.type = htons (GNUNET_MESSAGE_TYPE_CORE_ITERATE_PEERS_END);
666   GNUNET_SERVER_transmit_context_append_message (tc, &done_msg);
667   GNUNET_SERVER_transmit_context_run (tc, GNUNET_TIME_UNIT_FOREVER_REL);
668 }
669
670
671 /**
672  * Handle CORE_PEER_CONNECTED request.   Notify client about connection
673  * to the given neighbour.  For this request type, the client does not
674  * have to have transmitted an INIT request.  All current peers are
675  * returned, regardless of which message types they accept.
676  *
677  * @param cls unused
678  * @param client client sending the iteration request
679  * @param message iteration request message
680  */
681 void
682 GSC_SESSIONS_handle_client_have_peer (void *cls, struct GNUNET_SERVER_Client *client,
683                                       const struct GNUNET_MessageHeader *message)
684 {
685   struct GNUNET_MessageHeader done_msg;
686   struct GNUNET_SERVER_TransmitContext *tc;
687   const struct GNUNET_PeerIdentity *peer;
688
689   peer = (const struct GNUNET_PeerIdentity *) &message[1]; // YUCK!
690   tc = GNUNET_SERVER_transmit_context_create (client);
691   GNUNET_CONTAINER_multihashmap_get_multiple (sessions, &peer->hashPubKey,
692                                               &queue_connect_message, tc);
693   done_msg.size = htons (sizeof (struct GNUNET_MessageHeader));
694   done_msg.type = htons (GNUNET_MESSAGE_TYPE_CORE_ITERATE_PEERS_END);
695   GNUNET_SERVER_transmit_context_append_message (tc, &done_msg);
696   GNUNET_SERVER_transmit_context_run (tc, GNUNET_TIME_UNIT_FOREVER_REL);
697 }
698
699
700 /**
701  * We've received a typemap message from a peer, update ours.
702  * Notifies clients about the session.
703  *
704  * @param peer peer this is about
705  * @param msg typemap update message
706  */
707 void
708 GSC_SESSIONS_set_typemap (const struct GNUNET_PeerIdentity *peer,
709                           const struct GNUNET_MessageHeader *msg)
710 {
711   struct Session *session;
712   struct GSC_TypeMap *nmap;
713
714   nmap = GSC_TYPEMAP_get_from_message (msg);
715   if (NULL == nmap)
716     return; /* malformed */
717   session = find_session (peer);
718   if (NULL == session)
719   {
720     GNUNET_break (0);
721     return;
722   }
723   GSC_CLIENTS_notify_clients_about_neighbour (peer,
724                                               NULL, 0, /* FIXME: ATS */
725                                               session->tmap,
726                                               nmap);
727   if (NULL != session->tmap)
728     GSC_TYPEMAP_destroy (session->tmap);
729   session->tmap = nmap;
730 }
731
732
733 /**
734  * The given peer send a message of the specified type.  Make sure the
735  * respective bit is set in its type-map and that clients are notified
736  * about the session.
737  *
738  * @param peer peer this is about
739  * @param type type of the message
740  */
741 void
742 GSC_SESSIONS_add_to_typemap (const struct GNUNET_PeerIdentity *peer,
743                              uint16_t type)
744 {
745   struct Session *session;
746   struct GSC_TypeMap *nmap;
747
748   if (0 == memcmp (peer, &GSC_my_identity, sizeof (struct GNUNET_PeerIdentity)))
749     return;
750   session = find_session (peer);
751   GNUNET_assert (NULL != session);
752   if (GNUNET_YES ==
753       GSC_TYPEMAP_test_match (session->tmap,
754                               &type, 1))
755     return; /* already in it */
756   nmap = GSC_TYPEMAP_extend (session->tmap,
757                              &type, 1);
758   GSC_CLIENTS_notify_clients_about_neighbour (peer,
759                                               NULL, 0, /* FIXME: ATS */
760                                               session->tmap,
761                                               nmap);
762   if (NULL != session->tmap)
763     GSC_TYPEMAP_destroy (session->tmap);
764   session->tmap = nmap;
765 }
766
767
768 /**
769  * Initialize sessions subsystem.
770  */
771 void
772 GSC_SESSIONS_init ()
773 {
774   sessions = GNUNET_CONTAINER_multihashmap_create (128);
775 }
776
777
778 /**
779  * Helper function for GSC_SESSIONS_handle_client_iterate_peers.
780  *
781  * @param cls NULL
782  * @param key identity of the connected peer
783  * @param value the 'struct Session' for the peer
784  * @return GNUNET_OK (continue to iterate)
785  */
786 static int
787 free_session_helper (void *cls, const GNUNET_HashCode * key, void *value)
788 {
789   struct Session *session = value;
790
791   GSC_SESSIONS_end (&session->peer);
792   return GNUNET_OK;
793 }
794
795
796 /**
797  * Shutdown sessions subsystem.
798  */
799 void
800 GSC_SESSIONS_done ()
801 {
802   GNUNET_CONTAINER_multihashmap_iterate (sessions,
803                                          &free_session_helper,
804                                          NULL);
805   GNUNET_CONTAINER_multihashmap_destroy (sessions);
806   sessions = NULL;
807   GNUNET_STATISTICS_set (GSC_stats, 
808                          gettext_noop ("# established sessions"),
809                          0, GNUNET_NO);
810 }
811
812 /* end of gnunet-service-core_sessions.c */
813