-indent, doxygen
[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  * Message ready for encryption.  This struct is followed by the
39  * actual content of the message.
40  */
41 struct SessionMessageEntry
42 {
43
44   /**
45    * We keep messages in a doubly linked list.
46    */
47   struct SessionMessageEntry *next;
48
49   /**
50    * We keep messages in a doubly linked list.
51    */
52   struct SessionMessageEntry *prev;
53
54   /**
55    * Deadline for transmission, 1s after we received it (if we
56    * are not corking), otherwise "now".  Note that this message
57    * does NOT expire past its deadline.
58    */
59   struct GNUNET_TIME_Absolute deadline;
60
61   /**
62    * How long is the message? (number of bytes following the "struct
63    * MessageEntry", but not including the size of "struct
64    * MessageEntry" itself!)
65    */
66   size_t size;
67
68   /**
69    * How important is this message.
70    */
71   enum GNUNET_CORE_Priority priority;
72
73 };
74
75
76 /**
77  * Data kept per session.
78  */
79 struct Session
80 {
81   /**
82    * Identity of the other peer.
83    */
84   struct GNUNET_PeerIdentity peer;
85
86   /**
87    * Head of list of requests from clients for transmission to
88    * this peer.
89    */
90   struct GSC_ClientActiveRequest *active_client_request_head;
91
92   /**
93    * Tail of list of requests from clients for transmission to
94    * this peer.
95    */
96   struct GSC_ClientActiveRequest *active_client_request_tail;
97
98   /**
99    * Head of list of messages ready for encryption.
100    */
101   struct SessionMessageEntry *sme_head;
102
103   /**
104    * Tail of list of messages ready for encryption.
105    */
106   struct SessionMessageEntry *sme_tail;
107
108   /**
109    * Information about the key exchange with the other peer.
110    */
111   struct GSC_KeyExchangeInfo *kxinfo;
112
113   /**
114    * Current type map for this peer.
115    */
116   struct GSC_TypeMap *tmap;
117
118   /**
119    * Task to transmit corked messages with a delay.
120    */
121   GNUNET_SCHEDULER_TaskIdentifier cork_task;
122
123   /**
124    * Task to transmit our type map.
125    */
126   GNUNET_SCHEDULER_TaskIdentifier typemap_task;
127
128   /**
129    * Retransmission delay we currently use for the typemap
130    * transmissions (if not confirmed).
131    */
132   struct GNUNET_TIME_Relative typemap_delay;
133
134   /**
135    * Is the neighbour queue empty and thus ready for us
136    * to transmit an encrypted message?
137    */
138   int ready_to_transmit;
139
140   /**
141    * Is this the first time we're sending the typemap? If so,
142    * we want to send it a bit faster the second time.  0 if
143    * we are sending for the first time, 1 if not.
144    */
145   int first_typemap;
146 };
147
148
149 GNUNET_NETWORK_STRUCT_BEGIN
150
151 /**
152  * Message sent to confirm that a typemap was received.
153  */
154 struct TypeMapConfirmationMessage
155 {
156
157   /**
158    * Header with type #GNUNET_MESSAGE_TYPE_CORE_CONFIRM_TYPE_MAP.
159    */
160   struct GNUNET_MessageHeader header;
161
162   /**
163    * Reserved, always zero.
164    */
165   uint32_t reserved GNUNET_PACKED;
166
167   /**
168    * Hash of the (decompressed) type map that was received.
169    */
170   struct GNUNET_HashCode tm_hash;
171
172 };
173
174 GNUNET_NETWORK_STRUCT_END
175
176
177 /**
178  * Map of peer identities to `struct Session`.
179  */
180 static struct GNUNET_CONTAINER_MultiPeerMap *sessions;
181
182
183 /**
184  * Find the session for the given peer.
185  *
186  * @param peer identity of the peer
187  * @return NULL if we are not connected, otherwise the
188  *         session handle
189  */
190 static struct Session *
191 find_session (const struct GNUNET_PeerIdentity *peer)
192 {
193   return GNUNET_CONTAINER_multipeermap_get (sessions, peer);
194 }
195
196
197 /**
198  * End the session with the given peer (we are no longer
199  * connected).
200  *
201  * @param pid identity of peer to kill session with
202  */
203 void
204 GSC_SESSIONS_end (const struct GNUNET_PeerIdentity *pid)
205 {
206   struct Session *session;
207   struct GSC_ClientActiveRequest *car;
208   struct SessionMessageEntry *sme;
209
210   session = find_session (pid);
211   if (NULL == session)
212     return;
213   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
214               "Destroying session for peer `%4s'\n",
215               GNUNET_i2s (&session->peer));
216   if (GNUNET_SCHEDULER_NO_TASK != session->cork_task)
217   {
218     GNUNET_SCHEDULER_cancel (session->cork_task);
219     session->cork_task = GNUNET_SCHEDULER_NO_TASK;
220   }
221   while (NULL != (car = session->active_client_request_head))
222   {
223     GNUNET_CONTAINER_DLL_remove (session->active_client_request_head,
224                                  session->active_client_request_tail, car);
225     GSC_CLIENTS_reject_request (car);
226   }
227   while (NULL != (sme = session->sme_head))
228   {
229     GNUNET_CONTAINER_DLL_remove (session->sme_head,
230                                  session->sme_tail,
231                                  sme);
232     GNUNET_free (sme);
233   }
234   if (GNUNET_SCHEDULER_NO_TASK != session->typemap_task)
235   {
236     GNUNET_SCHEDULER_cancel (session->typemap_task);
237     session->typemap_task = GNUNET_SCHEDULER_NO_TASK;
238   }
239   GSC_CLIENTS_notify_clients_about_neighbour (&session->peer,
240                                               session->tmap, NULL);
241   GNUNET_assert (GNUNET_YES ==
242                  GNUNET_CONTAINER_multipeermap_remove (sessions,
243                                                        &session->peer,
244                                                        session));
245   GNUNET_STATISTICS_set (GSC_stats, gettext_noop ("# peers connected"),
246                          GNUNET_CONTAINER_multipeermap_size (sessions),
247                          GNUNET_NO);
248   GSC_TYPEMAP_destroy (session->tmap);
249   session->tmap = NULL;
250   GNUNET_free (session);
251 }
252
253
254 /**
255  * Transmit our current typemap message to the other peer.
256  * (Done periodically until the typemap is confirmed).
257  *
258  * @param cls the `struct Session *`
259  * @param tc unused
260  */
261 static void
262 transmit_typemap_task (void *cls,
263                        const struct GNUNET_SCHEDULER_TaskContext *tc)
264 {
265   struct Session *session = cls;
266   struct GNUNET_MessageHeader *hdr;
267   struct GNUNET_TIME_Relative delay;
268
269   session->typemap_delay = GNUNET_TIME_STD_BACKOFF (session->typemap_delay);
270   delay = session->typemap_delay;
271   /* randomize a bit to avoid spont. sync */
272   delay.rel_value_us +=
273       GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, 1000 * 1000);
274   session->typemap_task =
275       GNUNET_SCHEDULER_add_delayed (delay,
276                                     &transmit_typemap_task, session);
277   GNUNET_STATISTICS_update (GSC_stats,
278                             gettext_noop ("# type map refreshes sent"), 1,
279                             GNUNET_NO);
280   hdr = GSC_TYPEMAP_compute_type_map_message ();
281   GSC_KX_encrypt_and_transmit (session->kxinfo, hdr, ntohs (hdr->size));
282   GNUNET_free (hdr);
283 }
284
285
286 /**
287  * Restart the typemap task for the given session.
288  *
289  * @param session session to restart typemap transmission for
290  */
291 static void
292 start_typemap_task (struct Session *session)
293 {
294   if (GNUNET_SCHEDULER_NO_TASK != session->typemap_task)
295     GNUNET_SCHEDULER_cancel (session->typemap_task);
296   session->typemap_delay = GNUNET_TIME_UNIT_SECONDS;
297   session->typemap_task =
298     GNUNET_SCHEDULER_add_delayed (session->typemap_delay,
299                                   &transmit_typemap_task,
300                                   session);
301 }
302
303
304 /**
305  * Create a session, a key exchange was just completed.
306  *
307  * @param peer peer that is now connected
308  * @param kx key exchange that completed
309  */
310 void
311 GSC_SESSIONS_create (const struct GNUNET_PeerIdentity *peer,
312                      struct GSC_KeyExchangeInfo *kx)
313 {
314   struct Session *session;
315
316   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
317               "Creating session for peer `%4s'\n",
318               GNUNET_i2s (peer));
319   session = GNUNET_new (struct Session);
320   session->tmap = GSC_TYPEMAP_create ();
321   session->peer = *peer;
322   session->kxinfo = kx;
323   GNUNET_assert (GNUNET_OK ==
324                  GNUNET_CONTAINER_multipeermap_put (sessions,
325                                                     &session->peer,
326                                                     session,
327                                                     GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
328   GNUNET_STATISTICS_set (GSC_stats, gettext_noop ("# peers connected"),
329                          GNUNET_CONTAINER_multipeermap_size (sessions),
330                          GNUNET_NO);
331   GSC_CLIENTS_notify_clients_about_neighbour (peer,
332                                               NULL,
333                                               session->tmap);
334   start_typemap_task (session);
335 }
336
337
338 /**
339  * The other peer has indicated that he 'lost' the session
340  * (KX down), reinitialize the session on our end, in particular
341  * this means to restart the typemap transmission.
342  *
343  * @param peer peer that is now connected
344  */
345 void
346 GSC_SESSIONS_reinit (const struct GNUNET_PeerIdentity *peer)
347 {
348   struct Session *session;
349
350   session = find_session (peer);
351   if (NULL == session)
352   {
353     /* KX/session is new for both sides; thus no need to restart what
354        has not yet begun */
355     return;
356   }
357   start_typemap_task (session);
358 }
359
360
361 /**
362  * The other peer has confirmed receiving our type map,
363  * check if it is current and if so, stop retransmitting it.
364  *
365  * @param peer peer that confirmed the type map
366  * @param msg confirmation message we received
367  */
368 void
369 GSC_SESSIONS_confirm_typemap (const struct GNUNET_PeerIdentity *peer,
370                               const struct GNUNET_MessageHeader *msg)
371 {
372   const struct TypeMapConfirmationMessage *cmsg;
373   struct Session *session;
374
375   session = find_session (peer);
376   if (NULL == session)
377   {
378     GNUNET_break (0);
379     return;
380   }
381   if (ntohs (msg->size) != sizeof (struct TypeMapConfirmationMessage))
382   {
383     GNUNET_break_op (0);
384     return;
385   }
386   cmsg = (const struct TypeMapConfirmationMessage *) msg;
387   if (GNUNET_YES !=
388       GSC_TYPEMAP_check_hash (&cmsg->tm_hash))
389   {
390     /* our typemap has changed in the meantime, do not
391        accept confirmation */
392     GNUNET_STATISTICS_update (GSC_stats,
393                               gettext_noop
394                               ("# outdated typemap confirmations received"),
395                               1, GNUNET_NO);
396     return;
397   }
398   if (GNUNET_SCHEDULER_NO_TASK != session->typemap_task)
399   {
400     GNUNET_SCHEDULER_cancel (session->typemap_task);
401     session->typemap_task = GNUNET_SCHEDULER_NO_TASK;
402   }
403   GNUNET_STATISTICS_update (GSC_stats,
404                             gettext_noop
405                             ("# valid typemap confirmations received"),
406                             1, GNUNET_NO);
407 }
408
409
410 /**
411  * Notify the given client about the session (client is new).
412  *
413  * @param cls the `struct GSC_Client`
414  * @param key peer identity
415  * @param value the `struct Session`
416  * @return #GNUNET_OK (continue to iterate)
417  */
418 static int
419 notify_client_about_session (void *cls,
420                              const struct GNUNET_PeerIdentity *key,
421                              void *value)
422 {
423   struct GSC_Client *client = cls;
424   struct Session *session = value;
425
426   GSC_CLIENTS_notify_client_about_neighbour (client,
427                                              &session->peer,
428                                              NULL,      /* old TMAP: none */
429                                              session->tmap);
430   return GNUNET_OK;
431 }
432
433
434 /**
435  * We have a new client, notify it about all current sessions.
436  *
437  * @param client the new client
438  */
439 void
440 GSC_SESSIONS_notify_client_about_sessions (struct GSC_Client *client)
441 {
442   /* notify new client about existing sessions */
443   GNUNET_CONTAINER_multipeermap_iterate (sessions,
444                                          &notify_client_about_session,
445                                          client);
446 }
447
448
449 /**
450  * Try to perform a transmission on the given session.  Will solicit
451  * additional messages if the 'sme' queue is not full enough.
452  *
453  * @param session session to transmit messages from
454  */
455 static void
456 try_transmission (struct Session *session);
457
458
459 /**
460  * Queue a request from a client for transmission to a particular peer.
461  *
462  * @param car request to queue; this handle is then shared between
463  *         the caller (CLIENTS subsystem) and SESSIONS and must not
464  *         be released by either until either #GSC_SESSIONS_dequeue(),
465  *         #GSC_SESSIONS_transmit() or #GSC_CLIENTS_failed()
466  *         have been invoked on it
467  */
468 void
469 GSC_SESSIONS_queue_request (struct GSC_ClientActiveRequest *car)
470 {
471   struct Session *session;
472
473   session = find_session (&car->target);
474   if (NULL == session)
475   {
476     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
477                 "Dropped client request for transmission (am disconnected)\n");
478     GNUNET_break (0);           /* should have been rejected earlier */
479     GSC_CLIENTS_reject_request (car);
480     return;
481   }
482   if (car->msize > GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE)
483   {
484     GNUNET_break (0);
485     GSC_CLIENTS_reject_request (car);
486     return;
487   }
488   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
489               "Received client transmission request. queueing\n");
490   GNUNET_CONTAINER_DLL_insert (session->active_client_request_head,
491                                session->active_client_request_tail, car);
492   try_transmission (session);
493 }
494
495
496 /**
497  * Dequeue a request from a client from transmission to a particular peer.
498  *
499  * @param car request to dequeue; this handle will then be 'owned' by
500  *        the caller (CLIENTS sysbsystem)
501  */
502 void
503 GSC_SESSIONS_dequeue_request (struct GSC_ClientActiveRequest *car)
504 {
505   struct Session *session;
506
507   if (0 ==
508       memcmp (&car->target, &GSC_my_identity,
509               sizeof (struct GNUNET_PeerIdentity)))
510     return;
511   session = find_session (&car->target);
512   GNUNET_assert (NULL != session);
513   GNUNET_CONTAINER_DLL_remove (session->active_client_request_head,
514                                session->active_client_request_tail,
515                                car);
516 }
517
518
519 /**
520  * Discard all expired active transmission requests from clients.
521  *
522  * @param session session to clean up
523  */
524 static void
525 discard_expired_requests (struct Session *session)
526 {
527   struct GSC_ClientActiveRequest *pos;
528   struct GSC_ClientActiveRequest *nxt;
529   struct GNUNET_TIME_Absolute now;
530
531   now = GNUNET_TIME_absolute_get ();
532   pos = NULL;
533   nxt = session->active_client_request_head;
534   while (NULL != nxt)
535   {
536     pos = nxt;
537     nxt = pos->next;
538     if ((pos->deadline.abs_value_us < now.abs_value_us) &&
539         (GNUNET_YES != pos->was_solicited))
540     {
541       GNUNET_STATISTICS_update (GSC_stats,
542                                 gettext_noop
543                                 ("# messages discarded (expired prior to transmission)"),
544                                 1, GNUNET_NO);
545       GNUNET_CONTAINER_DLL_remove (session->active_client_request_head,
546                                    session->active_client_request_tail, pos);
547       GSC_CLIENTS_reject_request (pos);
548     }
549   }
550 }
551
552
553 /**
554  * Solicit messages for transmission, starting with those of the highest
555  * priority.
556  *
557  * @param session session to solict messages for
558  * @param msize how many bytes do we have already
559  */
560 static void
561 solicit_messages (struct Session *session,
562                   size_t msize)
563 {
564   struct GSC_ClientActiveRequest *car;
565   struct GSC_ClientActiveRequest *nxt;
566   size_t so_size;
567   enum GNUNET_CORE_Priority pmax;
568
569   discard_expired_requests (session);
570   so_size = msize;
571   pmax = GNUNET_CORE_PRIO_BACKGROUND;
572   for (car = session->active_client_request_head; NULL != car; car = car->next)
573   {
574     if (GNUNET_YES == car->was_solicited)
575       continue;
576     pmax = GNUNET_MAX (pmax, car->priority);
577   }
578   nxt = session->active_client_request_head;
579   while (NULL != (car = nxt))
580   {
581     nxt = car->next;
582     if (car->priority < pmax)
583       continue;
584     if (so_size + car->msize > GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE)
585       break;
586     so_size += car->msize;
587     if (GNUNET_YES == car->was_solicited)
588       continue;
589     car->was_solicited = GNUNET_YES;
590     GSC_CLIENTS_solicit_request (car);
591   }
592 }
593
594
595 /**
596  * Some messages were delayed (corked), but the timeout has now expired.
597  * Send them now.
598  *
599  * @param cls `struct Session` with the messages to transmit now
600  * @param tc scheduler context (unused)
601  */
602 static void
603 pop_cork_task (void *cls,
604                const struct GNUNET_SCHEDULER_TaskContext *tc)
605 {
606   struct Session *session = cls;
607
608   session->cork_task = GNUNET_SCHEDULER_NO_TASK;
609   try_transmission (session);
610 }
611
612
613 /**
614  * Try to perform a transmission on the given session. Will solicit
615  * additional messages if the 'sme' queue is not full enough or has
616  * only low-priority messages.
617  *
618  * @param session session to transmit messages from
619  */
620 static void
621 try_transmission (struct Session *session)
622 {
623   struct SessionMessageEntry *pos;
624   size_t msize;
625   struct GNUNET_TIME_Absolute now;
626   struct GNUNET_TIME_Absolute min_deadline;
627   enum GNUNET_CORE_Priority maxp;
628   enum GNUNET_CORE_Priority maxpc;
629   struct GSC_ClientActiveRequest *car;
630   int excess;
631
632   if (GNUNET_YES != session->ready_to_transmit)
633     return;
634   msize = 0;
635   min_deadline = GNUNET_TIME_UNIT_FOREVER_ABS;
636   /* if the peer has excess bandwidth, background traffic is allowed,
637      otherwise not */
638   excess = GSC_NEIGHBOURS_check_excess_bandwidth (&session->peer);
639   if (GNUNET_YES == excess)
640     maxp = GNUNET_CORE_PRIO_BACKGROUND;
641   else
642     maxp = GNUNET_CORE_PRIO_BEST_EFFORT;
643   /* determine highest priority of 'ready' messages we already solicited from clients */
644   pos = session->sme_head;
645   while ((NULL != pos) &&
646          (msize + pos->size <= GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE))
647   {
648     GNUNET_assert (pos->size < GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE);
649     msize += pos->size;
650     maxp = GNUNET_MAX (maxp, pos->priority);
651     min_deadline = GNUNET_TIME_absolute_min (min_deadline, pos->deadline);
652     pos = pos->next;
653   }
654   if (maxp < GNUNET_CORE_PRIO_CRITICAL_CONTROL)
655   {
656     /* if highest already solicited priority from clients is not critical,
657        check if there are higher-priority messages to be solicited from clients */
658     if (GNUNET_YES == excess)
659       maxpc = GNUNET_CORE_PRIO_BACKGROUND;
660     else
661       maxpc = GNUNET_CORE_PRIO_BEST_EFFORT;
662     for (car = session->active_client_request_head; NULL != car; car = car->next)
663     {
664       if (GNUNET_YES == car->was_solicited)
665         continue;
666       maxpc = GNUNET_MAX (maxpc, car->priority);
667     }
668     if (maxpc > maxp)
669     {
670       /* we have messages waiting for solicitation that have a higher
671          priority than those that we already accepted; solicit the
672          high-priority messages first */
673       solicit_messages (session, 0);
674       return;
675     }
676   }
677   else
678   {
679     /* never solicit more, we have critical messages to process */
680     excess = GNUNET_NO;
681     maxpc = GNUNET_CORE_PRIO_BACKGROUND;
682   }
683   now = GNUNET_TIME_absolute_get ();
684   if ( ( (GNUNET_YES == excess) ||
685          (maxpc >= GNUNET_CORE_PRIO_BEST_EFFORT) ) &&
686        ( (0 == msize) ||
687          ( (msize < GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE / 2) &&
688            (min_deadline.abs_value_us > now.abs_value_us))) )
689   {
690     /* not enough ready yet (tiny message & cork possible), or no messages at all,
691        and either excess bandwidth or best-effort or higher message waiting at
692        client; in this case, we try to solicit more */
693     solicit_messages (session,
694                       msize);
695     if (msize > 0)
696     {
697       /* if there is data to send, just not yet, make sure we do transmit
698        * it once the deadline is reached */
699       if (GNUNET_SCHEDULER_NO_TASK != session->cork_task)
700         GNUNET_SCHEDULER_cancel (session->cork_task);
701       session->cork_task =
702           GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_absolute_get_remaining
703                                         (min_deadline), &pop_cork_task,
704                                         session);
705     }
706     return;
707   }
708   /* create plaintext buffer of all messages (that fit), encrypt and
709      transmit */
710   {
711     static unsigned long long total_bytes;
712     static unsigned int total_msgs;
713     char pbuf[msize];           /* plaintext */
714     size_t used;
715
716     used = 0;
717     while ( (NULL != (pos = session->sme_head)) &&
718             (used + pos->size <= msize) )
719     {
720       memcpy (&pbuf[used], &pos[1], pos->size);
721       used += pos->size;
722       GNUNET_CONTAINER_DLL_remove (session->sme_head,
723                                    session->sme_tail,
724                                    pos);
725       GNUNET_free (pos);
726     }
727     /* compute average payload size */
728     total_bytes += used;
729     total_msgs++;
730     if (0 == total_msgs)
731     {
732       /* 2^32 messages, wrap around... */
733       total_msgs = 1;
734       total_bytes = used;
735     }
736     GNUNET_STATISTICS_set (GSC_stats,
737                            "# avg payload per encrypted message",
738                            total_bytes / total_msgs, GNUNET_NO);
739     /* now actually transmit... */
740     session->ready_to_transmit = GNUNET_NO;
741     GSC_KX_encrypt_and_transmit (session->kxinfo, pbuf, used);
742   }
743 }
744
745
746 /**
747  * Send an updated typemap message to the neighbour now,
748  * and restart typemap transmissions.
749  *
750  * @param cls the message
751  * @param key neighbour's identity
752  * @param value `struct Neighbour` of the target
753  * @return always #GNUNET_OK
754  */
755 static int
756 do_restart_typemap_message (void *cls,
757                             const struct GNUNET_PeerIdentity *key,
758                             void *value)
759 {
760   const struct GNUNET_MessageHeader *hdr = cls;
761   struct Session *session = value;
762   struct SessionMessageEntry *sme;
763   uint16_t size;
764
765   size = ntohs (hdr->size);
766   sme = GNUNET_malloc (sizeof (struct SessionMessageEntry) + size);
767   memcpy (&sme[1], hdr, size);
768   sme->size = size;
769   sme->priority = GNUNET_CORE_PRIO_CRITICAL_CONTROL;
770   GNUNET_CONTAINER_DLL_insert (session->sme_head,
771                                session->sme_tail,
772                                sme);
773   try_transmission (session);
774   start_typemap_task (session);
775   return GNUNET_OK;
776 }
777
778
779 /**
780  * Broadcast an updated typemap message to all neighbours.
781  * Restarts the retransmissions until the typemaps are confirmed.
782  *
783  * @param msg message to transmit
784  */
785 void
786 GSC_SESSIONS_broadcast_typemap (const struct GNUNET_MessageHeader *msg)
787 {
788   if (NULL == sessions)
789     return;
790   GNUNET_CONTAINER_multipeermap_iterate (sessions,
791                                          &do_restart_typemap_message,
792                                          (void *) msg);
793 }
794
795
796 /**
797  * Traffic is being solicited for the given peer.  This means that the
798  * message queue on the transport-level (NEIGHBOURS subsystem) is now
799  * empty and it is now OK to transmit another (non-control) message.
800  *
801  * @param pid identity of peer ready to receive data
802  */
803 void
804 GSC_SESSIONS_solicit (const struct GNUNET_PeerIdentity *pid)
805 {
806   struct Session *session;
807
808   session = find_session (pid);
809   if (NULL == session)
810     return;
811   session->ready_to_transmit = GNUNET_YES;
812   try_transmission (session);
813 }
814
815
816 /**
817  * Transmit a message to a particular peer.
818  *
819  * @param car original request that was queued and then solicited;
820  *            this handle will now be 'owned' by the SESSIONS subsystem
821  * @param msg message to transmit
822  * @param cork is corking allowed?
823  * @param priority how important is this message
824  */
825 void
826 GSC_SESSIONS_transmit (struct GSC_ClientActiveRequest *car,
827                        const struct GNUNET_MessageHeader *msg,
828                        int cork,
829                        enum GNUNET_CORE_Priority priority)
830 {
831   struct Session *session;
832   struct SessionMessageEntry *sme;
833   struct SessionMessageEntry *pos;
834   size_t msize;
835
836   session = find_session (&car->target);
837   if (NULL == session)
838     return;
839   msize = ntohs (msg->size);
840   sme = GNUNET_malloc (sizeof (struct SessionMessageEntry) + msize);
841   memcpy (&sme[1], msg, msize);
842   sme->size = msize;
843   sme->priority = priority;
844   if (GNUNET_YES == cork)
845     sme->deadline =
846         GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_MAX_CORK_DELAY);
847   pos = session->sme_head;
848   while ( (NULL != pos) &&
849           (pos->priority > sme->priority) )
850     pos = pos->next;
851   if (NULL == pos)
852     GNUNET_CONTAINER_DLL_insert_tail (session->sme_head,
853                                       session->sme_tail,
854                                       sme);
855   else
856     GNUNET_CONTAINER_DLL_insert_after (session->sme_head,
857                                        session->sme_tail,
858                                        pos->prev,
859                                        sme);
860   try_transmission (session);
861 }
862
863
864 /**
865  * We have received a typemap message from a peer, update ours.
866  * Notifies clients about the session.
867  *
868  * @param peer peer this is about
869  * @param msg typemap update message
870  */
871 void
872 GSC_SESSIONS_set_typemap (const struct GNUNET_PeerIdentity *peer,
873                           const struct GNUNET_MessageHeader *msg)
874 {
875   struct Session *session;
876   struct GSC_TypeMap *nmap;
877   struct SessionMessageEntry *sme;
878   struct TypeMapConfirmationMessage *tmc;
879
880   nmap = GSC_TYPEMAP_get_from_message (msg);
881   if (NULL == nmap)
882     return;                     /* malformed */
883   session = find_session (peer);
884   if (NULL == session)
885   {
886     GNUNET_break (0);
887     return;
888   }
889   sme = GNUNET_malloc (sizeof (struct SessionMessageEntry) +
890                        sizeof (struct TypeMapConfirmationMessage));
891   sme->deadline = GNUNET_TIME_absolute_get ();
892   sme->size = sizeof (struct TypeMapConfirmationMessage);
893   sme->priority = GNUNET_CORE_PRIO_CRITICAL_CONTROL;
894   tmc = (struct TypeMapConfirmationMessage *) &sme[1];
895   tmc->header.size = htons (sizeof (struct TypeMapConfirmationMessage));
896   tmc->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_CONFIRM_TYPE_MAP);
897   tmc->reserved = htonl (0);
898   GSC_TYPEMAP_hash (nmap,
899                     &tmc->tm_hash);
900   GNUNET_CONTAINER_DLL_insert (session->sme_head,
901                                session->sme_tail,
902                                sme);
903   try_transmission (session);
904   GSC_CLIENTS_notify_clients_about_neighbour (peer,
905                                               session->tmap,
906                                               nmap);
907   GSC_TYPEMAP_destroy (session->tmap);
908   session->tmap = nmap;
909 }
910
911
912 /**
913  * The given peer send a message of the specified type.  Make sure the
914  * respective bit is set in its type-map and that clients are notified
915  * about the session.
916  *
917  * @param peer peer this is about
918  * @param type type of the message
919  */
920 void
921 GSC_SESSIONS_add_to_typemap (const struct GNUNET_PeerIdentity *peer,
922                              uint16_t type)
923 {
924   struct Session *session;
925   struct GSC_TypeMap *nmap;
926
927   if (0 == memcmp (peer,
928                    &GSC_my_identity,
929                    sizeof (struct GNUNET_PeerIdentity)))
930     return;
931   session = find_session (peer);
932   GNUNET_assert (NULL != session);
933   if (GNUNET_YES == GSC_TYPEMAP_test_match (session->tmap, &type, 1))
934     return;                     /* already in it */
935   nmap = GSC_TYPEMAP_extend (session->tmap, &type, 1);
936   GSC_CLIENTS_notify_clients_about_neighbour (peer,
937                                               session->tmap, nmap);
938   GSC_TYPEMAP_destroy (session->tmap);
939   session->tmap = nmap;
940 }
941
942
943 /**
944  * Initialize sessions subsystem.
945  */
946 void
947 GSC_SESSIONS_init ()
948 {
949   sessions = GNUNET_CONTAINER_multipeermap_create (128,
950                                                    GNUNET_YES);
951 }
952
953
954 /**
955  * Helper function for #GSC_SESSIONS_done() to free all
956  * active sessions.
957  *
958  * @param cls NULL
959  * @param key identity of the connected peer
960  * @param value the `struct Session` for the peer
961  * @return #GNUNET_OK (continue to iterate)
962  */
963 static int
964 free_session_helper (void *cls,
965                      const struct GNUNET_PeerIdentity *key,
966                      void *value)
967 {
968   struct Session *session = value;
969
970   GSC_SESSIONS_end (&session->peer);
971   return GNUNET_OK;
972 }
973
974
975 /**
976  * Shutdown sessions subsystem.
977  */
978 void
979 GSC_SESSIONS_done ()
980 {
981   if (NULL != sessions)
982   {
983     GNUNET_CONTAINER_multipeermap_iterate (sessions,
984                                            &free_session_helper, NULL);
985     GNUNET_CONTAINER_multipeermap_destroy (sessions);
986     sessions = NULL;
987   }
988 }
989
990 /* end of gnunet-service-core_sessions.c */