-improve UDP logging
[oweals/gnunet.git] / src / core / gnunet-service-core_sessions.c
1 /*
2      This file is part of GNUnet.
3      Copyright (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   struct GNUNET_SCHEDULER_Task * cork_task;
122
123   /**
124    * Task to transmit our type map.
125    */
126   struct GNUNET_SCHEDULER_Task * 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 (NULL != session->cork_task)
217   {
218     GNUNET_SCHEDULER_cancel (session->cork_task);
219     session->cork_task = NULL;
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 (NULL != session->typemap_task)
235   {
236     GNUNET_SCHEDULER_cancel (session->typemap_task);
237     session->typemap_task = NULL;
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 (NULL != 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 (NULL != session->typemap_task)
399   {
400     GNUNET_SCHEDULER_cancel (session->typemap_task);
401     session->typemap_task = NULL;
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,
547                                    pos);
548       GSC_CLIENTS_reject_request (pos);
549     }
550   }
551 }
552
553
554 /**
555  * Solicit messages for transmission, starting with those of the highest
556  * priority.
557  *
558  * @param session session to solict messages for
559  * @param msize how many bytes do we have already
560  */
561 static void
562 solicit_messages (struct Session *session,
563                   size_t msize)
564 {
565   struct GSC_ClientActiveRequest *car;
566   struct GSC_ClientActiveRequest *nxt;
567   size_t so_size;
568   enum GNUNET_CORE_Priority pmax;
569
570   discard_expired_requests (session);
571   so_size = msize;
572   pmax = GNUNET_CORE_PRIO_BACKGROUND;
573   for (car = session->active_client_request_head; NULL != car; car = car->next)
574   {
575     if (GNUNET_YES == car->was_solicited)
576       continue;
577     pmax = GNUNET_MAX (pmax, car->priority);
578   }
579   nxt = session->active_client_request_head;
580   while (NULL != (car = nxt))
581   {
582     nxt = car->next;
583     if (car->priority < pmax)
584       continue;
585     if (so_size + car->msize > GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE)
586       break;
587     so_size += car->msize;
588     if (GNUNET_YES == car->was_solicited)
589       continue;
590     car->was_solicited = GNUNET_YES;
591     GSC_CLIENTS_solicit_request (car);
592   }
593 }
594
595
596 /**
597  * Some messages were delayed (corked), but the timeout has now expired.
598  * Send them now.
599  *
600  * @param cls `struct Session` with the messages to transmit now
601  * @param tc scheduler context (unused)
602  */
603 static void
604 pop_cork_task (void *cls,
605                const struct GNUNET_SCHEDULER_TaskContext *tc)
606 {
607   struct Session *session = cls;
608
609   session->cork_task = NULL;
610   try_transmission (session);
611 }
612
613
614 /**
615  * Try to perform a transmission on the given session. Will solicit
616  * additional messages if the 'sme' queue is not full enough or has
617  * only low-priority messages.
618  *
619  * @param session session to transmit messages from
620  */
621 static void
622 try_transmission (struct Session *session)
623 {
624   struct SessionMessageEntry *pos;
625   size_t msize;
626   struct GNUNET_TIME_Absolute now;
627   struct GNUNET_TIME_Absolute min_deadline;
628   enum GNUNET_CORE_Priority maxp;
629   enum GNUNET_CORE_Priority maxpc;
630   struct GSC_ClientActiveRequest *car;
631   int excess;
632
633   if (GNUNET_YES != session->ready_to_transmit)
634     return;
635   msize = 0;
636   min_deadline = GNUNET_TIME_UNIT_FOREVER_ABS;
637   /* if the peer has excess bandwidth, background traffic is allowed,
638      otherwise not */
639   excess = GSC_NEIGHBOURS_check_excess_bandwidth (&session->peer);
640   if (GNUNET_YES == excess)
641     maxp = GNUNET_CORE_PRIO_BACKGROUND;
642   else
643     maxp = GNUNET_CORE_PRIO_BEST_EFFORT;
644   /* determine highest priority of 'ready' messages we already solicited from clients */
645   pos = session->sme_head;
646   while ((NULL != pos) &&
647          (msize + pos->size <= GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE))
648   {
649     GNUNET_assert (pos->size < GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE);
650     msize += pos->size;
651     maxp = GNUNET_MAX (maxp, pos->priority);
652     min_deadline = GNUNET_TIME_absolute_min (min_deadline,
653                                              pos->deadline);
654     pos = pos->next;
655   }
656   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
657               "Calculating transmission set with %u priority (%s) and %s earliest deadline\n",
658               maxp,
659               (GNUNET_YES == excess) ? "excess bandwidth" : "limited bandwidth",
660               GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_remaining (min_deadline),
661                                                       GNUNET_YES));
662
663   if (maxp < GNUNET_CORE_PRIO_CRITICAL_CONTROL)
664   {
665     /* if highest already solicited priority from clients is not critical,
666        check if there are higher-priority messages to be solicited from clients */
667     if (GNUNET_YES == excess)
668       maxpc = GNUNET_CORE_PRIO_BACKGROUND;
669     else
670       maxpc = GNUNET_CORE_PRIO_BEST_EFFORT;
671     for (car = session->active_client_request_head; NULL != car; car = car->next)
672     {
673       if (GNUNET_YES == car->was_solicited)
674         continue;
675       maxpc = GNUNET_MAX (maxpc, car->priority);
676     }
677     if (maxpc > maxp)
678     {
679       /* we have messages waiting for solicitation that have a higher
680          priority than those that we already accepted; solicit the
681          high-priority messages first */
682       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
683                   "Soliciting messages based on priority (%u > %u)\n",
684                   maxpc,
685                   maxp);
686       solicit_messages (session, 0);
687       return;
688     }
689   }
690   else
691   {
692     /* never solicit more, we have critical messages to process */
693     excess = GNUNET_NO;
694     maxpc = GNUNET_CORE_PRIO_BACKGROUND;
695   }
696   now = GNUNET_TIME_absolute_get ();
697   if ( ( (GNUNET_YES == excess) ||
698          (maxpc >= GNUNET_CORE_PRIO_BEST_EFFORT) ) &&
699        ( (0 == msize) ||
700          ( (msize < GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE / 2) &&
701            (min_deadline.abs_value_us > now.abs_value_us))) )
702   {
703     /* not enough ready yet (tiny message & cork possible), or no messages at all,
704        and either excess bandwidth or best-effort or higher message waiting at
705        client; in this case, we try to solicit more */
706     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
707                 "Soliciting messages (excess %d, maxpc %d, message size %u, deadline %s)\n",
708                 excess,
709                 maxpc,
710                 msize,
711                 GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_remaining (min_deadline),
712                                                         GNUNET_YES));
713     solicit_messages (session,
714                       msize);
715     if (msize > 0)
716     {
717       /* if there is data to send, just not yet, make sure we do transmit
718        * it once the deadline is reached */
719       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
720                   "Corking until %s\n",
721                   GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_remaining (min_deadline),
722                                                           GNUNET_YES));
723       if (NULL != session->cork_task)
724         GNUNET_SCHEDULER_cancel (session->cork_task);
725       session->cork_task =
726           GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_absolute_get_remaining (min_deadline),
727                                         &pop_cork_task,
728                                         session);
729     }
730     return;
731   }
732   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
733               "Building combined plaintext buffer to transmit message!\n");
734   /* create plaintext buffer of all messages (that fit), encrypt and
735      transmit */
736   {
737     static unsigned long long total_bytes;
738     static unsigned int total_msgs;
739     char pbuf[msize];           /* plaintext */
740     size_t used;
741
742     used = 0;
743     while ( (NULL != (pos = session->sme_head)) &&
744             (used + pos->size <= msize) )
745     {
746       memcpy (&pbuf[used], &pos[1], pos->size);
747       used += pos->size;
748       GNUNET_CONTAINER_DLL_remove (session->sme_head,
749                                    session->sme_tail,
750                                    pos);
751       GNUNET_free (pos);
752     }
753     /* compute average payload size */
754     total_bytes += used;
755     total_msgs++;
756     if (0 == total_msgs)
757     {
758       /* 2^32 messages, wrap around... */
759       total_msgs = 1;
760       total_bytes = used;
761     }
762     GNUNET_STATISTICS_set (GSC_stats,
763                            "# avg payload per encrypted message",
764                            total_bytes / total_msgs, GNUNET_NO);
765     /* now actually transmit... */
766     session->ready_to_transmit = GNUNET_NO;
767     GSC_KX_encrypt_and_transmit (session->kxinfo, pbuf, used);
768   }
769 }
770
771
772 /**
773  * Send an updated typemap message to the neighbour now,
774  * and restart typemap transmissions.
775  *
776  * @param cls the message
777  * @param key neighbour's identity
778  * @param value `struct Neighbour` of the target
779  * @return always #GNUNET_OK
780  */
781 static int
782 do_restart_typemap_message (void *cls,
783                             const struct GNUNET_PeerIdentity *key,
784                             void *value)
785 {
786   const struct GNUNET_MessageHeader *hdr = cls;
787   struct Session *session = value;
788   struct SessionMessageEntry *sme;
789   uint16_t size;
790
791   size = ntohs (hdr->size);
792   sme = GNUNET_malloc (sizeof (struct SessionMessageEntry) + size);
793   memcpy (&sme[1], hdr, size);
794   sme->size = size;
795   sme->priority = GNUNET_CORE_PRIO_CRITICAL_CONTROL;
796   GNUNET_CONTAINER_DLL_insert (session->sme_head,
797                                session->sme_tail,
798                                sme);
799   try_transmission (session);
800   start_typemap_task (session);
801   return GNUNET_OK;
802 }
803
804
805 /**
806  * Broadcast an updated typemap message to all neighbours.
807  * Restarts the retransmissions until the typemaps are confirmed.
808  *
809  * @param msg message to transmit
810  */
811 void
812 GSC_SESSIONS_broadcast_typemap (const struct GNUNET_MessageHeader *msg)
813 {
814   if (NULL == sessions)
815     return;
816   GNUNET_CONTAINER_multipeermap_iterate (sessions,
817                                          &do_restart_typemap_message,
818                                          (void *) msg);
819 }
820
821
822 /**
823  * Traffic is being solicited for the given peer.  This means that the
824  * message queue on the transport-level (NEIGHBOURS subsystem) is now
825  * empty and it is now OK to transmit another (non-control) message.
826  *
827  * @param pid identity of peer ready to receive data
828  */
829 void
830 GSC_SESSIONS_solicit (const struct GNUNET_PeerIdentity *pid)
831 {
832   struct Session *session;
833
834   session = find_session (pid);
835   if (NULL == session)
836     return;
837   session->ready_to_transmit = GNUNET_YES;
838   try_transmission (session);
839 }
840
841
842 /**
843  * Transmit a message to a particular peer.
844  *
845  * @param car original request that was queued and then solicited;
846  *            this handle will now be 'owned' by the SESSIONS subsystem
847  * @param msg message to transmit
848  * @param cork is corking allowed?
849  * @param priority how important is this message
850  */
851 void
852 GSC_SESSIONS_transmit (struct GSC_ClientActiveRequest *car,
853                        const struct GNUNET_MessageHeader *msg,
854                        int cork,
855                        enum GNUNET_CORE_Priority priority)
856 {
857   struct Session *session;
858   struct SessionMessageEntry *sme;
859   struct SessionMessageEntry *pos;
860   size_t msize;
861
862   session = find_session (&car->target);
863   if (NULL == session)
864     return;
865   msize = ntohs (msg->size);
866   sme = GNUNET_malloc (sizeof (struct SessionMessageEntry) + msize);
867   memcpy (&sme[1], msg, msize);
868   sme->size = msize;
869   sme->priority = priority;
870   if (GNUNET_YES == cork)
871     sme->deadline =
872         GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_MAX_CORK_DELAY);
873   pos = session->sme_head;
874   while ( (NULL != pos) &&
875           (pos->priority >= sme->priority) )
876     pos = pos->next;
877   if (NULL == pos)
878     GNUNET_CONTAINER_DLL_insert_tail (session->sme_head,
879                                       session->sme_tail,
880                                       sme);
881   else
882     GNUNET_CONTAINER_DLL_insert_after (session->sme_head,
883                                        session->sme_tail,
884                                        pos->prev,
885                                        sme);
886   try_transmission (session);
887 }
888
889
890 /**
891  * We have received a typemap message from a peer, update ours.
892  * Notifies clients about the session.
893  *
894  * @param peer peer this is about
895  * @param msg typemap update message
896  */
897 void
898 GSC_SESSIONS_set_typemap (const struct GNUNET_PeerIdentity *peer,
899                           const struct GNUNET_MessageHeader *msg)
900 {
901   struct Session *session;
902   struct GSC_TypeMap *nmap;
903   struct SessionMessageEntry *sme;
904   struct TypeMapConfirmationMessage *tmc;
905
906   nmap = GSC_TYPEMAP_get_from_message (msg);
907   if (NULL == nmap)
908     return;                     /* malformed */
909   session = find_session (peer);
910   if (NULL == session)
911   {
912     GNUNET_break (0);
913     return;
914   }
915   sme = GNUNET_malloc (sizeof (struct SessionMessageEntry) +
916                        sizeof (struct TypeMapConfirmationMessage));
917   sme->deadline = GNUNET_TIME_absolute_get ();
918   sme->size = sizeof (struct TypeMapConfirmationMessage);
919   sme->priority = GNUNET_CORE_PRIO_CRITICAL_CONTROL;
920   tmc = (struct TypeMapConfirmationMessage *) &sme[1];
921   tmc->header.size = htons (sizeof (struct TypeMapConfirmationMessage));
922   tmc->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_CONFIRM_TYPE_MAP);
923   tmc->reserved = htonl (0);
924   GSC_TYPEMAP_hash (nmap,
925                     &tmc->tm_hash);
926   GNUNET_CONTAINER_DLL_insert (session->sme_head,
927                                session->sme_tail,
928                                sme);
929   try_transmission (session);
930   GSC_CLIENTS_notify_clients_about_neighbour (peer,
931                                               session->tmap,
932                                               nmap);
933   GSC_TYPEMAP_destroy (session->tmap);
934   session->tmap = nmap;
935 }
936
937
938 /**
939  * The given peer send a message of the specified type.  Make sure the
940  * respective bit is set in its type-map and that clients are notified
941  * about the session.
942  *
943  * @param peer peer this is about
944  * @param type type of the message
945  */
946 void
947 GSC_SESSIONS_add_to_typemap (const struct GNUNET_PeerIdentity *peer,
948                              uint16_t type)
949 {
950   struct Session *session;
951   struct GSC_TypeMap *nmap;
952
953   if (0 == memcmp (peer,
954                    &GSC_my_identity,
955                    sizeof (struct GNUNET_PeerIdentity)))
956     return;
957   session = find_session (peer);
958   GNUNET_assert (NULL != session);
959   if (GNUNET_YES == GSC_TYPEMAP_test_match (session->tmap, &type, 1))
960     return;                     /* already in it */
961   nmap = GSC_TYPEMAP_extend (session->tmap, &type, 1);
962   GSC_CLIENTS_notify_clients_about_neighbour (peer,
963                                               session->tmap, nmap);
964   GSC_TYPEMAP_destroy (session->tmap);
965   session->tmap = nmap;
966 }
967
968
969 /**
970  * Initialize sessions subsystem.
971  */
972 void
973 GSC_SESSIONS_init ()
974 {
975   sessions = GNUNET_CONTAINER_multipeermap_create (128,
976                                                    GNUNET_YES);
977 }
978
979
980 /**
981  * Helper function for #GSC_SESSIONS_done() to free all
982  * active sessions.
983  *
984  * @param cls NULL
985  * @param key identity of the connected peer
986  * @param value the `struct Session` for the peer
987  * @return #GNUNET_OK (continue to iterate)
988  */
989 static int
990 free_session_helper (void *cls,
991                      const struct GNUNET_PeerIdentity *key,
992                      void *value)
993 {
994   struct Session *session = value;
995
996   GSC_SESSIONS_end (&session->peer);
997   return GNUNET_OK;
998 }
999
1000
1001 /**
1002  * Shutdown sessions subsystem.
1003  */
1004 void
1005 GSC_SESSIONS_done ()
1006 {
1007   if (NULL != sessions)
1008   {
1009     GNUNET_CONTAINER_multipeermap_iterate (sessions,
1010                                            &free_session_helper, NULL);
1011     GNUNET_CONTAINER_multipeermap_destroy (sessions);
1012     sessions = NULL;
1013   }
1014 }
1015
1016 /* end of gnunet-service-core_sessions.c */