Extended testcase, fixed bugs in client -> service data traffic handling
[oweals/gnunet.git] / src / mesh / gnunet-service-mesh.c
1 /*
2      This file is part of GNUnet.
3      (C) 2001 - 2011 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  * @file mesh/gnunet-service-mesh.c
23  * @brief GNUnet MESH service
24  * @author Bartlomiej Polot
25  *
26  * STRUCTURE:
27  * - DATA STRUCTURES
28  * - GLOBAL VARIABLES
29  * - GENERAL HELPERS
30  * - PERIODIC FUNCTIONS
31  * - MESH NETWORK HANDLER HELPERS
32  * - MESH NETWORK HANDLES
33  * - MESH LOCAL HANDLER HELPERS
34  * - MESH LOCAL HANDLES
35  * - MAIN FUNCTIONS (main & run)
36  *
37  * TODO:
38  * - error reporting (CREATE/CHANGE/ADD/DEL?) -- new message!
39  * - partial disconnect reporting -- same as error reporting?
40  * - add vs create? change vs. keep-alive? same msg or different ones? -- thinking...
41  * - speed requirement specification (change?) in mesh API -- API call
42  * - add ping message
43  * - add connection confirmation message
44  * - handle trnsmt_rdy return values
45  */
46
47 #include "platform.h"
48 #include "mesh.h"
49 #include "mesh_protocol.h"
50 #include "gnunet_dht_service.h"
51 #include "mesh_tunnel_tree.h"
52
53 /* TODO: move into configuration file */
54 #define REFRESH_PATH_TIME       GNUNET_TIME_relative_multiply(\
55                                     GNUNET_TIME_UNIT_SECONDS,\
56                                     300)
57 #define APP_ANNOUNCE_TIME       GNUNET_TIME_relative_multiply(\
58                                     GNUNET_TIME_UNIT_SECONDS,\
59                                     5)
60
61 #define ID_ANNOUNCE_TIME        GNUNET_TIME_relative_multiply(\
62                                     GNUNET_TIME_UNIT_SECONDS,\
63                                     10)
64
65 #define GET_RESTART_TIME        GNUNET_TIME_relative_multiply(\
66                                     GNUNET_TIME_UNIT_SECONDS,\
67                                     5)
68
69 /******************************************************************************/
70 /************************      DATA STRUCTURES     ****************************/
71 /******************************************************************************/
72
73 /** FWD declaration */
74 struct MeshPeerInfo;
75
76 /**
77  * Struct containing all info possibly needed to build a package when called
78  * back by core.
79  */
80 struct MeshDataDescriptor
81 {
82     /** ID of the tunnel this packet travels in */
83   struct MESH_TunnelID *origin;
84
85     /** Data itself */
86   void *data;
87
88     /** Client that asked for the transmission, if any */
89   struct GNUNET_SERVER_Client *client;
90
91     /** Who was this message being sent to */
92   struct MeshPeerInfo *peer;
93
94     /** Ultimate destination of the packet */
95   GNUNET_PEER_Id destination;
96
97     /** Number of identical messages sent to different hops (multicast) */
98   unsigned int *copies;
99
100     /** Which handler was used to request the transmission */
101   unsigned int handler_n;
102
103     /** Size of the data */
104   size_t size;
105
106 };
107
108
109 /**
110  * Struct containing all information regarding a given peer
111  */
112 struct MeshPeerInfo
113 {
114     /**
115      * ID of the peer
116      */
117   GNUNET_PEER_Id id;
118
119     /**
120      * Last time we heard from this peer
121      */
122   struct GNUNET_TIME_Absolute last_contact;
123
124     /**
125      * Number of attempts to reconnect so far
126      */
127   int n_reconnect_attempts;
128
129     /**
130      * Paths to reach the peer, ordered by ascending hop count
131      */
132   struct MeshPeerPath *path_head;
133
134     /**
135      * Paths to reach the peer, ordered by ascending hop count
136      */
137   struct MeshPeerPath *path_tail;
138
139     /**
140      * Handle to stop the DHT search for a path to this peer
141      */
142   struct GNUNET_DHT_GetHandle *dhtget;
143
144     /**
145      * Handles to stop queued transmissions for this peer
146      */
147   struct GNUNET_CORE_TransmitHandle *core_transmit[CORE_QUEUE_SIZE];
148
149     /**
150      * Pointer to info stuctures used as cls for queued transmissions
151      */
152   void *infos[CORE_QUEUE_SIZE];
153
154     /**
155      * Type of message being in each transmission
156      */
157   uint16_t types[CORE_QUEUE_SIZE];
158
159     /**
160      * Array of tunnels this peer participates in
161      * (most probably a small amount, therefore not a hashmap)
162      * When the path to the peer changes, notify these tunnels to let them
163      * re-adjust their path trees.
164      */
165   struct MeshTunnel **tunnels;
166
167     /**
168      * Number of tunnels this peers participates in
169      */
170   unsigned int ntunnels;
171 };
172
173
174 /**
175  * Data scheduled to transmit (to local client or remote peer)
176  */
177 struct MeshQueue
178 {
179     /**
180      * Double linked list
181      */
182   struct MeshQueue *next;
183   struct MeshQueue *prev;
184
185     /**
186      * Target of the data (NULL if target is client)
187      */
188   struct MeshPeerInfo *peer;
189
190     /**
191      * Client to send the data to (NULL if target is peer)
192      */
193   struct MeshClient *client;
194
195     /**
196      * Size of the message to transmit
197      */
198   unsigned int size;
199
200     /**
201      * How old is the data?
202      */
203   struct GNUNET_TIME_Absolute timestamp;
204
205     /**
206      * Data itself
207      */
208   struct GNUNET_MessageHeader *data;
209 };
210
211 /**
212  * Globally unique tunnel identification (owner + number)
213  * DO NOT USE OVER THE NETWORK
214  */
215 struct MESH_TunnelID
216 {
217     /**
218      * Node that owns the tunnel
219      */
220   GNUNET_PEER_Id oid;
221
222     /**
223      * Tunnel number to differentiate all the tunnels owned by the node oid
224      * ( tid < GNUNET_MESH_LOCAL_TUNNEL_ID_CLI )
225      */
226   MESH_TunnelNumber tid;
227 };
228
229
230 struct MeshClient;              /* FWD declaration */
231
232 /**
233  * Struct containing all information regarding a tunnel
234  * For an intermediate node the improtant info used will be:
235  * - id        Tunnel unique identification
236  * - paths[0]  To know where to send it next
237  * - metainfo: ready, speeds, accounting
238  */
239 struct MeshTunnel
240 {
241     /**
242      * Tunnel ID
243      */
244   struct MESH_TunnelID id;
245
246     /**
247      * Local tunnel number ( >= GNUNET_MESH_LOCAL_TUNNEL_ID_CLI or 0 )
248      */
249   MESH_TunnelNumber local_tid;
250
251     /**
252      * Last time the tunnel was used
253      */
254   struct GNUNET_TIME_Absolute timestamp;
255
256     /**
257      * Peers in the tunnel, indexed by PeerIdentity -> (MeshPeerInfo)
258      */
259   struct GNUNET_CONTAINER_MultiHashMap *peers;
260
261     /**
262      * Number of peers that are connected and potentially ready to receive data
263      */
264   unsigned int peers_ready;
265
266     /**
267      * Number of peers that have been added to the tunnel
268      */
269   unsigned int peers_total;
270
271     /**
272      * Client owner of the tunnel, if any
273      */
274   struct MeshClient *client;
275
276     /**
277      * Messages ready to transmit
278      */
279   struct MeshQueue *queue_head;
280   struct MeshQueue *queue_tail;
281
282   /**
283    * Tunnel paths
284    */
285   struct MeshTunnelTree *tree;
286
287   /**
288    * Application type we are looking for in this tunnel
289    */
290   GNUNET_MESH_ApplicationType type;
291
292     /**
293      * Used to search peers offering a service
294      */
295   struct GNUNET_DHT_GetHandle *dht_get_type;
296
297   /**
298    * Task to keep the used paths alive
299    */
300   GNUNET_SCHEDULER_TaskIdentifier path_refresh_task;
301 };
302
303
304 /**
305  * Info needed to work with tunnel paths and peers
306  */
307 struct MeshPathInfo
308 {
309   /**
310    * Tunnel
311    */
312   struct MeshTunnel *t;
313
314   /**
315    * Destination peer
316    */
317   struct MeshPeerInfo *peer;
318
319   /**
320    * Path itself
321    */
322   struct MeshPeerPath *path;
323   
324   /**
325    * Position in peer's transmit queue
326    */
327   unsigned int pos;
328 };
329
330
331 /**
332  * Struct containing information about a client of the service
333  */
334 struct MeshClient
335 {
336     /**
337      * Linked list
338      */
339   struct MeshClient *next;
340   struct MeshClient *prev;
341
342     /**
343      * Tunnels that belong to this client, indexed by local id
344      */
345   struct GNUNET_CONTAINER_MultiHashMap *tunnels;
346
347     /**
348      * Handle to communicate with the client
349      */
350   struct GNUNET_SERVER_Client *handle;
351
352     /**
353      * Applications that this client has claimed to provide
354      */
355   struct GNUNET_CONTAINER_MultiHashMap *apps;
356
357     /**
358      * Messages that this client has declared interest in
359      */
360   struct GNUNET_CONTAINER_MultiHashMap *types;
361
362 #if MESH_DEBUG
363     /**
364      * ID of the client, for debug messages
365      */
366   unsigned int id;
367 #endif
368
369 };
370
371
372
373 /******************************************************************************/
374 /************************      DEBUG FUNCTIONS     ****************************/
375 /******************************************************************************/
376
377
378 /**
379  * GNUNET_SCHEDULER_Task for printing a message after some operation is done
380  * @param cls string to print
381  * @param tc task context
382  */
383 static void
384 mesh_debug (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
385 {
386   char *s = cls;
387
388   if (GNUNET_SCHEDULER_REASON_SHUTDOWN == tc->reason)
389   {
390     return;
391   }
392   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: %s\n", s);
393 }
394
395
396 /******************************************************************************/
397 /***********************      GLOBAL VARIABLES     ****************************/
398 /******************************************************************************/
399
400 /**
401  * All the clients
402  */
403 static struct MeshClient *clients;
404 static struct MeshClient *clients_tail;
405
406 /**
407  * Tunnels known, indexed by MESH_TunnelID (MeshTunnel)
408  */
409 static struct GNUNET_CONTAINER_MultiHashMap *tunnels;
410
411 /**
412  * Peers known, indexed by PeerIdentity (MeshPeerInfo)
413  */
414 static struct GNUNET_CONTAINER_MultiHashMap *peers;
415
416 /**
417  * Handle to communicate with core
418  */
419 static struct GNUNET_CORE_Handle *core_handle;
420
421 /**
422  * Handle to use DHT
423  */
424 static struct GNUNET_DHT_Handle *dht_handle;
425
426 /**
427  * Handle to server
428  */
429 static struct GNUNET_SERVER_Handle *server_handle;
430
431 /**
432  * Notification context, to send messages to local clients
433  */
434 static struct GNUNET_SERVER_NotificationContext *nc;
435
436 /**
437  * Local peer own ID (memory efficient handle)
438  */
439 static GNUNET_PEER_Id myid;
440
441 /**
442  * Local peer own ID (full value)
443  */
444 static struct GNUNET_PeerIdentity my_full_id;
445
446 /**
447  * Own private key
448  */
449 static struct GNUNET_CRYPTO_RsaPrivateKey* my_private_key;
450
451 /**
452  * Own public key.
453  */
454 static struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded my_public_key;
455
456 /**
457  * Tunnel ID for the next created tunnel (global tunnel number)
458  */
459 static MESH_TunnelNumber next_tid;
460
461 /**
462  * Tunnel ID for the next incoming tunnel (local tunnel number)
463  */
464 static MESH_TunnelNumber next_local_tid;
465
466 /**
467  * All application types provided by this peer
468  */
469 static struct GNUNET_CONTAINER_MultiHashMap *applications;
470
471 /**
472  * All message types clients of this peer are interested in
473  */
474 static struct GNUNET_CONTAINER_MultiHashMap *types;
475
476 /**
477  * Task to periodically announce provided applications
478  */
479 GNUNET_SCHEDULER_TaskIdentifier announce_applications_task;
480
481 /**
482  * Task to periodically announce itself in the network
483  */
484 GNUNET_SCHEDULER_TaskIdentifier announce_id_task;
485
486 #if MESH_DEBUG
487 unsigned int next_client_id;
488 #endif
489
490
491 /******************************************************************************/
492 /************************         ITERATORS        ****************************/
493 /******************************************************************************/
494
495 /* FIXME move iterators here */
496
497
498 /******************************************************************************/
499 /************************    PERIODIC FUNCTIONS    ****************************/
500 /******************************************************************************/
501
502 /**
503  * Announce iterator over for each application provided by the peer
504  *
505  * @param cls closure
506  * @param key current key code
507  * @param value value in the hash map
508  * @return GNUNET_YES if we should continue to
509  *         iterate,
510  *         GNUNET_NO if not.
511  */
512 static int
513 announce_application (void *cls, const GNUNET_HashCode * key, void *value)
514 {
515   /* FIXME are hashes in multihash map equal on all aquitectures? */
516   GNUNET_DHT_put (dht_handle,
517                   key,
518                   10U,
519                   GNUNET_DHT_RO_RECORD_ROUTE |
520                     GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE,
521                   GNUNET_BLOCK_TYPE_TEST,
522                   sizeof (struct GNUNET_PeerIdentity),
523                   (const char *) &my_full_id,
524 #if MESH_DEBUG
525                   GNUNET_TIME_UNIT_FOREVER_ABS, GNUNET_TIME_UNIT_FOREVER_REL,
526                   &mesh_debug, "DHT_put for app completed");
527 #else
528                   GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get (),
529                                             APP_ANNOUNCE_TIME),
530                   APP_ANNOUNCE_TIME, NULL, NULL);
531 #endif
532   return GNUNET_OK;
533 }
534
535
536 /**
537  * Periodically announce what applications are provided by local clients
538  *
539  * @param cls closure
540  * @param tc task context
541  */
542 static void
543 announce_applications (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
544 {
545   if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
546   {
547     announce_applications_task = GNUNET_SCHEDULER_NO_TASK;
548     return;
549   }
550   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: Starting PUT for apps\n");
551   GNUNET_CONTAINER_multihashmap_iterate (applications, &announce_application,
552                                          NULL);
553   announce_applications_task =
554       GNUNET_SCHEDULER_add_delayed (APP_ANNOUNCE_TIME, &announce_applications,
555                                     cls);
556   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: Finished PUT for apps\n");
557   return;
558 }
559
560
561 /**
562  * Periodically announce self id in the DHT
563  *
564  * @param cls closure
565  * @param tc task context
566  */
567 static void
568 announce_id (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
569 {
570   if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
571   {
572     announce_id_task = GNUNET_SCHEDULER_NO_TASK;
573     return;
574   }
575   /* TODO
576    * - Set data expiration in function of X
577    * - Adapt X to churn
578    */
579   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: DHT_put for ID %s started.\n",
580               GNUNET_h2s_full (&my_full_id.hashPubKey));
581   GNUNET_DHT_put (dht_handle,   /* DHT handle */
582                   &my_full_id.hashPubKey,       /* Key to use */
583                   10U,          /* Replication level */
584                   GNUNET_DHT_RO_RECORD_ROUTE |
585                     GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE,   /* DHT options */
586                   GNUNET_BLOCK_TYPE_TEST,       /* Block type */
587                   sizeof(my_full_id),   /* Size of the data */
588                   (char *)&my_full_id,  /* Data itself */
589                   GNUNET_TIME_absolute_get_forever (),  /* Data expiration */
590                   GNUNET_TIME_UNIT_FOREVER_REL, /* Retry time */
591 #if MESH_DEBUG
592                   &mesh_debug, "DHT_put for id completed");
593 #else
594                   NULL,         /* Continuation */
595                   NULL);        /* Continuation closure */
596 #endif
597   announce_id_task =
598       GNUNET_SCHEDULER_add_delayed (ID_ANNOUNCE_TIME, &announce_id, cls);
599 }
600
601
602 /**
603  * Function to process paths received for a new peer addition. The recorded
604  * paths form the initial tunnel, which can be optimized later.
605  * Called on each result obtained for the DHT search.
606  *
607  * @param cls closure
608  * @param exp when will this value expire
609  * @param key key of the result
610  * @param type type of the result
611  * @param size number of bytes in data
612  * @param data pointer to the result data
613  */
614 static void
615 dht_get_id_handler (void *cls, struct GNUNET_TIME_Absolute exp,
616                     const GNUNET_HashCode * key,
617                     const struct GNUNET_PeerIdentity *get_path,
618                     unsigned int get_path_length,
619                     const struct GNUNET_PeerIdentity *put_path,
620                     unsigned int put_path_length,
621                     enum GNUNET_BLOCK_Type type, size_t size, const void *data);
622
623
624 /******************************************************************************/
625 /******************      GENERAL HELPER FUNCTIONS      ************************/
626 /******************************************************************************/
627
628 /**
629  * Check if client has registered with the service and has not disconnected
630  *
631  * @param client the client to check
632  *
633  * @return non-NULL if client exists in the global DLL
634  */
635 static struct MeshClient *
636 client_get (struct GNUNET_SERVER_Client *client)
637 {
638   struct MeshClient *c;
639
640   c = clients;
641   while (NULL != c)
642   {
643     if (c->handle == client)
644       return c;
645     c = c->next;
646   }
647   return NULL;
648 }
649
650
651 /**
652  * Checks if a given client has subscribed to certain message type
653  *
654  * @param message_type Type of message to check
655  * @param c Client to check
656  *
657  * @return GNUNET_YES or GNUNET_NO, depending on subscription status
658  *
659  * TODO inline?
660  */
661 static int
662 client_is_subscribed (uint16_t message_type, struct MeshClient *c)
663 {
664   GNUNET_HashCode hc;
665
666   GNUNET_CRYPTO_hash (&message_type, sizeof (uint16_t), &hc);
667   return GNUNET_CONTAINER_multihashmap_contains (c->types, &hc);
668 }
669
670
671 /**
672  * Send the message to all clients that have subscribed to its type
673  *
674  * @param msg Pointer to the message itself
675  * @return number of clients this message was sent to
676  */
677 static unsigned int
678 send_subscribed_clients (struct GNUNET_MessageHeader *msg)
679 {
680   struct MeshClient *c;
681   unsigned int count;
682   uint16_t type;
683
684   type = ntohs (msg->type);
685   for (count = 0, c = clients; c != NULL; c = c->next)
686   {
687     if (client_is_subscribed (type, c))
688     {
689       count++;
690       GNUNET_SERVER_notification_context_unicast (nc, c->handle, msg,
691                                                   GNUNET_YES);
692     }
693   }
694   return count;
695 }
696
697
698 /**
699  * Notify the client that owns the tunnel that a peer has connected to it
700  * 
701  * @param t Tunnel whose owner to notify
702  * @param id Short id of the peer that has connected
703  */
704 static void
705 send_client_peer_connected (const struct MeshTunnel *t, const GNUNET_PEER_Id id)
706 {
707   struct GNUNET_MESH_PeerControl pc;
708
709   pc.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD);
710   pc.header.size = htons (sizeof (struct GNUNET_MESH_PeerControl));
711   pc.tunnel_id = htonl (t->local_tid);
712   GNUNET_PEER_resolve (id, &pc.peer);
713   GNUNET_SERVER_notification_context_unicast (nc, t->client->handle,
714                                               &pc.header, GNUNET_NO);
715 }
716
717
718 /**
719  * Function called to notify a client about the socket
720  * being ready to queue more data.  "buf" will be
721  * NULL and "size" zero if the socket was closed for
722  * writing in the meantime.
723  *
724  * @param cls closure
725  * @param size number of bytes available in buf
726  * @param buf where the callee should write the message
727  * @return number of bytes written to buf
728  */
729 static size_t
730 send_core_create_path (void *cls, size_t size, void *buf);
731
732 /**
733  * Cancel a core transmission that was already requested and free all resources
734  * associated to the request.
735  * 
736  * @param peer PeeInfo of the peer whose transmission is cancelled.
737  * @param i Position of the transmission to be cancelled.
738  */
739 static void
740 peer_info_cancel_transmission(struct MeshPeerInfo *peer, unsigned int i)
741 {
742   if (peer->core_transmit[i])
743   {
744     struct MeshDataDescriptor *dd;
745     struct MeshPathInfo *path_info;
746     GNUNET_CORE_notify_transmit_ready_cancel (peer->core_transmit[i]);
747     /* TODO: notify that tranmission has failed */
748     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
749                 "MESH:   Cancelled data transmission at %u\n",
750                 i);
751     switch (peer->types[i])
752     {
753       case GNUNET_MESSAGE_TYPE_MESH_MULTICAST:
754       case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
755       case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
756         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:    type payload\n");
757         dd = peer->infos[i];
758         if (0 == --(*dd->copies))
759         {
760           GNUNET_free (dd->copies);
761           GNUNET_free (dd->data);
762         }
763         break;
764       case GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE:
765         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:    type create path\n");
766         path_info = peer->infos[i];
767         path_destroy(path_info->path);
768         break;
769     }
770     GNUNET_free (peer->infos[i]);
771   } 
772 }
773
774
775 /**
776  * 
777  */
778 static unsigned int
779 peer_info_transmit_slot (struct MeshPeerInfo *peer)
780 {
781   unsigned int i;
782
783   for (i = 0; peer->core_transmit[i]; i++)
784   {
785     if (i == (CORE_QUEUE_SIZE - 1))
786     {
787       /* All positions are taken! Overwriting! */
788       GNUNET_break (0);
789       peer_info_cancel_transmission(peer, 0);
790       return 0;
791     }
792   }
793   return i;
794 }
795
796
797 /**
798  * Retrieve the MeshPeerInfo stucture associated with the peer, create one
799  * and insert it in the appropiate structures if the peer is not known yet.
800  *
801  * @param peer Full identity of the peer.
802  *
803  * @return Existing or newly created peer info.
804  */
805 static struct MeshPeerInfo *
806 peer_info_get (const struct GNUNET_PeerIdentity *peer)
807 {
808   struct MeshPeerInfo *peer_info;
809
810   peer_info = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
811   if (NULL == peer_info)
812   {
813     peer_info =
814         (struct MeshPeerInfo *) GNUNET_malloc (sizeof (struct MeshPeerInfo));
815     GNUNET_CONTAINER_multihashmap_put (peers, &peer->hashPubKey, peer_info,
816                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
817     peer_info->id = GNUNET_PEER_intern (peer);
818   }
819
820   return peer_info;
821 }
822
823
824 /**
825  * Retrieve the MeshPeerInfo stucture associated with the peer, create one
826  * and insert it in the appropiate structures if the peer is not known yet.
827  *
828  * @param peer Short identity of the peer.
829  *
830  * @return Existing or newly created peer info.
831  */
832 static struct MeshPeerInfo *
833 peer_info_get_short (const GNUNET_PEER_Id peer)
834 {
835   struct GNUNET_PeerIdentity id;
836
837   GNUNET_PEER_resolve(peer, &id);
838   return peer_info_get(&id);
839 }
840
841
842 /**
843  * Sends a CREATE PATH message for a path to a peer, properly registrating
844  * all used resources.
845  * 
846  * @param peer PeerInfo of the final peer for whom this path is being created.
847  * @param p Path itself.
848  * @param t Tunnel for which the path is created.
849  */
850 static void
851 send_create_path (struct MeshPeerInfo *peer,
852                   struct MeshPeerPath *p,
853                   struct MeshTunnel *t)
854 {
855   struct GNUNET_PeerIdentity id;
856   struct MeshPathInfo *path_info;
857   struct MeshPeerInfo *neighbor;
858   unsigned int i;
859
860   if (NULL == p)
861   {
862     p = tree_get_path_to_peer(t->tree, peer->id);
863     if (NULL == p)
864     {
865       GNUNET_break (0);
866       return;
867     }
868   }
869   for (i = 0; i < p->length; i++)
870   {
871     if (p->peers[i] == myid)
872       break;
873   }
874   if (i >= p->length - 1)
875   {
876     path_destroy(p);
877     GNUNET_break (0);
878     return;
879   }
880   GNUNET_PEER_resolve(p->peers[i + 1], &id);
881
882   path_info = GNUNET_malloc (sizeof (struct MeshPathInfo));
883   path_info->path = p;
884   path_info->peer = peer;
885   path_info->t = t;
886   neighbor = peer_info_get(&id);
887   path_info->pos = peer_info_transmit_slot(neighbor);
888   neighbor->types[path_info->pos] = GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE;
889   neighbor->infos[path_info->pos] = path_info;
890   neighbor->core_transmit[path_info->pos] = 
891       GNUNET_CORE_notify_transmit_ready (
892           core_handle, /* handle */
893           0, /* cork */
894           0, /* priority */
895           GNUNET_TIME_UNIT_FOREVER_REL, /* timeout */
896           &id, /* target */
897           sizeof (struct GNUNET_MESH_ManipulatePath)
898           + (p->length * sizeof (struct GNUNET_PeerIdentity)), /*size */
899           &send_core_create_path, /* callback */
900           path_info);        /* cls */
901 }
902
903
904 /**
905  * Try to establish a new connection to this peer.
906  * Use the best path for the given tunnel.
907  * If the peer doesn't have any path to it yet, try to get one. 
908  * If the peer already has some path, send a CREATE PATH towards it.
909  *
910  * @param peer PeerInfo of the peer.
911  * @param t Tunnel for which to create the path, if possible.
912  */
913 static void
914 peer_info_connect (struct MeshPeerInfo *peer, struct MeshTunnel *t)
915 {
916   struct MeshPeerPath *p;
917   struct MeshPathInfo *path_info;
918
919   if (NULL != peer->path_head)
920   {
921     p = tree_get_path_to_peer(t->tree, peer->id);
922     if (p->length > 1)
923     {
924       send_create_path(peer, p, t);
925     }
926     else
927     {
928       path_destroy(p);
929       send_client_peer_connected(t, myid);
930     }
931   }
932   else if (NULL == peer->dhtget)
933   {
934     struct GNUNET_PeerIdentity id;
935
936     GNUNET_PEER_resolve(peer->id, &id);
937     path_info = GNUNET_malloc(sizeof(struct MeshPathInfo));
938     path_info->peer = peer;
939     path_info->t = t;
940     peer->dhtget =
941         GNUNET_DHT_get_start(dht_handle,       /* handle */
942                              GNUNET_TIME_UNIT_FOREVER_REL,     /* timeout */
943                              GNUNET_BLOCK_TYPE_TEST,   /* type */
944                              &id.hashPubKey,       /* key to search */
945                              4,         /* replication level */
946                              GNUNET_DHT_RO_RECORD_ROUTE |
947                                GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE,
948                              NULL,     /* xquery */
949                              0,        /* xquery bits */
950                              &dht_get_id_handler,
951                              path_info);
952   }
953   /* Otherwise, there is no path but the DHT get is already started. */
954 }
955
956
957 #if LATER
958 /**
959  * Destroy the peer_info and free any allocated resources linked to it
960  * @param t tunnel the path belongs to
961  * @param pi the peer_info to destroy
962  * @return GNUNET_OK on success
963  */
964 static int
965 peer_info_destroy (struct MeshPeerInfo *pi)
966 {
967   GNUNET_HashCode hash;
968   struct GNUNET_PeerIdentity id;
969
970   GNUNET_PEER_resolve (pi->id, &id);
971   GNUNET_PEER_change_rc (pi->id, -1);
972   GNUNET_CRYPTO_hash (&id, sizeof (struct GNUNET_PeerIdentity), &hash);
973
974   GNUNET_CONTAINER_multihashmap_remove (peers, &hash, pi);
975   GNUNET_SCHEDULER_cancel (pi->path_refresh_task);
976   GNUNET_free (pi);
977   return GNUNET_OK;
978 }
979 #endif
980
981
982 /**
983  * Notify a tunnel that a connection has broken that affects at least
984  * some of its peers.
985  *
986  * @param t Tunnel affected.
987  * @param peer Peer that (at least) has been affected by the disconnection.
988  * @param p1 Peer that got disconnected from p2.
989  * @param p2 Peer that got disconnected from p1.
990  *
991  * @return Short ID of the peer disconnected (either p1 or p2).
992  *         0 if the tunnel remained unaffected.
993  */
994 static GNUNET_PEER_Id
995 tunnel_notify_connection_broken (struct MeshTunnel *t,
996                                  struct MeshPeerInfo *peer, GNUNET_PEER_Id p1,
997                                  GNUNET_PEER_Id p2);
998
999 /**
1000  * Remove all paths that rely on a direct connection between p1 and p2
1001  * from the peer itself and notify all tunnels about it.
1002  *
1003  * @param peer PeerInfo of affected peer.
1004  * @param p1 GNUNET_PEER_Id of one peer.
1005  * @param p2 GNUNET_PEER_Id of another peer that was connected to the first and
1006  *           no longer is.
1007  *
1008  * TODO: optimize (see below)
1009  */
1010 static void
1011 path_remove_from_peer (struct MeshPeerInfo *peer,
1012                        GNUNET_PEER_Id p1,
1013                        GNUNET_PEER_Id p2)
1014 {
1015   struct GNUNET_PeerIdentity id;
1016   struct MeshPeerPath *p;
1017   struct MeshPeerPath *aux;
1018   struct MeshPeerInfo *peer_d;
1019   GNUNET_PEER_Id d;
1020   unsigned int destroyed;
1021   unsigned int best;
1022   unsigned int cost;
1023   unsigned int i;
1024
1025   destroyed = 0;
1026   p = peer->path_head;
1027   while (NULL != p)
1028   {
1029     aux = p->next;
1030     for (i = 0; i < (p->length - 1); i++)
1031     {
1032       if ((p->peers[i] == p1 && p->peers[i + 1] == p2) ||
1033           (p->peers[i] == p2 && p->peers[i + 1] == p1))
1034       {
1035         path_destroy (p);
1036         destroyed++;
1037         break;
1038       }
1039     }
1040     p = aux;
1041   }
1042   if (0 == destroyed)
1043     return;
1044
1045   for (i = 0; i < peer->ntunnels; i++)
1046   {
1047     d = tunnel_notify_connection_broken (peer->tunnels[i], peer, p1, p2);
1048     /* TODO
1049      * Problem: one or more peers have been deleted from the tunnel tree.
1050      * We don't know who they are to try to add them again.
1051      * We need to try to find a new path for each of the disconnected peers.
1052      * Some of them might already have a path to reach them that does not
1053      * involve p1 and p2. Adding all anew might render in a better tree than
1054      * the trivial immediate fix.
1055      * 
1056      * Trivial immiediate fix: try to reconnect to the disconnected node. All
1057      * its children will be reachable trough him.
1058      */
1059     peer_d = peer_info_get_short(d);
1060     best = UINT_MAX;
1061     aux = NULL;
1062     for (p = peer_d->path_head; NULL != p; p = p->next)
1063     {
1064       if ((cost = path_get_cost(peer->tunnels[i]->tree, p)) < best)
1065       {
1066         best = cost;
1067         aux = p;
1068       }
1069     }
1070     if (NULL != aux)
1071     {
1072       /* No callback, as peer will be already disconnected */
1073       tree_add_path(peer->tunnels[i]->tree, aux, NULL);
1074     }
1075     else
1076     {
1077       struct MeshPathInfo *path_info;
1078
1079       if (NULL != peer_d->dhtget)
1080         return;
1081       path_info = GNUNET_malloc(sizeof(struct MeshPathInfo));
1082       path_info->path = p;
1083       path_info->peer = peer_d;
1084       path_info->t = peer->tunnels[i];
1085       peer_d->dhtget =
1086           GNUNET_DHT_get_start(dht_handle,       /* handle */
1087                                GNUNET_TIME_UNIT_FOREVER_REL, /* timeout */
1088                                GNUNET_BLOCK_TYPE_TEST,   /* type */
1089                                &id.hashPubKey,   /*key to search */
1090                                4,        /* replication level */
1091                                GNUNET_DHT_RO_RECORD_ROUTE |
1092                                  GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE,
1093                                NULL,     /* xquery */
1094                                0,        /* xquery bits */
1095                                &dht_get_id_handler,
1096                                (void *) path_info);
1097     }
1098   }
1099 }
1100
1101
1102 /**
1103  * Add the path to the peer and update the path used to reach it in case this
1104  * is the shortest.
1105  *
1106  * @param peer_info Destination peer to add the path to.
1107  * @param path New path to add. Last peer must be the peer in arg 1.
1108  *             Path will be either used of freed if already known.
1109  *
1110  * TODO: trim the part from origin to us? Add it as path to origin?
1111  */
1112 void
1113 path_add_to_peer (struct MeshPeerInfo *peer_info, struct MeshPeerPath *path)
1114 {
1115   struct MeshPeerPath *aux;
1116   unsigned int l;
1117   unsigned int l2;
1118
1119   if (NULL == peer_info || NULL == path)
1120   {
1121     GNUNET_break (0);
1122     return;
1123   }
1124
1125   l = path_get_length (path);
1126   if (0 == l)
1127   {
1128     GNUNET_free (path);
1129     return;
1130   }
1131
1132   for (aux = peer_info->path_head; aux != NULL; aux = aux->next)
1133   {
1134     l2 = path_get_length (aux);
1135     if (l2 > l)
1136     {
1137       GNUNET_CONTAINER_DLL_insert_before (peer_info->path_head,
1138                                           peer_info->path_tail, aux, path);
1139     }
1140     else
1141     {
1142       if (l2 == l && memcmp(path->peers, aux->peers, l) == 0)
1143       {
1144         path_destroy(path);
1145         return;
1146       }
1147     }
1148   }
1149   GNUNET_CONTAINER_DLL_insert_tail (peer_info->path_head, peer_info->path_tail,
1150                                     path);
1151   return;
1152 }
1153
1154
1155 /**
1156  * Add the path to the origin peer and update the path used to reach it in case
1157  * this is the shortest.
1158  * The path is given in peer_info -> destination, therefore we turn the path
1159  * upside down first.
1160  *
1161  * @param peer_info Peer to add the path to, being the origin of the path.
1162  * @param path New path to add after being inversed.
1163  */
1164 static void
1165 path_add_to_origin (struct MeshPeerInfo *peer_info, struct MeshPeerPath *path)
1166 {
1167   path_invert(path);
1168   path_add_to_peer (peer_info, path);
1169 }
1170
1171
1172 /**
1173  * Build a PeerPath from the paths returned from the DHT, reversing the paths
1174  * to obtain a local peer -> destination path and interning the peer ids.
1175  *
1176  * @return Newly allocated and created path
1177  */
1178 static struct MeshPeerPath *
1179 path_build_from_dht (const struct GNUNET_PeerIdentity *get_path,
1180                      unsigned int get_path_length,
1181                      const struct GNUNET_PeerIdentity *put_path,
1182                      unsigned int put_path_length)
1183 {
1184   struct MeshPeerPath *p;
1185   GNUNET_PEER_Id id;
1186   int i;
1187
1188   p = path_new (1);
1189   p->peers[0] = myid;
1190   GNUNET_PEER_change_rc(myid, 1);
1191   i = get_path_length;
1192   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "MESH:    GET has %d hops.\n", i);
1193   for (i--; i >= 0; i--)
1194   {
1195     id = GNUNET_PEER_intern (&get_path[i]);
1196     if (p->length > 0 && id == p->peers[p->length - 1])
1197     {
1198       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "MESH:    Optimizing 1 hop out.\n");
1199       GNUNET_PEER_change_rc(id, -1);
1200     }
1201     else
1202     {
1203       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1204                  "MESH:    Adding from GET: %s.\n",
1205                  GNUNET_i2s(&get_path[i]));
1206       p->length++;
1207       p->peers = GNUNET_realloc (p->peers, sizeof (GNUNET_PEER_Id) * p->length);
1208       p->peers[p->length - 1] = id;
1209     }
1210   }
1211   i = put_path_length;
1212   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "MESH:    PUT has %d hops.\n", i);
1213   for (i--; i >= 0; i--)
1214   {
1215     id = GNUNET_PEER_intern (&put_path[i]);
1216     if (id == myid)
1217     {
1218       /* PUT path went through us, so discard the path up until now and start
1219        * from here to get a much shorter (and loop-free) path.
1220        */
1221       path_destroy (p);
1222       p = path_new (0);
1223     }
1224     if (p->length > 0 && id == p->peers[p->length - 1])
1225     {
1226       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "MESH:    Optimizing 1 hop out.\n");
1227       GNUNET_PEER_change_rc(id, -1);
1228     }
1229     else
1230     {
1231       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1232             "MESH:    Adding from PUT: %s.\n",
1233             GNUNET_i2s(&put_path[i]));
1234       p->length++;
1235       p->peers = GNUNET_realloc (p->peers, sizeof (GNUNET_PEER_Id) * p->length);
1236       p->peers[p->length - 1] = id;
1237     }
1238   }
1239 #if MESH_DEBUG
1240   if (get_path_length > 0)
1241     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1242                 "MESH:    (first of GET: %s)\n",
1243                 GNUNET_h2s_full(&get_path[0].hashPubKey));
1244   if (put_path_length > 0)
1245     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1246                 "MESH:    (first of PUT: %s)\n",
1247                 GNUNET_h2s_full(&put_path[0].hashPubKey));
1248   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1249               "MESH:    In total: %d hops\n",
1250               p->length);
1251   for (i = 0; i < p->length; i++)
1252   {
1253     struct GNUNET_PeerIdentity peer_id;
1254
1255     GNUNET_PEER_resolve(p->peers[i], &peer_id);
1256     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1257               "MESH:        %u: %s\n",
1258               p->peers[i],
1259               GNUNET_h2s_full(&peer_id.hashPubKey));
1260   }
1261 #endif
1262   return p;
1263 }
1264
1265
1266 /**
1267  * Send keepalive packets for a peer
1268  *
1269  * @param cls Closure (tunnel for which to send the keepalive).
1270  * @param tc Notification context.
1271  *
1272  * TODO: implement explicit multicast keepalive?
1273  */
1274 void
1275 path_refresh (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
1276
1277
1278 /**
1279  * Search for a tunnel among the tunnels for a client
1280  *
1281  * @param c the client whose tunnels to search in
1282  * @param tid the local id of the tunnel
1283  *
1284  * @return tunnel handler, NULL if doesn't exist
1285  */
1286 static struct MeshTunnel *
1287 tunnel_get_by_local_id (struct MeshClient *c, MESH_TunnelNumber tid)
1288 {
1289   GNUNET_HashCode hash;
1290
1291   GNUNET_CRYPTO_hash (&tid, sizeof (MESH_TunnelNumber), &hash);
1292   return GNUNET_CONTAINER_multihashmap_get (c->tunnels, &hash);
1293 }
1294
1295
1296 /**
1297  * Search for a tunnel by global ID using PEER_ID
1298  *
1299  * @param pi owner of the tunnel
1300  * @param tid global tunnel number
1301  *
1302  * @return tunnel handler, NULL if doesn't exist
1303  */
1304 static struct MeshTunnel *
1305 tunnel_get_by_pi (GNUNET_PEER_Id pi, MESH_TunnelNumber tid)
1306 {
1307   struct MESH_TunnelID id;
1308   GNUNET_HashCode hash;
1309
1310   id.oid = pi;
1311   id.tid = tid;
1312
1313   GNUNET_CRYPTO_hash (&id, sizeof (struct MESH_TunnelID), &hash);
1314   return GNUNET_CONTAINER_multihashmap_get (tunnels, &hash);
1315 }
1316
1317
1318 /**
1319  * Search for a tunnel by global ID using full PeerIdentities
1320  *
1321  * @param oid owner of the tunnel
1322  * @param tid global tunnel number
1323  *
1324  * @return tunnel handler, NULL if doesn't exist
1325  */
1326 static struct MeshTunnel *
1327 tunnel_get (struct GNUNET_PeerIdentity *oid, MESH_TunnelNumber tid)
1328 {
1329   return tunnel_get_by_pi (GNUNET_PEER_search (oid), tid);
1330 }
1331
1332
1333 /**
1334  * Callback used to notify a client owner of a tunnel that a peer has
1335  * disconnected, most likely because of a path change.
1336  *
1337  * @param n Node in the tree representing the disconnected peer
1338  */
1339 void
1340 notify_peer_disconnected (const struct MeshTunnelTreeNode *n)
1341 {
1342   struct MeshPeerInfo *peer;
1343
1344   if (NULL != n->t->client && NULL != nc)
1345   {
1346     struct GNUNET_MESH_PeerControl msg;
1347     msg.header.size = htons (sizeof (msg));
1348     msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_DEL);
1349     msg.tunnel_id = htonl (n->t->local_tid);
1350     GNUNET_PEER_resolve (n->peer, &msg.peer);
1351     GNUNET_SERVER_notification_context_unicast (nc, n->t->client->handle,
1352                                                 &msg.header, GNUNET_NO);
1353   }
1354   peer = peer_info_get_short(n->peer);
1355   peer_info_connect(peer, n->t);
1356 }
1357
1358
1359 /**
1360  * Add a peer to a tunnel, accomodating paths accordingly and initializing all
1361  * needed rescources.
1362  * If peer already exists, reevaluate shortest path and change if different.
1363  *
1364  * @param t Tunnel we want to add a new peer to
1365  * @param peer PeerInfo of the peer being added
1366  *
1367  */
1368 static void
1369 tunnel_add_peer (struct MeshTunnel *t, struct MeshPeerInfo *peer)
1370 {
1371   struct GNUNET_PeerIdentity id;
1372   struct MeshPeerPath *best_p;
1373   struct MeshPeerPath *p;
1374   unsigned int best_cost;
1375   unsigned int cost;
1376
1377   GNUNET_PEER_resolve(peer->id, &id);
1378   if (GNUNET_NO ==
1379       GNUNET_CONTAINER_multihashmap_contains(t->peers, &id.hashPubKey))
1380   {
1381     t->peers_total++;
1382     GNUNET_array_append (peer->tunnels, peer->ntunnels, t);
1383     GNUNET_CONTAINER_multihashmap_put(
1384       t->peers,
1385       &id.hashPubKey,
1386       peer,
1387       GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
1388   }
1389
1390   if (NULL != (p = peer->path_head))
1391   {
1392     best_p = p;
1393     best_cost = path_get_cost(t->tree, p);
1394     while (NULL != p)
1395     {
1396       if ((cost = path_get_cost (t->tree, p)) < best_cost)
1397       {
1398         best_cost = cost;
1399         best_p = p;
1400       }
1401       p = p->next;
1402     }
1403     tree_add_path (t->tree, best_p, &notify_peer_disconnected);
1404     if (GNUNET_SCHEDULER_NO_TASK == t->path_refresh_task)
1405       t->path_refresh_task =
1406           GNUNET_SCHEDULER_add_delayed (t->tree->refresh, &path_refresh, t);
1407   }
1408   else
1409   {
1410     /* Start a DHT get if necessary */
1411     peer_info_connect(peer, t);
1412   }
1413 }
1414
1415 /**
1416  * Add a path to a tunnel which we don't own, just to remember the next hop.
1417  * If destination node was already in the tunnel, the first hop information
1418  * will be replaced with the new path.
1419  *
1420  * @param t Tunnel we want to add a new peer to
1421  * @param p Path to add
1422  * @param own_pos Position of local node in path.
1423  *
1424  */
1425 static void
1426 tunnel_add_path (struct MeshTunnel *t,
1427                  struct MeshPeerPath *p,
1428                  unsigned int own_pos)
1429 {
1430   struct GNUNET_PeerIdentity id;
1431
1432   GNUNET_assert (0 != own_pos);
1433   tree_add_path(t->tree, p, NULL);
1434   if (NULL == t->tree->me)
1435     t->tree->me = tree_find_peer(t->tree->root, p->peers[own_pos]);
1436   GNUNET_PEER_resolve (p->peers[own_pos + 1], &id);
1437   tree_update_first_hops(t->tree, t->tree->me, &id);
1438 }
1439
1440
1441 /**
1442  * Notify a tunnel that a connection has broken that affects at least
1443  * some of its peers.
1444  *
1445  * @param t Tunnel affected.
1446  * @param peer Peer that (at least) has been affected by the disconnection.
1447  * @param p1 Peer that got disconnected from p2.
1448  * @param p2 Peer that got disconnected from p1.
1449  *
1450  * @return Short ID of the peer disconnected (either p1 or p2).
1451  *         0 if the tunnel remained unaffected.
1452  */
1453 static GNUNET_PEER_Id
1454 tunnel_notify_connection_broken (struct MeshTunnel *t,
1455                                  struct MeshPeerInfo *peer,
1456                                  GNUNET_PEER_Id p1,
1457                                  GNUNET_PEER_Id p2)
1458 {
1459   return tree_notify_connection_broken (t->tree, p1, p2,
1460                                         &notify_peer_disconnected);
1461 }
1462
1463
1464 /**
1465  * Destroy the tunnel and free any allocated resources linked to it
1466  *
1467  * @param t the tunnel to destroy
1468  *
1469  * @return GNUNET_OK on success
1470  */
1471 static int
1472 tunnel_destroy (struct MeshTunnel *t)
1473 {
1474   struct MeshClient *c;
1475   struct MeshQueue *q;
1476   struct MeshQueue *qn;
1477   GNUNET_HashCode hash;
1478   int r;
1479
1480   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: DESTROYING TUNNEL at %p\n", t);
1481   if (NULL == t)
1482     return GNUNET_OK;
1483
1484   c = t->client;
1485 #if MESH_DEBUG
1486   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   by client %u\n", c->id);
1487 #endif
1488
1489   GNUNET_CRYPTO_hash (&t->id, sizeof (struct MESH_TunnelID), &hash);
1490   if (GNUNET_YES != GNUNET_CONTAINER_multihashmap_remove (tunnels, &hash, t))
1491   {
1492     r = GNUNET_SYSERR;
1493   }
1494
1495   GNUNET_CRYPTO_hash (&t->local_tid, sizeof (MESH_TunnelNumber), &hash);
1496   if (GNUNET_YES != GNUNET_CONTAINER_multihashmap_remove (c->tunnels, &hash, t))
1497   {
1498     r = GNUNET_SYSERR;
1499   }
1500   GNUNET_CONTAINER_multihashmap_destroy (t->peers);
1501   q = t->queue_head;
1502   while (NULL != q)
1503   {
1504     if (NULL != q->data)
1505       GNUNET_free (q->data);
1506     qn = q->next;
1507     GNUNET_free (q);
1508     q = qn;
1509     /* TODO cancel core transmit ready in case it was active */
1510   }
1511   tree_destroy(t->tree);
1512   if (NULL != t->dht_get_type)
1513     GNUNET_DHT_get_stop(t->dht_get_type);
1514   t->dht_get_type = NULL;
1515   GNUNET_free (t);
1516   return r;
1517 }
1518
1519
1520 /**
1521  * tunnel_destroy_iterator: iterator for deleting each tunnel that belongs to a
1522  * client when the client disconnects.
1523  * 
1524  * @param cls closure (client that is disconnecting)
1525  * @param key the hash of the local tunnel id (used to access the hashmap)
1526  * @param value the value stored at the key (tunnel to destroy)
1527  * 
1528  * @return GNUNET_OK on success
1529  */
1530 static int
1531 tunnel_destroy_iterator (void *cls, const GNUNET_HashCode * key, void *value)
1532 {
1533   struct MeshTunnel *t = value;
1534   int r;
1535
1536   if (NULL != t->dht_get_type)
1537   {
1538     GNUNET_DHT_get_stop (t->dht_get_type);
1539   }
1540   r = tunnel_destroy (t);
1541   return r;
1542 }
1543
1544
1545 /******************************************************************************/
1546 /****************      MESH NETWORK HANDLER HELPERS     ***********************/
1547 /******************************************************************************/
1548
1549 /**
1550  * Function called to notify a client about the socket
1551  * being ready to queue more data.  "buf" will be
1552  * NULL and "size" zero if the socket was closed for
1553  * writing in the meantime.
1554  *
1555  * @param cls closure
1556  * @param size number of bytes available in buf
1557  * @param buf where the callee should write the message
1558  * @return number of bytes written to buf
1559  */
1560 static size_t
1561 send_core_create_path (void *cls, size_t size, void *buf)
1562 {
1563   struct MeshPathInfo *info = cls;
1564   struct GNUNET_MESH_ManipulatePath *msg;
1565   struct GNUNET_PeerIdentity *peer_ptr;
1566   struct MeshPeerInfo *peer = info->peer;
1567   struct MeshTunnel *t = info->t;
1568   struct MeshPeerPath *p = info->path;
1569   size_t size_needed;
1570   int i;
1571
1572   size_needed =
1573       sizeof (struct GNUNET_MESH_ManipulatePath) +
1574       p->length * sizeof (struct GNUNET_PeerIdentity);
1575
1576   if (size < size_needed || NULL == buf)
1577   {
1578     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: create path retransmit!\n");
1579     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   buf:  %p\n", buf);
1580     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   size: (%u/%u)\n",
1581                 size, size_needed);
1582     info->peer->core_transmit[info->pos] = 
1583       GNUNET_CORE_notify_transmit_ready (core_handle, 0, 0,
1584                                         GNUNET_TIME_UNIT_FOREVER_REL,
1585                                         path_get_first_hop (t->tree, peer->id),
1586                                         size_needed,
1587                                         &send_core_create_path,
1588                                         info);
1589     return 0;
1590   }
1591
1592   msg = (struct GNUNET_MESH_ManipulatePath *) buf;
1593   msg->header.size = htons (size_needed);
1594   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE);
1595   msg->tid = ntohl (t->id.tid);
1596
1597   peer_ptr = (struct GNUNET_PeerIdentity *) &msg[1];
1598   for (i = 0; i < p->length; i++)
1599   {
1600     GNUNET_PEER_resolve (p->peers[i], peer_ptr++);
1601   }
1602
1603   path_destroy (p);
1604   GNUNET_free (info);
1605
1606   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1607               "MESH: CREATE PATH (%u bytes long) sent!\n",
1608               size_needed);
1609   return size_needed;
1610 }
1611
1612
1613 #if LATER
1614 /**
1615  * Function called to notify a client about the socket
1616  * being ready to queue more data.  "buf" will be
1617  * NULL and "size" zero if the socket was closed for
1618  * writing in the meantime.
1619  *
1620  * @param cls closure (MeshDataDescriptor with all info to build packet)
1621  * @param size number of bytes available in buf
1622  * @param buf where the callee should write the message
1623  * @return number of bytes written to buf
1624  */
1625 static size_t
1626 send_core_data_to_origin (void *cls, size_t size, void *buf)
1627 {
1628   struct MeshDataDescriptor *info = cls;
1629   struct GNUNET_MESH_ToOrigin *msg = buf;
1630   size_t total_size;
1631
1632   GNUNET_assert (NULL != info);
1633   total_size = sizeof (struct GNUNET_MESH_ToOrigin) + info->size;
1634   GNUNET_assert (total_size < 65536);   /* UNIT16_MAX */
1635
1636   if (total_size > size)
1637   {
1638     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1639                 "not enough buffer to send data to origin\n");
1640     return 0;
1641   }
1642   msg->header.size = htons (total_size);
1643   msg->header.type = htons (GNUNET_MESSAGE_TYPE_DATA_MESSAGE_TO_ORIGIN);
1644   GNUNET_PEER_resolve (info->origin->oid, &msg->oid);
1645   msg->tid = htonl (info->origin->tid);
1646   if (0 != info->size)
1647   {
1648     memcpy (&msg[1], &info[1], info->size);
1649   }
1650   if (NULL != info->client)
1651   {
1652     GNUNET_SERVER_receive_done (info->client, GNUNET_OK);
1653   }
1654   GNUNET_free (info);
1655   return total_size;
1656 }
1657 #endif
1658
1659
1660 /**
1661  * Function called to notify a client about the socket
1662  * being ready to queue more data.  "buf" will be
1663  * NULL and "size" zero if the socket was closed for
1664  * writing in the meantime.
1665  *
1666  * @param cls closure (data itself)
1667  * @param size number of bytes available in buf
1668  * @param buf where the callee should write the message
1669  * 
1670  * @return number of bytes written to buf
1671  */
1672 static size_t
1673 send_core_data_multicast (void *cls, size_t size, void *buf)
1674 {
1675   struct MeshDataDescriptor *info = cls;
1676   struct GNUNET_MESH_Multicast *msg = buf;
1677   size_t total_size;
1678
1679   GNUNET_assert (NULL != info);
1680   GNUNET_assert (NULL != info->peer);
1681   total_size = info->size + sizeof (struct GNUNET_MESH_Multicast);
1682   GNUNET_assert (total_size < GNUNET_SERVER_MAX_MESSAGE_SIZE);
1683
1684   if (total_size > size)
1685   {
1686     /* Retry */
1687     struct GNUNET_PeerIdentity id;
1688
1689     GNUNET_PEER_resolve(info->peer->id, &id);
1690     info->peer->infos[info->handler_n] = info;
1691     info->peer->types[info->handler_n] = GNUNET_MESSAGE_TYPE_MESH_MULTICAST;
1692     info->peer->core_transmit[info->handler_n] =
1693       GNUNET_CORE_notify_transmit_ready (core_handle,
1694                                          0,
1695                                          0,
1696                                          GNUNET_TIME_UNIT_FOREVER_REL,
1697                                          &id,
1698                                          total_size,
1699                                          &send_core_data_multicast,
1700                                          info);
1701     return 0;
1702   }
1703   info->peer->core_transmit[info->handler_n] = NULL;
1704   info->peer->infos[info->handler_n] = NULL;
1705   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_MULTICAST);
1706   msg->header.size = htons (total_size);
1707   GNUNET_PEER_resolve (info->origin->oid, &msg->oid);
1708   msg->tid = htonl (info->origin->tid);
1709   memcpy (&msg[1], info->data, info->size);
1710   if (0 == --(*info->copies))
1711   {
1712     if (NULL != info->client)
1713     {
1714       /* FIXME One unresponsive neighbor (who doesn't "call" tmt_rdy) can lock
1715        *       the client from sending anything else to the service.
1716        *       - Call receive_done after certain timeout.
1717        *       - Here cancel the timeout.
1718        */
1719       GNUNET_SERVER_receive_done (info->client, GNUNET_OK);
1720     }
1721     GNUNET_free (info->data);
1722     GNUNET_free (info->copies);
1723   }
1724   GNUNET_free (info);
1725   return total_size;
1726 }
1727
1728
1729 /**
1730  * Function called to notify a client about the socket
1731  * being ready to queue more data.  "buf" will be
1732  * NULL and "size" zero if the socket was closed for
1733  * writing in the meantime.
1734  *
1735  * @param cls closure (MeshDataDescriptor)
1736  * @param size number of bytes available in buf
1737  * @param buf where the callee should write the message
1738  * @return number of bytes written to buf
1739  */
1740 static size_t
1741 send_core_path_ack (void *cls, size_t size, void *buf)
1742 {
1743   struct MeshDataDescriptor *info = cls;
1744   struct GNUNET_MESH_PathACK *msg = buf;
1745
1746   GNUNET_assert (NULL != info);
1747   if (info->peer)
1748   {
1749     info->peer->core_transmit[info->handler_n] = NULL;
1750   }
1751   if (sizeof (struct GNUNET_MESH_PathACK) > size)
1752   {
1753     GNUNET_break (0);
1754     return 0;
1755   }
1756   msg->header.size = htons (sizeof (struct GNUNET_MESH_PathACK));
1757   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_ACK);
1758   GNUNET_PEER_resolve (info->origin->oid, &msg->oid);
1759   msg->tid = htonl (info->origin->tid);
1760   msg->peer_id = my_full_id;
1761   GNUNET_free (info);
1762   /* TODO add signature */
1763
1764   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: PATH ACK sent!\n");
1765   return sizeof (struct GNUNET_MESH_PathACK);
1766 }
1767
1768
1769 /**
1770  * Function called to notify a client about the socket
1771  * being ready to queue more data.  "buf" will be
1772  * NULL and "size" zero if the socket was closed for
1773  * writing in the meantime.
1774  *
1775  * @param cls closure (data itself)
1776  * @param size number of bytes available in buf
1777  * @param buf where the callee should write the message
1778  * @return number of bytes written to buf
1779  */
1780 static size_t
1781 send_core_data_raw (void *cls, size_t size, void *buf)
1782 {
1783   struct GNUNET_MessageHeader *msg = cls;
1784   size_t total_size;
1785
1786   GNUNET_assert (NULL != msg);
1787   total_size = ntohs (msg->size);
1788
1789   if (total_size > size)
1790   {
1791     GNUNET_break (0);
1792     return 0;
1793   }
1794   memcpy (buf, msg, total_size);
1795   GNUNET_free (cls);
1796   return total_size;
1797 }
1798
1799
1800 #if LATER
1801 /**
1802  * Send another peer a notification to destroy a tunnel
1803  * @param cls The tunnel to destroy
1804  * @param size Size in the buffer
1805  * @param buf Memory where to put the data to transmit
1806  * @return Size of data put in buffer
1807  */
1808 static size_t
1809 send_p2p_tunnel_destroy (void *cls, size_t size, void *buf)
1810 {
1811   struct MeshTunnel *t = cls;
1812   struct MeshClient *c;
1813   struct GNUNET_MESH_TunnelMessage *msg;
1814
1815   c = t->client;
1816   msg = buf;
1817   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_DESTROY);
1818    /*FIXME*/ msg->header.size =
1819       htons (sizeof (struct GNUNET_MESH_TunnelMessage));
1820   msg->tunnel_id = htonl (t->id.tid);
1821
1822   tunnel_destroy (c, t);
1823   return sizeof (struct GNUNET_MESH_TunnelMessage);
1824 }
1825 #endif
1826
1827
1828 /******************************************************************************/
1829 /********************      MESH NETWORK HANDLERS     **************************/
1830 /******************************************************************************/
1831
1832
1833 /**
1834  * Core handler for path creation
1835  * struct GNUNET_CORE_MessageHandler
1836  *
1837  * @param cls closure
1838  * @param message message
1839  * @param peer peer identity this notification is about
1840  * @param atsi performance data
1841  * @return GNUNET_OK to keep the connection open,
1842  *         GNUNET_SYSERR to close it (signal serious error)
1843  *
1844  */
1845 static int
1846 handle_mesh_path_create (void *cls, const struct GNUNET_PeerIdentity *peer,
1847                          const struct GNUNET_MessageHeader *message,
1848                          const struct GNUNET_TRANSPORT_ATS_Information *atsi)
1849 {
1850   unsigned int own_pos;
1851   uint16_t size;
1852   uint16_t i;
1853   MESH_TunnelNumber tid;
1854   struct GNUNET_MESH_ManipulatePath *msg;
1855   struct GNUNET_PeerIdentity *pi;
1856   GNUNET_HashCode hash;
1857   struct MeshPeerPath *path;
1858   struct MeshPeerInfo *dest_peer_info;
1859   struct MeshPeerInfo *orig_peer_info;
1860   struct MeshTunnel *t;
1861
1862   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1863               "MESH: Received a path create msg [%s]\n",
1864               GNUNET_i2s(&my_full_id));
1865   size = ntohs (message->size);
1866   if (size < sizeof (struct GNUNET_MESH_ManipulatePath))
1867   {
1868     GNUNET_break_op (0);
1869     return GNUNET_OK;
1870   }
1871
1872   size -= sizeof (struct GNUNET_MESH_ManipulatePath);
1873   if (size % sizeof (struct GNUNET_PeerIdentity))
1874   {
1875     GNUNET_break_op (0);
1876     return GNUNET_OK;
1877   }
1878   size /= sizeof (struct GNUNET_PeerIdentity);
1879   if (size < 2)
1880   {
1881     GNUNET_break_op (0);
1882     return GNUNET_OK;
1883   }
1884   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1885               "MESH:     path has %u hops.\n",
1886               size);
1887   msg = (struct GNUNET_MESH_ManipulatePath *) message;
1888
1889   tid = ntohl (msg->tid);
1890   pi = (struct GNUNET_PeerIdentity *) &msg[1];
1891   t = tunnel_get (pi, tid);
1892   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1893               "MESH:     path is for tunnel %s [%X].\n",
1894               GNUNET_i2s(pi),
1895               tid);
1896   if (NULL == t)
1897   {
1898     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   Creating tunnel\n");
1899     t = GNUNET_malloc (sizeof (struct MeshTunnel));
1900     t->id.oid = GNUNET_PEER_intern (pi);
1901     t->id.tid = tid;
1902     t->peers = GNUNET_CONTAINER_multihashmap_create (32);
1903     t->local_tid = next_local_tid++;
1904     /* FIXME test if taken */
1905     next_local_tid |= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV;
1906     t->tree = tree_new(t, t->id.oid);
1907
1908     GNUNET_CRYPTO_hash (&t->id, sizeof (struct MESH_TunnelID), &hash);
1909     if (GNUNET_OK !=
1910         GNUNET_CONTAINER_multihashmap_put (tunnels, &hash, t,
1911                                            GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
1912     {
1913       GNUNET_break (0);
1914       return GNUNET_OK;
1915     }
1916   }
1917   dest_peer_info =
1918       GNUNET_CONTAINER_multihashmap_get (peers, &pi[size - 1].hashPubKey);
1919   if (NULL == dest_peer_info)
1920   {
1921     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1922                 "MESH:   Creating PeerInfo for destination.\n");
1923     dest_peer_info = GNUNET_malloc (sizeof (struct MeshPeerInfo));
1924     dest_peer_info->id = GNUNET_PEER_intern (&pi[size - 1]);
1925     GNUNET_CONTAINER_multihashmap_put (peers, &pi[size - 1].hashPubKey,
1926                                        dest_peer_info,
1927                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
1928   }
1929   orig_peer_info = GNUNET_CONTAINER_multihashmap_get (peers, &pi->hashPubKey);
1930   if (NULL == orig_peer_info)
1931   {
1932     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1933                 "MESH:   Creating PeerInfo for origin.\n");
1934     orig_peer_info = GNUNET_malloc (sizeof (struct MeshPeerInfo));
1935     orig_peer_info->id = GNUNET_PEER_intern (pi);
1936     GNUNET_CONTAINER_multihashmap_put (peers, &pi->hashPubKey, orig_peer_info,
1937                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
1938   }
1939   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   Creating path...\n");
1940   path = path_new (size);
1941   own_pos = 0;
1942   for (i = 0; i < size; i++)
1943   {
1944     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1945                 "MESH:   ... adding %s\n",
1946                 GNUNET_i2s(&pi[i]));
1947     path->peers[i] = GNUNET_PEER_intern (&pi[i]);
1948     if (path->peers[i] == myid)
1949       own_pos = i;
1950   }
1951   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1952                 "MESH:   Own position: %u\n", own_pos);
1953   if (own_pos == 0)
1954   {
1955     /* cannot be self, must be 'not found' */
1956     /* create path: self not found in path through self */
1957     GNUNET_break_op (0);
1958     path_destroy (path);
1959     /* FIXME error. destroy tunnel? leave for timeout? */
1960     return 0;
1961   }
1962   tunnel_add_path (t, path, own_pos);
1963   t->tree->me = tree_find_peer(t->tree->root, myid);
1964   if (own_pos == size - 1)
1965   {
1966     /* It is for us! Send ack. */
1967     struct GNUNET_MESH_TunnelNotification cmsg;
1968     struct MeshDataDescriptor *info;
1969     unsigned int j;
1970
1971     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1972                 "MESH:   It's for us!\n");
1973     path_add_to_origin (orig_peer_info, path);
1974     info = GNUNET_malloc (sizeof (struct MeshDataDescriptor));
1975     info->origin = &t->id;
1976     info->peer = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
1977     GNUNET_assert (NULL != info->peer);
1978     for (j = 0; info->peer->core_transmit[j]; j++)
1979     {
1980       if (j == (CORE_QUEUE_SIZE - 1))
1981       {
1982         GNUNET_free (info);
1983         GNUNET_break (0);
1984         return GNUNET_OK;
1985       }
1986     }
1987     info->handler_n = j;
1988     info->peer->types[j] = GNUNET_MESSAGE_TYPE_MESH_PATH_ACK;
1989     info->peer->infos[j] = info;
1990     info->peer->core_transmit[j] =
1991         GNUNET_CORE_notify_transmit_ready (core_handle, 0, 100,
1992                                            GNUNET_TIME_UNIT_FOREVER_REL, peer,
1993                                            sizeof (struct GNUNET_MESH_PathACK),
1994                                            &send_core_path_ack, info);
1995     cmsg.header.size = htons(sizeof(cmsg));
1996     cmsg.header.type = htons(GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_CREATE);
1997     GNUNET_PEER_resolve(t->id.oid, &cmsg.peer);
1998     cmsg.tunnel_id = htonl(t->local_tid);
1999     GNUNET_SERVER_notification_context_broadcast(nc, &cmsg.header, GNUNET_NO);
2000   }
2001   else
2002   {
2003     struct MeshPeerPath *path2;
2004
2005     /* It's for somebody else! Retransmit. */
2006     path2 = path_duplicate(path);
2007     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2008                 "MESH:   Retransmitting.\n");
2009     path_add_to_peer(dest_peer_info, path);
2010     path = path_duplicate(path2);
2011     path_add_to_origin(orig_peer_info, path2);
2012     send_create_path(dest_peer_info, path, t);
2013   }
2014   return GNUNET_OK;
2015 }
2016
2017
2018 /**
2019  * Core handler for mesh network traffic going from the origin to a peer
2020  *
2021  * @param cls closure
2022  * @param peer peer identity this notification is about
2023  * @param message message
2024  * @param atsi performance data
2025  * @return GNUNET_OK to keep the connection open,
2026  *         GNUNET_SYSERR to close it (signal serious error)
2027  */
2028 static int
2029 handle_mesh_data_unicast (void *cls, const struct GNUNET_PeerIdentity *peer,
2030                           const struct GNUNET_MessageHeader *message,
2031                           const struct GNUNET_TRANSPORT_ATS_Information *atsi)
2032 {
2033   struct GNUNET_MESH_Unicast *msg;
2034   struct MeshTunnel *t;
2035   GNUNET_PEER_Id pid;
2036   size_t size;
2037
2038   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2039               "MESH: got a unicast packet from %s\n",
2040               GNUNET_i2s (peer));
2041   size = ntohs (message->size);
2042   if (size <
2043       sizeof (struct GNUNET_MESH_Unicast) +
2044       sizeof (struct GNUNET_MessageHeader))
2045   {
2046     GNUNET_break (0);
2047     return GNUNET_OK;
2048   }
2049   msg = (struct GNUNET_MESH_Unicast *) message;
2050   t = tunnel_get (&msg->oid, ntohl (msg->tid));
2051   if (NULL == t)
2052   {
2053     /* TODO notify back: we don't know this tunnel */
2054     GNUNET_break_op (0);
2055     return GNUNET_OK;
2056   }
2057   pid = GNUNET_PEER_search(&msg->destination);
2058   if (pid == myid)
2059   {
2060     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2061                 "MESH:   it's for us! sending to clients...\n");
2062     send_subscribed_clients ((struct GNUNET_MessageHeader *) &msg[1]);
2063     return GNUNET_OK;
2064   }
2065   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2066               "MESH:   not for us, retransmitting...\n");
2067   msg = GNUNET_malloc (size);
2068   memcpy (msg, message, size);
2069   GNUNET_CORE_notify_transmit_ready (core_handle, 0, 0,
2070                                      GNUNET_TIME_UNIT_FOREVER_REL,
2071                                      path_get_first_hop (t->tree, pid),
2072                                      size,
2073                                      &send_core_data_raw, msg);
2074   return GNUNET_OK;
2075 }
2076
2077
2078 /**
2079  * Core handler for mesh network traffic going from the origin to all peers
2080  *
2081  * @param cls closure
2082  * @param message message
2083  * @param peer peer identity this notification is about
2084  * @param atsi performance data
2085  * @return GNUNET_OK to keep the connection open,
2086  *         GNUNET_SYSERR to close it (signal serious error)
2087  *
2088  * TODO: Check who we got this from, to validate route.
2089  */
2090 static int
2091 handle_mesh_data_multicast (void *cls, const struct GNUNET_PeerIdentity *peer,
2092                             const struct GNUNET_MessageHeader *message,
2093                             const struct GNUNET_TRANSPORT_ATS_Information *atsi)
2094 {
2095   struct GNUNET_MESH_Multicast *msg;
2096   struct GNUNET_PeerIdentity *id;
2097   struct MeshDataDescriptor *info;
2098   struct MeshTunnelTreeNode *n;
2099   struct MeshTunnel *t;
2100   unsigned int *copies;
2101   unsigned int i;
2102   size_t size;
2103   void *data;
2104
2105   size = ntohs (message->size) - sizeof (struct GNUNET_MESH_Multicast);
2106   if (size < sizeof (struct GNUNET_MessageHeader))
2107   {
2108     GNUNET_break_op (0);
2109     return GNUNET_OK;
2110   }
2111   msg = (struct GNUNET_MESH_Multicast *) message;
2112   t = tunnel_get (&msg->oid, ntohl (msg->tid));
2113
2114   if (NULL == t)
2115   {
2116     /* TODO notify that we dont know that tunnel */
2117     GNUNET_break_op (0);
2118     return GNUNET_OK;
2119   }
2120
2121   /* Transmit to locally interested clients */
2122   if (GNUNET_CONTAINER_multihashmap_contains (t->peers, &my_full_id.hashPubKey))
2123   {
2124     send_subscribed_clients ((struct GNUNET_MessageHeader *) &msg[1]);
2125   }
2126   n = t->tree->me->children_head;
2127   if (NULL == n)
2128     return GNUNET_OK;
2129   copies = GNUNET_malloc (sizeof (unsigned int));
2130   for (*copies = 0; NULL != n; n = n->next)
2131     (*copies)++;
2132   n = t->tree->me->children_head;
2133   data = GNUNET_malloc (size);
2134   memcpy (data, &msg[1], size);
2135   while (NULL != n)
2136   {
2137     info = GNUNET_malloc (sizeof (struct MeshDataDescriptor));
2138     info->origin = &t->id;
2139     info->data = data;
2140     info->size = size;
2141     info->copies = copies;
2142     info->client = t->client->handle;
2143     info->destination = n->peer;
2144     id = path_get_first_hop(t->tree, n->peer);
2145     info->peer = peer_info_get(id);
2146     GNUNET_assert (NULL != info->peer);
2147     for (i = 0; NULL != info->peer->core_transmit[i]; i++)
2148     {
2149       if (i == (CORE_QUEUE_SIZE - 1))
2150       {
2151         GNUNET_free (info);
2152         GNUNET_break (0);
2153         return GNUNET_OK;
2154       }
2155     }
2156     info->handler_n = i;
2157     info->peer->infos[i] = info;
2158     info->peer->types[i] = GNUNET_MESSAGE_TYPE_MESH_MULTICAST;
2159     info->peer->core_transmit[i] =
2160         GNUNET_CORE_notify_transmit_ready (core_handle, 0, 0,
2161                                            GNUNET_TIME_UNIT_FOREVER_REL, id,
2162                                            ntohs (msg->header.size),
2163                                            &send_core_data_multicast, info);
2164   }
2165
2166   return GNUNET_OK;
2167 }
2168
2169
2170 /**
2171  * Core handler for mesh network traffic
2172  *
2173  * @param cls closure
2174  * @param message message
2175  * @param peer peer identity this notification is about
2176  * @param atsi performance data
2177  *
2178  * @return GNUNET_OK to keep the connection open,
2179  *         GNUNET_SYSERR to close it (signal serious error)
2180  */
2181 static int
2182 handle_mesh_data_to_orig (void *cls, const struct GNUNET_PeerIdentity *peer,
2183                           const struct GNUNET_MessageHeader *message,
2184                           const struct GNUNET_TRANSPORT_ATS_Information *atsi)
2185 {
2186   struct GNUNET_MESH_ToOrigin *msg;
2187   struct GNUNET_PeerIdentity id;
2188   struct MeshPeerInfo *peer_info;
2189   struct MeshTunnel *t;
2190   size_t size;
2191
2192   size = ntohs (message->size);
2193   if (size < sizeof (struct GNUNET_MESH_ToOrigin) +     /* Payload must be */
2194       sizeof (struct GNUNET_MessageHeader))     /* at least a header */
2195   {
2196     GNUNET_break_op (0);
2197     return GNUNET_OK;
2198   }
2199   msg = (struct GNUNET_MESH_ToOrigin *) message;
2200   t = tunnel_get (&msg->oid, ntohl (msg->tid));
2201
2202   if (NULL == t)
2203   {
2204     /* TODO notify that we dont know this tunnel (whom)? */
2205     return GNUNET_OK;
2206   }
2207
2208   if (t->id.oid == myid)
2209   {
2210     if (NULL == t->client)
2211     {
2212       /* got data packet for ownerless tunnel */
2213       GNUNET_break_op (0);
2214       return GNUNET_OK;
2215     }
2216     /* TODO signature verification */
2217     GNUNET_SERVER_notification_context_unicast (nc, t->client->handle, message,
2218                                                 GNUNET_YES);
2219     return GNUNET_OK;
2220   }
2221   peer_info = peer_info_get (&msg->oid);
2222   if (NULL == peer_info)
2223   {
2224     /* unknown origin of tunnel */
2225     GNUNET_break (0);
2226     return GNUNET_OK;
2227   }
2228   GNUNET_PEER_resolve (t->tree->me->parent->peer, &id);
2229   msg = GNUNET_malloc (size);
2230   memcpy (msg, message, size);
2231   GNUNET_CORE_notify_transmit_ready (core_handle, 0, 0,
2232                                      GNUNET_TIME_UNIT_FOREVER_REL, &id, size,
2233                                      &send_core_data_raw, msg);
2234
2235   return GNUNET_OK;
2236 }
2237
2238
2239 /**
2240  * Core handler for path ACKs
2241  *
2242  * @param cls closure
2243  * @param message message
2244  * @param peer peer identity this notification is about
2245  * @param atsi performance data
2246  *
2247  * @return GNUNET_OK to keep the connection open,
2248  *         GNUNET_SYSERR to close it (signal serious error)
2249  */
2250 static int
2251 handle_mesh_path_ack (void *cls, const struct GNUNET_PeerIdentity *peer,
2252                       const struct GNUNET_MessageHeader *message,
2253                       const struct GNUNET_TRANSPORT_ATS_Information *atsi)
2254 {
2255   struct GNUNET_MESH_PathACK *msg;
2256   struct GNUNET_PeerIdentity id;
2257   struct MeshTunnelTreeNode *n;
2258   struct MeshPeerInfo *peer_info;
2259   struct MeshTunnel *t;
2260
2261   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2262               "MESH: Received a path ACK msg [%s]\n",
2263               GNUNET_i2s(&my_full_id));
2264   msg = (struct GNUNET_MESH_PathACK *) message;
2265   t = tunnel_get (&msg->oid, msg->tid);
2266   if (NULL == t)
2267   {
2268     /* TODO notify that we don't know the tunnel */
2269     return GNUNET_OK;
2270   }
2271
2272   /* Message for us? */
2273   if (0 == memcmp (&msg->oid, &my_full_id, sizeof (struct GNUNET_PeerIdentity)))
2274   {
2275     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2276                 "MESH:   It's for us!\n");
2277     if (NULL == t->client)
2278     {
2279       GNUNET_break_op (0);
2280       return GNUNET_OK;
2281     }
2282     peer_info = peer_info_get (&msg->peer_id);
2283     if (NULL == peer_info)
2284     {
2285       GNUNET_break_op (0);
2286       return GNUNET_OK;
2287     }
2288     n = tree_find_peer(t->tree->root, peer_info->id);
2289     if (NULL == n)
2290     {
2291       GNUNET_break_op (0);
2292       return GNUNET_OK;
2293     }
2294     n->status = MESH_PEER_READY;
2295     send_client_peer_connected(t, peer_info->id);
2296     return GNUNET_OK;
2297   }
2298   
2299   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2300               "MESH:   not for us, retransmitting...\n");
2301   GNUNET_PEER_resolve(t->tree->me->parent->peer, &id);
2302   peer_info = peer_info_get (&msg->oid);
2303   if (NULL == peer_info)
2304   {
2305     /* If we know the tunnel, we should DEFINITELY know the peer */
2306     GNUNET_break (0);
2307     return GNUNET_OK;
2308   }
2309   msg = GNUNET_malloc (sizeof (struct GNUNET_MESH_PathACK));
2310   memcpy (msg, message, sizeof (struct GNUNET_MESH_PathACK));
2311   GNUNET_CORE_notify_transmit_ready (core_handle, 0, 0,
2312                                      GNUNET_TIME_UNIT_FOREVER_REL,
2313                                      &id,
2314                                      sizeof (struct GNUNET_MESH_PathACK),
2315                                      &send_core_data_raw, msg);
2316   return GNUNET_OK;
2317 }
2318
2319
2320 /**
2321  * Functions to handle messages from core
2322  */
2323 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
2324   {&handle_mesh_path_create, GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE, 0},
2325   {&handle_mesh_data_unicast, GNUNET_MESSAGE_TYPE_MESH_UNICAST, 0},
2326   {&handle_mesh_data_multicast, GNUNET_MESSAGE_TYPE_MESH_MULTICAST, 0},
2327   {&handle_mesh_data_to_orig, GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN, 0},
2328   {&handle_mesh_path_ack, GNUNET_MESSAGE_TYPE_MESH_PATH_ACK,
2329    sizeof (struct GNUNET_MESH_PathACK)},
2330   {NULL, 0, 0}
2331 };
2332
2333
2334
2335 /******************************************************************************/
2336 /****************       MESH LOCAL HANDLER HELPERS      ***********************/
2337 /******************************************************************************/
2338
2339 /**
2340  * deregister_app: iterator for removing each application registered by a client
2341  * 
2342  * @param cls closure
2343  * @param key the hash of the application id (used to access the hashmap)
2344  * @param value the value stored at the key (client)
2345  * 
2346  * @return GNUNET_OK on success
2347  */
2348 static int
2349 deregister_app (void *cls, const GNUNET_HashCode * key, void *value)
2350 {
2351   GNUNET_break (GNUNET_YES == 
2352       GNUNET_CONTAINER_multihashmap_remove (applications, key, value));
2353   return GNUNET_OK;
2354 }
2355
2356 #if LATER
2357 /**
2358  * notify_client_connection_failure: notify a client that the connection to the
2359  * requested remote peer is not possible (for instance, no route found)
2360  * Function called when the socket is ready to queue more data. "buf" will be
2361  * NULL and "size" zero if the socket was closed for writing in the meantime.
2362  *
2363  * @param cls closure
2364  * @param size number of bytes available in buf
2365  * @param buf where the callee should write the message
2366  * @return number of bytes written to buf
2367  */
2368 static size_t
2369 notify_client_connection_failure (void *cls, size_t size, void *buf)
2370 {
2371   int size_needed;
2372   struct MeshPeerInfo *peer_info;
2373   struct GNUNET_MESH_PeerControl *msg;
2374   struct GNUNET_PeerIdentity id;
2375
2376   if (0 == size && NULL == buf)
2377   {
2378     // TODO retry? cancel?
2379     return 0;
2380   }
2381
2382   size_needed = sizeof (struct GNUNET_MESH_PeerControl);
2383   peer_info = (struct MeshPeerInfo *) cls;
2384   msg = (struct GNUNET_MESH_PeerControl *) buf;
2385   msg->header.size = htons (sizeof (struct GNUNET_MESH_PeerControl));
2386   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_DISCONNECTED);
2387 //     msg->tunnel_id = htonl(peer_info->t->tid);
2388   GNUNET_PEER_resolve (peer_info->id, &id);
2389   memcpy (&msg->peer, &id, sizeof (struct GNUNET_PeerIdentity));
2390
2391   return size_needed;
2392 }
2393 #endif
2394
2395
2396 /**
2397  * Send keepalive packets for a peer
2398  *
2399  * @param cls Closure (tunnel for which to send the keepalive).
2400  * @param tc Notification context.
2401  *
2402  * TODO: implement explicit multicast keepalive?
2403  */
2404 void
2405 path_refresh (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2406 {
2407   struct MeshTunnel *t = cls;
2408   struct GNUNET_MessageHeader *payload;
2409   struct GNUNET_MESH_Multicast *msg;
2410   size_t size;
2411
2412   t->path_refresh_task = GNUNET_SCHEDULER_NO_TASK;
2413   if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
2414   {
2415     return;
2416   }
2417
2418   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2419               "MESH: sending keepalive for tunnel %d\n",
2420               t->id.tid);
2421
2422   size = sizeof(struct GNUNET_MESH_Multicast) +
2423          sizeof(struct GNUNET_MessageHeader);
2424   msg = GNUNET_malloc (size);
2425   msg->header.size = htons (size);
2426   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_MULTICAST);
2427   msg->oid = my_full_id;
2428   msg->tid = htonl(t->id.tid);
2429   payload = (struct GNUNET_MessageHeader *) &msg[1];
2430   payload->size = htons (sizeof(struct GNUNET_MessageHeader));
2431   payload->type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE);
2432   handle_mesh_data_multicast (NULL, &my_full_id, &msg->header, NULL);
2433
2434   GNUNET_free (msg);
2435   t->path_refresh_task =
2436       GNUNET_SCHEDULER_add_delayed (t->tree->refresh, &path_refresh, t);
2437   return;
2438 }
2439
2440
2441 /**
2442  * Function to process paths received for a new peer addition. The recorded
2443  * paths form the initial tunnel, which can be optimized later.
2444  * Called on each result obtained for the DHT search.
2445  *
2446  * @param cls closure
2447  * @param exp when will this value expire
2448  * @param key key of the result
2449  * @param type type of the result
2450  * @param size number of bytes in data
2451  * @param data pointer to the result data
2452  *
2453  * TODO: re-issue the request after certain time? cancel after X results?
2454  */
2455 static void
2456 dht_get_id_handler (void *cls, struct GNUNET_TIME_Absolute exp,
2457                     const GNUNET_HashCode * key,
2458                     const struct GNUNET_PeerIdentity *get_path,
2459                     unsigned int get_path_length,
2460                     const struct GNUNET_PeerIdentity *put_path,
2461                     unsigned int put_path_length,
2462                     enum GNUNET_BLOCK_Type type, size_t size, const void *data)
2463 {
2464   struct MeshPathInfo *path_info = cls;
2465   struct MeshPeerPath *p;
2466   struct GNUNET_PeerIdentity pi;
2467   int i;
2468
2469   GNUNET_PEER_resolve (path_info->peer->id, &pi);
2470   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2471              "MESH: Got results from DHT for %s\n",
2472              GNUNET_h2s_full(&pi.hashPubKey));
2473   GNUNET_DHT_get_stop(path_info->peer->dhtget);
2474   path_info->peer->dhtget = NULL;
2475
2476   p = path_build_from_dht (get_path, get_path_length,
2477                            put_path, put_path_length);
2478   path_add_to_peer (path_info->peer, p);
2479   for (i = 0; i < path_info->peer->ntunnels; i++)
2480   {
2481     tunnel_add_peer (path_info->peer->tunnels[i], path_info->peer);
2482     peer_info_connect(path_info->peer, path_info->t);
2483   }
2484   GNUNET_free (path_info);
2485
2486   return;
2487 }
2488
2489
2490 /**
2491  * Function to process paths received for a new peer addition. The recorded
2492  * paths form the initial tunnel, which can be optimized later.
2493  * Called on each result obtained for the DHT search.
2494  *
2495  * @param cls closure
2496  * @param exp when will this value expire
2497  * @param key key of the result
2498  * @param type type of the result
2499  * @param size number of bytes in data
2500  * @param data pointer to the result data
2501  */
2502 static void
2503 dht_get_type_handler (void *cls, struct GNUNET_TIME_Absolute exp,
2504                       const GNUNET_HashCode * key,
2505                       const struct GNUNET_PeerIdentity *get_path,
2506                       unsigned int get_path_length,
2507                       const struct GNUNET_PeerIdentity *put_path,
2508                       unsigned int put_path_length,
2509                       enum GNUNET_BLOCK_Type type, size_t size,
2510                       const void *data)
2511 {
2512   const struct GNUNET_PeerIdentity *pi = data;
2513   struct GNUNET_PeerIdentity id;
2514   struct MeshTunnel *t = cls;
2515   struct MeshPeerInfo *peer_info;
2516   struct MeshPathInfo *path_info;
2517   struct MeshPeerPath *p;
2518   int i;
2519
2520   if (size != sizeof (struct GNUNET_PeerIdentity))
2521   {
2522     GNUNET_break_op (0);
2523     return;
2524   }
2525   GNUNET_assert (NULL != t->client);
2526   GNUNET_DHT_get_stop (t->dht_get_type);
2527   t->dht_get_type = NULL;
2528   peer_info = peer_info_get (pi);
2529   GNUNET_CONTAINER_multihashmap_put (t->peers, &pi->hashPubKey, peer_info,
2530                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
2531
2532   if ((NULL == get_path || NULL == put_path) && NULL == peer_info->path_head &&
2533       NULL == peer_info->dhtget)
2534   {
2535     path_info = GNUNET_malloc (sizeof (struct MeshPathInfo));
2536     path_info->peer = peer_info;
2537     path_info->t = t;
2538     /* we don't have a route to the peer, let's try a direct lookup */
2539     peer_info->dhtget =
2540         GNUNET_DHT_get_start (dht_handle, /* handle */
2541                               GNUNET_TIME_UNIT_FOREVER_REL, /* timeout */
2542                               GNUNET_BLOCK_TYPE_TEST, /* block type */
2543                               &pi->hashPubKey, /* key to look up */
2544                               10U, /* replication level */
2545                               GNUNET_DHT_RO_RECORD_ROUTE |
2546                                 GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE,
2547                               /* option to dht: record route */
2548                               NULL,     /* xquery */
2549                               0,        /* xquery bits */
2550                               dht_get_id_handler,  /* callback */
2551                               path_info);       /* closure */
2552     return;
2553   }
2554
2555   p = path_build_from_dht (get_path, get_path_length, put_path, put_path_length);
2556   path_add_to_peer (peer_info, p);
2557   tunnel_add_peer(t, peer_info);
2558   p = tree_get_path_to_peer(t->tree, peer_info->id);
2559 #if MESH_DEBUG
2560   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2561               "MESH: new route for tunnel 0x%x found, has %u hops\n",
2562               t->local_tid, p->length);
2563   for (i = 0; i < p->length; i++)
2564   {
2565     GNUNET_PEER_resolve (p->peers[0], &id);
2566     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:\t%d\t%s\n", i,
2567                 GNUNET_h2s_full (&id.hashPubKey));
2568   }
2569 #endif
2570
2571   if (p->length > 1)
2572   {
2573     send_create_path(peer_info, p, t);
2574     return;
2575   }
2576   path_destroy(p);
2577   send_client_peer_connected(t, myid);
2578 }
2579
2580
2581 /******************************************************************************/
2582 /*********************       MESH LOCAL HANDLES      **************************/
2583 /******************************************************************************/
2584
2585
2586 /**
2587  * Handler for client disconnection
2588  *
2589  * @param cls closure
2590  * @param client identification of the client; NULL
2591  *        for the last call when the server is destroyed
2592  */
2593 static void
2594 handle_local_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
2595 {
2596   struct MeshClient *c;
2597   struct MeshClient *next;
2598
2599   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: client disconnected\n");
2600   if (client == NULL)
2601      GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:    (SERVER DOWN)\n");
2602   c = clients;
2603   while (NULL != c)
2604   {
2605     if (c->handle != client && NULL != client)
2606     {
2607       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:    ... searching\n");
2608       c = c->next;
2609       continue;
2610     }
2611     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: matching client found\n");
2612     if (NULL != c->tunnels)
2613     {
2614       GNUNET_CONTAINER_multihashmap_iterate (c->tunnels,
2615                                              &tunnel_destroy_iterator,
2616                                              c);
2617       GNUNET_CONTAINER_multihashmap_destroy (c->tunnels);
2618     }
2619
2620     /* deregister clients applications */
2621     if (NULL != c->apps)
2622     {
2623       GNUNET_CONTAINER_multihashmap_iterate (c->apps, &deregister_app, NULL);
2624       GNUNET_CONTAINER_multihashmap_destroy (c->apps);
2625     }
2626     if (0 == GNUNET_CONTAINER_multihashmap_size (applications) &&
2627         GNUNET_SCHEDULER_NO_TASK != announce_applications_task)
2628     {
2629       GNUNET_SCHEDULER_cancel (announce_applications_task);
2630       announce_applications_task = GNUNET_SCHEDULER_NO_TASK;
2631     }
2632     if (NULL != c->types)
2633       GNUNET_CONTAINER_multihashmap_destroy (c->types);
2634     GNUNET_CONTAINER_DLL_remove (clients, clients_tail, c);
2635     next = c->next;
2636     GNUNET_free (c);
2637     c = next;
2638   }
2639
2640   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:    done!\n");
2641   return;
2642 }
2643
2644
2645 /**
2646  * Handler for new clients
2647  *
2648  * @param cls closure
2649  * @param client identification of the client
2650  * @param message the actual message, which includes messages the client wants
2651  */
2652 static void
2653 handle_local_new_client (void *cls, struct GNUNET_SERVER_Client *client,
2654                          const struct GNUNET_MessageHeader *message)
2655 {
2656   struct GNUNET_MESH_ClientConnect *cc_msg;
2657   struct MeshClient *c;
2658   GNUNET_MESH_ApplicationType *a;
2659   unsigned int size;
2660   uint16_t ntypes;
2661   uint16_t *t;
2662   uint16_t napps;
2663   uint16_t i;
2664
2665   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: new client connected\n");
2666   /* Check data sanity */
2667   size = ntohs (message->size) - sizeof (struct GNUNET_MESH_ClientConnect);
2668   cc_msg = (struct GNUNET_MESH_ClientConnect *) message;
2669   ntypes = ntohs (cc_msg->types);
2670   napps = ntohs (cc_msg->applications);
2671   if (size !=
2672       ntypes * sizeof (uint16_t) + napps * sizeof (GNUNET_MESH_ApplicationType))
2673   {
2674     GNUNET_break (0);
2675     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2676     return;
2677   }
2678
2679   /* Create new client structure */
2680   c = GNUNET_malloc (sizeof (struct MeshClient));
2681 #if MESH_DEBUG
2682   c->id = next_client_id++;
2683 #endif
2684   c->handle = client;
2685   a = (GNUNET_MESH_ApplicationType *) &cc_msg[1];
2686   if (napps > 0)
2687   {
2688     GNUNET_MESH_ApplicationType at;
2689     GNUNET_HashCode hc;
2690
2691     c->apps = GNUNET_CONTAINER_multihashmap_create (napps);
2692     for (i = 0; i < napps; i++)
2693     {
2694       at = ntohl (a[i]);
2695       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   app type: %u\n", at);
2696       GNUNET_CRYPTO_hash (&at, sizeof (at), &hc);
2697       /* store in clients hashmap */
2698       GNUNET_CONTAINER_multihashmap_put (c->apps, &hc, c,
2699                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2700       /* store in global hashmap, for announcements */
2701       GNUNET_CONTAINER_multihashmap_put (applications, &hc, c,
2702                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2703     }
2704     if (GNUNET_SCHEDULER_NO_TASK == announce_applications_task)
2705       announce_applications_task =
2706           GNUNET_SCHEDULER_add_now (&announce_applications, NULL);
2707
2708   }
2709   if (ntypes > 0)
2710   {
2711     uint16_t u16;
2712     GNUNET_HashCode hc;
2713
2714     t = (uint16_t *) & a[napps];
2715     c->types = GNUNET_CONTAINER_multihashmap_create (ntypes);
2716     for (i = 0; i < ntypes; i++)
2717     {
2718       u16 = ntohs (t[i]);
2719       GNUNET_CRYPTO_hash (&u16, sizeof (u16), &hc);
2720
2721       /* store in clients hashmap */
2722       GNUNET_CONTAINER_multihashmap_put (c->types, &hc, c,
2723                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2724       /* store in global hashmap */
2725       GNUNET_CONTAINER_multihashmap_put (types, &hc, c,
2726                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2727     }
2728   }
2729   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2730               "MESH:  client has %u+%u subscriptions\n", napps, ntypes);
2731
2732   GNUNET_CONTAINER_DLL_insert (clients, clients_tail, c);
2733   c->tunnels = GNUNET_CONTAINER_multihashmap_create (32);
2734   GNUNET_SERVER_notification_context_add (nc, client);
2735
2736   GNUNET_SERVER_receive_done (client, GNUNET_OK);
2737 #if MESH_DEBUG
2738   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: new client processed\n");
2739 #endif
2740 }
2741
2742
2743 /**
2744  * Handler for requests of new tunnels
2745  *
2746  * @param cls closure
2747  * @param client identification of the client
2748  * @param message the actual message
2749  */
2750 static void
2751 handle_local_tunnel_create (void *cls, struct GNUNET_SERVER_Client *client,
2752                             const struct GNUNET_MessageHeader *message)
2753 {
2754   struct GNUNET_MESH_TunnelMessage *t_msg;
2755   struct MeshTunnel *t;
2756   struct MeshClient *c;
2757   GNUNET_HashCode hash;
2758
2759   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: new tunnel requested\n");
2760
2761   /* Sanity check for client registration */
2762   if (NULL == (c = client_get (client)))
2763   {
2764     GNUNET_break (0);
2765     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2766     return;
2767   }
2768 #if MESH_DEBUG
2769   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   by client %u\n", c->id);
2770 #endif
2771
2772   /* Message sanity check */
2773   if (sizeof (struct GNUNET_MESH_TunnelMessage) != ntohs (message->size))
2774   {
2775     GNUNET_break (0);
2776     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2777     return;
2778   }
2779
2780   t_msg = (struct GNUNET_MESH_TunnelMessage *) message;
2781   /* Sanity check for tunnel numbering */
2782   if (0 == (ntohl (t_msg->tunnel_id) & GNUNET_MESH_LOCAL_TUNNEL_ID_CLI))
2783   {
2784     GNUNET_break (0);
2785     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2786     return;
2787   }
2788   /* Sanity check for duplicate tunnel IDs */
2789   if (NULL != tunnel_get_by_local_id (c, ntohl (t_msg->tunnel_id)))
2790   {
2791     GNUNET_break (0);
2792     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2793     return;
2794   }
2795
2796   t = GNUNET_malloc (sizeof (struct MeshTunnel));
2797   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: CREATED TUNNEL at %p\n", t);
2798   while (NULL != tunnel_get_by_pi (myid, next_tid))
2799     next_tid = (next_tid + 1) & ~GNUNET_MESH_LOCAL_TUNNEL_ID_CLI;
2800   t->id.tid = next_tid++;
2801   t->id.oid = myid;
2802   t->local_tid = ntohl (t_msg->tunnel_id);
2803   t->client = c;
2804   t->peers = GNUNET_CONTAINER_multihashmap_create (32);
2805
2806   GNUNET_CRYPTO_hash (&t->local_tid, sizeof (MESH_TunnelNumber), &hash);
2807   if (GNUNET_OK !=
2808       GNUNET_CONTAINER_multihashmap_put (c->tunnels, &hash, t,
2809                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
2810   {
2811     GNUNET_break (0);
2812     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2813     return;
2814   }
2815
2816   GNUNET_CRYPTO_hash (&t->id, sizeof (struct MESH_TunnelID), &hash);
2817   if (GNUNET_OK !=
2818       GNUNET_CONTAINER_multihashmap_put (tunnels, &hash, t,
2819                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
2820   {
2821     GNUNET_break (0);
2822     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2823     return;
2824   }
2825   t->tree = tree_new (t, myid);
2826   t->tree->refresh = REFRESH_PATH_TIME;
2827   t->tree->root->status = MESH_PEER_READY;
2828   t->tree->me = t->tree->root;
2829
2830   GNUNET_SERVER_receive_done (client, GNUNET_OK);
2831   return;
2832 }
2833
2834
2835 /**
2836  * Handler for requests of deleting tunnels
2837  *
2838  * @param cls closure
2839  * @param client identification of the client
2840  * @param message the actual message
2841  */
2842 static void
2843 handle_local_tunnel_destroy (void *cls, struct GNUNET_SERVER_Client *client,
2844                              const struct GNUNET_MessageHeader *message)
2845 {
2846   struct GNUNET_MESH_TunnelMessage *tunnel_msg;
2847   struct MeshClient *c;
2848   struct MeshTunnel *t;
2849   MESH_TunnelNumber tid;
2850   GNUNET_HashCode hash;
2851
2852   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: destroying tunnel\n");
2853
2854   /* Sanity check for client registration */
2855   if (NULL == (c = client_get (client)))
2856   {
2857     GNUNET_break (0);
2858     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2859     return;
2860   }
2861   /* Message sanity check */
2862   if (sizeof (struct GNUNET_MESH_TunnelMessage) != ntohs (message->size))
2863   {
2864     GNUNET_break (0);
2865     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2866     return;
2867   }
2868 #if MESH_DEBUG
2869   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   by client %u\n", c->id);
2870 #endif
2871   tunnel_msg = (struct GNUNET_MESH_TunnelMessage *) message;
2872
2873   /* Retrieve tunnel */
2874   tid = ntohl (tunnel_msg->tunnel_id);
2875
2876   /* Remove from local id hashmap */
2877   GNUNET_CRYPTO_hash (&tid, sizeof (MESH_TunnelNumber), &hash);
2878   t = GNUNET_CONTAINER_multihashmap_get (c->tunnels, &hash);
2879   GNUNET_CONTAINER_multihashmap_remove (c->tunnels, &hash, t);
2880
2881   /* Remove from global id hashmap */
2882   GNUNET_CRYPTO_hash (&t->id, sizeof (struct MESH_TunnelID), &hash);
2883   GNUNET_break (GNUNET_YES == 
2884       GNUNET_CONTAINER_multihashmap_remove (tunnels, &hash, t));
2885
2886 //     notify_tunnel_destroy(t); FIXME
2887   tunnel_destroy(t);
2888   GNUNET_SERVER_receive_done (client, GNUNET_OK);
2889   return;
2890 }
2891
2892
2893 /**
2894  * Handler for connection requests to new peers
2895  *
2896  * @param cls closure
2897  * @param client identification of the client
2898  * @param message the actual message (PeerControl)
2899  */
2900 static void
2901 handle_local_connect_add (void *cls, struct GNUNET_SERVER_Client *client,
2902                           const struct GNUNET_MessageHeader *message)
2903 {
2904   struct GNUNET_MESH_PeerControl *peer_msg;
2905   struct MeshPeerInfo *peer_info;
2906   struct MeshClient *c;
2907   struct MeshTunnel *t;
2908   MESH_TunnelNumber tid;
2909
2910   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "MESH: Got connection request\n");
2911   /* Sanity check for client registration */
2912   if (NULL == (c = client_get (client)))
2913   {
2914     GNUNET_break (0);
2915     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2916     return;
2917   }
2918
2919   peer_msg = (struct GNUNET_MESH_PeerControl *) message;
2920   /* Sanity check for message size */
2921   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (peer_msg->header.size))
2922   {
2923     GNUNET_break (0);
2924     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2925     return;
2926   }
2927
2928   /* Tunnel exists? */
2929   tid = ntohl (peer_msg->tunnel_id);
2930   t = tunnel_get_by_local_id (c, tid);
2931   if (NULL == t)
2932   {
2933     GNUNET_break (0);
2934     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2935     return;
2936   }
2937
2938   /* Does client own tunnel? */
2939   if (t->client->handle != client)
2940   {
2941     GNUNET_break (0);
2942     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2943     return;
2944   }
2945   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "MESH:      for %s\n",
2946              GNUNET_h2s_full(&peer_msg->peer.hashPubKey));
2947   peer_info = peer_info_get (&peer_msg->peer);
2948
2949   tunnel_add_peer(t, peer_info);
2950   peer_info_connect(peer_info, t);
2951
2952   GNUNET_SERVER_receive_done (client, GNUNET_OK);
2953   return;
2954 }
2955
2956
2957 /**
2958  * Handler for disconnection requests of peers in a tunnel
2959  *
2960  * @param cls closure
2961  * @param client identification of the client
2962  * @param message the actual message (PeerControl)
2963  */
2964 static void
2965 handle_local_connect_del (void *cls, struct GNUNET_SERVER_Client *client,
2966                           const struct GNUNET_MessageHeader *message)
2967 {
2968   struct GNUNET_MESH_PeerControl *peer_msg;
2969   struct MeshClient *c;
2970   struct MeshTunnel *t;
2971   MESH_TunnelNumber tid;
2972
2973   /* Sanity check for client registration */
2974   if (NULL == (c = client_get (client)))
2975   {
2976     GNUNET_break (0);
2977     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2978     return;
2979   }
2980   peer_msg = (struct GNUNET_MESH_PeerControl *) message;
2981   /* Sanity check for message size */
2982   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (peer_msg->header.size))
2983   {
2984     GNUNET_break (0);
2985     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2986     return;
2987   }
2988
2989   /* Tunnel exists? */
2990   tid = ntohl (peer_msg->tunnel_id);
2991   t = tunnel_get_by_local_id (c, tid);
2992   if (NULL == t)
2993   {
2994     GNUNET_break (0);
2995     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2996     return;
2997   }
2998
2999   /* Does client own tunnel? */
3000   if (t->client->handle != client)
3001   {
3002     GNUNET_break (0);
3003     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3004     return;
3005   }
3006
3007   /* Ok, delete peer from tunnel */
3008   GNUNET_CONTAINER_multihashmap_remove_all (t->peers,
3009                                             &peer_msg->peer.hashPubKey);
3010
3011   GNUNET_SERVER_receive_done (client, GNUNET_OK);
3012   return;
3013 }
3014
3015
3016 /**
3017  * Handler for connection requests to new peers by type
3018  *
3019  * @param cls closure
3020  * @param client identification of the client
3021  * @param message the actual message (ConnectPeerByType)
3022  */
3023 static void
3024 handle_local_connect_by_type (void *cls, struct GNUNET_SERVER_Client *client,
3025                               const struct GNUNET_MessageHeader *message)
3026 {
3027   struct GNUNET_MESH_ConnectPeerByType *connect_msg;
3028   struct MeshClient *c;
3029   struct MeshTunnel *t;
3030   GNUNET_HashCode hash;
3031   MESH_TunnelNumber tid;
3032
3033   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: got connect by type request\n");
3034   /* Sanity check for client registration */
3035   if (NULL == (c = client_get (client)))
3036   {
3037     GNUNET_break (0);
3038     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3039     return;
3040   }
3041
3042   connect_msg = (struct GNUNET_MESH_ConnectPeerByType *) message;
3043   /* Sanity check for message size */
3044   if (sizeof (struct GNUNET_MESH_ConnectPeerByType) !=
3045       ntohs (connect_msg->header.size))
3046   {
3047     GNUNET_break (0);
3048     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3049     return;
3050   }
3051
3052   /* Tunnel exists? */
3053   tid = ntohl (connect_msg->tunnel_id);
3054   t = tunnel_get_by_local_id (c, tid);
3055   if (NULL == t)
3056   {
3057     GNUNET_break (0);
3058     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3059     return;
3060   }
3061
3062   /* Does client own tunnel? */
3063   if (t->client->handle != client)
3064   {
3065     GNUNET_break (0);
3066     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3067     return;
3068   }
3069
3070   /* Do WE have the service? */
3071   t->type = ntohl (connect_msg->type);
3072   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:  type requested: %u\n", t->type);
3073   GNUNET_CRYPTO_hash (&t->type, sizeof (GNUNET_MESH_ApplicationType), &hash);
3074   if (GNUNET_CONTAINER_multihashmap_contains (applications, &hash) ==
3075       GNUNET_YES)
3076   {
3077     /* Yes! Fast forward, add ourselves to the tunnel and send the
3078      * good news to the client
3079      */
3080     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:  available locally\n");
3081     GNUNET_CONTAINER_multihashmap_put (t->peers, &my_full_id.hashPubKey,
3082                                        peer_info_get (&my_full_id),
3083                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
3084
3085     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:  notifying client\n");
3086     send_client_peer_connected(t, myid);
3087     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:  Done\n");
3088     GNUNET_SERVER_receive_done (client, GNUNET_OK);
3089     return;
3090   }
3091   /* Ok, lets find a peer offering the service */
3092   if (NULL != t->dht_get_type)
3093   {
3094     GNUNET_DHT_get_stop (t->dht_get_type);
3095   }
3096   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:  looking in DHT for %s\n",
3097               GNUNET_h2s_full (&hash));
3098   t->dht_get_type =
3099       GNUNET_DHT_get_start (dht_handle,
3100                             GNUNET_TIME_UNIT_FOREVER_REL,
3101                             GNUNET_BLOCK_TYPE_TEST,
3102                             &hash,
3103                             10U,
3104                             GNUNET_DHT_RO_RECORD_ROUTE |
3105                               GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE,
3106                             NULL, 0,
3107                             &dht_get_type_handler, t);
3108
3109   GNUNET_SERVER_receive_done (client, GNUNET_OK);
3110   return;
3111 }
3112
3113
3114 /**
3115  * Handler for client traffic directed to one peer
3116  *
3117  * @param cls closure
3118  * @param client identification of the client
3119  * @param message the actual message
3120  */
3121 static void
3122 handle_local_unicast (void *cls, struct GNUNET_SERVER_Client *client,
3123                       const struct GNUNET_MessageHeader *message)
3124 {
3125   struct MeshClient *c;
3126   struct MeshTunnel *t;
3127   struct MeshPeerInfo *pi;
3128   struct GNUNET_MESH_Unicast *data_msg;
3129   MESH_TunnelNumber tid;
3130   size_t size;
3131
3132   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3133               "MESH: Got a unicast request from a client!\n");
3134
3135   /* Sanity check for client registration */
3136   if (NULL == (c = client_get (client)))
3137   {
3138     GNUNET_break (0);
3139     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3140     return;
3141   }
3142   data_msg = (struct GNUNET_MESH_Unicast *) message;
3143   /* Sanity check for message size */
3144   size = ntohs (message->size);
3145   if (sizeof (struct GNUNET_MESH_Unicast) +
3146       sizeof (struct GNUNET_MessageHeader) > size)
3147   {
3148     GNUNET_break (0);
3149     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3150     return;
3151   }
3152
3153   /* Tunnel exists? */
3154   tid = ntohl (data_msg->tid);
3155   t = tunnel_get_by_local_id (c, tid);
3156   if (NULL == t)
3157   {
3158     GNUNET_break (0);
3159     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3160     return;
3161   }
3162
3163   /*  Is it a local tunnel? Then, does client own the tunnel? */
3164   if (t->client->handle != NULL && t->client->handle != client)
3165   {
3166     GNUNET_break (0);
3167     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3168     return;
3169   }
3170
3171   pi = GNUNET_CONTAINER_multihashmap_get (t->peers,
3172                                           &data_msg->destination.hashPubKey);
3173   /* Is the selected peer in the tunnel? */
3174   if (NULL == pi)
3175   {
3176     GNUNET_break (0);
3177     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3178     return;
3179   }
3180
3181   /* Ok, everything is correct, send the message
3182    * (pretend we got it from a mesh peer)
3183    */
3184   {
3185     char buf[ntohs (message->size)];
3186     struct GNUNET_MESH_Unicast *copy;
3187
3188     /* Work around const limitation */
3189     copy = (struct GNUNET_MESH_Unicast *) buf;
3190     memcpy (buf, data_msg, size);
3191     copy->oid = my_full_id;
3192     copy->tid = htonl (t->id.tid);
3193     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3194                 "MESH:   calling generic handler...\n");
3195     handle_mesh_data_unicast (NULL, &my_full_id, &copy->header, NULL);
3196   }
3197   GNUNET_SERVER_receive_done (client, GNUNET_OK);
3198   return;
3199 }
3200
3201 /**
3202  * Handler for client traffic directed to all peers in a tunnel
3203  *
3204  * @param cls closure
3205  * @param client identification of the client
3206  * @param message the actual message
3207  */
3208 static void
3209 handle_local_multicast (void *cls, struct GNUNET_SERVER_Client *client,
3210                         const struct GNUNET_MessageHeader *message)
3211 {
3212   struct MeshClient *c;
3213   struct MeshTunnel *t;
3214   struct GNUNET_MESH_Multicast *data_msg;
3215   MESH_TunnelNumber tid;
3216
3217   /* Sanity check for client registration */
3218   if (NULL == (c = client_get (client)))
3219   {
3220     GNUNET_break (0);
3221     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3222     return;
3223   }
3224   data_msg = (struct GNUNET_MESH_Multicast *) message;
3225   /* Sanity check for message size */
3226   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (data_msg->header.size))
3227   {
3228     GNUNET_break (0);
3229     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3230     return;
3231   }
3232
3233   /* Tunnel exists? */
3234   tid = ntohl (data_msg->tid);
3235   t = tunnel_get_by_local_id (c, tid);
3236   if (NULL == t)
3237   {
3238     GNUNET_break (0);
3239     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3240     return;
3241   }
3242
3243   /* Does client own tunnel? */
3244   if (t->client->handle != client)
3245   {
3246     GNUNET_break (0);
3247     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3248     return;
3249   }
3250
3251   {
3252     char buf[ntohs(message->size)];
3253     struct GNUNET_MESH_Multicast *copy;
3254
3255     copy = (struct GNUNET_MESH_Multicast *)buf;
3256     memcpy(buf, message, ntohs(message->size));
3257     copy->oid = my_full_id;
3258     copy->tid = htonl(t->id.tid);
3259     handle_mesh_data_multicast(client, &my_full_id, &copy->header, NULL);
3260   }
3261
3262   /* receive done gets called when last copy is sent */
3263   return;
3264 }
3265
3266 /**
3267  * Functions to handle messages from clients
3268  */
3269 static struct GNUNET_SERVER_MessageHandler client_handlers[] = {
3270   {&handle_local_new_client, NULL, GNUNET_MESSAGE_TYPE_MESH_LOCAL_CONNECT, 0},
3271   {&handle_local_tunnel_create, NULL,
3272    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_CREATE,
3273    sizeof (struct GNUNET_MESH_TunnelMessage)},
3274   {&handle_local_tunnel_destroy, NULL,
3275    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_DESTROY,
3276    sizeof (struct GNUNET_MESH_TunnelMessage)},
3277   {&handle_local_connect_add, NULL,
3278    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD,
3279    sizeof (struct GNUNET_MESH_PeerControl)},
3280   {&handle_local_connect_del, NULL,
3281    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_DEL,
3282    sizeof (struct GNUNET_MESH_PeerControl)},
3283   {&handle_local_connect_by_type, NULL,
3284    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD_BY_TYPE,
3285    sizeof (struct GNUNET_MESH_ConnectPeerByType)},
3286   {&handle_local_unicast, NULL,
3287    GNUNET_MESSAGE_TYPE_MESH_UNICAST, 0},
3288   {&handle_local_unicast, NULL,
3289    GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN, 0},
3290   {&handle_local_multicast, NULL,
3291    GNUNET_MESSAGE_TYPE_MESH_MULTICAST, 0},
3292   {NULL, NULL, 0, 0}
3293 };
3294
3295
3296 /**
3297  * To be called on core init/fail.
3298  *
3299  * @param cls service closure
3300  * @param server handle to the server for this service
3301  * @param identity the public identity of this peer
3302  */
3303 static void
3304 core_init (void *cls, struct GNUNET_CORE_Handle *server,
3305            const struct GNUNET_PeerIdentity *identity)
3306 {
3307   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: Core init\n");
3308   core_handle = server;
3309   if (0 != memcmp(identity, &my_full_id, sizeof(my_full_id)) || NULL == server)
3310   {
3311     GNUNET_log(GNUNET_ERROR_TYPE_ERROR, _("MESH: Wrong CORE service\n"));
3312     GNUNET_SCHEDULER_shutdown();   
3313   }
3314   return;
3315 }
3316
3317 /**
3318  * Method called whenever a given peer connects.
3319  *
3320  * @param cls closure
3321  * @param peer peer identity this notification is about
3322  * @param atsi performance data for the connection
3323  */
3324 static void
3325 core_connect (void *cls, const struct GNUNET_PeerIdentity *peer,
3326               const struct GNUNET_TRANSPORT_ATS_Information *atsi)
3327 {
3328   struct MeshPeerInfo *peer_info;
3329   struct MeshPeerPath *path;
3330
3331 #if MESH_DEBUG_CONNECTION
3332   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: Peer connected\n");
3333   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:      %s\n",
3334               GNUNET_h2s(&my_full_id.hashPubKey));
3335 #endif
3336   peer_info = peer_info_get (peer);
3337   if (myid == peer_info->id)
3338   {
3339 #if MESH_DEBUG_CONNECTION
3340     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:      (self)\n");
3341 #endif
3342     return;
3343   }
3344 #if MESH_DEBUG_CONNECTION
3345   else
3346   {
3347     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:      %s\n",
3348                 GNUNET_h2s(&peer->hashPubKey));
3349   }
3350 #endif
3351   path = path_new (2);
3352   path->peers[0] = myid;
3353   path->peers[1] = peer_info->id;
3354   GNUNET_PEER_change_rc(myid, 1);
3355   GNUNET_PEER_change_rc(peer_info->id, 1);
3356   path_add_to_peer (peer_info, path);
3357   return;
3358 }
3359
3360 /**
3361  * Method called whenever a peer disconnects.
3362  *
3363  * @param cls closure
3364  * @param peer peer identity this notification is about
3365  */
3366 static void
3367 core_disconnect (void *cls, const struct GNUNET_PeerIdentity *peer)
3368 {
3369   struct MeshPeerInfo *pi;
3370   unsigned int i;
3371
3372 #if MESH_DEBUG_CONNECTION
3373   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: Peer disconnected\n");
3374 #endif
3375   pi = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
3376   if (NULL == pi)
3377   {
3378     GNUNET_break (0);
3379     return;
3380   }
3381   for (i = 0; i < CORE_QUEUE_SIZE; i++)
3382   {
3383     peer_info_cancel_transmission(pi, i);
3384   }
3385   path_remove_from_peer (pi, pi->id, myid);
3386 #if MESH_DEBUG_CONNECTION
3387   if (myid == pi->id)
3388   {
3389     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:      (self)\n");
3390   }
3391 #endif
3392   return;
3393 }
3394
3395
3396 /******************************************************************************/
3397 /************************      MAIN FUNCTIONS      ****************************/
3398 /******************************************************************************/
3399
3400 /**
3401  * Iterator over hash map entries.
3402  *
3403  * @param cls closure
3404  * @param key current key code
3405  * @param value value in the hash map
3406  * @return GNUNET_YES if we should continue to
3407  *         iterate,
3408  *         GNUNET_NO if not.
3409  */
3410 int
3411 shutdown_tunnel (void *cls, const GNUNET_HashCode * key, void *value)
3412 {
3413   struct MeshTunnel *t = value;
3414   tunnel_destroy(t);
3415   return GNUNET_YES;
3416 }
3417
3418 /**
3419  * Task run during shutdown.
3420  *
3421  * @param cls unused
3422  * @param tc unused
3423  */
3424 static void
3425 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3426 {
3427   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: shutting down\n");
3428   /* TODO: destroy tunnels? */
3429   if (core_handle != NULL)
3430   {
3431     GNUNET_CORE_disconnect (core_handle);
3432     core_handle = NULL;
3433   }
3434   GNUNET_CONTAINER_multihashmap_iterate(tunnels, &shutdown_tunnel, NULL);
3435   if (dht_handle != NULL)
3436   {
3437     GNUNET_DHT_disconnect (dht_handle);
3438     dht_handle = NULL;
3439   }
3440   if (nc != NULL)
3441   {
3442     GNUNET_SERVER_notification_context_destroy (nc);
3443     nc = NULL;
3444   }
3445   if (GNUNET_SCHEDULER_NO_TASK != announce_id_task)
3446   {
3447     GNUNET_SCHEDULER_cancel (announce_id_task);
3448     announce_id_task = GNUNET_SCHEDULER_NO_TASK;
3449   }
3450   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: shut down\n");
3451 }
3452
3453 /**
3454  * Process mesh requests.
3455  *
3456  * @param cls closure
3457  * @param server the initialized server
3458  * @param c configuration to use
3459  */
3460 static void
3461 run (void *cls, struct GNUNET_SERVER_Handle *server,
3462      const struct GNUNET_CONFIGURATION_Handle *c)
3463 {
3464   struct MeshPeerInfo *peer;
3465   struct MeshPeerPath *p;
3466   char *keyfile;
3467
3468   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: starting to run\n");
3469   server_handle = server;
3470   core_handle = GNUNET_CORE_connect (c, /* Main configuration */
3471                                      CORE_QUEUE_SIZE,   /* queue size */
3472                                      NULL,      /* Closure passed to MESH functions */
3473                                      &core_init,        /* Call core_init once connected */
3474                                      &core_connect,     /* Handle connects */
3475                                      &core_disconnect,  /* remove peers on disconnects */
3476                                      NULL,      /* Don't notify about all incoming messages */
3477                                      GNUNET_NO, /* For header only in notification */
3478                                      NULL,      /* Don't notify about all outbound messages */
3479                                      GNUNET_NO, /* For header-only out notification */
3480                                      core_handlers);    /* Register these handlers */
3481   if (core_handle == NULL)
3482   {
3483     GNUNET_break (0);
3484     GNUNET_SCHEDULER_shutdown ();
3485     return;
3486   }
3487
3488   if (GNUNET_OK !=
3489        GNUNET_CONFIGURATION_get_value_filename (c, "GNUNETD", "HOSTKEY",
3490                                                 &keyfile))
3491   {
3492     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3493                 _
3494                 ("Mesh service is lacking key configuration settings.  Exiting.\n"));
3495     GNUNET_SCHEDULER_shutdown ();
3496     return;
3497   }
3498   my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
3499   GNUNET_free (keyfile);
3500   if (my_private_key == NULL)
3501   {
3502     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3503                 _("Mesh service could not access hostkey.  Exiting.\n"));
3504     GNUNET_SCHEDULER_shutdown ();
3505     return;
3506   }
3507   GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
3508   GNUNET_CRYPTO_hash (&my_public_key, sizeof (my_public_key),
3509                       &my_full_id.hashPubKey);
3510   myid = GNUNET_PEER_intern (&my_full_id);
3511
3512   dht_handle = GNUNET_DHT_connect (c, 64);
3513   if (dht_handle == NULL)
3514   {
3515     GNUNET_break (0);
3516   }
3517
3518   next_tid = 0;
3519   next_local_tid = GNUNET_MESH_LOCAL_TUNNEL_ID_SERV;
3520
3521   tunnels = GNUNET_CONTAINER_multihashmap_create (32);
3522   peers = GNUNET_CONTAINER_multihashmap_create (32);
3523   applications = GNUNET_CONTAINER_multihashmap_create (32);
3524   types = GNUNET_CONTAINER_multihashmap_create (32);
3525
3526   GNUNET_SERVER_add_handlers (server_handle, client_handlers);
3527   nc = GNUNET_SERVER_notification_context_create (server_handle,
3528                                                   LOCAL_QUEUE_SIZE);
3529   GNUNET_SERVER_disconnect_notify (server_handle,
3530                                    &handle_local_client_disconnect,
3531                                    NULL);
3532
3533
3534   clients = NULL;
3535   clients_tail = NULL;
3536 #if MESH_DEBUG
3537   next_client_id = 0;
3538 #endif
3539
3540   announce_applications_task = GNUNET_SCHEDULER_NO_TASK;
3541   announce_id_task = GNUNET_SCHEDULER_add_now (&announce_id, cls);
3542
3543   /* Create a peer_info for the local peer */
3544   peer = peer_info_get(&my_full_id);
3545   p = path_new (1);
3546   p->peers[0] = myid;
3547   path_add_to_peer(peer, p);
3548
3549   /* Scheduled the task to clean up when shutdown is called */
3550   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
3551                                 NULL);
3552
3553   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: end of run()\n");
3554 }
3555
3556 /**
3557  * The main function for the mesh service.
3558  *
3559  * @param argc number of arguments from the command line
3560  * @param argv command line arguments
3561  * @return 0 ok, 1 on error
3562  */
3563 int
3564 main (int argc, char *const *argv)
3565 {
3566   int ret;
3567
3568 #if MESH_DEBUG
3569 //   fprintf (stderr, "main ()\n");
3570 #endif
3571   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: main()\n");
3572   ret =
3573       (GNUNET_OK ==
3574        GNUNET_SERVICE_run (argc, argv, "mesh", GNUNET_SERVICE_OPTION_NONE, &run,
3575                            NULL)) ? 0 : 1;
3576   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: main() END\n");
3577 #if MESH_DEBUG
3578 //   fprintf (stderr, "main () END\n");
3579 #endif
3580   return ret;
3581 }