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