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