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