f4f5a41e15a605efb80ce6888cc8eac912cb8396
[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., 51 Franklin Street, Fifth Floor,
18      Boston, MA 02110-1301, 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                                 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, NULL);
249   GNUNET_assert (GNUNET_YES ==
250                  GNUNET_CONTAINER_multipeermap_remove (sessions,
251                                                        &session->peer,
252                                                        session));
253   GNUNET_STATISTICS_set (GSC_stats, gettext_noop ("# peers connected"),
254                          GNUNET_CONTAINER_multipeermap_size (sessions),
255                          GNUNET_NO);
256   GSC_TYPEMAP_destroy (session->tmap);
257   session->tmap = NULL;
258   GNUNET_free (session);
259 }
260
261
262 /**
263  * Transmit our current typemap message to the other peer.
264  * (Done periodically until the typemap is confirmed).
265  *
266  * @param cls the `struct Session *`
267  * @param tc unused
268  */
269 static void
270 transmit_typemap_task (void *cls,
271                        const struct GNUNET_SCHEDULER_TaskContext *tc)
272 {
273   struct Session *session = cls;
274   struct GNUNET_MessageHeader *hdr;
275   struct GNUNET_TIME_Relative delay;
276
277   session->typemap_delay = GNUNET_TIME_STD_BACKOFF (session->typemap_delay);
278   delay = session->typemap_delay;
279   /* randomize a bit to avoid spont. sync */
280   delay.rel_value_us +=
281       GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, 1000 * 1000);
282   session->typemap_task =
283       GNUNET_SCHEDULER_add_delayed (delay,
284                                     &transmit_typemap_task, session);
285   GNUNET_STATISTICS_update (GSC_stats,
286                             gettext_noop ("# type map refreshes sent"),
287                             1,
288                             GNUNET_NO);
289   hdr = GSC_TYPEMAP_compute_type_map_message ();
290   GSC_KX_encrypt_and_transmit (session->kxinfo,
291                                hdr,
292                                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 (NULL != 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,
344                                               session->tmap);
345   start_typemap_task (session);
346 }
347
348
349 /**
350  * The other peer has indicated that he 'lost' the session
351  * (KX down), reinitialize the session on our end, in particular
352  * this means to restart the typemap transmission.
353  *
354  * @param peer peer that is now connected
355  */
356 void
357 GSC_SESSIONS_reinit (const struct GNUNET_PeerIdentity *peer)
358 {
359   struct Session *session;
360
361   session = find_session (peer);
362   if (NULL == session)
363   {
364     /* KX/session is new for both sides; thus no need to restart what
365        has not yet begun */
366     return;
367   }
368   start_typemap_task (session);
369 }
370
371
372 /**
373  * The other peer has confirmed receiving our type map,
374  * check if it is current and if so, stop retransmitting it.
375  *
376  * @param peer peer that confirmed the type map
377  * @param msg confirmation message we received
378  */
379 void
380 GSC_SESSIONS_confirm_typemap (const struct GNUNET_PeerIdentity *peer,
381                               const struct GNUNET_MessageHeader *msg)
382 {
383   const struct TypeMapConfirmationMessage *cmsg;
384   struct Session *session;
385
386   session = find_session (peer);
387   if (NULL == session)
388   {
389     GNUNET_break (0);
390     return;
391   }
392   if (ntohs (msg->size) != sizeof (struct TypeMapConfirmationMessage))
393   {
394     GNUNET_break_op (0);
395     return;
396   }
397   cmsg = (const struct TypeMapConfirmationMessage *) msg;
398   if (GNUNET_YES !=
399       GSC_TYPEMAP_check_hash (&cmsg->tm_hash))
400   {
401     /* our typemap has changed in the meantime, do not
402        accept confirmation */
403     GNUNET_STATISTICS_update (GSC_stats,
404                               gettext_noop
405                               ("# outdated typemap confirmations received"),
406                               1, GNUNET_NO);
407     return;
408   }
409   if (NULL != session->typemap_task)
410   {
411     GNUNET_SCHEDULER_cancel (session->typemap_task);
412     session->typemap_task = NULL;
413   }
414   GNUNET_STATISTICS_update (GSC_stats,
415                             gettext_noop
416                             ("# valid typemap confirmations received"),
417                             1, GNUNET_NO);
418 }
419
420
421 /**
422  * Notify the given client about the session (client is new).
423  *
424  * @param cls the `struct GSC_Client`
425  * @param key peer identity
426  * @param value the `struct Session`
427  * @return #GNUNET_OK (continue to iterate)
428  */
429 static int
430 notify_client_about_session (void *cls,
431                              const struct GNUNET_PeerIdentity *key,
432                              void *value)
433 {
434   struct GSC_Client *client = cls;
435   struct Session *session = value;
436
437   GSC_CLIENTS_notify_client_about_neighbour (client,
438                                              &session->peer,
439                                              NULL,      /* old TMAP: none */
440                                              session->tmap);
441   return GNUNET_OK;
442 }
443
444
445 /**
446  * We have a new client, notify it about all current sessions.
447  *
448  * @param client the new client
449  */
450 void
451 GSC_SESSIONS_notify_client_about_sessions (struct GSC_Client *client)
452 {
453   /* notify new client about existing sessions */
454   GNUNET_CONTAINER_multipeermap_iterate (sessions,
455                                          &notify_client_about_session,
456                                          client);
457 }
458
459
460 /**
461  * Try to perform a transmission on the given session.  Will solicit
462  * additional messages if the 'sme' queue is not full enough.
463  *
464  * @param session session to transmit messages from
465  */
466 static void
467 try_transmission (struct Session *session);
468
469
470 /**
471  * Queue a request from a client for transmission to a particular peer.
472  *
473  * @param car request to queue; this handle is then shared between
474  *         the caller (CLIENTS subsystem) and SESSIONS and must not
475  *         be released by either until either #GSC_SESSIONS_dequeue(),
476  *         #GSC_SESSIONS_transmit() or #GSC_CLIENTS_failed()
477  *         have been invoked on it
478  */
479 void
480 GSC_SESSIONS_queue_request (struct GSC_ClientActiveRequest *car)
481 {
482   struct Session *session;
483
484   session = find_session (&car->target);
485   if (NULL == session)
486   {
487     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
488                 "Dropped client request for transmission (am disconnected)\n");
489     GNUNET_break (0);           /* should have been rejected earlier */
490     GSC_CLIENTS_reject_request (car,
491                                 GNUNET_NO);
492     return;
493   }
494   if (car->msize > GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE)
495   {
496     GNUNET_break (0);
497     GSC_CLIENTS_reject_request (car,
498                                 GNUNET_YES);
499     return;
500   }
501   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
502               "Received client transmission request. queueing\n");
503   GNUNET_CONTAINER_DLL_insert (session->active_client_request_head,
504                                session->active_client_request_tail,
505                                car);
506   try_transmission (session);
507 }
508
509
510 /**
511  * Dequeue a request from a client from transmission to a particular peer.
512  *
513  * @param car request to dequeue; this handle will then be 'owned' by
514  *        the caller (CLIENTS sysbsystem)
515  */
516 void
517 GSC_SESSIONS_dequeue_request (struct GSC_ClientActiveRequest *car)
518 {
519   struct Session *session;
520
521   if (0 ==
522       memcmp (&car->target,
523               &GSC_my_identity,
524               sizeof (struct GNUNET_PeerIdentity)))
525     return;
526   session = find_session (&car->target);
527   GNUNET_assert (NULL != session);
528   GNUNET_CONTAINER_DLL_remove (session->active_client_request_head,
529                                session->active_client_request_tail,
530                                car);
531   /* dequeueing of 'high' priority messages may unblock
532      transmission for lower-priority messages, so we also
533      need to try in this case. */
534   try_transmission (session);
535 }
536
537
538 /**
539  * Solicit messages for transmission, starting with those of the highest
540  * priority.
541  *
542  * @param session session to solict messages for
543  * @param msize how many bytes do we have already
544  */
545 static void
546 solicit_messages (struct Session *session,
547                   size_t msize)
548 {
549   struct GSC_ClientActiveRequest *car;
550   struct GSC_ClientActiveRequest *nxt;
551   size_t so_size;
552   enum GNUNET_CORE_Priority pmax;
553
554   so_size = msize;
555   pmax = GNUNET_CORE_PRIO_BACKGROUND;
556   for (car = session->active_client_request_head; NULL != car; car = car->next)
557   {
558     if (GNUNET_YES == car->was_solicited)
559       continue;
560     pmax = GNUNET_MAX (pmax, car->priority);
561   }
562   nxt = session->active_client_request_head;
563   while (NULL != (car = nxt))
564   {
565     nxt = car->next;
566     if (car->priority < pmax)
567       continue;
568     if (so_size + car->msize > GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE)
569       break;
570     so_size += car->msize;
571     if (GNUNET_YES == car->was_solicited)
572       continue;
573     car->was_solicited = GNUNET_YES;
574     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
575                 "Soliciting message with priority %u\n",
576                 car->priority);
577     GSC_CLIENTS_solicit_request (car);
578     /* The above call may *dequeue* requests and thereby
579        clobber 'nxt'. Hence we need to restart from the
580        head of the list. */
581     nxt = session->active_client_request_head;
582     so_size = msize;
583   }
584 }
585
586
587 /**
588  * Some messages were delayed (corked), but the timeout has now expired.
589  * Send them now.
590  *
591  * @param cls `struct Session` with the messages to transmit now
592  * @param tc scheduler context (unused)
593  */
594 static void
595 pop_cork_task (void *cls,
596                const struct GNUNET_SCHEDULER_TaskContext *tc)
597 {
598   struct Session *session = cls;
599
600   session->cork_task = NULL;
601   try_transmission (session);
602 }
603
604
605 /**
606  * Try to perform a transmission on the given session. Will solicit
607  * additional messages if the 'sme' queue is not full enough or has
608  * only low-priority messages.
609  *
610  * @param session session to transmit messages from
611  */
612 static void
613 try_transmission (struct Session *session)
614 {
615   struct SessionMessageEntry *pos;
616   size_t msize;
617   struct GNUNET_TIME_Absolute now;
618   struct GNUNET_TIME_Absolute min_deadline;
619   enum GNUNET_CORE_Priority maxp;
620   enum GNUNET_CORE_Priority maxpc;
621   struct GSC_ClientActiveRequest *car;
622   int excess;
623
624   if (GNUNET_YES != session->ready_to_transmit)
625   {
626     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
627                 "Already ready to transmit, not evaluating queue\n");
628     return;
629   }
630   msize = 0;
631   min_deadline = GNUNET_TIME_UNIT_FOREVER_ABS;
632   /* if the peer has excess bandwidth, background traffic is allowed,
633      otherwise not */
634   if (MAX_ENCRYPTED_MESSAGE_QUEUE_SIZE <=
635       GSC_NEIGHBOURS_get_queue_size (&session->peer))
636   {
637     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
638                 "Transmission queue already very long, waiting...\n");
639     return; /* queue already too long */
640   }
641   excess = GSC_NEIGHBOURS_check_excess_bandwidth (&session->peer);
642   if (GNUNET_YES == excess)
643     maxp = GNUNET_CORE_PRIO_BACKGROUND;
644   else
645     maxp = GNUNET_CORE_PRIO_BEST_EFFORT;
646   /* determine highest priority of 'ready' messages we already solicited from clients */
647   pos = session->sme_head;
648   while ((NULL != pos) &&
649          (msize + pos->size <= GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE))
650   {
651     GNUNET_assert (pos->size < GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE);
652     msize += pos->size;
653     maxp = GNUNET_MAX (maxp, pos->priority);
654     min_deadline = GNUNET_TIME_absolute_min (min_deadline,
655                                              pos->deadline);
656     pos = pos->next;
657   }
658   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
659               "Calculating transmission set with %u priority (%s) and %s earliest deadline\n",
660               maxp,
661               (GNUNET_YES == excess) ? "excess bandwidth" : "limited bandwidth",
662               GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_remaining (min_deadline),
663                                                       GNUNET_YES));
664
665   if (maxp < GNUNET_CORE_PRIO_CRITICAL_CONTROL)
666   {
667     /* if highest already solicited priority from clients is not critical,
668        check if there are higher-priority messages to be solicited from clients */
669     if (GNUNET_YES == excess)
670       maxpc = GNUNET_CORE_PRIO_BACKGROUND;
671     else
672       maxpc = GNUNET_CORE_PRIO_BEST_EFFORT;
673     for (car = session->active_client_request_head; NULL != car; car = car->next)
674     {
675       if (GNUNET_YES == car->was_solicited)
676         continue;
677       maxpc = GNUNET_MAX (maxpc, car->priority);
678     }
679     if (maxpc > maxp)
680     {
681       /* we have messages waiting for solicitation that have a higher
682          priority than those that we already accepted; solicit the
683          high-priority messages first */
684       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
685                   "Soliciting messages based on priority (%u > %u)\n",
686                   maxpc,
687                   maxp);
688       solicit_messages (session, 0);
689       return;
690     }
691   }
692   else
693   {
694     /* never solicit more, we have critical messages to process */
695     excess = GNUNET_NO;
696     maxpc = GNUNET_CORE_PRIO_BACKGROUND;
697   }
698   now = GNUNET_TIME_absolute_get ();
699   if ( ( (GNUNET_YES == excess) ||
700          (maxpc >= GNUNET_CORE_PRIO_BEST_EFFORT) ) &&
701        ( (0 == msize) ||
702          ( (msize < GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE / 2) &&
703            (min_deadline.abs_value_us > now.abs_value_us))) )
704   {
705     /* not enough ready yet (tiny message & cork possible), or no messages at all,
706        and either excess bandwidth or best-effort or higher message waiting at
707        client; in this case, we try to solicit more */
708     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
709                 "Soliciting messages (excess %d, maxpc %d, message size %u, deadline %s)\n",
710                 excess,
711                 maxpc,
712                 msize,
713                 GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_remaining (min_deadline),
714                                                         GNUNET_YES));
715     solicit_messages (session,
716                       msize);
717     if (msize > 0)
718     {
719       /* if there is data to send, just not yet, make sure we do transmit
720        * it once the deadline is reached */
721       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
722                   "Corking until %s\n",
723                   GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_remaining (min_deadline),
724                                                           GNUNET_YES));
725       if (NULL != session->cork_task)
726         GNUNET_SCHEDULER_cancel (session->cork_task);
727       session->cork_task =
728           GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_absolute_get_remaining (min_deadline),
729                                         &pop_cork_task,
730                                         session);
731     }
732     else
733     {
734       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
735                   "Queue empty, waiting for solicitations\n");
736     }
737     return;
738   }
739   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
740               "Building combined plaintext buffer to transmit message!\n");
741   /* create plaintext buffer of all messages (that fit), encrypt and
742      transmit */
743   {
744     static unsigned long long total_bytes;
745     static unsigned int total_msgs;
746     char pbuf[msize];           /* plaintext */
747     size_t used;
748
749     used = 0;
750     while ( (NULL != (pos = session->sme_head)) &&
751             (used + pos->size <= msize) )
752     {
753       memcpy (&pbuf[used], &pos[1], pos->size);
754       used += pos->size;
755       GNUNET_CONTAINER_DLL_remove (session->sme_head,
756                                    session->sme_tail,
757                                    pos);
758       GNUNET_free (pos);
759     }
760     /* compute average payload size */
761     total_bytes += used;
762     total_msgs++;
763     if (0 == total_msgs)
764     {
765       /* 2^32 messages, wrap around... */
766       total_msgs = 1;
767       total_bytes = used;
768     }
769     GNUNET_STATISTICS_set (GSC_stats,
770                            "# avg payload per encrypted message",
771                            total_bytes / total_msgs,
772                            GNUNET_NO);
773     /* now actually transmit... */
774     session->ready_to_transmit = GNUNET_NO;
775     GSC_KX_encrypt_and_transmit (session->kxinfo,
776                                  pbuf,
777                                  used);
778   }
779 }
780
781
782 /**
783  * Send an updated typemap message to the neighbour now,
784  * and restart typemap transmissions.
785  *
786  * @param cls the message
787  * @param key neighbour's identity
788  * @param value `struct Neighbour` of the target
789  * @return always #GNUNET_OK
790  */
791 static int
792 do_restart_typemap_message (void *cls,
793                             const struct GNUNET_PeerIdentity *key,
794                             void *value)
795 {
796   const struct GNUNET_MessageHeader *hdr = cls;
797   struct Session *session = value;
798   struct SessionMessageEntry *sme;
799   uint16_t size;
800
801   size = ntohs (hdr->size);
802   sme = GNUNET_malloc (sizeof (struct SessionMessageEntry) + size);
803   memcpy (&sme[1], hdr, size);
804   sme->size = size;
805   sme->priority = GNUNET_CORE_PRIO_CRITICAL_CONTROL;
806   GNUNET_CONTAINER_DLL_insert (session->sme_head,
807                                session->sme_tail,
808                                sme);
809   try_transmission (session);
810   start_typemap_task (session);
811   return GNUNET_OK;
812 }
813
814
815 /**
816  * Broadcast an updated typemap message to all neighbours.
817  * Restarts the retransmissions until the typemaps are confirmed.
818  *
819  * @param msg message to transmit
820  */
821 void
822 GSC_SESSIONS_broadcast_typemap (const struct GNUNET_MessageHeader *msg)
823 {
824   if (NULL == sessions)
825     return;
826   GNUNET_CONTAINER_multipeermap_iterate (sessions,
827                                          &do_restart_typemap_message,
828                                          (void *) msg);
829 }
830
831
832 /**
833  * Traffic is being solicited for the given peer.  This means that the
834  * message queue on the transport-level (NEIGHBOURS subsystem) is now
835  * empty and it is now OK to transmit another (non-control) message.
836  *
837  * @param pid identity of peer ready to receive data
838  */
839 void
840 GSC_SESSIONS_solicit (const struct GNUNET_PeerIdentity *pid)
841 {
842   struct Session *session;
843
844   session = find_session (pid);
845   if (NULL == session)
846     return;
847   session->ready_to_transmit = GNUNET_YES;
848   try_transmission (session);
849 }
850
851
852 /**
853  * Transmit a message to a particular peer.
854  *
855  * @param car original request that was queued and then solicited;
856  *            this handle will now be 'owned' by the SESSIONS subsystem
857  * @param msg message to transmit
858  * @param cork is corking allowed?
859  * @param priority how important is this message
860  */
861 void
862 GSC_SESSIONS_transmit (struct GSC_ClientActiveRequest *car,
863                        const struct GNUNET_MessageHeader *msg,
864                        int cork,
865                        enum GNUNET_CORE_Priority priority)
866 {
867   struct Session *session;
868   struct SessionMessageEntry *sme;
869   struct SessionMessageEntry *pos;
870   size_t msize;
871
872   session = find_session (&car->target);
873   if (NULL == session)
874     return;
875   msize = ntohs (msg->size);
876   sme = GNUNET_malloc (sizeof (struct SessionMessageEntry) + msize);
877   memcpy (&sme[1], msg, msize);
878   sme->size = msize;
879   sme->priority = priority;
880   if (GNUNET_YES == cork)
881     sme->deadline =
882         GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_MAX_CORK_DELAY);
883   pos = session->sme_head;
884   while ( (NULL != pos) &&
885           (pos->priority >= sme->priority) )
886     pos = pos->next;
887   if (NULL == pos)
888     GNUNET_CONTAINER_DLL_insert_tail (session->sme_head,
889                                       session->sme_tail,
890                                       sme);
891   else
892     GNUNET_CONTAINER_DLL_insert_after (session->sme_head,
893                                        session->sme_tail,
894                                        pos->prev,
895                                        sme);
896   try_transmission (session);
897 }
898
899
900 /**
901  * We have received a typemap message from a peer, update ours.
902  * Notifies clients about the session.
903  *
904  * @param peer peer this is about
905  * @param msg typemap update message
906  */
907 void
908 GSC_SESSIONS_set_typemap (const struct GNUNET_PeerIdentity *peer,
909                           const struct GNUNET_MessageHeader *msg)
910 {
911   struct Session *session;
912   struct GSC_TypeMap *nmap;
913   struct SessionMessageEntry *sme;
914   struct TypeMapConfirmationMessage *tmc;
915
916   nmap = GSC_TYPEMAP_get_from_message (msg);
917   if (NULL == nmap)
918     return;                     /* malformed */
919   session = find_session (peer);
920   if (NULL == session)
921   {
922     GNUNET_break (0);
923     return;
924   }
925   sme = GNUNET_malloc (sizeof (struct SessionMessageEntry) +
926                        sizeof (struct TypeMapConfirmationMessage));
927   sme->deadline = GNUNET_TIME_absolute_get ();
928   sme->size = sizeof (struct TypeMapConfirmationMessage);
929   sme->priority = GNUNET_CORE_PRIO_CRITICAL_CONTROL;
930   tmc = (struct TypeMapConfirmationMessage *) &sme[1];
931   tmc->header.size = htons (sizeof (struct TypeMapConfirmationMessage));
932   tmc->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_CONFIRM_TYPE_MAP);
933   tmc->reserved = htonl (0);
934   GSC_TYPEMAP_hash (nmap,
935                     &tmc->tm_hash);
936   GNUNET_CONTAINER_DLL_insert (session->sme_head,
937                                session->sme_tail,
938                                sme);
939   try_transmission (session);
940   GSC_CLIENTS_notify_clients_about_neighbour (peer,
941                                               session->tmap,
942                                               nmap);
943   GSC_TYPEMAP_destroy (session->tmap);
944   session->tmap = nmap;
945 }
946
947
948 /**
949  * The given peer send a message of the specified type.  Make sure the
950  * respective bit is set in its type-map and that clients are notified
951  * about the session.
952  *
953  * @param peer peer this is about
954  * @param type type of the message
955  */
956 void
957 GSC_SESSIONS_add_to_typemap (const struct GNUNET_PeerIdentity *peer,
958                              uint16_t type)
959 {
960   struct Session *session;
961   struct GSC_TypeMap *nmap;
962
963   if (0 == memcmp (peer,
964                    &GSC_my_identity,
965                    sizeof (struct GNUNET_PeerIdentity)))
966     return;
967   session = find_session (peer);
968   GNUNET_assert (NULL != session);
969   if (GNUNET_YES == GSC_TYPEMAP_test_match (session->tmap, &type, 1))
970     return;                     /* already in it */
971   nmap = GSC_TYPEMAP_extend (session->tmap, &type, 1);
972   GSC_CLIENTS_notify_clients_about_neighbour (peer,
973                                               session->tmap, nmap);
974   GSC_TYPEMAP_destroy (session->tmap);
975   session->tmap = nmap;
976 }
977
978
979 /**
980  * Initialize sessions subsystem.
981  */
982 void
983 GSC_SESSIONS_init ()
984 {
985   sessions = GNUNET_CONTAINER_multipeermap_create (128,
986                                                    GNUNET_YES);
987 }
988
989
990 /**
991  * Helper function for #GSC_SESSIONS_done() to free all
992  * active sessions.
993  *
994  * @param cls NULL
995  * @param key identity of the connected peer
996  * @param value the `struct Session` for the peer
997  * @return #GNUNET_OK (continue to iterate)
998  */
999 static int
1000 free_session_helper (void *cls,
1001                      const struct GNUNET_PeerIdentity *key,
1002                      void *value)
1003 {
1004   struct Session *session = value;
1005
1006   GSC_SESSIONS_end (&session->peer);
1007   return GNUNET_OK;
1008 }
1009
1010
1011 /**
1012  * Shutdown sessions subsystem.
1013  */
1014 void
1015 GSC_SESSIONS_done ()
1016 {
1017   if (NULL != sessions)
1018   {
1019     GNUNET_CONTAINER_multipeermap_iterate (sessions,
1020                                            &free_session_helper, NULL);
1021     GNUNET_CONTAINER_multipeermap_destroy (sessions);
1022     sessions = NULL;
1023   }
1024 }
1025
1026 /* end of gnunet-service-core_sessions.c */