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