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