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