-make checkers happy by always initializing map, also extra check just in case the...
[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_SERVER_receive_done (client, GNUNET_OK);
437     return;
438   }
439
440   GMCH_handle_local_destroy (ch, c, chid < GNUNET_MESH_LOCAL_CHANNEL_ID_SERV);
441
442   GNUNET_SERVER_receive_done (client, GNUNET_OK);
443   return;
444 }
445
446
447 /**
448  * Handler for client traffic
449  *
450  * @param cls closure
451  * @param client identification of the client
452  * @param message the actual message
453  */
454 static void
455 handle_data (void *cls, struct GNUNET_SERVER_Client *client,
456              const struct GNUNET_MessageHeader *message)
457 {
458   struct GNUNET_MESH_LocalData *msg;
459   struct MeshClient *c;
460   struct MeshChannel *ch;
461   MESH_ChannelNumber chid;
462   size_t size;
463   int fwd;
464
465   LOG (GNUNET_ERROR_TYPE_DEBUG, "\n\nGot data from a client!\n");
466
467   /* Sanity check for client registration */
468   if (NULL == (c = GML_client_get (client)))
469   {
470     GNUNET_break (0);
471     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
472     return;
473   }
474   LOG (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
475
476   msg = (struct GNUNET_MESH_LocalData *) message;
477
478   /* Sanity check for message size */
479   size = ntohs (message->size) - sizeof (struct GNUNET_MESH_LocalData);
480   if (size < sizeof (struct GNUNET_MessageHeader))
481   {
482     GNUNET_break (0);
483     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
484     return;
485   }
486
487   /* Channel exists? */
488   chid = ntohl (msg->id);
489   LOG (GNUNET_ERROR_TYPE_DEBUG, "  on channel %X\n", chid);
490   fwd = chid < GNUNET_MESH_LOCAL_CHANNEL_ID_SERV;
491   ch = GML_channel_get (c, chid);
492   if (NULL == ch)
493   {
494     GNUNET_break (0);
495     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
496     return;
497   }
498
499   if (GNUNET_OK !=
500       GMCH_handle_local_data (ch, c,
501                               (struct GNUNET_MessageHeader *)&msg[1], fwd))
502   {
503     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
504     return;
505   }
506
507   LOG (GNUNET_ERROR_TYPE_DEBUG, "receive done OK\n");
508   GNUNET_SERVER_receive_done (client, GNUNET_OK);
509
510   return;
511 }
512
513
514 /**
515  * Handler for client's ACKs for payload traffic.
516  *
517  * @param cls Closure (unused).
518  * @param client Identification of the client.
519  * @param message The actual message.
520  */
521 static void
522 handle_ack (void *cls, struct GNUNET_SERVER_Client *client,
523             const struct GNUNET_MessageHeader *message)
524 {
525   struct GNUNET_MESH_LocalAck *msg;
526   struct MeshChannel *ch;
527   struct MeshClient *c;
528   MESH_ChannelNumber chid;
529   int fwd;
530
531   LOG (GNUNET_ERROR_TYPE_DEBUG, "\n\nGot a local ACK\n");
532
533   /* Sanity check for client registration */
534   if (NULL == (c = GML_client_get (client)))
535   {
536     GNUNET_break (0);
537     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
538     return;
539   }
540   LOG (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
541
542   msg = (struct GNUNET_MESH_LocalAck *) message;
543
544   /* Channel exists? */
545   chid = ntohl (msg->channel_id);
546   LOG (GNUNET_ERROR_TYPE_DEBUG, "  on channel %X\n", chid);
547   ch = GML_channel_get (c, chid);
548   LOG (GNUNET_ERROR_TYPE_DEBUG, "   -- ch %p\n", ch);
549   if (NULL == ch)
550   {
551     LOG (GNUNET_ERROR_TYPE_DEBUG, "Channel %X unknown.\n", chid);
552     LOG (GNUNET_ERROR_TYPE_DEBUG, "  for client %u.\n", c->id);
553     GNUNET_SERVER_receive_done (client, GNUNET_OK);
554     return;
555   }
556
557   /* If client is root, the ACK is going FWD, therefore this is "BCK ACK". */
558   /* If client is dest, the ACK is going BCK, therefore this is "FWD ACK" */
559   fwd = chid >= GNUNET_MESH_LOCAL_CHANNEL_ID_SERV;
560
561   GMCH_handle_local_ack (ch, fwd);
562   GNUNET_SERVER_receive_done (client, GNUNET_OK);
563
564   return;
565 }
566
567
568 /*
569  * Iterator over all tunnels to send a monitoring client info about each tunnel.
570  *
571  * @param cls Closure (client handle).
572  * @param key Key (hashed tunnel ID, unused).
573  * @param value Tunnel info.
574  *
575  * @return #GNUNET_YES, to keep iterating.
576  */
577 // static int
578 // monitor_all_tunnels_iterator (void *cls,
579 //                               const struct GNUNET_HashCode * key,
580 //                               void *value)
581 // {
582 //   struct GNUNET_SERVER_Client *client = cls;
583 //   struct MeshChannel *ch = value;
584 //   struct GNUNET_MESH_LocalMonitor *msg;
585 //
586 //   msg = GNUNET_malloc (sizeof(struct GNUNET_MESH_LocalMonitor));
587 //   msg->channel_id = htonl (ch->gid);
588 //   msg->header.size = htons (sizeof (struct GNUNET_MESH_LocalMonitor));
589 //   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_INFO_TUNNELS);
590 //
591 //   LOG (GNUNET_ERROR_TYPE_INFO,
592 //               "*  sending info about tunnel %s\n",
593 //               GNUNET_i2s (&msg->owner));
594 //
595 //   GNUNET_SERVER_notification_context_unicast (nc, client,
596 //                                               &msg->header, GNUNET_NO);
597 //   return GNUNET_YES;
598 // }
599
600
601 /**
602  * Handler for client's MONITOR request.
603  *
604  * @param cls Closure (unused).
605  * @param client Identification of the client.
606  * @param message The actual message.
607  */
608 static void
609 handle_get_tunnels (void *cls, struct GNUNET_SERVER_Client *client,
610                     const struct GNUNET_MessageHeader *message)
611 {
612   struct MeshClient *c;
613
614   /* Sanity check for client registration */
615   if (NULL == (c = GML_client_get (client)))
616   {
617     GNUNET_break (0);
618     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
619     return;
620   }
621
622   LOG (GNUNET_ERROR_TYPE_INFO,
623               "Received get tunnels request from client %u\n",
624               c->id);
625 //   GNUNET_CONTAINER_multihashmap_iterate (tunnels,
626 //                                          monitor_all_tunnels_iterator,
627 //                                          client);
628   LOG (GNUNET_ERROR_TYPE_INFO,
629               "Get tunnels request from client %u completed\n",
630               c->id);
631   GNUNET_SERVER_receive_done (client, GNUNET_OK);
632 }
633
634
635 /**
636  * Handler for client's MONITOR_TUNNEL request.
637  *
638  * @param cls Closure (unused).
639  * @param client Identification of the client.
640  * @param message The actual message.
641  */
642 void
643 handle_show_tunnel (void *cls, struct GNUNET_SERVER_Client *client,
644                     const struct GNUNET_MessageHeader *message)
645 {
646   const struct GNUNET_MESH_LocalMonitor *msg;
647   struct GNUNET_MESH_LocalMonitor *resp;
648   struct MeshClient *c;
649   struct MeshChannel *ch;
650
651   /* Sanity check for client registration */
652   if (NULL == (c = GML_client_get (client)))
653   {
654     GNUNET_break (0);
655     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
656     return;
657   }
658
659   msg = (struct GNUNET_MESH_LocalMonitor *) message;
660   LOG (GNUNET_ERROR_TYPE_INFO,
661               "Received tunnel info request from client %u for tunnel %s[%X]\n",
662               c->id,
663               &msg->owner,
664               ntohl (msg->channel_id));
665 //   ch = channel_get (&msg->owner, ntohl (msg->channel_id));
666   ch = NULL; // FIXME
667   if (NULL == ch)
668   {
669     /* We don't know the tunnel */
670     struct GNUNET_MESH_LocalMonitor warn;
671
672     warn = *msg;
673     GNUNET_SERVER_notification_context_unicast (nc, client,
674                                                 &warn.header,
675                                                 GNUNET_NO);
676     GNUNET_SERVER_receive_done (client, GNUNET_OK);
677     return;
678   }
679
680   /* Initialize context */
681   resp = GNUNET_malloc (sizeof (struct GNUNET_MESH_LocalMonitor));
682   *resp = *msg;
683   resp->header.size = htons (sizeof (struct GNUNET_MESH_LocalMonitor));
684   GNUNET_SERVER_notification_context_unicast (nc, c->handle,
685                                               &resp->header, GNUNET_NO);
686   GNUNET_free (resp);
687
688   LOG (GNUNET_ERROR_TYPE_INFO,
689               "Monitor tunnel request from client %u completed\n",
690               c->id);
691   GNUNET_SERVER_receive_done (client, GNUNET_OK);
692 }
693
694
695 /**
696  * Functions to handle messages from clients
697  */
698 static struct GNUNET_SERVER_MessageHandler client_handlers[] = {
699   {&handle_new_client, NULL, GNUNET_MESSAGE_TYPE_MESH_LOCAL_CONNECT, 0},
700   {&handle_channel_create, NULL, GNUNET_MESSAGE_TYPE_MESH_CHANNEL_CREATE,
701    sizeof (struct GNUNET_MESH_ChannelMessage)},
702   {&handle_channel_destroy, NULL, GNUNET_MESSAGE_TYPE_MESH_CHANNEL_DESTROY,
703    sizeof (struct GNUNET_MESH_ChannelMessage)},
704   {&handle_data, NULL, GNUNET_MESSAGE_TYPE_MESH_LOCAL_DATA, 0},
705   {&handle_ack, NULL, GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK,
706    sizeof (struct GNUNET_MESH_LocalAck)},
707   {&handle_get_tunnels, NULL, GNUNET_MESSAGE_TYPE_MESH_LOCAL_INFO_TUNNELS,
708    sizeof (struct GNUNET_MessageHeader)},
709   {&handle_show_tunnel, NULL, GNUNET_MESSAGE_TYPE_MESH_LOCAL_INFO_TUNNEL,
710    sizeof (struct GNUNET_MESH_LocalMonitor)},
711   {NULL, NULL, 0, 0}
712 };
713
714
715
716 /******************************************************************************/
717 /********************************    API    ***********************************/
718 /******************************************************************************/
719
720 /**
721  * Initialize server subsystem.
722  *
723  * @param handle Server handle.
724  */
725 void
726 GML_init (struct GNUNET_SERVER_Handle *handle)
727 {
728   LOG (GNUNET_ERROR_TYPE_DEBUG, "init\n");
729   server_handle = handle;
730   GNUNET_SERVER_suspend (server_handle);
731   ports = GNUNET_CONTAINER_multihashmap32_create (32);
732 }
733
734
735 /**
736  * Install server (service) handlers and start listening to clients.
737  */
738 void
739 GML_start (void)
740 {
741   GNUNET_SERVER_add_handlers (server_handle, client_handlers);
742   GNUNET_SERVER_connect_notify (server_handle,  &handle_client_connect, NULL);
743   GNUNET_SERVER_disconnect_notify (server_handle, &handle_client_disconnect,
744                                    NULL);
745   nc = GNUNET_SERVER_notification_context_create (server_handle, 1);
746
747   clients_head = NULL;
748   clients_tail = NULL;
749   next_client_id = 0;
750   GNUNET_SERVER_resume (server_handle);
751 }
752
753
754 /**
755  * Shutdown server.
756  */
757 void
758 GML_shutdown (void)
759 {
760   if (nc != NULL)
761   {
762     GNUNET_SERVER_notification_context_destroy (nc);
763     nc = NULL;
764   }
765 }
766
767
768 /**
769  * Get a channel from a client.
770  *
771  * @param c Client to check.
772  * @param chid Channel ID, must be local (> 0x800...).
773  *
774  * @return non-NULL if channel exists in the clients lists
775  */
776 struct MeshChannel *
777 GML_channel_get (struct MeshClient *c, MESH_ChannelNumber chid)
778 {
779   struct GNUNET_CONTAINER_MultiHashMap32 *map;
780
781   if (0 == (chid & GNUNET_MESH_LOCAL_CHANNEL_ID_CLI))
782   {
783     GNUNET_break_op (0);
784     LOG (GNUNET_ERROR_TYPE_DEBUG, "CHID %X not a local chid\n", chid);
785     return NULL;
786   }
787
788   if (chid >= GNUNET_MESH_LOCAL_CHANNEL_ID_SERV)
789     map = c->incoming_channels;
790   else if (chid >= GNUNET_MESH_LOCAL_CHANNEL_ID_CLI)
791     map = c->own_channels;
792   else
793   {
794     GNUNET_break (0);
795     map = NULL;
796   }
797   if (NULL == map)
798   {
799     GNUNET_break (0);
800     LOG (GNUNET_ERROR_TYPE_DEBUG,
801          "Client %s does no t have a valid map for CHID %X\n",
802          GML_2s (c), chid);
803     return NULL;
804   }
805   return GNUNET_CONTAINER_multihashmap32_get (map, chid);
806 }
807
808
809 /**
810  * Add a channel to a client
811  *
812  * @param client Client.
813  * @param chid Channel ID.
814  * @param ch Channel.
815  */
816 void
817 GML_channel_add (struct MeshClient *client,
818                  uint32_t chid,
819                  struct MeshChannel *ch)
820 {
821   if (chid >= GNUNET_MESH_LOCAL_CHANNEL_ID_SERV)
822     GNUNET_CONTAINER_multihashmap32_put (client->incoming_channels, chid, ch,
823                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
824   else if (chid >= GNUNET_MESH_LOCAL_CHANNEL_ID_CLI)
825     GNUNET_CONTAINER_multihashmap32_put (client->own_channels, chid, ch,
826                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
827   else
828     GNUNET_break (0);
829 }
830
831
832 /**
833  * Remove a channel from a client.
834  *
835  * @param client Client.
836  * @param chid Channel ID.
837  * @param ch Channel.
838  */
839 void
840 GML_channel_remove (struct MeshClient *client,
841                     uint32_t chid,
842                     struct MeshChannel *ch)
843 {
844   if (GNUNET_MESH_LOCAL_CHANNEL_ID_SERV <= chid)
845     GNUNET_break (GNUNET_YES ==
846                   GNUNET_CONTAINER_multihashmap32_remove (client->incoming_channels,
847                                                           chid, ch));
848   else if (GNUNET_MESH_LOCAL_CHANNEL_ID_CLI <= chid)
849     GNUNET_break (GNUNET_YES ==
850                   GNUNET_CONTAINER_multihashmap32_remove (client->own_channels,
851                                                           chid, ch));
852   else
853     GNUNET_break (0);
854 }
855
856
857 /**
858  * Get the tunnel's next free local channel ID.
859  *
860  * @param c Client.
861  *
862  * @return LID of a channel free to use.
863  */
864 MESH_ChannelNumber
865 GML_get_next_chid (struct MeshClient *c)
866 {
867   MESH_ChannelNumber chid;
868
869   while (NULL != GML_channel_get (c, c->next_chid))
870   {
871     LOG (GNUNET_ERROR_TYPE_DEBUG, "Channel %u exists...\n", c->next_chid);
872     c->next_chid = (c->next_chid + 1) | GNUNET_MESH_LOCAL_CHANNEL_ID_SERV;
873   }
874   chid = c->next_chid;
875   c->next_chid = (c->next_chid + 1) | GNUNET_MESH_LOCAL_CHANNEL_ID_SERV;
876
877   return chid;
878 }
879
880
881 /**
882  * Check if client has registered with the service and has not disconnected
883  *
884  * @param client the client to check
885  *
886  * @return non-NULL if client exists in the global DLL
887  */
888 struct MeshClient *
889 GML_client_get (struct GNUNET_SERVER_Client *client)
890 {
891   return GNUNET_SERVER_client_get_user_context (client, struct MeshClient);
892 }
893
894 /**
895  * Find a client that has opened a port
896  *
897  * @param port Port to check.
898  *
899  * @return non-NULL if a client has the port.
900  */
901 struct MeshClient *
902 GML_client_get_by_port (uint32_t port)
903 {
904   return GNUNET_CONTAINER_multihashmap32_get (ports, port);
905 }
906
907
908 /**
909  * Deletes a channel from a client (either owner or destination).
910  *
911  * @param c Client whose tunnel to delete.
912  * @param ch Channel which should be deleted.
913  * @param id Channel ID.
914  */
915 void
916 GML_client_delete_channel (struct MeshClient *c,
917                            struct MeshChannel *ch,
918                            MESH_ChannelNumber id)
919 {
920   int res;
921
922   if (GNUNET_MESH_LOCAL_CHANNEL_ID_SERV <= id)
923   {
924     res = GNUNET_CONTAINER_multihashmap32_remove (c->incoming_channels,
925                                                   id, ch);
926     if (GNUNET_YES != res)
927       LOG (GNUNET_ERROR_TYPE_DEBUG, "client_delete_channel dest KO\n");
928   }
929   else if (GNUNET_MESH_LOCAL_CHANNEL_ID_CLI <= id)
930   {
931     res = GNUNET_CONTAINER_multihashmap32_remove (c->own_channels,
932                                                   id, ch);
933     if (GNUNET_YES != res)
934       LOG (GNUNET_ERROR_TYPE_DEBUG, "client_delete_tunnel root KO\n");
935   }
936   else
937   {
938     GNUNET_break (0);
939   }
940 }
941
942 /**
943  * Build a local ACK message and send it to a local client, if needed.
944  *
945  * If the client was already allowed to send data, do nothing.
946  *
947  * @param c Client to whom send the ACK.
948  * @param id Channel ID to use
949  */
950 void
951 GML_send_ack (struct MeshClient *c, MESH_ChannelNumber id)
952 {
953   struct GNUNET_MESH_LocalAck msg;
954
955   LOG (GNUNET_ERROR_TYPE_DEBUG,
956               "send local %s ack on %X towards %p\n",
957               id < GNUNET_MESH_LOCAL_CHANNEL_ID_SERV ? "FWD" : "BCK", id, c);
958
959   msg.header.size = htons (sizeof (msg));
960   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK);
961   msg.channel_id = htonl (id);
962   GNUNET_SERVER_notification_context_unicast (nc,
963                                               c->handle,
964                                               &msg.header,
965                                               GNUNET_NO);
966
967 }
968
969
970 /**
971  * Build a local channel NACK message and send it to a local client.
972  *
973  * @param c Client to whom send the NACK.
974  * @param id Channel ID to use
975  */
976 void
977 GML_send_nack (struct MeshClient *c, MESH_ChannelNumber id)
978 {
979   struct GNUNET_MESH_LocalAck msg;
980
981   LOG (GNUNET_ERROR_TYPE_DEBUG,
982               "send local nack on %X towards %p\n",
983               id, c);
984
985   msg.header.size = htons (sizeof (msg));
986   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_NACK);
987   msg.channel_id = htonl (id);
988   GNUNET_SERVER_notification_context_unicast (nc,
989                                               c->handle,
990                                               &msg.header,
991                                               GNUNET_NO);
992
993 }
994
995
996 /**
997  * Notify the client that a new incoming channel was created.
998  *
999  * @param c Client to notify.
1000  * @param id Channel ID.
1001  * @param port Channel's destination port.
1002  * @param opt Options (bit array).
1003  * @param peer Origin peer.
1004  */
1005 void
1006 GML_send_channel_create (struct MeshClient *c,
1007                          uint32_t id, uint32_t port, uint32_t opt,
1008                          const struct GNUNET_PeerIdentity *peer)
1009 {
1010   struct GNUNET_MESH_ChannelMessage msg;
1011
1012   msg.header.size = htons (sizeof (msg));
1013   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_CHANNEL_CREATE);
1014   msg.channel_id = htonl (id);
1015   msg.port = htonl (port);
1016   msg.opt = htonl (opt);
1017   msg.peer = *peer;
1018   GNUNET_SERVER_notification_context_unicast (nc, c->handle,
1019                                               &msg.header, GNUNET_NO);
1020 }
1021
1022
1023 /**
1024  * Notify a client that a channel is no longer valid.
1025  *
1026  * @param c Client.
1027  * @param id ID of the channel that is destroyed.
1028  */
1029 void
1030 GML_send_channel_destroy (struct MeshClient *c, uint32_t id)
1031 {
1032   struct GNUNET_MESH_ChannelMessage msg;
1033
1034   if (NULL == c)
1035   {
1036     GNUNET_break (0);
1037     return;
1038   }
1039   if (GNUNET_YES == c->shutting_down)
1040     return;
1041   msg.header.size = htons (sizeof (msg));
1042   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_CHANNEL_DESTROY);
1043   msg.channel_id = htonl (id);
1044   msg.port = htonl (0);
1045   memset (&msg.peer, 0, sizeof (msg.peer));
1046   msg.opt = htonl (0);
1047   GNUNET_SERVER_notification_context_unicast (nc, c->handle,
1048                                               &msg.header, GNUNET_NO);
1049 }
1050
1051
1052 /**
1053  * Modify the mesh message ID from global to local and send to client.
1054  *
1055  * @param c Client to send to.
1056  * @param msg Message to modify and send.
1057  * @param id Channel ID to use (c can be both owner and client).
1058  */
1059 void
1060 GML_send_data (struct MeshClient *c,
1061                const struct GNUNET_MESH_Data *msg,
1062                MESH_ChannelNumber id)
1063 {
1064   struct GNUNET_MESH_LocalData *copy;
1065   uint16_t size = ntohs (msg->header.size) - sizeof (struct GNUNET_MESH_Data);
1066   char cbuf[size + sizeof (struct GNUNET_MESH_LocalData)];
1067
1068   if (size < sizeof (struct GNUNET_MessageHeader))
1069   {
1070     GNUNET_break_op (0);
1071     return;
1072   }
1073   if (NULL == c)
1074   {
1075     GNUNET_break (0);
1076     return;
1077   }
1078   copy = (struct GNUNET_MESH_LocalData *) cbuf;
1079   memcpy (&copy[1], &msg[1], size);
1080   copy->header.size = htons (sizeof (struct GNUNET_MESH_LocalData) + size);
1081   copy->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_DATA);
1082   copy->id = htonl (id);
1083   GNUNET_SERVER_notification_context_unicast (nc, c->handle,
1084                                               &copy->header, GNUNET_NO);
1085 }
1086
1087
1088 /**
1089  * Get the static string to represent a client.
1090  *
1091  * @param c Client.
1092  *
1093  * @return Static string for the client.
1094  */
1095 const char *
1096 GML_2s (const struct MeshClient *c)
1097 {
1098   static char buf[32];
1099
1100   sprintf (buf, "%u", c->id);
1101   return buf;
1102 }