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