Tweaked test configuration and log messages
[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: create path retransmit!\n");
1225     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   buf:  %p\n", buf);
1226     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   size: (%u/%u)\n",
1227                 size, size_needed);
1228     GNUNET_CORE_notify_transmit_ready (core_handle, 0, 0,
1229                                        GNUNET_TIME_UNIT_FOREVER_REL,
1230                                        path_get_first_hop (t->tree, peer->id),
1231                                        size_needed,
1232                                        &send_core_create_path,
1233                                        info);
1234     return 0;
1235   }
1236
1237   msg = (struct GNUNET_MESH_ManipulatePath *) buf;
1238   msg->header.size = htons (size_needed);
1239   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE);
1240   msg->tid = ntohl (t->id.tid);
1241
1242   peer_ptr = (struct GNUNET_PeerIdentity *) &msg[1];
1243   for (i = 0; i < p->length; i++)
1244   {
1245     GNUNET_PEER_resolve (p->peers[i], peer_ptr++);
1246   }
1247
1248   path_destroy (p);
1249   GNUNET_free (info);
1250
1251   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1252               "MESH: CREATE PATH (%u bytes long) sent!\n",
1253               size_needed);
1254   return size_needed;
1255 }
1256
1257
1258 #if LATER
1259 /**
1260  * Function called to notify a client about the socket
1261  * being ready to queue more data.  "buf" will be
1262  * NULL and "size" zero if the socket was closed for
1263  * writing in the meantime.
1264  *
1265  * @param cls closure (MeshDataDescriptor with all info to build packet)
1266  * @param size number of bytes available in buf
1267  * @param buf where the callee should write the message
1268  * @return number of bytes written to buf
1269  */
1270 static size_t
1271 send_core_data_to_origin (void *cls, size_t size, void *buf)
1272 {
1273   struct MeshDataDescriptor *info = cls;
1274   struct GNUNET_MESH_ToOrigin *msg = buf;
1275   size_t total_size;
1276
1277   GNUNET_assert (NULL != info);
1278   total_size = sizeof (struct GNUNET_MESH_ToOrigin) + info->size;
1279   GNUNET_assert (total_size < 65536);   /* UNIT16_MAX */
1280
1281   if (total_size > size)
1282   {
1283     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1284                 "not enough buffer to send data to origin\n");
1285     return 0;
1286   }
1287   msg->header.size = htons (total_size);
1288   msg->header.type = htons (GNUNET_MESSAGE_TYPE_DATA_MESSAGE_TO_ORIGIN);
1289   GNUNET_PEER_resolve (info->origin->oid, &msg->oid);
1290   msg->tid = htonl (info->origin->tid);
1291   if (0 != info->size)
1292   {
1293     memcpy (&msg[1], &info[1], info->size);
1294   }
1295   if (NULL != info->client)
1296   {
1297     GNUNET_SERVER_receive_done (info->client, GNUNET_OK);
1298   }
1299   GNUNET_free (info);
1300   return total_size;
1301 }
1302 #endif
1303
1304
1305 /**
1306  * Function called to notify a client about the socket
1307  * being ready to queue more data.  "buf" will be
1308  * NULL and "size" zero if the socket was closed for
1309  * writing in the meantime.
1310  *
1311  * @param cls closure (data itself)
1312  * @param size number of bytes available in buf
1313  * @param buf where the callee should write the message
1314  * 
1315  * @return number of bytes written to buf
1316  */
1317 static size_t
1318 send_core_data_multicast (void *cls, size_t size, void *buf)
1319 {
1320   struct MeshDataDescriptor *info = cls;
1321   struct GNUNET_MESH_Multicast *msg = buf;
1322   size_t total_size;
1323
1324   GNUNET_assert (NULL != info);
1325   GNUNET_assert (NULL != info->peer);
1326   total_size = info->size + sizeof (struct GNUNET_MESH_Multicast);
1327   GNUNET_assert (total_size < GNUNET_SERVER_MAX_MESSAGE_SIZE);
1328
1329   if (total_size > size)
1330   {
1331     /* Retry */
1332     struct GNUNET_PeerIdentity id;
1333
1334     GNUNET_PEER_resolve(info->peer->id, &id);
1335     info->peer->infos[info->handler_n] = info;
1336     info->peer->types[info->handler_n] = GNUNET_MESSAGE_TYPE_MESH_MULTICAST;
1337     info->peer->core_transmit[info->handler_n] =
1338       GNUNET_CORE_notify_transmit_ready (core_handle,
1339                                          0,
1340                                          0,
1341                                          GNUNET_TIME_UNIT_FOREVER_REL,
1342                                          &id,
1343                                          total_size,
1344                                          &send_core_data_multicast,
1345                                          info);
1346     return 0;
1347   }
1348   info->peer->core_transmit[info->handler_n] = NULL;
1349   info->peer->infos[info->handler_n] = NULL;
1350   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_MULTICAST);
1351   msg->header.size = htons (total_size);
1352   GNUNET_PEER_resolve (info->origin->oid, &msg->oid);
1353   msg->tid = htonl (info->origin->tid);
1354   memcpy (&msg[1], info->data, info->size);
1355   if (0 == --(*info->copies))
1356   {
1357     if (NULL != info->client)
1358     {
1359       /* FIXME One unresponsive neighbor (who doesn't "call" tmt_rdy) can lock
1360        *       the client from sending anything else to the service.
1361        *       - Call receive_done after certain timeout.
1362        *       - Here cancel the timeout.
1363        */
1364       GNUNET_SERVER_receive_done (info->client, GNUNET_OK);
1365     }
1366     GNUNET_free (info->data);
1367     GNUNET_free (info->copies);
1368   }
1369   GNUNET_free (info);
1370   return total_size;
1371 }
1372
1373
1374 /**
1375  * Function called to notify a client about the socket
1376  * being ready to queue more data.  "buf" will be
1377  * NULL and "size" zero if the socket was closed for
1378  * writing in the meantime.
1379  *
1380  * @param cls closure (MeshDataDescriptor)
1381  * @param size number of bytes available in buf
1382  * @param buf where the callee should write the message
1383  * @return number of bytes written to buf
1384  */
1385 static size_t
1386 send_core_path_ack (void *cls, size_t size, void *buf)
1387 {
1388   struct MeshDataDescriptor *info = cls;
1389   struct GNUNET_MESH_PathACK *msg = buf;
1390
1391   GNUNET_assert (NULL != info);
1392   if (info->peer)
1393   {
1394     info->peer->core_transmit[info->handler_n] = NULL;
1395   }
1396   if (sizeof (struct GNUNET_MESH_PathACK) > size)
1397   {
1398     GNUNET_break (0);
1399     return 0;
1400   }
1401   msg->header.size = htons (sizeof (struct GNUNET_MESH_PathACK));
1402   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_ACK);
1403   GNUNET_PEER_resolve (info->origin->oid, &msg->oid);
1404   msg->tid = htonl (info->origin->tid);
1405   msg->peer_id = my_full_id;
1406   GNUNET_free (info);
1407   /* TODO add signature */
1408
1409   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: PATH ACK sent!\n");
1410   return sizeof (struct GNUNET_MESH_PathACK);
1411 }
1412
1413
1414 /**
1415  * Function called to notify a client about the socket
1416  * being ready to queue more data.  "buf" will be
1417  * NULL and "size" zero if the socket was closed for
1418  * writing in the meantime.
1419  *
1420  * @param cls closure (data itself)
1421  * @param size number of bytes available in buf
1422  * @param buf where the callee should write the message
1423  * @return number of bytes written to buf
1424  */
1425 static size_t
1426 send_core_data_raw (void *cls, size_t size, void *buf)
1427 {
1428   struct GNUNET_MessageHeader *msg = cls;
1429   size_t total_size;
1430
1431   GNUNET_assert (NULL != msg);
1432   total_size = ntohs (msg->size);
1433
1434   if (total_size > size)
1435   {
1436     GNUNET_break (0);
1437     return 0;
1438   }
1439   memcpy (buf, msg, total_size);
1440   GNUNET_free (cls);
1441   return total_size;
1442 }
1443
1444
1445 #if LATER
1446 /**
1447  * Send another peer a notification to destroy a tunnel
1448  * @param cls The tunnel to destroy
1449  * @param size Size in the buffer
1450  * @param buf Memory where to put the data to transmit
1451  * @return Size of data put in buffer
1452  */
1453 static size_t
1454 send_p2p_tunnel_destroy (void *cls, size_t size, void *buf)
1455 {
1456   struct MeshTunnel *t = cls;
1457   struct MeshClient *c;
1458   struct GNUNET_MESH_TunnelMessage *msg;
1459
1460   c = t->client;
1461   msg = buf;
1462   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_DESTROY);
1463    /*FIXME*/ msg->header.size =
1464       htons (sizeof (struct GNUNET_MESH_TunnelMessage));
1465   msg->tunnel_id = htonl (t->id.tid);
1466
1467   tunnel_destroy (c, t);
1468   return sizeof (struct GNUNET_MESH_TunnelMessage);
1469 }
1470 #endif
1471
1472
1473 /**
1474  * Send the message to all clients that have subscribed to its type
1475  *
1476  * @param msg Pointer to the message itself
1477  * @return number of clients this message was sent to
1478  */
1479 static unsigned int
1480 send_subscribed_clients (struct GNUNET_MessageHeader *msg)
1481 {
1482   struct MeshClient *c;
1483   unsigned int count;
1484   uint16_t type;
1485
1486   type = ntohs (msg->type);
1487   for (count = 0, c = clients; c != NULL; c = c->next)
1488   {
1489     if (client_is_subscribed (type, c))
1490     {
1491       count++;
1492       GNUNET_SERVER_notification_context_unicast (nc, c->handle, msg,
1493                                                   GNUNET_YES);
1494     }
1495   }
1496   return count;
1497 }
1498
1499
1500
1501 /**
1502  * Notify the client that owns the tunnel that a peer has connected to it
1503  * 
1504  * @param t Tunnel whose owner to notify
1505  * @param id Short id of the peer that has connected
1506  */
1507 static void
1508 send_client_peer_connected (const struct MeshTunnel *t, const GNUNET_PEER_Id id)
1509 {
1510   struct GNUNET_MESH_PeerControl pc;
1511
1512   pc.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD);
1513   pc.header.size = htons (sizeof (struct GNUNET_MESH_PeerControl));
1514   pc.tunnel_id = htonl (t->local_tid);
1515   GNUNET_PEER_resolve (id, &pc.peer);
1516   GNUNET_SERVER_notification_context_unicast (nc, t->client->handle,
1517                                               &pc.header, GNUNET_NO);
1518 }
1519
1520
1521 /******************************************************************************/
1522 /********************      MESH NETWORK HANDLERS     **************************/
1523 /******************************************************************************/
1524
1525
1526 /**
1527  * Core handler for path creation
1528  * struct GNUNET_CORE_MessageHandler
1529  *
1530  * @param cls closure
1531  * @param message message
1532  * @param peer peer identity this notification is about
1533  * @param atsi performance data
1534  * @return GNUNET_OK to keep the connection open,
1535  *         GNUNET_SYSERR to close it (signal serious error)
1536  *
1537  */
1538 static int
1539 handle_mesh_path_create (void *cls, const struct GNUNET_PeerIdentity *peer,
1540                          const struct GNUNET_MessageHeader *message,
1541                          const struct GNUNET_TRANSPORT_ATS_Information *atsi)
1542 {
1543   unsigned int own_pos;
1544   uint16_t size;
1545   uint16_t i;
1546   MESH_TunnelNumber tid;
1547   struct GNUNET_MESH_ManipulatePath *msg;
1548   struct GNUNET_PeerIdentity *pi;
1549   struct GNUNET_PeerIdentity id;
1550   GNUNET_HashCode hash;
1551   struct MeshPeerPath *path;
1552   struct MeshPeerInfo *dest_peer_info;
1553   struct MeshPeerInfo *orig_peer_info;
1554   struct MeshTunnel *t;
1555
1556   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1557               "MESH: Received a path create msg\n");
1558   size = ntohs (message->size);
1559   if (size < sizeof (struct GNUNET_MESH_ManipulatePath))
1560   {
1561     GNUNET_break_op (0);
1562     return GNUNET_OK;
1563   }
1564
1565   size -= sizeof (struct GNUNET_MESH_ManipulatePath);
1566   if (size % sizeof (struct GNUNET_PeerIdentity))
1567   {
1568     GNUNET_break_op (0);
1569     return GNUNET_OK;
1570   }
1571   size /= sizeof (struct GNUNET_PeerIdentity);
1572   if (size < 2)
1573   {
1574     GNUNET_break_op (0);
1575     return GNUNET_OK;
1576   }
1577   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1578               "MESH:     path as %u hops.\n",
1579               size);
1580   msg = (struct GNUNET_MESH_ManipulatePath *) message;
1581
1582   tid = ntohl (msg->tid);
1583   pi = (struct GNUNET_PeerIdentity *) &msg[1];
1584   t = tunnel_get (pi, tid);
1585   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1586               "MESH:     path as for tunnel %s [%X].\n",
1587               GNUNET_i2s(pi),
1588               tid);
1589   if (NULL == t)
1590   {
1591     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   Creating tunnel\n");
1592     t = GNUNET_malloc (sizeof (struct MeshTunnel));
1593     t->id.oid = GNUNET_PEER_intern (pi);
1594     t->id.tid = tid;
1595     t->peers = GNUNET_CONTAINER_multihashmap_create (32);
1596
1597     GNUNET_CRYPTO_hash (&t->id, sizeof (struct MESH_TunnelID), &hash);
1598     if (GNUNET_OK !=
1599         GNUNET_CONTAINER_multihashmap_put (tunnels, &hash, t,
1600                                            GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
1601     {
1602       GNUNET_break (0);
1603       return GNUNET_OK;
1604     }
1605   }
1606   dest_peer_info =
1607       GNUNET_CONTAINER_multihashmap_get (peers, &pi[size - 1].hashPubKey);
1608   if (NULL == dest_peer_info)
1609   {
1610     dest_peer_info = GNUNET_malloc (sizeof (struct MeshPeerInfo));
1611     dest_peer_info->id = GNUNET_PEER_intern (&pi[size - 1]);
1612     GNUNET_CONTAINER_multihashmap_put (peers, &pi[size - 1].hashPubKey,
1613                                        dest_peer_info,
1614                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
1615   }
1616   orig_peer_info = GNUNET_CONTAINER_multihashmap_get (peers, &pi->hashPubKey);
1617   if (NULL == orig_peer_info)
1618   {
1619     orig_peer_info = GNUNET_malloc (sizeof (struct MeshPeerInfo));
1620     orig_peer_info->id = GNUNET_PEER_intern (pi);
1621     GNUNET_CONTAINER_multihashmap_put (peers, &pi->hashPubKey, orig_peer_info,
1622                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
1623   }
1624
1625   path = path_new (size);
1626   own_pos = 0;
1627   for (i = 0; i < size; i++)
1628   {
1629     path->peers[i] = GNUNET_PEER_intern (&pi[i]);
1630     if (path->peers[i] == myid)
1631       own_pos = i;
1632   }
1633   if (own_pos == 0)
1634   {                             /* cannot be self, must be 'not found' */
1635     /* create path: self not found in path through self */
1636     GNUNET_break_op (0);
1637     path_destroy (path);
1638     /* FIXME error. destroy tunnel? leave for timeout? */
1639     return 0;
1640   }
1641   if (own_pos == size - 1)
1642   {
1643     /* It is for us! Send ack. */
1644     struct MeshDataDescriptor *info;
1645     unsigned int j;
1646
1647     path_add_to_origin (orig_peer_info, path);  /* inverts path!  */
1648     info = GNUNET_malloc (sizeof (struct MeshDataDescriptor));
1649     info->origin = &t->id;
1650     info->peer = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
1651     GNUNET_assert (NULL != info->peer);
1652     for (j = 0; info->peer->core_transmit[j]; j++)
1653     {
1654       if (j == (CORE_QUEUE_SIZE - 1))
1655       {
1656         GNUNET_break (0);
1657         return GNUNET_OK;
1658       }
1659     }
1660     info->handler_n = j;
1661     info->peer->core_transmit[j] =
1662         GNUNET_CORE_notify_transmit_ready (core_handle, 0, 100,
1663                                            GNUNET_TIME_UNIT_FOREVER_REL, peer,
1664                                            sizeof (struct GNUNET_MESH_PathACK),
1665                                            &send_core_path_ack, info);
1666   }
1667   else
1668   {
1669     /* It's for somebody else! Retransmit. */
1670     struct MeshPathInfo *path_info;
1671
1672     path_info = GNUNET_malloc (sizeof (struct MeshPathInfo));
1673     path_info->t = t;
1674     path_info->path = path;
1675     path_info->peer = dest_peer_info;
1676
1677     path_add_to_peer (dest_peer_info, path);
1678     GNUNET_PEER_resolve (path->peers[own_pos + 1], &id);
1679     GNUNET_CORE_notify_transmit_ready (
1680         core_handle,
1681         0,
1682         0,
1683         GNUNET_TIME_UNIT_FOREVER_REL,
1684         &id,
1685         sizeof (struct GNUNET_MESH_ManipulatePath) +
1686         path->length * sizeof(struct GNUNET_PeerIdentity),
1687         &send_core_create_path,
1688         path_info);
1689   }
1690   return GNUNET_OK;
1691 }
1692
1693
1694 /**
1695  * Core handler for mesh network traffic going from the origin to a peer
1696  *
1697  * @param cls closure
1698  * @param peer peer identity this notification is about
1699  * @param message message
1700  * @param atsi performance data
1701  * @return GNUNET_OK to keep the connection open,
1702  *         GNUNET_SYSERR to close it (signal serious error)
1703  */
1704 static int
1705 handle_mesh_data_unicast (void *cls, const struct GNUNET_PeerIdentity *peer,
1706                           const struct GNUNET_MessageHeader *message,
1707                           const struct GNUNET_TRANSPORT_ATS_Information *atsi)
1708 {
1709   struct GNUNET_MESH_Unicast *msg;
1710   struct MeshTunnel *t;
1711   struct MeshPeerInfo *pi;
1712   size_t size;
1713
1714   size = ntohs (message->size);
1715   if (size <
1716       sizeof (struct GNUNET_MESH_Unicast) +
1717       sizeof (struct GNUNET_MessageHeader))
1718   {
1719     GNUNET_break (0);
1720     return GNUNET_OK;
1721   }
1722   msg = (struct GNUNET_MESH_Unicast *) message;
1723   t = tunnel_get (&msg->oid, ntohl (msg->tid));
1724   if (NULL == t)
1725   {
1726     /* TODO notify back: we don't know this tunnel */
1727     GNUNET_break_op (0);
1728     return GNUNET_OK;
1729   }
1730   pi = GNUNET_CONTAINER_multihashmap_get (t->peers,
1731                                           &msg->destination.hashPubKey);
1732   if (NULL == pi)
1733   {
1734     /* TODO maybe feedback, log to statistics */
1735     GNUNET_break_op (0);
1736     return GNUNET_OK;
1737   }
1738   if (pi->id == myid)
1739   {
1740     send_subscribed_clients ((struct GNUNET_MessageHeader *) &msg[1]);
1741     return GNUNET_OK;
1742   }
1743   msg = GNUNET_malloc (size);
1744   memcpy (msg, message, size);
1745   GNUNET_CORE_notify_transmit_ready (core_handle, 0, 0,
1746                                      GNUNET_TIME_UNIT_FOREVER_REL,
1747                                      path_get_first_hop (t->tree, pi->id),
1748                                      size,
1749                                      &send_core_data_raw, msg);
1750   return GNUNET_OK;
1751 }
1752
1753
1754 /**
1755  * Core handler for mesh network traffic going from the origin to all peers
1756  *
1757  * @param cls closure
1758  * @param message message
1759  * @param peer peer identity this notification is about
1760  * @param atsi performance data
1761  * @return GNUNET_OK to keep the connection open,
1762  *         GNUNET_SYSERR to close it (signal serious error)
1763  *
1764  * TODO: Check who we got this from, to validate route.
1765  */
1766 static int
1767 handle_mesh_data_multicast (void *cls, const struct GNUNET_PeerIdentity *peer,
1768                             const struct GNUNET_MessageHeader *message,
1769                             const struct GNUNET_TRANSPORT_ATS_Information *atsi)
1770 {
1771   struct GNUNET_MESH_Multicast *msg;
1772   struct GNUNET_PeerIdentity *id;
1773   struct MeshDataDescriptor *info;
1774   struct MeshTunnelTreeNode *n;
1775   struct MeshTunnel *t;
1776   unsigned int *copies;
1777   unsigned int i;
1778   size_t size;
1779   void *data;
1780
1781   size = ntohs (message->size) - sizeof (struct GNUNET_MESH_Multicast);
1782   if (size < sizeof (struct GNUNET_MessageHeader))
1783   {
1784     GNUNET_break_op (0);
1785     return GNUNET_OK;
1786   }
1787   msg = (struct GNUNET_MESH_Multicast *) message;
1788   t = tunnel_get (&msg->oid, ntohl (msg->tid));
1789
1790   if (NULL == t)
1791   {
1792     /* TODO notify that we dont know that tunnel */
1793     GNUNET_break_op (0);
1794     return GNUNET_OK;
1795   }
1796
1797   /* Transmit to locally interested clients */
1798   if (GNUNET_CONTAINER_multihashmap_contains (t->peers, &my_full_id.hashPubKey))
1799   {
1800     send_subscribed_clients ((struct GNUNET_MessageHeader *) &msg[1]);
1801   }
1802   n = t->tree->me->children_head;
1803   if (NULL == n)
1804     return GNUNET_OK;
1805   copies = GNUNET_malloc (sizeof (unsigned int));
1806   for (*copies = 0; NULL != n; n = n->next)
1807     (*copies)++;
1808   n = t->tree->me->children_head;
1809   data = GNUNET_malloc (size);
1810   memcpy (data, &msg[1], size);
1811   while (NULL != n)
1812   {
1813     info = GNUNET_malloc (sizeof (struct MeshDataDescriptor));
1814     info->origin = &t->id;
1815     info->data = data;
1816     info->size = size;
1817     info->copies = copies;
1818     info->client = t->client->handle;
1819     info->destination = n->peer;
1820     id = path_get_first_hop(t->tree, n->peer);
1821     info->peer = peer_info_get(id);
1822     GNUNET_assert (NULL != info->peer);
1823     for (i = 0; NULL != info->peer->core_transmit[i]; i++)
1824     {
1825       if (i == (CORE_QUEUE_SIZE - 1))
1826       {
1827         GNUNET_break (0);
1828         return GNUNET_OK;
1829       }
1830     }
1831     info->handler_n = i;
1832     info->peer->infos[i] = info;
1833     info->peer->types[i] = GNUNET_MESSAGE_TYPE_MESH_MULTICAST;
1834     info->peer->core_transmit[i] =
1835         GNUNET_CORE_notify_transmit_ready (core_handle, 0, 0,
1836                                            GNUNET_TIME_UNIT_FOREVER_REL, id,
1837                                            ntohs (msg->header.size),
1838                                            &send_core_data_multicast, info);
1839   }
1840
1841   return GNUNET_OK;
1842 }
1843
1844
1845 /**
1846  * Core handler for mesh network traffic
1847  *
1848  * @param cls closure
1849  * @param message message
1850  * @param peer peer identity this notification is about
1851  * @param atsi performance data
1852  *
1853  * @return GNUNET_OK to keep the connection open,
1854  *         GNUNET_SYSERR to close it (signal serious error)
1855  */
1856 static int
1857 handle_mesh_data_to_orig (void *cls, const struct GNUNET_PeerIdentity *peer,
1858                           const struct GNUNET_MessageHeader *message,
1859                           const struct GNUNET_TRANSPORT_ATS_Information *atsi)
1860 {
1861   struct GNUNET_MESH_ToOrigin *msg;
1862   struct GNUNET_PeerIdentity id;
1863   struct MeshPeerInfo *peer_info;
1864   struct MeshTunnel *t;
1865   size_t size;
1866
1867   size = ntohs (message->size);
1868   if (size < sizeof (struct GNUNET_MESH_ToOrigin) +     /* Payload must be */
1869       sizeof (struct GNUNET_MessageHeader))     /* at least a header */
1870   {
1871     GNUNET_break_op (0);
1872     return GNUNET_OK;
1873   }
1874   msg = (struct GNUNET_MESH_ToOrigin *) message;
1875   t = tunnel_get (&msg->oid, ntohl (msg->tid));
1876
1877   if (NULL == t)
1878   {
1879     /* TODO notify that we dont know this tunnel (whom)? */
1880     return GNUNET_OK;
1881   }
1882
1883   if (t->id.oid == myid)
1884   {
1885     if (NULL == t->client)
1886     {
1887       /* got data packet for ownerless tunnel */
1888       GNUNET_break_op (0);
1889       return GNUNET_OK;
1890     }
1891     /* TODO signature verification */
1892     GNUNET_SERVER_notification_context_unicast (nc, t->client->handle, message,
1893                                                 GNUNET_YES);
1894     return GNUNET_OK;
1895   }
1896   peer_info = peer_info_get (&msg->oid);
1897   if (NULL == peer_info)
1898   {
1899     /* unknown origin of tunnel */
1900     GNUNET_break (0);
1901     return GNUNET_OK;
1902   }
1903   GNUNET_PEER_resolve (t->tree->me->parent->peer, &id);
1904   msg = GNUNET_malloc (size);
1905   memcpy (msg, message, size);
1906   GNUNET_CORE_notify_transmit_ready (core_handle, 0, 0,
1907                                      GNUNET_TIME_UNIT_FOREVER_REL, &id, size,
1908                                      &send_core_data_raw, msg);
1909
1910   return GNUNET_OK;
1911 }
1912
1913
1914 /**
1915  * Core handler for path ACKs
1916  *
1917  * @param cls closure
1918  * @param message message
1919  * @param peer peer identity this notification is about
1920  * @param atsi performance data
1921  *
1922  * @return GNUNET_OK to keep the connection open,
1923  *         GNUNET_SYSERR to close it (signal serious error)
1924  */
1925 static int
1926 handle_mesh_path_ack (void *cls, const struct GNUNET_PeerIdentity *peer,
1927                       const struct GNUNET_MessageHeader *message,
1928                       const struct GNUNET_TRANSPORT_ATS_Information *atsi)
1929 {
1930   struct GNUNET_MESH_PathACK *msg;
1931   struct MeshTunnelTreeNode *n;
1932   struct MeshPeerInfo *peer_info;
1933   struct MeshTunnel *t;
1934
1935   msg = (struct GNUNET_MESH_PathACK *) message;
1936   t = tunnel_get (&msg->oid, msg->tid);
1937   if (NULL == t)
1938   {
1939     /* TODO notify that we don't know the tunnel */
1940     return GNUNET_OK;
1941   }
1942
1943   /* Message for us? */
1944   if (0 == memcmp (&msg->oid, &my_full_id, sizeof (struct GNUNET_PeerIdentity)))
1945   {
1946     if (NULL == t->client)
1947     {
1948       GNUNET_break_op (0);
1949       return GNUNET_OK;
1950     }
1951     peer_info = peer_info_get (&msg->peer_id);
1952     if (NULL == peer_info)
1953     {
1954       GNUNET_break_op (0);
1955       return GNUNET_OK;
1956     }
1957     n = tree_find_peer(t->tree->root, peer_info->id);
1958     if (NULL == n)
1959     {
1960       GNUNET_break_op (0);
1961       return GNUNET_OK;
1962     }
1963     n->status = MESH_PEER_READY;
1964     send_client_peer_connected(t, peer_info->id);
1965     return GNUNET_OK;
1966   }
1967
1968   peer_info = peer_info_get (&msg->oid);
1969   if (NULL == peer_info)
1970   {
1971     /* If we know the tunnel, we should DEFINITELY know the peer */
1972     GNUNET_break (0);
1973     return GNUNET_OK;
1974   }
1975   msg = GNUNET_malloc (sizeof (struct GNUNET_MESH_PathACK));
1976   memcpy (msg, message, sizeof (struct GNUNET_MESH_PathACK));
1977   GNUNET_CORE_notify_transmit_ready (core_handle, 0, 0,
1978                                      GNUNET_TIME_UNIT_FOREVER_REL,
1979                                      path_get_first_hop (t->tree,
1980                                                          peer_info->id),
1981                                      sizeof (struct GNUNET_MESH_PathACK),
1982                                      &send_core_data_raw, msg);
1983   return GNUNET_OK;
1984 }
1985
1986
1987 /**
1988  * Functions to handle messages from core
1989  */
1990 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
1991   {&handle_mesh_path_create, GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE, 0},
1992   {&handle_mesh_data_unicast, GNUNET_MESSAGE_TYPE_MESH_UNICAST, 0},
1993   {&handle_mesh_data_multicast, GNUNET_MESSAGE_TYPE_MESH_MULTICAST, 0},
1994   {&handle_mesh_data_to_orig, GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN, 0},
1995   {&handle_mesh_path_ack, GNUNET_MESSAGE_TYPE_MESH_PATH_ACK,
1996    sizeof (struct GNUNET_MESH_PathACK)},
1997   {NULL, 0, 0}
1998 };
1999
2000
2001
2002 /******************************************************************************/
2003 /****************       MESH LOCAL HANDLER HELPERS      ***********************/
2004 /******************************************************************************/
2005
2006 /**
2007  * deregister_app: iterator for removing each application registered by a client
2008  * 
2009  * @param cls closure
2010  * @param key the hash of the application id (used to access the hashmap)
2011  * @param value the value stored at the key (client)
2012  * 
2013  * @return GNUNET_OK on success
2014  */
2015 static int
2016 deregister_app (void *cls, const GNUNET_HashCode * key, void *value)
2017 {
2018   GNUNET_CONTAINER_multihashmap_remove (applications, key, value);
2019   return GNUNET_OK;
2020 }
2021
2022 #if LATER
2023 /**
2024  * notify_client_connection_failure: notify a client that the connection to the
2025  * requested remote peer is not possible (for instance, no route found)
2026  * Function called when the socket is ready to queue more data. "buf" will be
2027  * NULL and "size" zero if the socket was closed for writing in the meantime.
2028  *
2029  * @param cls closure
2030  * @param size number of bytes available in buf
2031  * @param buf where the callee should write the message
2032  * @return number of bytes written to buf
2033  */
2034 static size_t
2035 notify_client_connection_failure (void *cls, size_t size, void *buf)
2036 {
2037   int size_needed;
2038   struct MeshPeerInfo *peer_info;
2039   struct GNUNET_MESH_PeerControl *msg;
2040   struct GNUNET_PeerIdentity id;
2041
2042   if (0 == size && NULL == buf)
2043   {
2044     // TODO retry? cancel?
2045     return 0;
2046   }
2047
2048   size_needed = sizeof (struct GNUNET_MESH_PeerControl);
2049   peer_info = (struct MeshPeerInfo *) cls;
2050   msg = (struct GNUNET_MESH_PeerControl *) buf;
2051   msg->header.size = htons (sizeof (struct GNUNET_MESH_PeerControl));
2052   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_DISCONNECTED);
2053 //     msg->tunnel_id = htonl(peer_info->t->tid);
2054   GNUNET_PEER_resolve (peer_info->id, &id);
2055   memcpy (&msg->peer, &id, sizeof (struct GNUNET_PeerIdentity));
2056
2057   return size_needed;
2058 }
2059 #endif
2060
2061
2062 /**
2063  * Send keepalive packets for a peer
2064  *
2065  * @param cls Closure (tunnel for which to send the keepalive).
2066  * @param tc Notification context.
2067  *
2068  * TODO: implement explicit multicast keepalive?
2069  */
2070 void
2071 path_refresh (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2072 {
2073   struct MeshTunnel *t = cls;
2074   struct GNUNET_MessageHeader *payload;
2075   struct GNUNET_MESH_Multicast *msg;
2076   size_t size;
2077
2078   t->path_refresh_task = GNUNET_SCHEDULER_NO_TASK;
2079   if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
2080   {
2081     return;
2082   }
2083
2084   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2085               "MESH: sending keepalive for tunnel %d\n",
2086               t->id.tid);
2087
2088   size = sizeof(struct GNUNET_MESH_Multicast) +
2089          sizeof(struct GNUNET_MessageHeader);
2090   msg = GNUNET_malloc (size);
2091   msg->header.size = htons (size);
2092   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_MULTICAST);
2093   msg->oid = my_full_id;
2094   msg->tid = htonl(t->id.tid);
2095   payload = (struct GNUNET_MessageHeader *) &msg[1];
2096   payload->size = htons (sizeof(struct GNUNET_MessageHeader));
2097   payload->type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE);
2098   handle_mesh_data_multicast (NULL, &my_full_id, &msg->header, NULL);
2099
2100   GNUNET_free (msg);
2101   t->path_refresh_task =
2102       GNUNET_SCHEDULER_add_delayed (t->tree->refresh, &path_refresh, t);
2103   return;
2104 }
2105
2106 #if LATER /* FIXME DHT */
2107 /**
2108  * Function to process paths received for a new peer addition. The recorded
2109  * paths form the initial tunnel, which can be optimized later.
2110  * Called on each result obtained for the DHT search.
2111  *
2112  * @param cls closure
2113  * @param exp when will this value expire
2114  * @param key key of the result
2115  * @param type type of the result
2116  * @param size number of bytes in data
2117  * @param data pointer to the result data
2118  *
2119  * TODO: re-issue the request after certain time? cancel after X results?
2120  */
2121 static void
2122 dht_get_id_handler (void *cls, struct GNUNET_TIME_Absolute exp,
2123                     const GNUNET_HashCode * key,
2124                     const struct GNUNET_PeerIdentity *get_path,
2125                     unsigned int get_path_length,
2126                     const struct GNUNET_PeerIdentity *put_path,
2127                     unsigned int put_path_length,
2128                     enum GNUNET_BLOCK_Type type, size_t size, const void *data)
2129 {
2130   struct MeshPathInfo *path_info = cls;
2131   struct MeshPathInfo *path_info_aux;
2132   struct MeshPeerPath *p;
2133   struct MeshPeerPath *aux;
2134   struct GNUNET_PeerIdentity pi;
2135   int i;
2136
2137   GNUNET_PEER_resolve (path_info->peer->id, &pi);
2138   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2139              "MESH: Got results from DHT for %s\n",
2140              GNUNET_h2s_full(&pi.hashPubKey));
2141   if (NULL == get_path || NULL == put_path)
2142   {
2143     if (NULL == path_info->peer->path_head)
2144     {
2145       // Find ourselves some alternate initial path to the destination: retry
2146       GNUNET_DHT_get_stop (path_info->peer->dhtget);
2147 //       path_info->peer->dhtget = GNUNET_DHT_get_start (dht_handle,       /* handle */ FIXME DHT
2148 //                                                       GNUNET_TIME_UNIT_FOREVER_REL,     /* timeout */
2149 //                                                       GNUNET_BLOCK_TYPE_TEST,   /* type */
2150 //                                                       &pi.hashPubKey,   /*key to search */
2151 //                                                       4,        /* replication level */
2152 //                                                       GNUNET_DHT_RO_RECORD_ROUTE, 
2153 //                                                       NULL,     /* xquery */
2154 //                                                       0,        /* xquery bits */
2155 //                                                       &dht_get_id_handler,
2156 //                                                       (void *) path_info);
2157       return;
2158     }
2159   }
2160
2161   p = path_build_from_dht (get_path, get_path_length, put_path, put_path_length);
2162   path_add_to_peer (path_info->peer, p);
2163   for (i = 0; i < path_info->peer->ntunnels; i++)
2164   {
2165     tunnel_add_peer (path_info->peer->tunnels[i], path_info->peer);
2166     aux = tree_get_path_to_peer(path_info->peer->tunnels[i]->tree,
2167                                 path_info->peer->id);
2168     if (aux->length > 1)
2169     {
2170       struct GNUNET_PeerIdentity id;
2171
2172       path_info_aux = GNUNET_malloc (sizeof (struct MeshPathInfo));
2173       path_info_aux->path = aux;
2174       path_info_aux->peer = path_info->peer;
2175       path_info_aux->t = path_info->t;
2176       GNUNET_PEER_resolve (p->peers[1], &id);
2177       GNUNET_CORE_notify_transmit_ready (core_handle, /* handle */
2178                                       0, /* cork */
2179                                       0, /* priority */
2180                                       GNUNET_TIME_UNIT_FOREVER_REL,
2181                                       /* timeout */
2182                                       &id, /* target */
2183                                       sizeof (struct GNUNET_MESH_ManipulatePath)
2184                                       +
2185                                       (aux->length *
2186                                         sizeof (struct GNUNET_PeerIdentity)),
2187                                       /*size */
2188                                       &send_core_create_path,
2189                                       /* callback */
2190                                       path_info_aux);        /* cls */
2191     }
2192     else
2193     {
2194       send_client_peer_connected(path_info->t, myid);
2195     }
2196   }
2197   GNUNET_free (path_info);
2198
2199   return;
2200 }
2201
2202
2203 /**
2204  * Function to process paths received for a new peer addition. The recorded
2205  * paths form the initial tunnel, which can be optimized later.
2206  * Called on each result obtained for the DHT search.
2207  *
2208  * @param cls closure
2209  * @param exp when will this value expire
2210  * @param key key of the result
2211  * @param type type of the result
2212  * @param size number of bytes in data
2213  * @param data pointer to the result data
2214  */
2215 static void
2216 dht_get_type_handler (void *cls, struct GNUNET_TIME_Absolute exp,
2217                       const GNUNET_HashCode * key,
2218                       const struct GNUNET_PeerIdentity *get_path,
2219                       unsigned int get_path_length,
2220                       const struct GNUNET_PeerIdentity *put_path,
2221                       unsigned int put_path_length,
2222                       enum GNUNET_BLOCK_Type type, size_t size,
2223                       const void *data)
2224 {
2225   const struct GNUNET_PeerIdentity *pi = data;
2226   struct GNUNET_PeerIdentity id;
2227   struct MeshTunnel *t = cls;
2228   struct MeshPeerInfo *peer_info;
2229   struct MeshPathInfo *path_info;
2230   struct MeshPeerPath *p;
2231   int i;
2232
2233   if (size != sizeof (struct GNUNET_PeerIdentity))
2234   {
2235     GNUNET_break_op (0);
2236     return;
2237   }
2238   GNUNET_assert (NULL != t->client);
2239   GNUNET_DHT_get_stop (t->client->dht_get_type);
2240   t->client->dht_get_type = NULL;
2241   peer_info = peer_info_get (pi);
2242   GNUNET_CONTAINER_multihashmap_put (t->peers, &pi->hashPubKey, peer_info,
2243                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
2244
2245   if ((NULL == get_path || NULL == put_path) && NULL == peer_info->path_head &&
2246       NULL == peer_info->dhtget)
2247   {
2248 //     path_info = GNUNET_malloc (sizeof (struct MeshPathInfo)); FIXME DHT
2249 //     path_info->peer = peer_info;
2250 //     path_info->t = t;
2251 //     /* we don't have a route to the peer, let's try a direct lookup */
2252 //     peer_info->dhtget = GNUNET_DHT_get_start (dht_handle,
2253 //                                               /* handle */
2254 //                                               GNUNET_TIME_UNIT_FOREVER_REL,
2255 //                                               /* timeout */
2256 //                                               GNUNET_BLOCK_TYPE_TEST,
2257 //                                               /* block type */
2258 //                                               &pi->hashPubKey,
2259 //                                               /* key to look up */
2260 //                                               10U,
2261 //                                               /* replication level */
2262 //                                               GNUNET_DHT_RO_RECORD_ROUTE,
2263 //                                               /* option to dht: record route */
2264 //                                               NULL,     /* xquery */
2265 //                                               0,        /* xquery bits */
2266 //                                               dht_get_id_handler,
2267 //                                               /* callback */
2268 //                                               path_info);       /* closure */
2269     return;
2270   }
2271
2272   p = path_build_from_dht (get_path, get_path_length, put_path, put_path_length);
2273   path_add_to_peer (peer_info, p);
2274   tunnel_add_peer(t, peer_info);
2275   p = tree_get_path_to_peer(t->tree, peer_info->id);
2276 #if MESH_DEBUG
2277   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2278               "MESH: new route for tunnel 0x%x found, has %u hops\n",
2279               t->local_tid, p->length);
2280   for (i = 0; i < p->length; i++)
2281   {
2282     GNUNET_PEER_resolve (p->peers[0], &id);
2283     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:\t%d\t%s\n", i,
2284                 GNUNET_h2s_full (&id.hashPubKey));
2285   }
2286 #endif
2287
2288   if (p->length > 1)
2289   {
2290     path_info = GNUNET_malloc(sizeof(struct MeshPathInfo));
2291     path_info->t = t;
2292     path_info->peer = peer_info;
2293     path_info->path = p;
2294     GNUNET_PEER_resolve (p->peers[1], &id);
2295     GNUNET_CORE_notify_transmit_ready (core_handle,
2296                                      /* handle */
2297                                      0,
2298                                      /* cork */
2299                                      0,
2300                                      /* priority */
2301                                      GNUNET_TIME_UNIT_FOREVER_REL,
2302                                      /* timeout */
2303                                      &id,
2304                                      /* target */
2305                                      sizeof (struct GNUNET_MESH_ManipulatePath)
2306                                      +
2307                                      (p->length *
2308                                       sizeof (struct GNUNET_PeerIdentity)),
2309                                      /*size */
2310                                      &send_core_create_path,
2311                                      /* callback */
2312                                      path_info);        /* cls */
2313     return;
2314   }
2315   path_destroy(p);
2316   send_client_peer_connected(t, myid);
2317 }
2318
2319 #endif
2320
2321 /******************************************************************************/
2322 /*********************       MESH LOCAL HANDLES      **************************/
2323 /******************************************************************************/
2324
2325
2326 /**
2327  * Handler for client disconnection
2328  *
2329  * @param cls closure
2330  * @param client identification of the client; NULL
2331  *        for the last call when the server is destroyed
2332  */
2333 static void
2334 handle_local_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
2335 {
2336   struct MeshClient *c;
2337   struct MeshClient *next;
2338
2339   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: client disconnected\n");
2340   if (client == NULL)
2341      GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:    (SERVER DOWN)\n");
2342   c = clients;
2343   while (NULL != c)
2344   {
2345     if (c->handle != client && NULL != client)
2346     {
2347       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:    ... searching\n");
2348       c = c->next;
2349       continue;
2350     }
2351     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: matching client found\n");
2352     if (NULL != c->tunnels)
2353     {
2354       GNUNET_CONTAINER_multihashmap_iterate (c->tunnels,
2355                                              &tunnel_destroy_iterator,
2356                                              c);
2357       GNUNET_CONTAINER_multihashmap_destroy (c->tunnels);
2358     }
2359
2360     /* deregister clients applications */
2361     if (NULL != c->apps)
2362     {
2363       GNUNET_CONTAINER_multihashmap_iterate (c->apps, &deregister_app, NULL);
2364       GNUNET_CONTAINER_multihashmap_destroy (c->apps);
2365     }
2366     if (0 == GNUNET_CONTAINER_multihashmap_size (applications) &&
2367         GNUNET_SCHEDULER_NO_TASK != announce_applications_task)
2368     {
2369       GNUNET_SCHEDULER_cancel (announce_applications_task);
2370       announce_applications_task = GNUNET_SCHEDULER_NO_TASK;
2371     }
2372     if (NULL != c->types)
2373       GNUNET_CONTAINER_multihashmap_destroy (c->types);
2374     if (NULL != c->dht_get_type)
2375       GNUNET_DHT_get_stop (c->dht_get_type);
2376     GNUNET_CONTAINER_DLL_remove (clients, clients_tail, c);
2377     next = c->next;
2378     GNUNET_free (c);
2379     c = next;
2380   }
2381
2382   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:    done!\n");
2383   return;
2384 }
2385
2386
2387 /**
2388  * Handler for new clients
2389  *
2390  * @param cls closure
2391  * @param client identification of the client
2392  * @param message the actual message, which includes messages the client wants
2393  */
2394 static void
2395 handle_local_new_client (void *cls, struct GNUNET_SERVER_Client *client,
2396                          const struct GNUNET_MessageHeader *message)
2397 {
2398   struct GNUNET_MESH_ClientConnect *cc_msg;
2399   struct MeshClient *c;
2400   GNUNET_MESH_ApplicationType *a;
2401   unsigned int size;
2402   uint16_t ntypes;
2403   uint16_t *t;
2404   uint16_t napps;
2405   uint16_t i;
2406
2407   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: new client connected\n");
2408   /* Check data sanity */
2409   size = ntohs (message->size) - sizeof (struct GNUNET_MESH_ClientConnect);
2410   cc_msg = (struct GNUNET_MESH_ClientConnect *) message;
2411   ntypes = ntohs (cc_msg->types);
2412   napps = ntohs (cc_msg->applications);
2413   if (size !=
2414       ntypes * sizeof (uint16_t) + napps * sizeof (GNUNET_MESH_ApplicationType))
2415   {
2416     GNUNET_break (0);
2417     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2418     return;
2419   }
2420
2421   /* Create new client structure */
2422   c = GNUNET_malloc (sizeof (struct MeshClient));
2423 #if MESH_DEBUG
2424   c->id = next_client_id++;
2425 #endif
2426   c->handle = client;
2427   a = (GNUNET_MESH_ApplicationType *) &cc_msg[1];
2428   if (napps > 0)
2429   {
2430     GNUNET_MESH_ApplicationType at;
2431     GNUNET_HashCode hc;
2432
2433     c->apps = GNUNET_CONTAINER_multihashmap_create (napps);
2434     for (i = 0; i < napps; i++)
2435     {
2436       at = ntohl (a[i]);
2437       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   app type: %u\n", at);
2438       GNUNET_CRYPTO_hash (&at, sizeof (at), &hc);
2439       /* store in clients hashmap */
2440       GNUNET_CONTAINER_multihashmap_put (c->apps, &hc, c,
2441                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2442       /* store in global hashmap, for announcements */
2443       GNUNET_CONTAINER_multihashmap_put (applications, &hc, c,
2444                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2445     }
2446     if (GNUNET_SCHEDULER_NO_TASK == announce_applications_task)
2447       announce_applications_task =
2448           GNUNET_SCHEDULER_add_now (&announce_applications, NULL);
2449
2450   }
2451   if (ntypes > 0)
2452   {
2453     uint16_t u16;
2454     GNUNET_HashCode hc;
2455
2456     t = (uint16_t *) & a[napps];
2457     c->types = GNUNET_CONTAINER_multihashmap_create (ntypes);
2458     for (i = 0; i < ntypes; i++)
2459     {
2460       u16 = ntohs (t[i]);
2461       GNUNET_CRYPTO_hash (&u16, sizeof (u16), &hc);
2462
2463       /* store in clients hashmap */
2464       GNUNET_CONTAINER_multihashmap_put (c->types, &hc, c,
2465                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2466       /* store in global hashmap */
2467       GNUNET_CONTAINER_multihashmap_put (types, &hc, c,
2468                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2469     }
2470   }
2471   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2472               "MESH:  client has %u+%u subscriptions\n", napps, ntypes);
2473
2474   GNUNET_CONTAINER_DLL_insert (clients, clients_tail, c);
2475   c->tunnels = GNUNET_CONTAINER_multihashmap_create (32);
2476   GNUNET_SERVER_notification_context_add (nc, client);
2477
2478   GNUNET_SERVER_receive_done (client, GNUNET_OK);
2479 #if MESH_DEBUG
2480   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: new client processed\n");
2481 #endif
2482 }
2483
2484
2485 /**
2486  * Handler for requests of new tunnels
2487  *
2488  * @param cls closure
2489  * @param client identification of the client
2490  * @param message the actual message
2491  */
2492 static void
2493 handle_local_tunnel_create (void *cls, struct GNUNET_SERVER_Client *client,
2494                             const struct GNUNET_MessageHeader *message)
2495 {
2496   struct GNUNET_MESH_TunnelMessage *t_msg;
2497   struct MeshTunnel *t;
2498   struct MeshClient *c;
2499   GNUNET_HashCode hash;
2500
2501   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: new tunnel requested\n");
2502
2503   /* Sanity check for client registration */
2504   if (NULL == (c = client_get (client)))
2505   {
2506     GNUNET_break (0);
2507     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2508     return;
2509   }
2510 #if MESH_DEBUG
2511   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   by client %u\n", c->id);
2512 #endif
2513
2514   /* Message sanity check */
2515   if (sizeof (struct GNUNET_MESH_TunnelMessage) != ntohs (message->size))
2516   {
2517     GNUNET_break (0);
2518     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2519     return;
2520   }
2521
2522   t_msg = (struct GNUNET_MESH_TunnelMessage *) message;
2523   /* Sanity check for tunnel numbering */
2524   if (0 == (ntohl (t_msg->tunnel_id) & GNUNET_MESH_LOCAL_TUNNEL_ID_CLI))
2525   {
2526     GNUNET_break (0);
2527     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2528     return;
2529   }
2530   /* Sanity check for duplicate tunnel IDs */
2531   if (NULL != tunnel_get_by_local_id (c, ntohl (t_msg->tunnel_id)))
2532   {
2533     GNUNET_break (0);
2534     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2535     return;
2536   }
2537
2538   t = GNUNET_malloc (sizeof (struct MeshTunnel));
2539   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: CREATED TUNNEL at %p\n", t);
2540   while (NULL != tunnel_get_by_pi (myid, next_tid))
2541     next_tid = (next_tid + 1) & ~GNUNET_MESH_LOCAL_TUNNEL_ID_CLI;
2542   t->id.tid = next_tid++;
2543   t->id.oid = myid;
2544   t->local_tid = ntohl (t_msg->tunnel_id);
2545   t->client = c;
2546   t->peers = GNUNET_CONTAINER_multihashmap_create (32);
2547
2548   GNUNET_CRYPTO_hash (&t->local_tid, sizeof (MESH_TunnelNumber), &hash);
2549   if (GNUNET_OK !=
2550       GNUNET_CONTAINER_multihashmap_put (c->tunnels, &hash, t,
2551                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
2552   {
2553     GNUNET_break (0);
2554     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2555     return;
2556   }
2557
2558   GNUNET_CRYPTO_hash (&t->id, sizeof (struct MESH_TunnelID), &hash);
2559   if (GNUNET_OK !=
2560       GNUNET_CONTAINER_multihashmap_put (tunnels, &hash, t,
2561                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
2562   {
2563     GNUNET_break (0);
2564     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2565     return;
2566   }
2567   t->tree = tree_new (t, myid);
2568   t->tree->refresh = REFRESH_PATH_TIME;
2569   t->tree->root->status = MESH_PEER_READY;
2570   t->tree->me = t->tree->root;
2571
2572   GNUNET_SERVER_receive_done (client, GNUNET_OK);
2573   return;
2574 }
2575
2576
2577 /**
2578  * Handler for requests of deleting tunnels
2579  *
2580  * @param cls closure
2581  * @param client identification of the client
2582  * @param message the actual message
2583  */
2584 static void
2585 handle_local_tunnel_destroy (void *cls, struct GNUNET_SERVER_Client *client,
2586                              const struct GNUNET_MessageHeader *message)
2587 {
2588   struct GNUNET_MESH_TunnelMessage *tunnel_msg;
2589   struct MeshClient *c;
2590   struct MeshTunnel *t;
2591   MESH_TunnelNumber tid;
2592   GNUNET_HashCode hash;
2593
2594   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: destroying tunnel\n");
2595
2596   /* Sanity check for client registration */
2597   if (NULL == (c = client_get (client)))
2598   {
2599     GNUNET_break (0);
2600     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2601     return;
2602   }
2603   /* Message sanity check */
2604   if (sizeof (struct GNUNET_MESH_TunnelMessage) != ntohs (message->size))
2605   {
2606     GNUNET_break (0);
2607     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2608     return;
2609   }
2610 #if MESH_DEBUG
2611   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   by client %u\n", c->id);
2612 #endif
2613   tunnel_msg = (struct GNUNET_MESH_TunnelMessage *) message;
2614
2615   /* Retrieve tunnel */
2616   tid = ntohl (tunnel_msg->tunnel_id);
2617
2618   /* Remove from local id hashmap */
2619   GNUNET_CRYPTO_hash (&tid, sizeof (MESH_TunnelNumber), &hash);
2620   t = GNUNET_CONTAINER_multihashmap_get (c->tunnels, &hash);
2621   GNUNET_CONTAINER_multihashmap_remove (c->tunnels, &hash, t);
2622
2623   /* Remove from global id hashmap */
2624   GNUNET_CRYPTO_hash (&t->id, sizeof (struct MESH_TunnelID), &hash);
2625   GNUNET_CONTAINER_multihashmap_remove (tunnels, &hash, t);
2626
2627 //     notify_tunnel_destroy(t); FIXME
2628   tunnel_destroy(t);
2629   GNUNET_SERVER_receive_done (client, GNUNET_OK);
2630   return;
2631 }
2632
2633
2634 /**
2635  * Handler for connection requests to new peers
2636  *
2637  * @param cls closure
2638  * @param client identification of the client
2639  * @param message the actual message (PeerControl)
2640  */
2641 static void
2642 handle_local_connect_add (void *cls, struct GNUNET_SERVER_Client *client,
2643                           const struct GNUNET_MessageHeader *message)
2644 {
2645   struct GNUNET_MESH_PeerControl *peer_msg;
2646   struct MeshPathInfo *path_info;
2647   struct MeshPeerInfo *peer_info;
2648   struct MeshClient *c;
2649   struct MeshTunnel *t;
2650   MESH_TunnelNumber tid;
2651
2652   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "MESH: Got connection request\n");
2653   /* Sanity check for client registration */
2654   if (NULL == (c = client_get (client)))
2655   {
2656     GNUNET_break (0);
2657     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2658     return;
2659   }
2660
2661   peer_msg = (struct GNUNET_MESH_PeerControl *) message;
2662   /* Sanity check for message size */
2663   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (peer_msg->header.size))
2664   {
2665     GNUNET_break (0);
2666     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2667     return;
2668   }
2669
2670   /* Tunnel exists? */
2671   tid = ntohl (peer_msg->tunnel_id);
2672   t = tunnel_get_by_local_id (c, tid);
2673   if (NULL == t)
2674   {
2675     GNUNET_break (0);
2676     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2677     return;
2678   }
2679
2680   /* Does client own tunnel? */
2681   if (t->client->handle != client)
2682   {
2683     GNUNET_break (0);
2684     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2685     return;
2686   }
2687   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "MESH:      for %s\n",
2688              GNUNET_h2s_full(&peer_msg->peer.hashPubKey));
2689   peer_info = peer_info_get (&peer_msg->peer);
2690
2691   /* Start DHT search if needed, otherwise just add peer to tunnel. */
2692   if (NULL == peer_info->dhtget && NULL == peer_info->path_head)
2693   {
2694 //     path_info = GNUNET_malloc(sizeof(struct MeshPathInfo));
2695 //     path_info->peer = peer_info;
2696 //     path_info->t = t;
2697 //     peer_info->dhtget = GNUNET_DHT_get_start(dht_handle,       /* handle */ FIXME DHT
2698 //                                           GNUNET_TIME_UNIT_FOREVER_REL,     /* timeout */
2699 //                                           GNUNET_BLOCK_TYPE_TEST,   /* type */
2700 //                                           &peer_msg->peer.hashPubKey,   /*key to search */
2701 //                                           4,        /* replication level */
2702 //                                           GNUNET_DHT_RO_RECORD_ROUTE,
2703 //                                           NULL,     /* xquery */
2704 //                                           0,        /* xquery bits */
2705 //                                           &dht_get_id_handler,
2706 //                                           (void *) path_info);
2707   }
2708   else if (NULL != peer_info->path_head)
2709   {
2710     unsigned int i;
2711     for (i = 0; i < CORE_QUEUE_SIZE; i++)
2712     {
2713       if (NULL == peer_info->core_transmit[i])
2714         break;
2715     }
2716     if (CORE_QUEUE_SIZE == i)
2717     {
2718       GNUNET_break (0);
2719       GNUNET_SERVER_receive_done (client, GNUNET_OK);
2720       return;
2721     }
2722     path_info = GNUNET_malloc(sizeof(struct MeshPathInfo));
2723     path_info->peer = peer_info;
2724     path_info->t = t;
2725     tunnel_add_peer(t, peer_info);
2726     path_info->path = tree_get_path_to_peer(t->tree, peer_info->id);
2727     peer_info = peer_info_get(path_get_first_hop(t->tree, path_info->peer->id));
2728     peer_info->infos[i] = path_info;
2729     peer_info->types[i] = GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE;
2730     peer_info->core_transmit[i] =
2731       GNUNET_CORE_notify_transmit_ready (
2732         core_handle,
2733         0,
2734         0,
2735         GNUNET_TIME_UNIT_FOREVER_REL,
2736         path_get_first_hop(t->tree, path_info->peer->id),
2737         sizeof (struct GNUNET_MESH_ManipulatePath)
2738         + path_info->path->length * sizeof(struct GNUNET_PeerIdentity),
2739         &send_core_create_path,
2740         path_info);
2741   }
2742   /* Otherwise: there is no path yet, but there is a DHT_get active already. */
2743   GNUNET_SERVER_receive_done (client, GNUNET_OK);
2744   return;
2745 }
2746
2747
2748 /**
2749  * Handler for disconnection requests of peers in a tunnel
2750  *
2751  * @param cls closure
2752  * @param client identification of the client
2753  * @param message the actual message (PeerControl)
2754  */
2755 static void
2756 handle_local_connect_del (void *cls, struct GNUNET_SERVER_Client *client,
2757                           const struct GNUNET_MessageHeader *message)
2758 {
2759   struct GNUNET_MESH_PeerControl *peer_msg;
2760   struct MeshClient *c;
2761   struct MeshTunnel *t;
2762   MESH_TunnelNumber tid;
2763
2764   /* Sanity check for client registration */
2765   if (NULL == (c = client_get (client)))
2766   {
2767     GNUNET_break (0);
2768     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2769     return;
2770   }
2771   peer_msg = (struct GNUNET_MESH_PeerControl *) message;
2772   /* Sanity check for message size */
2773   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (peer_msg->header.size))
2774   {
2775     GNUNET_break (0);
2776     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2777     return;
2778   }
2779
2780   /* Tunnel exists? */
2781   tid = ntohl (peer_msg->tunnel_id);
2782   t = tunnel_get_by_local_id (c, tid);
2783   if (NULL == t)
2784   {
2785     GNUNET_break (0);
2786     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2787     return;
2788   }
2789
2790   /* Does client own tunnel? */
2791   if (t->client->handle != client)
2792   {
2793     GNUNET_break (0);
2794     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2795     return;
2796   }
2797
2798   /* Ok, delete peer from tunnel */
2799   GNUNET_CONTAINER_multihashmap_remove_all (t->peers,
2800                                             &peer_msg->peer.hashPubKey);
2801
2802   GNUNET_SERVER_receive_done (client, GNUNET_OK);
2803   return;
2804 }
2805
2806
2807 /**
2808  * Handler for connection requests to new peers by type
2809  *
2810  * @param cls closure
2811  * @param client identification of the client
2812  * @param message the actual message (ConnectPeerByType)
2813  */
2814 static void
2815 handle_local_connect_by_type (void *cls, struct GNUNET_SERVER_Client *client,
2816                               const struct GNUNET_MessageHeader *message)
2817 {
2818   struct GNUNET_MESH_ConnectPeerByType *connect_msg;
2819   struct MeshClient *c;
2820   struct MeshTunnel *t;
2821   GNUNET_HashCode hash;
2822   GNUNET_MESH_ApplicationType type;
2823   MESH_TunnelNumber tid;
2824
2825   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: got connect by type request\n");
2826   /* Sanity check for client registration */
2827   if (NULL == (c = client_get (client)))
2828   {
2829     GNUNET_break (0);
2830     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2831     return;
2832   }
2833
2834   connect_msg = (struct GNUNET_MESH_ConnectPeerByType *) message;
2835   /* Sanity check for message size */
2836   if (sizeof (struct GNUNET_MESH_ConnectPeerByType) !=
2837       ntohs (connect_msg->header.size))
2838   {
2839     GNUNET_break (0);
2840     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2841     return;
2842   }
2843
2844   /* Tunnel exists? */
2845   tid = ntohl (connect_msg->tunnel_id);
2846   t = tunnel_get_by_local_id (c, tid);
2847   if (NULL == t)
2848   {
2849     GNUNET_break (0);
2850     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2851     return;
2852   }
2853
2854   /* Does client own tunnel? */
2855   if (t->client->handle != client)
2856   {
2857     GNUNET_break (0);
2858     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2859     return;
2860   }
2861
2862   /* Do WE have the service? */
2863   type = ntohl (connect_msg->type);
2864   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:  type requested: %u\n", type);
2865   GNUNET_CRYPTO_hash (&type, sizeof (GNUNET_MESH_ApplicationType), &hash);
2866   if (GNUNET_CONTAINER_multihashmap_contains (applications, &hash) ==
2867       GNUNET_YES)
2868   {
2869     /* Yes! Fast forward, add ourselves to the tunnel and send the
2870      * good news to the client
2871      */
2872     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:  available locally\n");
2873     GNUNET_CONTAINER_multihashmap_put (t->peers, &my_full_id.hashPubKey,
2874                                        peer_info_get (&my_full_id),
2875                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
2876
2877     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:  notifying client\n");
2878     send_client_peer_connected(t, myid);
2879     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:  Done\n");
2880     GNUNET_SERVER_receive_done (client, GNUNET_OK);
2881     return;
2882   }
2883   /* Ok, lets find a peer offering the service */
2884   if (c->dht_get_type)
2885   {
2886     GNUNET_DHT_get_stop (c->dht_get_type);
2887   }
2888   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:  looking in DHT for %s\n",
2889               GNUNET_h2s_full (&hash));
2890 //   c->dht_get_type = FIXME DHT
2891 //       GNUNET_DHT_get_start (dht_handle, GNUNET_TIME_UNIT_FOREVER_REL,
2892 //                             GNUNET_BLOCK_TYPE_TEST, &hash, 10U,
2893 //                             GNUNET_DHT_RO_RECORD_ROUTE, NULL, 0,
2894 //                             &dht_get_type_handler, t);
2895
2896   GNUNET_SERVER_receive_done (client, GNUNET_OK);
2897   return;
2898 }
2899
2900
2901 /**
2902  * Handler for client traffic directed to one peer
2903  *
2904  * @param cls closure
2905  * @param client identification of the client
2906  * @param message the actual message
2907  */
2908 static void
2909 handle_local_unicast (void *cls, struct GNUNET_SERVER_Client *client,
2910                       const struct GNUNET_MessageHeader *message)
2911 {
2912   struct MeshClient *c;
2913   struct MeshTunnel *t;
2914   struct MeshPeerInfo *pi;
2915   struct GNUNET_MESH_Unicast *data_msg;
2916   MESH_TunnelNumber tid;
2917   size_t size;
2918
2919   /* Sanity check for client registration */
2920   if (NULL == (c = client_get (client)))
2921   {
2922     GNUNET_break (0);
2923     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2924     return;
2925   }
2926   data_msg = (struct GNUNET_MESH_Unicast *) message;
2927   /* Sanity check for message size */
2928   size = ntohs (message->size);
2929   if (sizeof (struct GNUNET_MESH_Unicast) +
2930       sizeof (struct GNUNET_MessageHeader) > size)
2931   {
2932     GNUNET_break (0);
2933     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2934     return;
2935   }
2936
2937   /* Tunnel exists? */
2938   tid = ntohl (data_msg->tid);
2939   t = tunnel_get_by_local_id (c, tid);
2940   if (NULL == t)
2941   {
2942     GNUNET_break (0);
2943     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2944     return;
2945   }
2946
2947   /*  Is it a local tunnel? Then, does client own the tunnel? */
2948   if (t->client->handle != NULL && t->client->handle != client)
2949   {
2950     GNUNET_break (0);
2951     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2952     return;
2953   }
2954
2955   pi = GNUNET_CONTAINER_multihashmap_get (t->peers,
2956                                           &data_msg->destination.hashPubKey);
2957   /* Is the selected peer in the tunnel? */
2958   if (NULL == pi)
2959   {
2960     GNUNET_break (0);
2961     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2962     return;
2963   }
2964
2965   /* Ok, everything is correct, send the message
2966    * (pretend we got it from a mesh peer)
2967    */
2968   {
2969     char buf[ntohs (message->size)];
2970     struct GNUNET_MESH_Unicast *copy;
2971
2972     /* Work around const limitation */
2973     copy = (struct GNUNET_MESH_Unicast *) buf;
2974     memcpy (buf, data_msg, size);
2975     copy->oid = my_full_id;
2976     copy->tid = htonl (t->id.tid);
2977     handle_mesh_data_unicast (NULL, &my_full_id, &copy->header, NULL);
2978   }
2979   GNUNET_SERVER_receive_done (client, GNUNET_OK);
2980   return;
2981 }
2982
2983 /**
2984  * Handler for client traffic directed to all peers in a tunnel
2985  *
2986  * @param cls closure
2987  * @param client identification of the client
2988  * @param message the actual message
2989  */
2990 static void
2991 handle_local_multicast (void *cls, struct GNUNET_SERVER_Client *client,
2992                         const struct GNUNET_MessageHeader *message)
2993 {
2994   struct MeshClient *c;
2995   struct MeshTunnel *t;
2996   struct GNUNET_MESH_Multicast *data_msg;
2997   MESH_TunnelNumber tid;
2998
2999   /* Sanity check for client registration */
3000   if (NULL == (c = client_get (client)))
3001   {
3002     GNUNET_break (0);
3003     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3004     return;
3005   }
3006   data_msg = (struct GNUNET_MESH_Multicast *) message;
3007   /* Sanity check for message size */
3008   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (data_msg->header.size))
3009   {
3010     GNUNET_break (0);
3011     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3012     return;
3013   }
3014
3015   /* Tunnel exists? */
3016   tid = ntohl (data_msg->tid);
3017   t = tunnel_get_by_local_id (c, tid);
3018   if (NULL == t)
3019   {
3020     GNUNET_break (0);
3021     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3022     return;
3023   }
3024
3025   /* Does client own tunnel? */
3026   if (t->client->handle != client)
3027   {
3028     GNUNET_break (0);
3029     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3030     return;
3031   }
3032
3033   {
3034     char buf[ntohs(message->size)];
3035     struct GNUNET_MESH_Multicast *copy;
3036
3037     copy = (struct GNUNET_MESH_Multicast *)buf;
3038     memcpy(buf, message, ntohs(message->size));
3039     copy->oid = my_full_id;
3040     copy->tid = htonl(t->id.tid);
3041     handle_mesh_data_multicast(client, &my_full_id, &copy->header, NULL);
3042   }
3043
3044   /* receive done gets called when last copy is sent */
3045   return;
3046 }
3047
3048 /**
3049  * Functions to handle messages from clients
3050  */
3051 static struct GNUNET_SERVER_MessageHandler client_handlers[] = {
3052   {&handle_local_new_client, NULL, GNUNET_MESSAGE_TYPE_MESH_LOCAL_CONNECT, 0},
3053   {&handle_local_tunnel_create, NULL,
3054    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_CREATE,
3055    sizeof (struct GNUNET_MESH_TunnelMessage)},
3056   {&handle_local_tunnel_destroy, NULL,
3057    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_DESTROY,
3058    sizeof (struct GNUNET_MESH_TunnelMessage)},
3059   {&handle_local_connect_add, NULL,
3060    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD,
3061    sizeof (struct GNUNET_MESH_PeerControl)},
3062   {&handle_local_connect_del, NULL,
3063    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_DEL,
3064    sizeof (struct GNUNET_MESH_PeerControl)},
3065   {&handle_local_connect_by_type, NULL,
3066    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD_BY_TYPE,
3067    sizeof (struct GNUNET_MESH_ConnectPeerByType)},
3068   {&handle_local_unicast, NULL,
3069    GNUNET_MESSAGE_TYPE_MESH_UNICAST, 0},
3070   {&handle_local_unicast, NULL,
3071    GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN, 0},
3072   {&handle_local_multicast, NULL,
3073    GNUNET_MESSAGE_TYPE_MESH_MULTICAST, 0},
3074   {NULL, NULL, 0, 0}
3075 };
3076
3077
3078 /**
3079  * To be called on core init/fail.
3080  *
3081  * @param cls service closure
3082  * @param server handle to the server for this service
3083  * @param identity the public identity of this peer
3084  * @param publicKey the public key of this peer
3085  */
3086 static void
3087 core_init (void *cls, struct GNUNET_CORE_Handle *server,
3088            const struct GNUNET_PeerIdentity *identity,
3089            const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *publicKey)
3090 {
3091   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: Core init\n");
3092   core_handle = server;
3093   if (0 != memcmp(identity, &my_full_id, sizeof(my_full_id)) || NULL == server)
3094   {
3095     GNUNET_log(GNUNET_ERROR_TYPE_ERROR, _("MESH: Wrong CORE service\n"));
3096     GNUNET_SCHEDULER_shutdown();   
3097   }
3098   return;
3099 }
3100
3101 /**
3102  * Method called whenever a given peer connects.
3103  *
3104  * @param cls closure
3105  * @param peer peer identity this notification is about
3106  * @param atsi performance data for the connection
3107  */
3108 static void
3109 core_connect (void *cls, const struct GNUNET_PeerIdentity *peer,
3110               const struct GNUNET_TRANSPORT_ATS_Information *atsi)
3111 {
3112   struct MeshPeerInfo *peer_info;
3113   struct MeshPeerPath *path;
3114
3115 //   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: Peer connected\n");
3116 //   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:      %s\n",
3117 //               GNUNET_h2s(&my_full_id.hashPubKey));
3118   peer_info = peer_info_get (peer);
3119   if (myid == peer_info->id)
3120   {
3121 //     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:      (self)\n");
3122     return;
3123   }
3124   else
3125   {
3126 //     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:      %s\n",
3127 //                 GNUNET_h2s(&peer->hashPubKey));
3128   }
3129   path = path_new (2);
3130   path->peers[0] = myid;
3131   path->peers[1] = peer_info->id;
3132   path_add_to_peer (peer_info, path);
3133   return;
3134 }
3135
3136 /**
3137  * Method called whenever a peer disconnects.
3138  *
3139  * @param cls closure
3140  * @param peer peer identity this notification is about
3141  */
3142 static void
3143 core_disconnect (void *cls, const struct GNUNET_PeerIdentity *peer)
3144 {
3145   struct MeshPeerInfo *pi;
3146   unsigned int i;
3147
3148   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: Peer disconnected\n");
3149   pi = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
3150   if (!pi)
3151   {
3152     GNUNET_break (0);
3153     return;
3154   }
3155   for (i = 0; i < CORE_QUEUE_SIZE; i++)
3156   {
3157     if (pi->core_transmit[i])
3158     {
3159       struct MeshDataDescriptor *dd;
3160       struct MeshPathInfo *path_info;
3161       GNUNET_CORE_notify_transmit_ready_cancel (pi->core_transmit[i]);
3162       /* TODO: notify that tranmission has failed */
3163       switch (pi->types[i])
3164       {
3165         case GNUNET_MESSAGE_TYPE_MESH_MULTICAST:
3166         case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
3167         case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
3168           dd = pi->infos[i];
3169           if (0 == --(*dd->copies))
3170           {
3171             GNUNET_free (dd->copies);
3172             GNUNET_free (dd->data);
3173           }
3174           break;
3175         case GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE:
3176           path_info = pi->infos[i];
3177           path_destroy(path_info->path);
3178           break;
3179       }
3180       GNUNET_free (pi->infos[i]);
3181     }
3182   }
3183   path_remove_from_peer (pi, pi->id, myid);
3184   if (myid == pi->id)
3185   {
3186     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:      (self)\n");
3187   }
3188   return;
3189 }
3190
3191
3192 /******************************************************************************/
3193 /************************      MAIN FUNCTIONS      ****************************/
3194 /******************************************************************************/
3195
3196 /**
3197  * Task run during shutdown.
3198  *
3199  * @param cls unused
3200  * @param tc unused
3201  */
3202 static void
3203 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3204 {
3205 //   struct MeshClient *c;
3206
3207   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: shutting down\n");
3208   if (core_handle != NULL)
3209   {
3210     GNUNET_CORE_disconnect (core_handle);
3211     core_handle = NULL;
3212   }
3213 //   if (dht_handle != NULL) FIXME DHT
3214 //   {
3215 //     for (c = clients; NULL != c; c = c->next)
3216 //       if (NULL != c->dht_get_type)
3217 //         GNUNET_DHT_get_stop (c->dht_get_type);
3218 //     GNUNET_DHT_disconnect (dht_handle);
3219 //     dht_handle = NULL;
3220 //   }
3221   if (nc != NULL)
3222   {
3223     GNUNET_SERVER_notification_context_destroy (nc);
3224     nc = NULL;
3225   }
3226   if (GNUNET_SCHEDULER_NO_TASK != announce_id_task)
3227   {
3228     GNUNET_SCHEDULER_cancel (announce_id_task);
3229     announce_id_task = GNUNET_SCHEDULER_NO_TASK;
3230   }
3231   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: shut down\n");
3232 }
3233
3234 /**
3235  * Process mesh requests.
3236  *
3237  * @param cls closure
3238  * @param server the initialized server
3239  * @param c configuration to use
3240  */
3241 static void
3242 run (void *cls, struct GNUNET_SERVER_Handle *server,
3243      const struct GNUNET_CONFIGURATION_Handle *c)
3244 {
3245   struct MeshPeerInfo *peer;
3246   struct MeshPeerPath *p;
3247   char *keyfile;
3248
3249   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: starting to run\n");
3250   server_handle = server;
3251   core_handle = GNUNET_CORE_connect (c, /* Main configuration */
3252                                      CORE_QUEUE_SIZE,   /* queue size */
3253                                      NULL,      /* Closure passed to MESH functions */
3254                                      &core_init,        /* Call core_init once connected */
3255                                      &core_connect,     /* Handle connects */
3256                                      &core_disconnect,  /* remove peers on disconnects */
3257                                      NULL,      /* Do we care about "status" updates? */
3258                                      NULL,      /* Don't notify about all incoming messages */
3259                                      GNUNET_NO, /* For header only in notification */
3260                                      NULL,      /* Don't notify about all outbound messages */
3261                                      GNUNET_NO, /* For header-only out notification */
3262                                      core_handlers);    /* Register these handlers */
3263   if (core_handle == NULL)
3264   {
3265     GNUNET_break (0);
3266     GNUNET_SCHEDULER_shutdown ();
3267     return;
3268   }
3269
3270   if (GNUNET_OK !=
3271        GNUNET_CONFIGURATION_get_value_filename (c, "GNUNETD", "HOSTKEY",
3272                                                 &keyfile))
3273   {
3274     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3275                 _
3276                 ("Mesh service is lacking key configuration settings.  Exiting.\n"));
3277     GNUNET_SCHEDULER_shutdown ();
3278     return;
3279   }
3280   my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
3281   GNUNET_free (keyfile);
3282   if (my_private_key == NULL)
3283   {
3284     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3285                 _("Mesh service could not access hostkey.  Exiting.\n"));
3286     GNUNET_SCHEDULER_shutdown ();
3287     return;
3288   }
3289   GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
3290   GNUNET_CRYPTO_hash (&my_public_key, sizeof (my_public_key),
3291                       &my_full_id.hashPubKey);
3292   myid = GNUNET_PEER_intern (&my_full_id);
3293
3294 //   dht_handle = GNUNET_DHT_connect (c, 64); FIXME DHT
3295 //   if (dht_handle == NULL)
3296 //   {
3297 //     GNUNET_break (0);
3298 //   }
3299
3300   next_tid = 0;
3301
3302   tunnels = GNUNET_CONTAINER_multihashmap_create (32);
3303   peers = GNUNET_CONTAINER_multihashmap_create (32);
3304   applications = GNUNET_CONTAINER_multihashmap_create (32);
3305   types = GNUNET_CONTAINER_multihashmap_create (32);
3306
3307   GNUNET_SERVER_add_handlers (server_handle, client_handlers);
3308   nc = GNUNET_SERVER_notification_context_create (server_handle,
3309                                                   LOCAL_QUEUE_SIZE);
3310   GNUNET_SERVER_disconnect_notify (server_handle,
3311                                    &handle_local_client_disconnect,
3312                                    NULL);
3313
3314
3315   clients = NULL;
3316   clients_tail = NULL;
3317 #if MESH_DEBUG
3318   next_client_id = 0;
3319 #endif
3320
3321   announce_applications_task = GNUNET_SCHEDULER_NO_TASK;
3322   announce_id_task = GNUNET_SCHEDULER_add_now (&announce_id, cls);
3323
3324   /* Create a peer_info for the local peer */
3325   peer = peer_info_get(&my_full_id);
3326   p = path_new (1);
3327   p->peers[0] = myid;
3328   path_add_to_peer(peer, p);
3329
3330   /* Scheduled the task to clean up when shutdown is called */
3331   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
3332                                 NULL);
3333
3334   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: end of run()\n");
3335 }
3336
3337 /**
3338  * The main function for the mesh service.
3339  *
3340  * @param argc number of arguments from the command line
3341  * @param argv command line arguments
3342  * @return 0 ok, 1 on error
3343  */
3344 int
3345 main (int argc, char *const *argv)
3346 {
3347   int ret;
3348
3349 #if MESH_DEBUG
3350 //   fprintf (stderr, "main ()\n");
3351 #endif
3352   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: main()\n");
3353   ret =
3354       (GNUNET_OK ==
3355        GNUNET_SERVICE_run (argc, argv, "mesh", GNUNET_SERVICE_OPTION_NONE, &run,
3356                            NULL)) ? 0 : 1;
3357   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: main() END\n");
3358 #if MESH_DEBUG
3359 //   fprintf (stderr, "main () END\n");
3360 #endif
3361   return ret;
3362 }