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