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