fixing 1845
[oweals/gnunet.git] / src / core / gnunet-service-core_clients.c
1 /*
2      This file is part of GNUnet.
3      (C) 2009, 2010, 2011 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_clients.c
23  * @brief code for managing interactions with clients of core service
24  * @author Christian Grothoff
25  */
26 #include "platform.h"
27 #include "gnunet_util_lib.h"
28 #include "gnunet_statistics_service.h"
29 #include "gnunet_transport_service.h"
30 #include "gnunet-service-core.h"
31 #include "gnunet-service-core_clients.h"
32 #include "gnunet-service-core_sessions.h"
33 #include "gnunet-service-core_typemap.h"
34 #include "core.h"
35
36 #define DEBUG_CONNECTS GNUNET_YES
37
38 /**
39  * How many messages do we queue up at most for optional
40  * notifications to a client?  (this can cause notifications
41  * about outgoing messages to be dropped).
42  */
43 #define MAX_NOTIFY_QUEUE 1024
44
45
46 /**
47  * Data structure for each client connected to the core service.
48  */
49 struct GSC_Client
50 {
51   /**
52    * Clients are kept in a linked list.
53    */
54   struct GSC_Client *next;
55
56   /**
57    * Clients are kept in a linked list.
58    */
59   struct GSC_Client *prev;
60
61   /**
62    * Handle for the client with the server API.
63    */
64   struct GNUNET_SERVER_Client *client_handle;
65
66   /**
67    * Array of the types of messages this peer cares
68    * about (with "tcnt" entries).  Allocated as part
69    * of this client struct, do not free!
70    */
71   const uint16_t *types;
72
73   /**
74    * Map of peer identities to active transmission requests of this
75    * client to the peer (of type 'struct GSC_ClientActiveRequest').
76    */
77   struct GNUNET_CONTAINER_MultiHashMap *requests;
78
79 #if DEBUG_CONNECTS
80   /**
81    * Map containing all peers that this client knows we're connected to.
82    */
83   struct GNUNET_CONTAINER_MultiHashMap *connectmap;
84 #endif
85
86   /**
87    * Options for messages this client cares about,
88    * see GNUNET_CORE_OPTION_ values.
89    */
90   uint32_t options;
91
92   /**
93    * Number of types of incoming messages this client
94    * specifically cares about.  Size of the "types" array.
95    */
96   unsigned int tcnt;
97
98 };
99
100
101 /**
102  * Head of linked list of our clients.
103  */
104 static struct GSC_Client *client_head;
105
106 /**
107  * Tail of linked list of our clients.
108  */
109 static struct GSC_Client *client_tail;
110
111 /**
112  * Context for notifications we need to send to our clients.
113  */
114 static struct GNUNET_SERVER_NotificationContext *notifier;
115
116 /**
117  * Tokenizer for messages received from clients.
118  */
119 static struct GNUNET_SERVER_MessageStreamTokenizer *client_mst;
120
121
122 /**
123  * Lookup our client struct given the server's client handle.
124  *
125  * @param client server client handle to look up
126  * @return our client handle for the client
127  */
128 static struct GSC_Client *
129 find_client (struct GNUNET_SERVER_Client *client)
130 {
131   struct GSC_Client *c;
132
133   c = client_head;
134   while ((c != NULL) && (c->client_handle != client))
135     c = c->next;
136   return c;
137 }
138
139
140 /**
141  * Send a message to one of our clients.
142  *
143  * @param client target for the message
144  * @param msg message to transmit
145  * @param can_drop could this message be dropped if the
146  *        client's queue is getting too large?
147  */
148 static void
149 send_to_client (struct GSC_Client *client, 
150                 const struct GNUNET_MessageHeader *msg,
151                 int can_drop)
152 {
153 #if DEBUG_CORE
154   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
155               "Preparing to send %u bytes of message of type %u to client.\n",
156               (unsigned int) ntohs (msg->size),
157               (unsigned int) ntohs (msg->type));
158 #endif
159   GNUNET_SERVER_notification_context_unicast (notifier, client->client_handle,
160                                               msg, can_drop);
161 }
162
163
164 /**
165  * Send a message to one of our clients.
166  *
167  * @param client target for the message
168  * @param msg message to transmit
169  * @param can_drop could this message be dropped if the
170  *        client's queue is getting too large?
171  */
172 void
173 GSC_CLIENTS_send_to_client (struct GNUNET_SERVER_Client *client,
174                             const struct GNUNET_MessageHeader *msg,
175                             int can_drop)
176 {
177   struct GSC_Client *c;
178
179   c = find_client (client);
180   if (NULL == c)
181   {
182     GNUNET_break (0);
183     return;
184   }
185   send_to_client (c, msg, can_drop);
186 }
187
188
189 /**
190  * Test if the client is interested in messages of the given type.
191  *
192  * @param type message type
193  * @param c client to test
194  * @return GNUNET_YES if 'c' is interested, GNUNET_NO if not.
195  */
196 static int
197 type_match (uint16_t type,
198             struct GSC_Client *c)
199 {
200   unsigned int i;
201
202   if (c->tcnt == 0)
203     return GNUNET_YES; /* peer without handlers matches ALL */
204   for (i=0;i<c->tcnt;i++)
205     if (type == c->types[i])
206       return GNUNET_YES;
207   return GNUNET_NO;
208 }
209
210
211 /**
212  * Send a message to all of our current clients that have the right
213  * options set.
214  *
215  * @param msg message to multicast
216  * @param can_drop can this message be discarded if the queue is too long
217  * @param options mask to use
218  * @param type type of the embedded message, 0 for none
219  */
220 static void
221 send_to_all_clients (const struct GNUNET_PeerIdentity *sender,
222                      const struct GNUNET_MessageHeader *msg, 
223                      int can_drop,
224                      int options,
225                      uint16_t type)
226 {
227   struct GSC_Client *c;
228
229   for (c = client_head; c != NULL; c = c->next)
230   {
231     if ( (0 == (options & GNUNET_CORE_OPTION_SEND_FULL_INBOUND)) &&
232          (GNUNET_YES == type_match (type, c)) )
233       continue; /* not the full message, but we'd like the full one! */
234     if ( (0 == (c->options & options)) &&
235          (GNUNET_YES != type_match (type, c)) )
236       continue; /* neither options nor type match permit the message */
237 #if DEBUG_CORE
238     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
239                 "Sending message to client interested in messages of type %u.\n",
240                 (unsigned int) type);
241 #endif
242 #if DEBUG_CONNECTS
243     GNUNET_assert (GNUNET_YES ==
244                    GNUNET_CONTAINER_multihashmap_contains (c->connectmap,
245                                                            &sender->hashPubKey));
246 #endif
247     send_to_client (c, msg, can_drop);
248   }
249 }
250
251
252 /**
253  * Handle CORE_INIT request.
254  *
255  * @param cls unused
256  * @param client new client that sent INIT
257  * @param message the 'struct InitMessage' (presumably)
258  */
259 static void
260 handle_client_init (void *cls, struct GNUNET_SERVER_Client *client,
261                     const struct GNUNET_MessageHeader *message)
262 {
263   const struct InitMessage *im;
264   struct InitReplyMessage irm;
265   struct GSC_Client *c;
266   uint16_t msize;
267   const uint16_t *types;
268   uint16_t *wtypes;
269   unsigned int i;
270
271   /* check that we don't have an entry already */
272   c = find_client (client);
273   if (NULL != c)
274   {
275     GNUNET_break (0);
276     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
277     return;
278   }
279   msize = ntohs (message->size);
280   if (msize < sizeof (struct InitMessage))
281   {
282     GNUNET_break (0);
283     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
284     return;
285   }
286   GNUNET_SERVER_notification_context_add (notifier, client);
287   im = (const struct InitMessage *) message;
288   types = (const uint16_t *) &im[1];
289   msize -= sizeof (struct InitMessage);
290   c = GNUNET_malloc (sizeof (struct GSC_Client) + msize);
291   c->client_handle = client;
292   c->tcnt = msize / sizeof (uint16_t);
293   c->options = ntohl (im->options);
294   c->types = (const uint16_t *) &c[1];
295 #if DEBUG_CONNECTS
296   c->connectmap = GNUNET_CONTAINER_multihashmap_create (16);
297   GNUNET_assert (GNUNET_YES ==
298                  GNUNET_CONTAINER_multihashmap_put (c->connectmap,
299                                                     &GSC_my_identity.hashPubKey,
300                                                     NULL,
301                                                     GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
302 #endif
303
304   wtypes = (uint16_t *) & c[1];
305   for (i = 0; i < c->tcnt; i++)
306     wtypes[i] = ntohs (types[i]);
307   GSC_TYPEMAP_add (wtypes, c->tcnt);
308   GNUNET_CONTAINER_DLL_insert (client_head,
309                                client_tail,
310                                c);
311 #if DEBUG_CORE
312   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
313               "Client connecting to core service is interested in %u message types\n", 
314               (unsigned int) c->tcnt);
315 #endif
316   /* send init reply message */
317   irm.header.size = htons (sizeof (struct InitReplyMessage));
318   irm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_INIT_REPLY);
319   irm.reserved = htonl (0);
320   irm.my_identity = GSC_my_identity;
321   send_to_client (c, &irm.header, GNUNET_NO);
322   GSC_SESSIONS_notify_client_about_sessions (c);
323   GNUNET_SERVER_receive_done (client, GNUNET_OK);
324 }
325
326
327 /**
328  * Handle CORE_SEND_REQUEST message.
329  *
330  * @param cls unused
331  * @param client new client that sent CORE_SEND_REQUEST
332  * @param message the 'struct SendMessageRequest' (presumably)
333  */
334 static void
335 handle_client_send_request (void *cls, struct GNUNET_SERVER_Client *client,
336                             const struct GNUNET_MessageHeader *message)
337 {
338   const struct SendMessageRequest *req;
339   struct GSC_Client *c;
340   struct GSC_ClientActiveRequest *car;
341
342   req = (const struct SendMessageRequest *) message;
343   c = find_client (client);
344   if (c == NULL)
345   {
346     /* client did not send INIT first! */
347     GNUNET_break (0);
348     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
349     return;
350   }
351   if (c->requests == NULL)
352     c->requests = GNUNET_CONTAINER_multihashmap_create (16);
353 #if DEBUG_CORE
354   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
355               "Client asked for transmission to `%s'\n",
356               GNUNET_i2s (&req->peer));
357 #endif
358   car = GNUNET_CONTAINER_multihashmap_get (c->requests, &req->peer.hashPubKey);
359   if (car == NULL)
360   {
361     /* create new entry */
362     car = GNUNET_malloc (sizeof (struct GSC_ClientActiveRequest));
363     GNUNET_assert (GNUNET_OK ==
364                    GNUNET_CONTAINER_multihashmap_put (c->requests,
365                                                       &req->peer.hashPubKey,
366                                                       car,
367                                                       GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST));
368     car->client_handle = c;
369   }
370   else
371   {
372     GSC_SESSIONS_dequeue_request (car);
373   }
374   car->target = req->peer;
375   car->deadline = GNUNET_TIME_absolute_ntoh (req->deadline);
376   car->priority = ntohl (req->priority);
377   car->msize = ntohs (req->size);
378   car->smr_id = req->smr_id;
379   car->was_solicited = GNUNET_NO;
380   if (0 ==
381       memcmp (&req->peer, &GSC_my_identity, sizeof (struct GNUNET_PeerIdentity)))
382     GSC_CLIENTS_solicit_request (car);
383   else
384     GSC_SESSIONS_queue_request (car);
385   GNUNET_SERVER_receive_done (client, GNUNET_OK);
386 }
387
388
389 /**
390  * Closure for the 'client_tokenizer_callback'.
391  */
392 struct TokenizerContext
393 {
394
395   /**
396    * Active request handle for the message.
397    */ 
398   struct GSC_ClientActiveRequest *car;
399
400   /**
401    * Is corking allowed (set only once we have the real message).
402    */
403   int cork;
404
405 };
406
407
408 /**
409  * Handle CORE_SEND request.
410  *
411  * @param cls unused
412  * @param client the client issuing the request
413  * @param message the "struct SendMessage"
414  */
415 static void
416 handle_client_send (void *cls, struct GNUNET_SERVER_Client *client,
417                     const struct GNUNET_MessageHeader *message)
418 {
419   const struct SendMessage *sm;
420   struct GSC_Client *c;
421   struct TokenizerContext tc;
422   uint16_t msize;
423
424   msize = ntohs (message->size);
425   if (msize <
426       sizeof (struct SendMessage) + sizeof (struct GNUNET_MessageHeader))
427   {
428     GNUNET_break (0);
429     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
430     return;
431   }
432   sm = (const struct SendMessage *) message;
433   msize -= sizeof (struct SendMessage);
434   GNUNET_break (0 == ntohl (sm->reserved));
435   c = find_client (client);
436   if (c == NULL)
437   {
438     /* client did not send INIT first! */
439     GNUNET_break (0);
440     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
441     return;
442   }
443   tc.car = GNUNET_CONTAINER_multihashmap_get (c->requests, &sm->peer.hashPubKey);
444   if (NULL == tc.car)
445   {
446     /* Must have been that we first approved the request, then got disconnected
447        (which triggered removal of the 'car') and now the client gives us a message
448        just *before* the client learns about the disconnect.  Theoretically, we
449        might also now be *again* connected.  So this can happen (but should be
450        rare).  If it does happen, the message is discarded. */
451     GNUNET_STATISTICS_update (GSC_stats, 
452                               gettext_noop ("# messages discarded (session disconnected)"),
453                               1,
454                               GNUNET_NO);
455     GNUNET_SERVER_receive_done (client, GNUNET_OK);
456     return;
457   }
458   GNUNET_assert (GNUNET_YES ==
459                  GNUNET_CONTAINER_multihashmap_remove (c->requests, 
460                                                        &sm->peer.hashPubKey,
461                                                        tc.car));
462   tc.cork = ntohl (sm->cork);
463 #if DEBUG_CORE
464   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
465               "Client asked for transmission of %u bytes to `%s' %s\n",
466               msize,
467               GNUNET_i2s (&sm->peer),
468               tc.cork ? "now" : "");
469 #endif
470   GNUNET_SERVER_mst_receive (client_mst,
471                              &tc, 
472                              (const char*) &sm[1], msize,
473                              GNUNET_YES,
474                              GNUNET_NO);
475   if (0 !=
476       memcmp (&tc.car->target, &GSC_my_identity, sizeof (struct GNUNET_PeerIdentity)))  
477     GSC_SESSIONS_dequeue_request (tc.car);
478   GNUNET_free (tc.car);  
479   GNUNET_SERVER_receive_done (client, GNUNET_OK);
480 }
481
482
483 /**
484  * Functions with this signature are called whenever a complete
485  * message is received by the tokenizer.  Used by the 'client_mst' for
486  * dispatching messages from clients to either the SESSION subsystem
487  * or other CLIENT (for loopback).
488  *
489  * @param cls closure
490  * @param client reservation request ('struct GSC_ClientActiveRequest')
491  * @param message the actual message
492  */
493 static void
494 client_tokenizer_callback (void *cls, void *client,
495                            const struct GNUNET_MessageHeader *message)
496 {
497   struct TokenizerContext *tc = client;
498   struct GSC_ClientActiveRequest *car = tc->car;
499
500   if (0 ==
501       memcmp (&car->target, &GSC_my_identity, sizeof (struct GNUNET_PeerIdentity)))  
502   {
503 #if DEBUG_CORE
504     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
505                 "Delivering message of type %u to myself\n",
506                 ntohs (message->type));
507 #endif
508     GSC_CLIENTS_deliver_message (&GSC_my_identity, 
509                                  NULL, 0,
510                                  message,
511                                  ntohs (message->size),
512                                  GNUNET_CORE_OPTION_SEND_FULL_INBOUND | GNUNET_CORE_OPTION_SEND_FULL_OUTBOUND);  
513     GSC_CLIENTS_deliver_message (&GSC_my_identity, 
514                                  NULL, 0,
515                                  message,
516                                  sizeof (struct GNUNET_MessageHeader),
517                                  GNUNET_CORE_OPTION_SEND_HDR_INBOUND | GNUNET_CORE_OPTION_SEND_HDR_OUTBOUND);  
518   }
519   else
520   {
521 #if DEBUG_CORE
522     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
523                 "Delivering message of type %u to %s\n",
524                 ntohs (message->type),
525                 GNUNET_i2s (&car->target));
526 #endif
527     GSC_SESSIONS_transmit (car, message, tc->cork);
528   }
529 }
530
531
532 /**
533  * Free client request records.
534  *
535  * @param cls NULL
536  * @param key identity of peer for which this is an active request
537  * @param value the 'struct GSC_ClientActiveRequest' to free
538  * @return GNUNET_YES (continue iteration)
539  */
540 static int
541 destroy_active_client_request (void *cls, const GNUNET_HashCode * key,
542                                void *value)
543 {
544   struct GSC_ClientActiveRequest *car = value;
545
546   GNUNET_assert (GNUNET_YES ==
547                  GNUNET_CONTAINER_multihashmap_remove (car->client_handle->requests,
548                                                        &car->target.hashPubKey,
549                                                        car));
550   GSC_SESSIONS_dequeue_request (car);
551   GNUNET_free (car);
552   return GNUNET_YES;
553 }
554
555
556 /**
557  * A client disconnected, clean up.
558  *
559  * @param cls closure
560  * @param client identification of the client
561  */
562 static void
563 handle_client_disconnect (void *cls,
564                           struct GNUNET_SERVER_Client *client)
565 {
566   struct GSC_Client *c;
567
568   if (client == NULL)
569     return;
570 #if DEBUG_CORE
571   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
572               "Client %p has disconnected from core service.\n", client);
573 #endif
574   c = find_client (client);
575   if (c == NULL)
576     return; /* client never sent INIT */
577   GNUNET_CONTAINER_DLL_remove (client_head,
578                                client_tail,
579                                c);
580   if (c->requests != NULL)
581   {
582     GNUNET_CONTAINER_multihashmap_iterate (c->requests,
583                                            &destroy_active_client_request,
584                                            NULL);
585     GNUNET_CONTAINER_multihashmap_destroy (c->requests);
586   }
587 #if DEBUG_CONNECTS
588   GNUNET_CONTAINER_multihashmap_destroy (c->connectmap);
589 #endif
590   GSC_TYPEMAP_remove (c->types, c->tcnt);
591   GNUNET_free (c);
592 }
593
594
595 /**
596  * Tell a client that we are ready to receive the message.
597  *
598  * @param car request that is now ready; the responsibility
599  *        for the handle remains shared between CLIENTS
600  *        and SESSIONS after this call.
601  */
602 void
603 GSC_CLIENTS_solicit_request (struct GSC_ClientActiveRequest *car)
604 {
605   struct GSC_Client *c;
606   struct SendMessageReady smr;
607
608   c = car->client_handle;
609   smr.header.size = htons (sizeof (struct SendMessageReady));
610   smr.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_SEND_READY);
611   smr.size = htons (car->msize);
612   smr.smr_id = car->smr_id;
613   smr.peer = car->target;
614 #if DEBUG_CONNECTS
615   GNUNET_assert (GNUNET_YES ==
616                  GNUNET_CONTAINER_multihashmap_contains (c->connectmap,
617                                                          &car->target.hashPubKey));
618 #endif
619   send_to_client (c, &smr.header, GNUNET_NO);
620 }
621
622
623 /**
624  * Tell a client that we will never be ready to receive the
625  * given message in time (disconnect or timeout).
626  *
627  * @param car request that now permanently failed; the
628  *        responsibility for the handle is now returned
629  *        to CLIENTS (SESSIONS is done with it).
630  */
631 void
632 GSC_CLIENTS_reject_request (struct GSC_ClientActiveRequest *car)
633 {
634   GNUNET_assert (GNUNET_YES ==
635                  GNUNET_CONTAINER_multihashmap_remove (car->client_handle->requests,
636                                                        &car->target.hashPubKey,
637                                                        car));
638   GNUNET_free (car);
639 }
640
641
642 /**
643  * Notify a particular client about a change to existing connection to
644  * one of our neighbours (check if the client is interested).  Called
645  * from 'GSC_SESSIONS_notify_client_about_sessions'.
646  *
647  * @param client client to notify
648  * @param neighbour identity of the neighbour that changed status
649  * @param atsi performance information about neighbour
650  * @param atsi_count number of entries in 'ats' array
651  * @param tmap_old previous type map for the neighbour, NULL for disconnect
652  * @param tmap_new updated type map for the neighbour, NULL for disconnect
653  * @param is_new GNUNET_YES if this is a completely new neighbour
654  */
655 void
656 GSC_CLIENTS_notify_client_about_neighbour (struct GSC_Client *client,
657                                            const struct GNUNET_PeerIdentity *neighbour,
658                                            const struct GNUNET_ATS_Information *atsi,
659                                            unsigned int atsi_count,
660                                            const struct GSC_TypeMap *tmap_old,
661                                            const struct GSC_TypeMap *tmap_new)
662 {
663   struct ConnectNotifyMessage *cnm;
664   size_t size;
665   char buf[GNUNET_SERVER_MAX_MESSAGE_SIZE - 1];
666   struct GNUNET_ATS_Information *a;
667   struct DisconnectNotifyMessage dcm;
668   int old_match;
669   int new_match;
670
671   old_match = GSC_TYPEMAP_test_match (tmap_old, client->types, client->tcnt);
672   new_match = GSC_TYPEMAP_test_match (tmap_new, client->types, client->tcnt);
673   if (old_match == new_match)
674   {
675     GNUNET_assert (old_match ==
676                    GNUNET_CONTAINER_multihashmap_contains (client->connectmap,
677                                                            &neighbour->hashPubKey));
678     return; /* no change */
679   }
680   if (old_match == GNUNET_NO)
681   {
682     /* send connect */  
683 #if DEBUG_CONNECTS
684     GNUNET_assert (GNUNET_NO ==
685                    GNUNET_CONTAINER_multihashmap_contains (client->connectmap,
686                                                            &neighbour->hashPubKey));
687     GNUNET_assert (GNUNET_YES ==
688                    GNUNET_CONTAINER_multihashmap_put (client->connectmap,
689                                                       &neighbour->hashPubKey,
690                                                       NULL,
691                                                       GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
692 #endif
693     size =
694       sizeof (struct ConnectNotifyMessage) +
695       (atsi_count) * sizeof (struct GNUNET_ATS_Information);
696     if (size >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
697       {
698         GNUNET_break (0);
699         /* recovery strategy: throw away performance data */
700         atsi_count = 0;
701         size = sizeof (struct ConnectNotifyMessage);
702       }
703     cnm = (struct ConnectNotifyMessage *) buf;
704     cnm->header.size = htons (size);
705     cnm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT);
706     cnm->ats_count = htonl (atsi_count);
707     a = (struct GNUNET_ATS_Information* ) &cnm[1];
708     memcpy (a, atsi,
709             sizeof (struct GNUNET_ATS_Information) * atsi_count);
710 #if DEBUG_CORE
711     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 
712                 "Sending `%s' message to client.\n",
713                 "NOTIFY_CONNECT");
714 #endif
715     cnm->peer = *neighbour;
716     send_to_client (client, &cnm->header, GNUNET_NO);
717   }
718   else
719   {
720     /* send disconnect */
721 #if DEBUG_CONNECTS
722     GNUNET_assert (GNUNET_YES ==
723                    GNUNET_CONTAINER_multihashmap_contains (client->connectmap,
724                                                            &neighbour->hashPubKey));
725     GNUNET_assert (GNUNET_YES ==
726                    GNUNET_CONTAINER_multihashmap_remove (client->connectmap,
727                                                          &neighbour->hashPubKey,
728                                                          NULL));
729 #endif
730     dcm.header.size = htons (sizeof (struct DisconnectNotifyMessage));
731     dcm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_DISCONNECT);
732     dcm.reserved = htonl (0);
733     dcm.peer = *neighbour;
734     send_to_client (client, &dcm.header, GNUNET_NO);
735   }
736 }
737
738
739 /**
740  * Notify all clients about a change to existing session.
741  * Called from SESSIONS whenever there is a change in sessions
742  * or types processed by the respective peer.
743  *
744  * @param neighbour identity of the neighbour that changed status
745  * @param atsi performance information about neighbour
746  * @param atsi_count number of entries in 'ats' array
747  * @param tmap_old previous type map for the neighbour, NULL for disconnect
748  * @param tmap_new updated type map for the neighbour, NULL for disconnect
749  */
750 void
751 GSC_CLIENTS_notify_clients_about_neighbour (const struct GNUNET_PeerIdentity *neighbour,
752                                             const struct GNUNET_ATS_Information *atsi,
753                                             unsigned int atsi_count,
754                                             const struct GSC_TypeMap *tmap_old,
755                                             const struct GSC_TypeMap *tmap_new)
756 {
757   struct GSC_Client *c;
758
759   for (c = client_head; c != NULL; c = c->next)
760     GSC_CLIENTS_notify_client_about_neighbour (c, neighbour, atsi,
761                                                atsi_count, 
762                                                tmap_old, tmap_new);
763 }
764
765
766 /**
767  * Deliver P2P message to interested clients.  Caller must have checked
768  * that the sending peer actually lists the given message type as one 
769  * of its types.
770  *
771  * @param sender peer who sent us the message 
772  * @param atsi performance information about neighbour
773  * @param atsi_count number of entries in 'ats' array
774  * @param msg the message
775  * @param msize number of bytes to transmit
776  * @param options options for checking which clients should
777  *        receive the message
778  */
779 void
780 GSC_CLIENTS_deliver_message (const struct GNUNET_PeerIdentity *sender,
781                              const struct GNUNET_ATS_Information *atsi,
782                              unsigned int atsi_count,
783                              const struct GNUNET_MessageHeader *msg,
784                              uint16_t msize,
785                              int options)
786 {
787   size_t size = msize + sizeof (struct NotifyTrafficMessage) +
788       atsi_count * sizeof (struct GNUNET_ATS_Information);
789   char buf[size];
790   struct NotifyTrafficMessage *ntm;
791   struct GNUNET_ATS_Information *a;
792
793   if (0 == options)
794   {
795     GNUNET_snprintf (buf, sizeof (buf),
796                      gettext_noop ("# bytes of messages of type %u received"),
797                      (unsigned int) ntohs (msg->type));
798     GNUNET_STATISTICS_update (GSC_stats, buf, msize, GNUNET_NO);
799   }
800   if (size >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
801   {
802     GNUNET_break (0);
803     /* recovery strategy: throw performance data away... */
804     atsi_count = 0;
805     size = msize + sizeof (struct NotifyTrafficMessage);
806   }
807 #if DEBUG_CORE
808   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
809               "Core service passes message from `%4s' of type %u to client.\n",
810               GNUNET_i2s (sender),
811               (unsigned int) ntohs (msg->type));
812 #endif
813   GSC_SESSIONS_add_to_typemap (sender, ntohs (msg->type));
814   ntm = (struct NotifyTrafficMessage *) buf;
815   ntm->header.size = htons (size);
816   ntm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_NOTIFY_INBOUND);
817   ntm->ats_count = htonl (atsi_count);
818   ntm->peer = *sender;
819   a = &ntm->ats;
820   memcpy (a, atsi,
821           sizeof (struct GNUNET_ATS_Information) * atsi_count);
822   a[atsi_count].type = htonl (GNUNET_ATS_ARRAY_TERMINATOR);
823   a[atsi_count].value = htonl (0);
824   memcpy (&a[atsi_count + 1], msg, msize);
825   send_to_all_clients (sender,
826                        &ntm->header, GNUNET_YES, 
827                        options, ntohs (msg->type));
828 }
829
830
831 /**
832  * Initialize clients subsystem.
833  *
834  * @param server handle to server clients connect to
835  */
836 void
837 GSC_CLIENTS_init (struct GNUNET_SERVER_Handle *server)
838 {
839   static const struct GNUNET_SERVER_MessageHandler handlers[] = {
840     {&handle_client_init, NULL,
841      GNUNET_MESSAGE_TYPE_CORE_INIT, 0},
842     {&GSC_SESSIONS_handle_client_iterate_peers, NULL,
843      GNUNET_MESSAGE_TYPE_CORE_ITERATE_PEERS,
844      sizeof (struct GNUNET_MessageHeader)},
845     {&GSC_SESSIONS_handle_client_have_peer, NULL,
846      GNUNET_MESSAGE_TYPE_CORE_PEER_CONNECTED,
847      sizeof (struct GNUNET_MessageHeader) +
848      sizeof (struct GNUNET_PeerIdentity)},
849     {&handle_client_send_request, NULL,
850      GNUNET_MESSAGE_TYPE_CORE_SEND_REQUEST,
851      sizeof (struct SendMessageRequest)},
852     {&handle_client_send, NULL,
853      GNUNET_MESSAGE_TYPE_CORE_SEND, 0},
854     {NULL, NULL, 0, 0}
855   };
856
857   /* setup notification */
858   client_mst = GNUNET_SERVER_mst_create (&client_tokenizer_callback, NULL);
859   notifier =
860       GNUNET_SERVER_notification_context_create (server, MAX_NOTIFY_QUEUE);
861   GNUNET_SERVER_disconnect_notify (server, &handle_client_disconnect, NULL);
862   GNUNET_SERVER_add_handlers (server, handlers);
863 }
864
865
866 /**
867  * Shutdown clients subsystem.
868  */
869 void
870 GSC_CLIENTS_done ()
871 {
872   struct GSC_Client *c;
873
874   while (NULL != (c = client_head))  
875     handle_client_disconnect (NULL, c->client_handle);
876   if (NULL != notifier)
877   {
878     GNUNET_SERVER_notification_context_destroy (notifier);
879     notifier = NULL;
880   }
881   GNUNET_SERVER_mst_destroy (client_mst);
882   client_mst = NULL;
883 }
884
885 /* end of gnunet-service-core_clients.c */