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