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