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