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