b7ac11c5e12b4e9912d733c484e2532ea3ce5ba1
[oweals/gnunet.git] / src / cadet / gnunet-service-cadet_local.c
1 /*
2      This file is part of GNUnet.
3      (C) 2013 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 #include "platform.h"
23 #include "gnunet_util_lib.h"
24
25 #include "gnunet_statistics_service.h"
26
27 #include "cadet.h"
28 #include "cadet_protocol.h" /* GNUNET_CADET_Data is shared */
29
30 #include "gnunet-service-cadet_local.h"
31 #include "gnunet-service-cadet_channel.h"
32
33 /* INFO DEBUG */
34 #include "gnunet-service-cadet_tunnel.h"
35 #include "gnunet-service-cadet_peer.h"
36
37 #define LOG(level, ...) GNUNET_log_from(level,"cadet-loc",__VA_ARGS__)
38
39 /******************************************************************************/
40 /********************************   STRUCTS  **********************************/
41 /******************************************************************************/
42
43 /**
44  * Struct containing information about a client of the service
45  *
46  * TODO: add a list of 'waiting' ports
47  */
48 struct CadetClient
49 {
50     /**
51      * Linked list next
52      */
53   struct CadetClient *next;
54
55     /**
56      * Linked list prev
57      */
58   struct CadetClient *prev;
59
60     /**
61      * Tunnels that belong to this client, indexed by local id
62      */
63   struct GNUNET_CONTAINER_MultiHashMap32 *own_channels;
64
65     /**
66      * Tunnels this client has accepted, indexed by incoming local id
67      */
68   struct GNUNET_CONTAINER_MultiHashMap32 *incoming_channels;
69
70     /**
71      * Channel ID for the next incoming channel.
72      */
73   CADET_ChannelNumber next_chid;
74
75     /**
76      * Handle to communicate with the client
77      */
78   struct GNUNET_SERVER_Client *handle;
79
80     /**
81      * Ports that this client has declared interest in.
82      * Indexed by port, contains *Client.
83      */
84   struct GNUNET_CONTAINER_MultiHashMap32 *ports;
85
86     /**
87      * Whether the client is active or shutting down (don't send confirmations
88      * to a client that is shutting down.
89      */
90   int shutting_down;
91
92     /**
93      * ID of the client, mainly for debug messages
94      */
95   unsigned int id;
96 };
97
98 /******************************************************************************/
99 /*******************************   GLOBALS  ***********************************/
100 /******************************************************************************/
101
102 /**
103  * Global handle to the statistics service.
104  */
105 extern struct GNUNET_STATISTICS_Handle *stats;
106
107 /**
108  * Handle to server lib.
109  */
110 static struct GNUNET_SERVER_Handle *server_handle;
111
112 /**
113  * DLL with all the clients, head.
114  */
115 static struct CadetClient *clients_head;
116
117 /**
118  * DLL with all the clients, tail.
119  */
120 static struct CadetClient *clients_tail;
121
122 /**
123  * Next ID to assign to a client.
124  */
125 unsigned int next_client_id;
126
127 /**
128  * All ports clients of this peer have opened.
129  */
130 static struct GNUNET_CONTAINER_MultiHashMap32 *ports;
131
132 /**
133  * Notification context, to send messages to local clients.
134  */
135 static struct GNUNET_SERVER_NotificationContext *nc;
136
137
138 /******************************************************************************/
139 /********************************   STATIC  ***********************************/
140 /******************************************************************************/
141
142 /**
143  * Remove client's ports from the global hashmap on disconnect.
144  *
145  * @param cls Closure (unused).
146  * @param key Port.
147  * @param value Client structure.
148  *
149  * @return GNUNET_OK, keep iterating.
150  */
151 static int
152 client_release_ports (void *cls,
153                       uint32_t key,
154                       void *value)
155 {
156   int res;
157
158   res = GNUNET_CONTAINER_multihashmap32_remove (ports, key, value);
159   if (GNUNET_YES != res)
160   {
161     GNUNET_break (0);
162     LOG (GNUNET_ERROR_TYPE_WARNING,
163                 "Port %u by client %p was not registered.\n",
164                 key, value);
165   }
166   return GNUNET_OK;
167 }
168
169
170
171 /******************************************************************************/
172 /********************************  HANDLES  ***********************************/
173 /******************************************************************************/
174
175
176 /**
177  * Handler for client connection.
178  *
179  * @param cls Closure (unused).
180  * @param client Client handler.
181  */
182 static void
183 handle_client_connect (void *cls, struct GNUNET_SERVER_Client *client)
184 {
185   struct CadetClient *c;
186
187   LOG (GNUNET_ERROR_TYPE_DEBUG, "client connected: %p\n", client);
188   if (NULL == client)
189     return;
190   c = GNUNET_new (struct CadetClient);
191   c->handle = client;
192   c->id = next_client_id++; /* overflow not important: just for debug */
193   c->next_chid = GNUNET_CADET_LOCAL_CHANNEL_ID_SERV;
194   GNUNET_SERVER_client_keep (client);
195   GNUNET_SERVER_client_set_user_context (client, c);
196   GNUNET_CONTAINER_DLL_insert (clients_head, clients_tail, c);
197 }
198
199
200 /**
201  * Iterator for deleting each channel whose client endpoint disconnected.
202  *
203  * @param cls Closure (client that has disconnected).
204  * @param key The local channel id (used to access the hashmap).
205  * @param value The value stored at the key (channel to destroy).
206  *
207  * @return GNUNET_OK, keep iterating.
208  */
209 static int
210 channel_destroy_iterator (void *cls,
211                           uint32_t key,
212                           void *value)
213 {
214   struct CadetChannel *ch = value;
215   struct CadetClient *c = cls;
216
217   LOG (GNUNET_ERROR_TYPE_DEBUG,
218               " Channel %s destroy, due to client %s shutdown.\n",
219               GCCH_2s (ch), GML_2s (c));
220
221   GCCH_handle_local_destroy (ch, c, key < GNUNET_CADET_LOCAL_CHANNEL_ID_SERV);
222   return GNUNET_OK;
223 }
224
225 /**
226  * Handler for client disconnection
227  *
228  * @param cls closure
229  * @param client identification of the client; NULL
230  *        for the last call when the server is destroyed
231  */
232 static void
233 handle_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
234 {
235   struct CadetClient *c;
236
237   LOG (GNUNET_ERROR_TYPE_DEBUG, "client disconnected: %p\n", client);
238   if (client == NULL)
239   {
240     LOG (GNUNET_ERROR_TYPE_DEBUG, "   (SERVER DOWN)\n");
241     return;
242   }
243
244   c = GML_client_get (client);
245   if (NULL != c)
246   {
247     LOG (GNUNET_ERROR_TYPE_DEBUG, "matching client found (%u, %p)\n",
248                 c->id, c);
249     GNUNET_SERVER_client_drop (c->handle);
250     c->shutting_down = GNUNET_YES;
251     if (NULL != c->own_channels)
252     {
253       GNUNET_CONTAINER_multihashmap32_iterate (c->own_channels,
254                                                &channel_destroy_iterator, c);
255       GNUNET_CONTAINER_multihashmap32_destroy (c->own_channels);
256     }
257
258     if (NULL != c->incoming_channels)
259     {
260       GNUNET_CONTAINER_multihashmap32_iterate (c->incoming_channels,
261                                                &channel_destroy_iterator, c);
262       GNUNET_CONTAINER_multihashmap32_destroy (c->incoming_channels);
263     }
264
265     if (NULL != c->ports)
266     {
267       GNUNET_CONTAINER_multihashmap32_iterate (c->ports,
268                                                &client_release_ports, c);
269       GNUNET_CONTAINER_multihashmap32_destroy (c->ports);
270     }
271     GNUNET_CONTAINER_DLL_remove (clients_head, clients_tail, c);
272     GNUNET_STATISTICS_update (stats, "# clients", -1, GNUNET_NO);
273     LOG (GNUNET_ERROR_TYPE_DEBUG, "  client free (%p)\n", c);
274     GNUNET_free (c);
275   }
276   else
277   {
278     LOG (GNUNET_ERROR_TYPE_WARNING, " context NULL!\n");
279   }
280   LOG (GNUNET_ERROR_TYPE_DEBUG, "done!\n");
281   return;
282 }
283
284
285 /**
286  * Handler for new clients
287  *
288  * @param cls closure
289  * @param client identification of the client
290  * @param message the actual message, which includes messages the client wants
291  */
292 static void
293 handle_new_client (void *cls, struct GNUNET_SERVER_Client *client,
294                    const struct GNUNET_MessageHeader *message)
295 {
296   struct GNUNET_CADET_ClientConnect *cc_msg;
297   struct CadetClient *c;
298   unsigned int size;
299   uint32_t *p;
300   unsigned int i;
301
302   LOG (GNUNET_ERROR_TYPE_DEBUG, "\n");
303   LOG (GNUNET_ERROR_TYPE_DEBUG, "new client connected %p\n", client);
304
305   /* Check data sanity */
306   size = ntohs (message->size) - sizeof (struct GNUNET_CADET_ClientConnect);
307   cc_msg = (struct GNUNET_CADET_ClientConnect *) message;
308   if (0 != (size % sizeof (uint32_t)))
309   {
310     GNUNET_break (0);
311     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
312     return;
313   }
314   size /= sizeof (uint32_t);
315
316   /* Initialize new client structure */
317   c = GNUNET_SERVER_client_get_user_context (client, struct CadetClient);
318   LOG (GNUNET_ERROR_TYPE_DEBUG, "  client id %u\n", c->id);
319   LOG (GNUNET_ERROR_TYPE_DEBUG, "  client has %u ports\n", size);
320   if (size > 0)
321   {
322     uint32_t u32;
323
324     p = (uint32_t *) &cc_msg[1];
325     c->ports = GNUNET_CONTAINER_multihashmap32_create (size);
326     for (i = 0; i < size; i++)
327     {
328       u32 = ntohl (p[i]);
329       LOG (GNUNET_ERROR_TYPE_DEBUG, "    port: %u\n", u32);
330
331       /* store in client's hashmap */
332       GNUNET_CONTAINER_multihashmap32_put (c->ports, u32, c,
333                                            GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
334       /* store in global hashmap */
335       /* FIXME only allow one client to have the port open,
336        *       have a backup hashmap with waiting clients */
337       GNUNET_CONTAINER_multihashmap32_put (ports, u32, c,
338                                            GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
339     }
340   }
341
342   c->own_channels = GNUNET_CONTAINER_multihashmap32_create (32);
343   c->incoming_channels = GNUNET_CONTAINER_multihashmap32_create (32);
344   GNUNET_SERVER_notification_context_add (nc, client);
345   GNUNET_STATISTICS_update (stats, "# clients", 1, GNUNET_NO);
346
347   GNUNET_SERVER_receive_done (client, GNUNET_OK);
348   LOG (GNUNET_ERROR_TYPE_DEBUG, "new client processed\n");
349 }
350
351
352 /**
353  * Handler for requests of new tunnels
354  *
355  * @param cls Closure.
356  * @param client Identification of the client.
357  * @param message The actual message.
358  */
359 static void
360 handle_channel_create (void *cls, struct GNUNET_SERVER_Client *client,
361                        const struct GNUNET_MessageHeader *message)
362 {
363   struct CadetClient *c;
364
365   LOG (GNUNET_ERROR_TYPE_DEBUG, "\n");
366   LOG (GNUNET_ERROR_TYPE_DEBUG, "new channel requested\n");
367
368   /* Sanity check for client registration */
369   if (NULL == (c = GML_client_get (client)))
370   {
371     GNUNET_break (0);
372     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
373     return;
374   }
375   LOG (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
376
377   /* Message size sanity check */
378   if (sizeof (struct GNUNET_CADET_ChannelMessage) != ntohs (message->size))
379   {
380     GNUNET_break (0);
381     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
382     return;
383   }
384
385   if (GNUNET_OK !=
386       GCCH_handle_local_create (c,
387                                 (struct GNUNET_CADET_ChannelMessage *) message))
388   {
389     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
390     return;
391   }
392
393   GNUNET_SERVER_receive_done (client, GNUNET_OK);
394   return;
395 }
396
397
398 /**
399  * Handler for requests of deleting tunnels
400  *
401  * @param cls closure
402  * @param client identification of the client
403  * @param message the actual message
404  */
405 static void
406 handle_channel_destroy (void *cls, struct GNUNET_SERVER_Client *client,
407                         const struct GNUNET_MessageHeader *message)
408 {
409   struct GNUNET_CADET_ChannelMessage *msg;
410   struct CadetClient *c;
411   struct CadetChannel *ch;
412   CADET_ChannelNumber chid;
413
414   LOG (GNUNET_ERROR_TYPE_DEBUG, "Got a DESTROY CHANNEL from client!\n");
415
416   /* Sanity check for client registration */
417   if (NULL == (c = GML_client_get (client)))
418   {
419     GNUNET_break (0);
420     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
421     return;
422   }
423   LOG (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
424
425   /* Message sanity check */
426   if (sizeof (struct GNUNET_CADET_ChannelMessage) != ntohs (message->size))
427   {
428     GNUNET_break (0);
429     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
430     return;
431   }
432
433   msg = (struct GNUNET_CADET_ChannelMessage *) message;
434
435   /* Retrieve tunnel */
436   chid = ntohl (msg->channel_id);
437   LOG (GNUNET_ERROR_TYPE_DEBUG, "  for channel %X\n", chid);
438   ch = GML_channel_get (c, chid);
439   if (NULL == ch)
440   {
441     LOG (GNUNET_ERROR_TYPE_DEBUG, "  channel %X not found\n", chid);
442     GNUNET_STATISTICS_update (stats,
443                               "# client destroy messages on unknown channel",
444                               1, GNUNET_NO);
445     GNUNET_SERVER_receive_done (client, GNUNET_OK);
446     return;
447   }
448
449   GCCH_handle_local_destroy (ch, c, chid < GNUNET_CADET_LOCAL_CHANNEL_ID_SERV);
450
451   GNUNET_SERVER_receive_done (client, GNUNET_OK);
452   return;
453 }
454
455
456 /**
457  * Handler for client traffic
458  *
459  * @param cls closure
460  * @param client identification of the client
461  * @param message the actual message
462  */
463 static void
464 handle_data (void *cls, struct GNUNET_SERVER_Client *client,
465              const struct GNUNET_MessageHeader *message)
466 {
467   struct GNUNET_CADET_LocalData *msg;
468   struct CadetClient *c;
469   struct CadetChannel *ch;
470   CADET_ChannelNumber chid;
471   size_t size;
472   int fwd;
473
474   LOG (GNUNET_ERROR_TYPE_DEBUG, "Got data from a client!\n");
475
476   /* Sanity check for client registration */
477   if (NULL == (c = GML_client_get (client)))
478   {
479     GNUNET_break (0);
480     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
481     return;
482   }
483   LOG (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
484
485   msg = (struct GNUNET_CADET_LocalData *) message;
486
487   /* Sanity check for message size */
488   size = ntohs (message->size) - sizeof (struct GNUNET_CADET_LocalData);
489   if (size < sizeof (struct GNUNET_MessageHeader))
490   {
491     GNUNET_break (0);
492     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
493     return;
494   }
495
496   /* Channel exists? */
497   chid = ntohl (msg->id);
498   LOG (GNUNET_ERROR_TYPE_DEBUG, "  on channel %X\n", chid);
499   fwd = chid < GNUNET_CADET_LOCAL_CHANNEL_ID_SERV;
500   ch = GML_channel_get (c, chid);
501   if (NULL == ch)
502   {
503     GNUNET_STATISTICS_update (stats,
504                               "# client data messages on unknown channel",
505                               1, GNUNET_NO);
506     GNUNET_SERVER_receive_done (client, GNUNET_OK);
507     return;
508   }
509
510   if (GNUNET_OK !=
511       GCCH_handle_local_data (ch, c,
512                               (struct GNUNET_MessageHeader *)&msg[1], fwd))
513   {
514     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
515     return;
516   }
517
518   LOG (GNUNET_ERROR_TYPE_DEBUG, "receive done OK\n");
519   GNUNET_SERVER_receive_done (client, GNUNET_OK);
520
521   return;
522 }
523
524
525 /**
526  * Handler for client's ACKs for payload traffic.
527  *
528  * @param cls Closure (unused).
529  * @param client Identification of the client.
530  * @param message The actual message.
531  */
532 static void
533 handle_ack (void *cls, struct GNUNET_SERVER_Client *client,
534             const struct GNUNET_MessageHeader *message)
535 {
536   struct GNUNET_CADET_LocalAck *msg;
537   struct CadetChannel *ch;
538   struct CadetClient *c;
539   CADET_ChannelNumber chid;
540   int fwd;
541
542   LOG (GNUNET_ERROR_TYPE_DEBUG, "\n");
543   LOG (GNUNET_ERROR_TYPE_DEBUG, "Got a local ACK\n");
544
545   /* Sanity check for client registration */
546   if (NULL == (c = GML_client_get (client)))
547   {
548     GNUNET_break (0);
549     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
550     return;
551   }
552   LOG (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
553
554   msg = (struct GNUNET_CADET_LocalAck *) message;
555
556   /* Channel exists? */
557   chid = ntohl (msg->channel_id);
558   LOG (GNUNET_ERROR_TYPE_DEBUG, "  on channel %X\n", chid);
559   ch = GML_channel_get (c, chid);
560   LOG (GNUNET_ERROR_TYPE_DEBUG, "   -- ch %p\n", ch);
561   if (NULL == ch)
562   {
563     LOG (GNUNET_ERROR_TYPE_DEBUG, "Channel %X unknown.\n", chid);
564     LOG (GNUNET_ERROR_TYPE_DEBUG, "  for client %u.\n", c->id);
565     GNUNET_STATISTICS_update (stats,
566                               "# client ack messages on unknown channel",
567                               1, GNUNET_NO);
568     GNUNET_SERVER_receive_done (client, GNUNET_OK);
569     return;
570   }
571
572   /* If client is root, the ACK is going FWD, therefore this is "BCK ACK". */
573   /* If client is dest, the ACK is going BCK, therefore this is "FWD ACK" */
574   fwd = chid >= GNUNET_CADET_LOCAL_CHANNEL_ID_SERV;
575
576   GCCH_handle_local_ack (ch, fwd);
577   GNUNET_SERVER_receive_done (client, GNUNET_OK);
578
579   return;
580 }
581
582
583 /**
584  * Iterator over all peers to send a monitoring client info about each peer.
585  *
586  * @param cls Closure ().
587  * @param peer Peer ID (tunnel remote peer).
588  * @param value Peer info.
589  *
590  * @return #GNUNET_YES, to keep iterating.
591  */
592 static int
593 get_all_peers_iterator (void *cls,
594                         const struct GNUNET_PeerIdentity * peer,
595                         void *value)
596 {
597   struct GNUNET_SERVER_Client *client = cls;
598   struct CadetPeer *p = value;
599   struct GNUNET_CADET_LocalInfoPeer msg;
600
601   msg.header.size = htons (sizeof (msg));
602   msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_PEERS);
603   msg.destination = *peer;
604   msg.paths = htons (GCP_count_paths (p));
605   msg.tunnel = htons (NULL != GCP_get_tunnel (p));
606
607   LOG (GNUNET_ERROR_TYPE_DEBUG, "sending info about peer %s\n",
608        GNUNET_i2s (peer));
609
610   GNUNET_SERVER_notification_context_unicast (nc, client,
611                                               &msg.header, GNUNET_NO);
612   return GNUNET_YES;
613 }
614
615
616 /**
617  * Iterator over all peers to dump info for each peer.
618  *
619  * @param cls Closure (unused).
620  * @param peer Peer ID (tunnel remote peer).
621  * @param value Peer info.
622  *
623  * @return #GNUNET_YES, to keep iterating.
624  */
625 static int
626 show_peer_iterator (void *cls,
627                         const struct GNUNET_PeerIdentity * peer,
628                         void *value)
629 {
630   struct CadetPeer *p = value;
631   struct CadetTunnel *t;
632
633   LOG (GNUNET_ERROR_TYPE_ERROR, "Peer %s\n", GCP_2s (p));
634   LOG (GNUNET_ERROR_TYPE_ERROR, " %u paths\n", GCP_count_paths (p));
635
636   t = GCP_get_tunnel (p);
637   if (NULL != t)
638     GCT_debug (t, GNUNET_ERROR_TYPE_ERROR);
639
640   LOG (GNUNET_ERROR_TYPE_ERROR, "\n");
641
642   return GNUNET_YES;
643 }
644
645
646 /**
647  * Handler for client's INFO PEERS request.
648  *
649  * @param cls Closure (unused).
650  * @param client Identification of the client.
651  * @param message The actual message.
652  */
653 static void
654 handle_get_peers (void *cls, struct GNUNET_SERVER_Client *client,
655                     const struct GNUNET_MessageHeader *message)
656 {
657   struct CadetClient *c;
658   struct GNUNET_MessageHeader reply;
659
660   /* Sanity check for client registration */
661   if (NULL == (c = GML_client_get (client)))
662   {
663     GNUNET_break (0);
664     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
665     return;
666   }
667
668   LOG (GNUNET_ERROR_TYPE_DEBUG,
669        "Received get peers request from client %u (%p)\n",
670        c->id, client);
671
672   GCP_iterate_all (get_all_peers_iterator, client);
673   reply.size = htons (sizeof (reply));
674   reply.type = htons (GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_PEERS);
675   GNUNET_SERVER_notification_context_unicast (nc, client, &reply, GNUNET_NO);
676
677   LOG (GNUNET_ERROR_TYPE_DEBUG,
678        "Get peers request from client %u completed\n", c->id);
679   GNUNET_SERVER_receive_done (client, GNUNET_OK);
680 }
681
682
683 /**
684  * Iterator over all tunnels to send a monitoring client info about each tunnel.
685  *
686  * @param cls Closure ().
687  * @param peer Peer ID (tunnel remote peer).
688  * @param value Tunnel info.
689  *
690  * @return #GNUNET_YES, to keep iterating.
691  */
692 static int
693 get_all_tunnels_iterator (void *cls,
694                           const struct GNUNET_PeerIdentity * peer,
695                           void *value)
696 {
697   struct GNUNET_SERVER_Client *client = cls;
698   struct CadetTunnel *t = value;
699   struct GNUNET_CADET_LocalInfoTunnel msg;
700
701   msg.header.size = htons (sizeof (msg));
702   msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_TUNNELS);
703   msg.destination = *peer;
704   msg.channels = htonl (GCT_count_channels (t));
705   msg.connections = htonl (GCT_count_connections (t));
706   msg.cstate = htons ((uint16_t) GCT_get_cstate (t));
707   msg.estate = htons ((uint16_t) GCT_get_estate (t));
708
709   LOG (GNUNET_ERROR_TYPE_DEBUG, "sending info about tunnel ->%s\n",
710        GNUNET_i2s (peer));
711
712   GNUNET_SERVER_notification_context_unicast (nc, client,
713                                               &msg.header, GNUNET_NO);
714   return GNUNET_YES;
715 }
716
717
718 /**
719  * Handler for client's INFO TUNNELS request.
720  *
721  * @param cls Closure (unused).
722  * @param client Identification of the client.
723  * @param message The actual message.
724  */
725 static void
726 handle_get_tunnels (void *cls, struct GNUNET_SERVER_Client *client,
727                     const struct GNUNET_MessageHeader *message)
728 {
729   struct CadetClient *c;
730   struct GNUNET_MessageHeader reply;
731
732   /* Sanity check for client registration */
733   if (NULL == (c = GML_client_get (client)))
734   {
735     GNUNET_break (0);
736     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
737     return;
738   }
739
740   LOG (GNUNET_ERROR_TYPE_DEBUG,
741        "Received get tunnels request from client %u (%p)\n",
742        c->id, client);
743
744   GCT_iterate_all (get_all_tunnels_iterator, client);
745   reply.size = htons (sizeof (reply));
746   reply.type = htons (GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_TUNNELS);
747   GNUNET_SERVER_notification_context_unicast (nc, client, &reply, GNUNET_NO);
748
749   LOG (GNUNET_ERROR_TYPE_DEBUG,
750        "Get tunnels request from client %u completed\n", c->id);
751   GNUNET_SERVER_receive_done (client, GNUNET_OK);
752 }
753
754
755 static void
756 iter_connection (void *cls, struct CadetConnection *c)
757 {
758   struct GNUNET_CADET_LocalInfoTunnel *msg = cls;
759   struct GNUNET_CADET_Hash *h = (struct GNUNET_CADET_Hash *) &msg[1];
760
761   h[msg->connections] = *(GCC_get_id (c));
762   msg->connections++;
763 }
764
765 static void
766 iter_channel (void *cls, struct CadetChannel *ch)
767 {
768   struct GNUNET_CADET_LocalInfoTunnel *msg = cls;
769   struct GNUNET_HashCode *h = (struct GNUNET_HashCode *) &msg[1];
770   CADET_ChannelNumber *chn = (CADET_ChannelNumber *) &h[msg->connections];
771
772   chn[msg->channels] = GCCH_get_id (ch);
773   msg->channels++;
774 }
775
776
777 /**
778  * Handler for client's SHOW_TUNNEL request.
779  *
780  * @param cls Closure (unused).
781  * @param client Identification of the client.
782  * @param message The actual message.
783  */
784 void
785 handle_show_tunnel (void *cls, struct GNUNET_SERVER_Client *client,
786                     const struct GNUNET_MessageHeader *message)
787 {
788   const struct GNUNET_CADET_LocalInfo *msg;
789   struct GNUNET_CADET_LocalInfoTunnel *resp;
790   struct CadetClient *c;
791   struct CadetTunnel *t;
792   unsigned int ch_n;
793   unsigned int c_n;
794   size_t size;
795
796   /* Sanity check for client registration */
797   if (NULL == (c = GML_client_get (client)))
798   {
799     GNUNET_break (0);
800     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
801     return;
802   }
803
804   msg = (struct GNUNET_CADET_LocalInfo *) message;
805   LOG (GNUNET_ERROR_TYPE_INFO,
806        "Received tunnel info request from client %u for tunnel %s\n",
807        c->id, GNUNET_i2s_full(&msg->peer));
808
809   t = GCP_get_tunnel (GCP_get (&msg->peer));
810   if (NULL == t)
811   {
812     /* We don't know the tunnel */
813     struct GNUNET_CADET_LocalInfoTunnel warn;
814
815     LOG (GNUNET_ERROR_TYPE_INFO, "Tunnel %s unknown %u\n",
816          GNUNET_i2s_full(&msg->peer), sizeof (warn));
817     warn.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_TUNNEL);
818     warn.header.size = htons (sizeof (warn));
819     warn.destination = msg->peer;
820     warn.channels = htonl (0);
821     warn.connections = htonl (0);
822     warn.cstate = htons (0);
823     warn.estate = htons (0);
824
825     GNUNET_SERVER_notification_context_unicast (nc, client,
826                                                 &warn.header,
827                                                 GNUNET_NO);
828     GNUNET_SERVER_receive_done (client, GNUNET_OK);
829     return;
830   }
831
832   /* Initialize context */
833   ch_n = GCT_count_channels (t);
834   c_n = GCT_count_connections (t);
835
836   size = sizeof (struct GNUNET_CADET_LocalInfoTunnel);
837   size += c_n * sizeof (struct GNUNET_CADET_Hash);
838   size += ch_n * sizeof (CADET_ChannelNumber);
839
840   resp = GNUNET_malloc (size);
841   resp->header.type = htons (GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_TUNNEL);
842   resp->header.size = htons (size);
843   GCT_iterate_connections (t, &iter_connection, resp);
844   GCT_iterate_channels (t, &iter_channel, resp);
845   /* Do not interleave with iterators, iter_channel needs conn in HBO */
846   resp->destination = msg->peer;
847   resp->connections = htonl (resp->connections);
848   resp->channels = htonl (resp->channels);
849   resp->cstate = htons (GCT_get_cstate (t));
850   resp->estate = htons (GCT_get_estate (t));
851   GNUNET_SERVER_notification_context_unicast (nc, c->handle,
852                                               &resp->header, GNUNET_NO);
853   GNUNET_free (resp);
854
855   LOG (GNUNET_ERROR_TYPE_INFO,
856        "Show tunnel request from client %u completed. %u conn, %u ch\n",
857        c->id, c_n, ch_n);
858   GNUNET_SERVER_receive_done (client, GNUNET_OK);
859 }
860
861
862 /**
863  * Handler for client's INFO_DUMP request.
864  *
865  * @param cls Closure (unused).
866  * @param client Identification of the client.
867  * @param message The actual message.
868  */
869 void
870 handle_info_dump (void *cls, struct GNUNET_SERVER_Client *client,
871                   const struct GNUNET_MessageHeader *message)
872 {
873   struct CadetClient *c;
874
875   /* Sanity check for client registration */
876   if (NULL == (c = GML_client_get (client)))
877   {
878     GNUNET_break (0);
879     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
880     return;
881   }
882
883   LOG (GNUNET_ERROR_TYPE_INFO, "Received dump info request from client %u\n",
884        c->id);
885
886   LOG (GNUNET_ERROR_TYPE_ERROR,
887        "*************************** DUMP START ***************************\n");
888
889   GCP_iterate_all (&show_peer_iterator, NULL);
890
891   LOG (GNUNET_ERROR_TYPE_ERROR,
892        "**************************** DUMP END ****************************\n");
893
894   GNUNET_SERVER_receive_done (client, GNUNET_OK);
895 }
896
897
898 /**
899  * Functions to handle messages from clients
900  */
901 static struct GNUNET_SERVER_MessageHandler client_handlers[] = {
902   {&handle_new_client, NULL, GNUNET_MESSAGE_TYPE_CADET_LOCAL_CONNECT, 0},
903   {&handle_channel_create, NULL, GNUNET_MESSAGE_TYPE_CADET_CHANNEL_CREATE,
904    sizeof (struct GNUNET_CADET_ChannelMessage)},
905   {&handle_channel_destroy, NULL, GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY,
906    sizeof (struct GNUNET_CADET_ChannelMessage)},
907   {&handle_data, NULL, GNUNET_MESSAGE_TYPE_CADET_LOCAL_DATA, 0},
908   {&handle_ack, NULL, GNUNET_MESSAGE_TYPE_CADET_LOCAL_ACK,
909    sizeof (struct GNUNET_CADET_LocalAck)},
910   {&handle_get_peers, NULL, GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_PEERS,
911    sizeof (struct GNUNET_MessageHeader)},
912   {&handle_get_tunnels, NULL, GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_TUNNELS,
913    sizeof (struct GNUNET_MessageHeader)},
914   {&handle_show_tunnel, NULL, GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_TUNNEL,
915    sizeof (struct GNUNET_CADET_LocalInfo)},
916   {&handle_info_dump, NULL, GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_DUMP,
917    sizeof (struct GNUNET_MessageHeader)},
918   {NULL, NULL, 0, 0}
919 };
920
921
922
923 /******************************************************************************/
924 /********************************    API    ***********************************/
925 /******************************************************************************/
926
927 /**
928  * Initialize server subsystem.
929  *
930  * @param handle Server handle.
931  */
932 void
933 GML_init (struct GNUNET_SERVER_Handle *handle)
934 {
935   LOG (GNUNET_ERROR_TYPE_DEBUG, "init\n");
936   server_handle = handle;
937   GNUNET_SERVER_suspend (server_handle);
938   ports = GNUNET_CONTAINER_multihashmap32_create (32);
939 }
940
941
942 /**
943  * Install server (service) handlers and start listening to clients.
944  */
945 void
946 GML_start (void)
947 {
948   GNUNET_SERVER_add_handlers (server_handle, client_handlers);
949   GNUNET_SERVER_connect_notify (server_handle,  &handle_client_connect, NULL);
950   GNUNET_SERVER_disconnect_notify (server_handle, &handle_client_disconnect,
951                                    NULL);
952   nc = GNUNET_SERVER_notification_context_create (server_handle, 1);
953
954   clients_head = NULL;
955   clients_tail = NULL;
956   next_client_id = 0;
957   GNUNET_SERVER_resume (server_handle);
958 }
959
960
961 /**
962  * Shutdown server.
963  */
964 void
965 GML_shutdown (void)
966 {
967   if (nc != NULL)
968   {
969     GNUNET_SERVER_notification_context_destroy (nc);
970     nc = NULL;
971   }
972 }
973
974
975 /**
976  * Get a channel from a client.
977  *
978  * @param c Client to check.
979  * @param chid Channel ID, must be local (> 0x800...).
980  *
981  * @return non-NULL if channel exists in the clients lists
982  */
983 struct CadetChannel *
984 GML_channel_get (struct CadetClient *c, CADET_ChannelNumber chid)
985 {
986   struct GNUNET_CONTAINER_MultiHashMap32 *map;
987
988   if (0 == (chid & GNUNET_CADET_LOCAL_CHANNEL_ID_CLI))
989   {
990     GNUNET_break_op (0);
991     LOG (GNUNET_ERROR_TYPE_DEBUG, "CHID %X not a local chid\n", chid);
992     return NULL;
993   }
994
995   if (chid >= GNUNET_CADET_LOCAL_CHANNEL_ID_SERV)
996     map = c->incoming_channels;
997   else if (chid >= GNUNET_CADET_LOCAL_CHANNEL_ID_CLI)
998     map = c->own_channels;
999   else
1000   {
1001     GNUNET_break (0);
1002     map = NULL;
1003   }
1004   if (NULL == map)
1005   {
1006     GNUNET_break (0);
1007     LOG (GNUNET_ERROR_TYPE_DEBUG,
1008          "Client %s does no t have a valid map for CHID %X\n",
1009          GML_2s (c), chid);
1010     return NULL;
1011   }
1012   return GNUNET_CONTAINER_multihashmap32_get (map, chid);
1013 }
1014
1015
1016 /**
1017  * Add a channel to a client
1018  *
1019  * @param client Client.
1020  * @param chid Channel ID.
1021  * @param ch Channel.
1022  */
1023 void
1024 GML_channel_add (struct CadetClient *client,
1025                  uint32_t chid,
1026                  struct CadetChannel *ch)
1027 {
1028   if (chid >= GNUNET_CADET_LOCAL_CHANNEL_ID_SERV)
1029     GNUNET_CONTAINER_multihashmap32_put (client->incoming_channels, chid, ch,
1030                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
1031   else if (chid >= GNUNET_CADET_LOCAL_CHANNEL_ID_CLI)
1032     GNUNET_CONTAINER_multihashmap32_put (client->own_channels, chid, ch,
1033                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
1034   else
1035     GNUNET_break (0);
1036 }
1037
1038
1039 /**
1040  * Remove a channel from a client.
1041  *
1042  * @param client Client.
1043  * @param chid Channel ID.
1044  * @param ch Channel.
1045  */
1046 void
1047 GML_channel_remove (struct CadetClient *client,
1048                     uint32_t chid,
1049                     struct CadetChannel *ch)
1050 {
1051   if (GNUNET_CADET_LOCAL_CHANNEL_ID_SERV <= chid)
1052     GNUNET_break (GNUNET_YES ==
1053                   GNUNET_CONTAINER_multihashmap32_remove (client->incoming_channels,
1054                                                           chid, ch));
1055   else if (GNUNET_CADET_LOCAL_CHANNEL_ID_CLI <= chid)
1056     GNUNET_break (GNUNET_YES ==
1057                   GNUNET_CONTAINER_multihashmap32_remove (client->own_channels,
1058                                                           chid, ch));
1059   else
1060     GNUNET_break (0);
1061 }
1062
1063
1064 /**
1065  * Get the tunnel's next free local channel ID.
1066  *
1067  * @param c Client.
1068  *
1069  * @return LID of a channel free to use.
1070  */
1071 CADET_ChannelNumber
1072 GML_get_next_chid (struct CadetClient *c)
1073 {
1074   CADET_ChannelNumber chid;
1075
1076   while (NULL != GML_channel_get (c, c->next_chid))
1077   {
1078     LOG (GNUNET_ERROR_TYPE_DEBUG, "Channel %u exists...\n", c->next_chid);
1079     c->next_chid = (c->next_chid + 1) | GNUNET_CADET_LOCAL_CHANNEL_ID_SERV;
1080   }
1081   chid = c->next_chid;
1082   c->next_chid = (c->next_chid + 1) | GNUNET_CADET_LOCAL_CHANNEL_ID_SERV;
1083
1084   return chid;
1085 }
1086
1087
1088 /**
1089  * Check if client has registered with the service and has not disconnected
1090  *
1091  * @param client the client to check
1092  *
1093  * @return non-NULL if client exists in the global DLL
1094  */
1095 struct CadetClient *
1096 GML_client_get (struct GNUNET_SERVER_Client *client)
1097 {
1098   return GNUNET_SERVER_client_get_user_context (client, struct CadetClient);
1099 }
1100
1101 /**
1102  * Find a client that has opened a port
1103  *
1104  * @param port Port to check.
1105  *
1106  * @return non-NULL if a client has the port.
1107  */
1108 struct CadetClient *
1109 GML_client_get_by_port (uint32_t port)
1110 {
1111   return GNUNET_CONTAINER_multihashmap32_get (ports, port);
1112 }
1113
1114
1115 /**
1116  * Deletes a channel from a client (either owner or destination).
1117  *
1118  * @param c Client whose tunnel to delete.
1119  * @param ch Channel which should be deleted.
1120  * @param id Channel ID.
1121  */
1122 void
1123 GML_client_delete_channel (struct CadetClient *c,
1124                            struct CadetChannel *ch,
1125                            CADET_ChannelNumber id)
1126 {
1127   int res;
1128
1129   if (GNUNET_CADET_LOCAL_CHANNEL_ID_SERV <= id)
1130   {
1131     res = GNUNET_CONTAINER_multihashmap32_remove (c->incoming_channels,
1132                                                   id, ch);
1133     if (GNUNET_YES != res)
1134       LOG (GNUNET_ERROR_TYPE_DEBUG, "client_delete_channel dest KO\n");
1135   }
1136   else if (GNUNET_CADET_LOCAL_CHANNEL_ID_CLI <= id)
1137   {
1138     res = GNUNET_CONTAINER_multihashmap32_remove (c->own_channels,
1139                                                   id, ch);
1140     if (GNUNET_YES != res)
1141       LOG (GNUNET_ERROR_TYPE_DEBUG, "client_delete_tunnel root KO\n");
1142   }
1143   else
1144   {
1145     GNUNET_break (0);
1146   }
1147 }
1148
1149 /**
1150  * Build a local ACK message and send it to a local client, if needed.
1151  *
1152  * If the client was already allowed to send data, do nothing.
1153  *
1154  * @param c Client to whom send the ACK.
1155  * @param id Channel ID to use
1156  */
1157 void
1158 GML_send_ack (struct CadetClient *c, CADET_ChannelNumber id)
1159 {
1160   struct GNUNET_CADET_LocalAck msg;
1161
1162   LOG (GNUNET_ERROR_TYPE_DEBUG,
1163               "send local %s ack on %X towards %p\n",
1164               id < GNUNET_CADET_LOCAL_CHANNEL_ID_SERV ? "FWD" : "BCK", id, c);
1165
1166   msg.header.size = htons (sizeof (msg));
1167   msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_LOCAL_ACK);
1168   msg.channel_id = htonl (id);
1169   GNUNET_SERVER_notification_context_unicast (nc,
1170                                               c->handle,
1171                                               &msg.header,
1172                                               GNUNET_NO);
1173
1174 }
1175
1176
1177
1178 /**
1179  * Notify the client that a new incoming channel was created.
1180  *
1181  * @param c Client to notify.
1182  * @param id Channel ID.
1183  * @param port Channel's destination port.
1184  * @param opt Options (bit array).
1185  * @param peer Origin peer.
1186  */
1187 void
1188 GML_send_channel_create (struct CadetClient *c,
1189                          uint32_t id, uint32_t port, uint32_t opt,
1190                          const struct GNUNET_PeerIdentity *peer)
1191 {
1192   struct GNUNET_CADET_ChannelMessage msg;
1193
1194   msg.header.size = htons (sizeof (msg));
1195   msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_CHANNEL_CREATE);
1196   msg.channel_id = htonl (id);
1197   msg.port = htonl (port);
1198   msg.opt = htonl (opt);
1199   msg.peer = *peer;
1200   GNUNET_SERVER_notification_context_unicast (nc, c->handle,
1201                                               &msg.header, GNUNET_NO);
1202 }
1203
1204
1205 /**
1206  * Build a local channel NACK message and send it to a local client.
1207  *
1208  * @param c Client to whom send the NACK.
1209  * @param id Channel ID to use
1210  */
1211 void
1212 GML_send_channel_nack (struct CadetClient *c, CADET_ChannelNumber id)
1213 {
1214   struct GNUNET_CADET_LocalAck msg;
1215
1216   LOG (GNUNET_ERROR_TYPE_DEBUG,
1217        "send local nack on %X towards %p\n",
1218        id, c);
1219
1220   msg.header.size = htons (sizeof (msg));
1221   msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_CHANNEL_NACK);
1222   msg.channel_id = htonl (id);
1223   GNUNET_SERVER_notification_context_unicast (nc,
1224                                               c->handle,
1225                                               &msg.header,
1226                                               GNUNET_NO);
1227
1228 }
1229
1230 /**
1231  * Notify a client that a channel is no longer valid.
1232  *
1233  * @param c Client.
1234  * @param id ID of the channel that is destroyed.
1235  */
1236 void
1237 GML_send_channel_destroy (struct CadetClient *c, uint32_t id)
1238 {
1239   struct GNUNET_CADET_ChannelMessage msg;
1240
1241   if (NULL == c)
1242   {
1243     GNUNET_break (0);
1244     return;
1245   }
1246   if (GNUNET_YES == c->shutting_down)
1247     return;
1248   msg.header.size = htons (sizeof (msg));
1249   msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY);
1250   msg.channel_id = htonl (id);
1251   msg.port = htonl (0);
1252   memset (&msg.peer, 0, sizeof (msg.peer));
1253   msg.opt = htonl (0);
1254   GNUNET_SERVER_notification_context_unicast (nc, c->handle,
1255                                               &msg.header, GNUNET_NO);
1256 }
1257
1258
1259 /**
1260  * Modify the cadet message ID from global to local and send to client.
1261  *
1262  * @param c Client to send to.
1263  * @param msg Message to modify and send.
1264  * @param id Channel ID to use (c can be both owner and client).
1265  */
1266 void
1267 GML_send_data (struct CadetClient *c,
1268                const struct GNUNET_CADET_Data *msg,
1269                CADET_ChannelNumber id)
1270 {
1271   struct GNUNET_CADET_LocalData *copy;
1272   uint16_t size = ntohs (msg->header.size) - sizeof (struct GNUNET_CADET_Data);
1273   char cbuf[size + sizeof (struct GNUNET_CADET_LocalData)];
1274
1275   if (size < sizeof (struct GNUNET_MessageHeader))
1276   {
1277     GNUNET_break_op (0);
1278     return;
1279   }
1280   if (NULL == c)
1281   {
1282     GNUNET_break (0);
1283     return;
1284   }
1285   copy = (struct GNUNET_CADET_LocalData *) cbuf;
1286   memcpy (&copy[1], &msg[1], size);
1287   copy->header.size = htons (sizeof (struct GNUNET_CADET_LocalData) + size);
1288   copy->header.type = htons (GNUNET_MESSAGE_TYPE_CADET_LOCAL_DATA);
1289   copy->id = htonl (id);
1290   GNUNET_SERVER_notification_context_unicast (nc, c->handle,
1291                                               &copy->header, GNUNET_NO);
1292 }
1293
1294
1295 /**
1296  * Get the static string to represent a client.
1297  *
1298  * @param c Client.
1299  *
1300  * @return Static string for the client.
1301  */
1302 const char *
1303 GML_2s (const struct CadetClient *c)
1304 {
1305   static char buf[32];
1306
1307   sprintf (buf, "%u", c->id);
1308   return buf;
1309 }