Added notification when peers go offline during a path change
[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 = GNUNET_malloc (sizeof (struct MeshPeerPath));
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  * Recursively destory the path tree of a tunnel.
1088  * Note: it does not liberate memory for itself, parent must do it!
1089  *
1090  * @param n The node to destroy, along with children.
1091  *
1092  * @return GNUNET_OK on success
1093  */
1094 static void
1095 tunnel_destroy_tree_node (struct MeshTunnelTreeNode *n)
1096 {
1097   unsigned int i;
1098
1099   for (i = 0; i < n->nchildren; i++)
1100   {
1101     tunnel_destroy_tree_node(&n->children[i]);
1102   }
1103   if (NULL != n->children)
1104     GNUNET_free (n->children);
1105 }
1106
1107
1108 /**
1109  * Destroy the tunnel and free any allocated resources linked to it
1110  *
1111  * @param t the tunnel to destroy
1112  *
1113  * @return GNUNET_OK on success
1114  */
1115 static int
1116 tunnel_destroy (struct MeshTunnel *t)
1117 {
1118   struct MeshClient *c;
1119   struct MeshQueue *q;
1120   struct MeshQueue *qn;
1121   GNUNET_HashCode hash;
1122   int r;
1123
1124   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: DESTROYING TUNNEL at %p\n", t);
1125   if (NULL == t)
1126     return GNUNET_OK;
1127
1128   c = t->client;
1129 #if MESH_DEBUG
1130   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   by client %u\n", c->id);
1131 #endif
1132
1133   GNUNET_CRYPTO_hash (&t->id, sizeof (struct MESH_TunnelID), &hash);
1134   if (GNUNET_YES != GNUNET_CONTAINER_multihashmap_remove (tunnels, &hash, t))
1135   {
1136     r = GNUNET_SYSERR;
1137   }
1138
1139   GNUNET_CRYPTO_hash (&t->local_tid, sizeof (MESH_TunnelNumber), &hash);
1140   if (GNUNET_YES != GNUNET_CONTAINER_multihashmap_remove (c->tunnels, &hash, t))
1141   {
1142     r = GNUNET_SYSERR;
1143   }
1144   GNUNET_CONTAINER_multihashmap_destroy (t->peers);
1145   q = t->queue_head;
1146   while (NULL != q)
1147   {
1148     if (NULL != q->data)
1149       GNUNET_free (q->data);
1150     qn = q->next;
1151     GNUNET_free (q);
1152     q = qn;
1153     /* TODO cancel core transmit ready in case it was active */
1154   }
1155
1156   GNUNET_CONTAINER_multihashmap_iterate(t->tree->first_hops, &iterate_free, t);
1157   GNUNET_CONTAINER_multihashmap_destroy(t->tree->first_hops);
1158   tunnel_destroy_tree_node(t->tree->root);
1159   GNUNET_free(t->tree->root);
1160   GNUNET_free (t->tree);
1161   GNUNET_free (t);
1162   return r;
1163 }
1164
1165
1166 /**
1167  * tunnel_destroy_iterator: iterator for deleting each tunnel that belongs to a
1168  * client when the client disconnects.
1169  * 
1170  * @param cls closure (client that is disconnecting)
1171  * @param key the hash of the local tunnel id (used to access the hashmap)
1172  * @param value the value stored at the key (tunnel to destroy)
1173  * 
1174  * @return GNUNET_OK on success
1175  */
1176 static int
1177 tunnel_destroy_iterator (void *cls, const GNUNET_HashCode * key, void *value)
1178 {
1179   int r;
1180
1181   r = tunnel_destroy ((struct MeshTunnel *) value);
1182   return r;
1183 }
1184
1185
1186 /******************************************************************************/
1187 /****************      MESH NETWORK HANDLER HELPERS     ***********************/
1188 /******************************************************************************/
1189
1190
1191 /**
1192  * Function called to notify a client about the socket
1193  * being ready to queue more data.  "buf" will be
1194  * NULL and "size" zero if the socket was closed for
1195  * writing in the meantime.
1196  *
1197  * @param cls closure
1198  * @param size number of bytes available in buf
1199  * @param buf where the callee should write the message
1200  * @return number of bytes written to buf
1201  */
1202 static size_t
1203 send_core_create_path (void *cls, size_t size, void *buf)
1204 {
1205   struct MeshPathInfo *info = cls;
1206   struct GNUNET_MESH_ManipulatePath *msg;
1207   struct GNUNET_PeerIdentity *peer_ptr;
1208   struct MeshPeerInfo *peer = info->peer;
1209   struct MeshTunnel *t = info->t;
1210   struct MeshPeerPath *p = info->path;
1211   size_t size_needed;
1212   int i;
1213
1214   size_needed =
1215       sizeof (struct GNUNET_MESH_ManipulatePath) +
1216       p->length * sizeof (struct GNUNET_PeerIdentity);
1217
1218   if (size < size_needed || NULL == buf)
1219   {
1220     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: Retransmitting create path\n");
1221     GNUNET_CORE_notify_transmit_ready (core_handle, 0, 0,
1222                                        GNUNET_TIME_UNIT_FOREVER_REL,
1223                                        path_get_first_hop (t->tree, peer->id),
1224                                        size_needed, &send_core_create_path,
1225                                        info);
1226     return 0;
1227   }
1228
1229   msg = (struct GNUNET_MESH_ManipulatePath *) buf;
1230   msg->header.size = htons (size_needed);
1231   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE);
1232   msg->tid = ntohl (t->id.tid);
1233
1234   peer_ptr = (struct GNUNET_PeerIdentity *) &msg[1];
1235   for (i = 0; i < p->length; i++)
1236   {
1237     GNUNET_PEER_resolve (p->peers[i], peer_ptr++);
1238   }
1239
1240   path_destroy (p);
1241   GNUNET_free (info);
1242
1243   return size_needed;
1244 }
1245
1246
1247 #if LATER
1248 /**
1249  * Function called to notify a client about the socket
1250  * being ready to queue more data.  "buf" will be
1251  * NULL and "size" zero if the socket was closed for
1252  * writing in the meantime.
1253  *
1254  * @param cls closure (MeshDataDescriptor with all info to build packet)
1255  * @param size number of bytes available in buf
1256  * @param buf where the callee should write the message
1257  * @return number of bytes written to buf
1258  */
1259 static size_t
1260 send_core_data_to_origin (void *cls, size_t size, void *buf)
1261 {
1262   struct MeshDataDescriptor *info = cls;
1263   struct GNUNET_MESH_ToOrigin *msg = buf;
1264   size_t total_size;
1265
1266   GNUNET_assert (NULL != info);
1267   total_size = sizeof (struct GNUNET_MESH_ToOrigin) + info->size;
1268   GNUNET_assert (total_size < 65536);   /* UNIT16_MAX */
1269
1270   if (total_size > size)
1271   {
1272     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1273                 "not enough buffer to send data to origin\n");
1274     return 0;
1275   }
1276   msg->header.size = htons (total_size);
1277   msg->header.type = htons (GNUNET_MESSAGE_TYPE_DATA_MESSAGE_TO_ORIGIN);
1278   GNUNET_PEER_resolve (info->origin->oid, &msg->oid);
1279   msg->tid = htonl (info->origin->tid);
1280   if (0 != info->size)
1281   {
1282     memcpy (&msg[1], &info[1], info->size);
1283   }
1284   if (NULL != info->client)
1285   {
1286     GNUNET_SERVER_receive_done (info->client, GNUNET_OK);
1287   }
1288   GNUNET_free (info);
1289   return total_size;
1290 }
1291 #endif
1292
1293 /**
1294  * Function called to notify a client about the socket
1295  * being ready to queue more data.  "buf" will be
1296  * NULL and "size" zero if the socket was closed for
1297  * writing in the meantime.
1298  *
1299  * @param cls closure (data itself)
1300  * @param size number of bytes available in buf
1301  * @param buf where the callee should write the message
1302  * @return number of bytes written to buf
1303  */
1304 static size_t
1305 send_core_data_unicast (void *cls, size_t size, void *buf)
1306 {
1307   struct MeshDataDescriptor *info = cls;
1308   struct GNUNET_MESH_Unicast *msg = buf;
1309   size_t total_size;
1310
1311   GNUNET_assert (NULL != info);
1312   total_size = sizeof (struct GNUNET_MESH_Unicast) + info->size;
1313   GNUNET_assert (total_size < 65536);   /* UNIT16_MAX */
1314
1315   if (total_size > size)
1316   {
1317     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1318                 "not enough buffer to send data to peer\n");
1319     return 0;
1320   }
1321   msg->header.size = htons (total_size);
1322   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_UNICAST);
1323   GNUNET_PEER_resolve (info->origin->oid, &msg->oid);
1324   GNUNET_PEER_resolve (info->destination, &msg->destination);
1325   msg->tid = htonl (info->origin->tid);
1326   if (0 != info->size)
1327   {
1328     memcpy (&msg[1], &info[1], info->size);
1329   }
1330   if (NULL != info->client)
1331   {
1332     GNUNET_SERVER_receive_done (info->client, GNUNET_OK);
1333   }
1334   GNUNET_free (info);
1335   return total_size;
1336 }
1337
1338
1339 /**
1340  * Function called to notify a client about the socket
1341  * being ready to queue more data.  "buf" will be
1342  * NULL and "size" zero if the socket was closed for
1343  * writing in the meantime.
1344  *
1345  * @param cls closure (data itself)
1346  * @param size number of bytes available in buf
1347  * @param buf where the callee should write the message
1348  * @return number of bytes written to buf
1349  */
1350 static size_t
1351 send_core_data_multicast (void *cls, size_t size, void *buf)
1352 {
1353   struct MeshDataDescriptor *info = cls;
1354   struct GNUNET_MESH_Multicast *msg = buf;
1355   size_t total_size;
1356
1357   GNUNET_assert (NULL != info);
1358   total_size = info->size + sizeof (struct GNUNET_MESH_Multicast);
1359   GNUNET_assert (total_size < GNUNET_SERVER_MAX_MESSAGE_SIZE);
1360
1361   if (info->peer)
1362   {
1363     info->peer->core_transmit[info->handler_n] = NULL;
1364   }
1365   if (total_size > size)
1366   {
1367     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1368                 "not enough buffer to send data futher\n");
1369     return 0;
1370   }
1371   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_MULTICAST);
1372   msg->header.size = htons (total_size);
1373   GNUNET_PEER_resolve (info->origin->oid, &msg->oid);
1374   msg->tid = htonl (info->origin->tid);
1375   memcpy (&msg[1], &info[1], total_size);
1376   if (0 == --info->copies)
1377   {
1378     if (NULL != info->client)
1379     {
1380       GNUNET_SERVER_receive_done (info->client, GNUNET_OK);
1381     }
1382     GNUNET_free (info);
1383   }
1384   return total_size;
1385 }
1386
1387
1388 /**
1389  * Function called to notify a client about the socket
1390  * being ready to queue more data.  "buf" will be
1391  * NULL and "size" zero if the socket was closed for
1392  * writing in the meantime.
1393  *
1394  * @param cls closure (MeshDataDescriptor)
1395  * @param size number of bytes available in buf
1396  * @param buf where the callee should write the message
1397  * @return number of bytes written to buf
1398  */
1399 static size_t
1400 send_core_path_ack (void *cls, size_t size, void *buf)
1401 {
1402   struct MeshDataDescriptor *info = cls;
1403   struct GNUNET_MESH_PathACK *msg = buf;
1404
1405   GNUNET_assert (NULL != info);
1406   if (info->peer)
1407   {
1408     info->peer->core_transmit[info->handler_n] = NULL;
1409   }
1410   if (sizeof (struct GNUNET_MESH_PathACK) > size)
1411   {
1412     GNUNET_break (0);
1413     return 0;
1414   }
1415   msg->header.size = htons (sizeof (struct GNUNET_MESH_PathACK));
1416   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_ACK);
1417   GNUNET_PEER_resolve (info->origin->oid, &msg->oid);
1418   msg->tid = htonl (info->origin->tid);
1419   msg->peer_id = my_full_id;
1420   GNUNET_free (info);
1421   /* TODO add signature */
1422
1423   return sizeof (struct GNUNET_MESH_PathACK);
1424 }
1425
1426
1427 /**
1428  * Function called to notify a client about the socket
1429  * being ready to queue more data.  "buf" will be
1430  * NULL and "size" zero if the socket was closed for
1431  * writing in the meantime.
1432  *
1433  * @param cls closure (data itself)
1434  * @param size number of bytes available in buf
1435  * @param buf where the callee should write the message
1436  * @return number of bytes written to buf
1437  */
1438 static size_t
1439 send_core_data_raw (void *cls, size_t size, void *buf)
1440 {
1441   struct GNUNET_MessageHeader *msg = cls;
1442   size_t total_size;
1443
1444   GNUNET_assert (NULL != msg);
1445   total_size = ntohs (msg->size);
1446
1447   if (total_size > size)
1448   {
1449     GNUNET_break (0);
1450     return 0;
1451   }
1452   memcpy (buf, msg, total_size);
1453   GNUNET_free (cls);
1454   return total_size;
1455 }
1456
1457
1458 #if LATER
1459 /**
1460  * Send another peer a notification to destroy a tunnel
1461  * @param cls The tunnel to destroy
1462  * @param size Size in the buffer
1463  * @param buf Memory where to put the data to transmit
1464  * @return Size of data put in buffer
1465  */
1466 static size_t
1467 send_p2p_tunnel_destroy (void *cls, size_t size, void *buf)
1468 {
1469   struct MeshTunnel *t = cls;
1470   struct MeshClient *c;
1471   struct GNUNET_MESH_TunnelMessage *msg;
1472
1473   c = t->client;
1474   msg = buf;
1475   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_DESTROY);
1476    /*FIXME*/ msg->header.size =
1477       htons (sizeof (struct GNUNET_MESH_TunnelMessage));
1478   msg->tunnel_id = htonl (t->id.tid);
1479
1480   tunnel_destroy (c, t);
1481   return sizeof (struct GNUNET_MESH_TunnelMessage);
1482 }
1483 #endif
1484
1485
1486 /**
1487  * Send the message to all clients that have subscribed to its type
1488  *
1489  * @param msg Pointer to the message itself
1490  * @return number of clients this message was sent to
1491  */
1492 static unsigned int
1493 send_subscribed_clients (struct GNUNET_MessageHeader *msg)
1494 {
1495   struct MeshClient *c;
1496   unsigned int count;
1497   uint16_t type;
1498
1499   type = ntohs (msg->type);
1500   for (count = 0, c = clients; c != NULL; c = c->next)
1501   {
1502     if (client_is_subscribed (type, c))
1503     {
1504       count++;
1505       GNUNET_SERVER_notification_context_unicast (nc, c->handle, msg,
1506                                                   GNUNET_YES);
1507     }
1508   }
1509   return count;
1510 }
1511
1512
1513
1514 /**
1515  * Notify the client that owns the tunnel that a peer has connected to it
1516  * 
1517  * @param t Tunnel whose owner to notify
1518  * @param id Short id of the peer that has connected
1519  */
1520 static void
1521 send_client_peer_connected (const struct MeshTunnel *t, const GNUNET_PEER_Id id)
1522 {
1523   struct GNUNET_MESH_PeerControl pc;
1524
1525   pc.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD);
1526   pc.header.size = htons (sizeof (struct GNUNET_MESH_PeerControl));
1527   pc.tunnel_id = htonl (t->local_tid);
1528   GNUNET_PEER_resolve (id, &pc.peer);
1529   GNUNET_SERVER_notification_context_unicast (nc, t->client->handle,
1530                                               &pc.header, GNUNET_NO);
1531 }
1532
1533
1534 /******************************************************************************/
1535 /********************      MESH NETWORK HANDLERS     **************************/
1536 /******************************************************************************/
1537
1538
1539 /**
1540  * Core handler for path creation
1541  * struct GNUNET_CORE_MessageHandler
1542  *
1543  * @param cls closure
1544  * @param message message
1545  * @param peer peer identity this notification is about
1546  * @param atsi performance data
1547  * @return GNUNET_OK to keep the connection open,
1548  *         GNUNET_SYSERR to close it (signal serious error)
1549  *
1550  */
1551 static int
1552 handle_mesh_path_create (void *cls, const struct GNUNET_PeerIdentity *peer,
1553                          const struct GNUNET_MessageHeader *message,
1554                          const struct GNUNET_TRANSPORT_ATS_Information *atsi)
1555 {
1556   unsigned int own_pos;
1557   uint16_t size;
1558   uint16_t i;
1559   MESH_TunnelNumber tid;
1560   struct GNUNET_MESH_ManipulatePath *msg;
1561   struct GNUNET_PeerIdentity *pi;
1562   struct GNUNET_PeerIdentity id;
1563   GNUNET_HashCode hash;
1564   struct MeshPeerPath *path;
1565   struct MeshPeerInfo *dest_peer_info;
1566   struct MeshPeerInfo *orig_peer_info;
1567   struct MeshTunnel *t;
1568
1569   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1570               "MESH: Received a MESH path create msg\n");
1571   size = ntohs (message->size);
1572   if (size < sizeof (struct GNUNET_MESH_ManipulatePath))
1573   {
1574     GNUNET_break_op (0);
1575     return GNUNET_OK;
1576   }
1577
1578   size -= sizeof (struct GNUNET_MESH_ManipulatePath);
1579   if (size % sizeof (struct GNUNET_PeerIdentity))
1580   {
1581     GNUNET_break_op (0);
1582     return GNUNET_OK;
1583   }
1584   size /= sizeof (struct GNUNET_PeerIdentity);
1585   if (size < 2)
1586   {
1587     GNUNET_break_op (0);
1588     return GNUNET_OK;
1589   }
1590   msg = (struct GNUNET_MESH_ManipulatePath *) message;
1591
1592   tid = ntohl (msg->tid);
1593   pi = (struct GNUNET_PeerIdentity *) &msg[1];
1594   t = tunnel_get (pi, tid);
1595
1596   if (NULL == t)
1597   {
1598     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: Creating tunnel\n");
1599     t = GNUNET_malloc (sizeof (struct MeshTunnel));
1600     t->id.oid = GNUNET_PEER_intern (pi);
1601     t->id.tid = tid;
1602     t->peers = GNUNET_CONTAINER_multihashmap_create (32);
1603
1604     GNUNET_CRYPTO_hash (&t->id, sizeof (struct MESH_TunnelID), &hash);
1605     if (GNUNET_OK !=
1606         GNUNET_CONTAINER_multihashmap_put (tunnels, &hash, t,
1607                                            GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
1608     {
1609       GNUNET_break (0);
1610       return GNUNET_OK;
1611     }
1612
1613   }
1614   dest_peer_info =
1615       GNUNET_CONTAINER_multihashmap_get (peers, &pi[size - 1].hashPubKey);
1616   if (NULL == dest_peer_info)
1617   {
1618     dest_peer_info = GNUNET_malloc (sizeof (struct MeshPeerInfo));
1619     dest_peer_info->id = GNUNET_PEER_intern (&pi[size - 1]);
1620     GNUNET_CONTAINER_multihashmap_put (peers, &pi[size - 1].hashPubKey,
1621                                        dest_peer_info,
1622                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
1623   }
1624   orig_peer_info = GNUNET_CONTAINER_multihashmap_get (peers, &pi->hashPubKey);
1625   if (NULL == orig_peer_info)
1626   {
1627     orig_peer_info = GNUNET_malloc (sizeof (struct MeshPeerInfo));
1628     orig_peer_info->id = GNUNET_PEER_intern (pi);
1629     GNUNET_CONTAINER_multihashmap_put (peers, &pi->hashPubKey, orig_peer_info,
1630                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
1631   }
1632
1633   path = GNUNET_malloc (sizeof (struct MeshPeerPath));
1634   path->length = size;
1635   path->peers = GNUNET_malloc (size * sizeof (GNUNET_PEER_Id));
1636   own_pos = 0;
1637   for (i = 0; i < size; i++)
1638   {
1639     path->peers[i] = GNUNET_PEER_intern (&pi[i]);
1640     if (path->peers[i] == myid)
1641       own_pos = i;
1642   }
1643   if (own_pos == 0)
1644   {                             /* cannot be self, must be 'not found' */
1645     /* create path: self not found in path through self */
1646     GNUNET_break_op (0);
1647     path_destroy (path);
1648     /* FIXME error. destroy tunnel? leave for timeout? */
1649     return 0;
1650   }
1651   if (own_pos == size - 1)
1652   {
1653     /* It is for us! Send ack. */
1654     struct MeshDataDescriptor *info;
1655     unsigned int j;
1656
1657     path_add_to_origin (orig_peer_info, path);  /* inverts path!  */
1658     info = GNUNET_malloc (sizeof (struct MeshDataDescriptor));
1659     info->origin = &t->id;
1660     info->peer = GNUNET_CONTAINER_multihashmap_get (peers, &id.hashPubKey);
1661     GNUNET_assert (info->peer);
1662     for (j = 0; info->peer->core_transmit[j]; j++)
1663     {
1664       if (j == 9)
1665       {
1666         GNUNET_break (0);
1667         return GNUNET_OK;
1668       }
1669     }
1670     info->handler_n = j;
1671     info->peer->core_transmit[j] =
1672         GNUNET_CORE_notify_transmit_ready (core_handle, 0, 100,
1673                                            GNUNET_TIME_UNIT_FOREVER_REL, peer,
1674                                            sizeof (struct GNUNET_MessageHeader),
1675                                            &send_core_path_ack, info);
1676   }
1677   else
1678   {
1679     /* It's for somebody else! Retransmit. */
1680     struct MeshPathInfo *path_info;
1681
1682     path_info = GNUNET_malloc (sizeof (struct MeshPathInfo));
1683     path_info->t = t;
1684     path_info->path = path;
1685     path_info->peer = dest_peer_info;
1686
1687     path_add_to_peer (dest_peer_info, path);
1688     GNUNET_PEER_resolve (path->peers[own_pos + 1], &id);
1689     GNUNET_CORE_notify_transmit_ready (core_handle, 0, 0,
1690                                        GNUNET_TIME_UNIT_FOREVER_REL, &id,
1691                                        sizeof (struct GNUNET_MessageHeader),
1692                                        &send_core_create_path, path_info);
1693   }
1694   return GNUNET_OK;
1695 }
1696
1697
1698 /**
1699  * Core handler for mesh network traffic going from the origin to a peer
1700  *
1701  * @param cls closure
1702  * @param peer peer identity this notification is about
1703  * @param message message
1704  * @param atsi performance data
1705  * @return GNUNET_OK to keep the connection open,
1706  *         GNUNET_SYSERR to close it (signal serious error)
1707  */
1708 static int
1709 handle_mesh_data_unicast (void *cls, const struct GNUNET_PeerIdentity *peer,
1710                           const struct GNUNET_MessageHeader *message,
1711                           const struct GNUNET_TRANSPORT_ATS_Information *atsi)
1712 {
1713   struct GNUNET_MESH_Unicast *msg;
1714   struct MeshTunnel *t;
1715   struct MeshPeerInfo *pi;
1716   size_t size;
1717
1718   size = ntohs (message->size);
1719   if (size <
1720       sizeof (struct GNUNET_MESH_Unicast) +
1721       sizeof (struct GNUNET_MessageHeader))
1722   {
1723     GNUNET_break (0);
1724     return GNUNET_OK;
1725   }
1726   msg = (struct GNUNET_MESH_Unicast *) message;
1727   t = tunnel_get (&msg->oid, ntohl (msg->tid));
1728   if (NULL == t)
1729   {
1730     /* TODO notify back: we don't know this tunnel */
1731     return GNUNET_OK;
1732   }
1733   pi = GNUNET_CONTAINER_multihashmap_get (t->peers,
1734                                           &msg->destination.hashPubKey);
1735   if (NULL == pi)
1736   {
1737     /* TODO maybe feedback, log to statistics */
1738     return GNUNET_OK;
1739   }
1740   if (pi->id == myid)
1741   {
1742     send_subscribed_clients ((struct GNUNET_MessageHeader *) &msg[1]);
1743     return GNUNET_OK;
1744   }
1745   msg = GNUNET_malloc (size);
1746   memcpy (msg, message, size);
1747   GNUNET_CORE_notify_transmit_ready (core_handle, 0, 0,
1748                                      GNUNET_TIME_UNIT_FOREVER_REL,
1749                                      path_get_first_hop (t->tree, pi->id),
1750                                      size,
1751                                      &send_core_data_raw, msg);
1752   return GNUNET_OK;
1753 }
1754
1755
1756 /**
1757  * Core handler for mesh network traffic going from the origin to all peers
1758  *
1759  * @param cls closure
1760  * @param message message
1761  * @param peer peer identity this notification is about
1762  * @param atsi performance data
1763  * @return GNUNET_OK to keep the connection open,
1764  *         GNUNET_SYSERR to close it (signal serious error)
1765  */
1766 static int
1767 handle_mesh_data_multicast (void *cls, const struct GNUNET_PeerIdentity *peer,
1768                             const struct GNUNET_MessageHeader *message,
1769                             const struct GNUNET_TRANSPORT_ATS_Information *atsi)
1770 {
1771   struct GNUNET_MESH_Multicast *msg;
1772   struct GNUNET_PeerIdentity id;
1773   struct MeshDataDescriptor *info;
1774   struct MeshPathInfo neighbors;
1775   struct MeshTunnel *t;
1776   size_t size;
1777   uint16_t i;
1778   uint16_t j;
1779
1780
1781   size = ntohs (message->size);
1782   if (size <
1783       sizeof (struct GNUNET_MESH_Multicast) +
1784       sizeof (struct GNUNET_MessageHeader))
1785   {
1786     GNUNET_break_op (0);
1787     return GNUNET_OK;
1788   }
1789   msg = (struct GNUNET_MESH_Multicast *) message;
1790   t = tunnel_get (&msg->oid, ntohl (msg->tid));
1791
1792   if (NULL == t)
1793   {
1794     /* TODO notify that we dont know that tunnel */
1795     return GNUNET_OK;
1796   }
1797
1798   /* Transmit to locally interested clients */
1799   if (GNUNET_CONTAINER_multihashmap_contains (t->peers, &my_full_id.hashPubKey))
1800   {
1801     send_subscribed_clients ((struct GNUNET_MessageHeader *) &msg[1]);
1802   }
1803
1804   /* Retransmit to other peers.
1805    * Using path here as just a collection of peers, not a path per se.
1806    */
1807   neighbors.t = t;
1808   neighbors.path = GNUNET_malloc (sizeof (struct MeshPeerPath));
1809   GNUNET_CONTAINER_multihashmap_iterate (t->peers, &iterate_collect_neighbors,
1810                                          &neighbors);
1811   if (0 == neighbors.path->length)
1812   {
1813     GNUNET_free (neighbors.path);
1814     return GNUNET_OK;
1815   }
1816   size -= sizeof (struct GNUNET_MESH_Multicast);
1817   info = GNUNET_malloc (sizeof (struct MeshDataDescriptor) + size);
1818   info->origin = &t->id;
1819   info->copies = neighbors.path->length;
1820   for (i = 0; i < info->copies; i++)
1821   {
1822     GNUNET_PEER_resolve (neighbors.path->peers[i], &id);
1823     info->peer = GNUNET_CONTAINER_multihashmap_get (peers, &id.hashPubKey);
1824     GNUNET_assert (NULL != info->peer);
1825     for (j = 0; 0 != info->peer->core_transmit[j]; j++)
1826     {
1827       if (j == (CORE_QUEUE_SIZE - 1))
1828       {
1829         GNUNET_break (0);
1830         return GNUNET_OK;
1831       }
1832     }
1833     info->handler_n = j;
1834     info->peer->infos[j] = info;
1835     info->peer->core_transmit[j] =
1836         GNUNET_CORE_notify_transmit_ready (core_handle, 0, 0,
1837                                            GNUNET_TIME_UNIT_FOREVER_REL, &id,
1838                                            ntohs (msg->header.size),
1839                                            &send_core_data_multicast, info);
1840   }
1841   GNUNET_free (neighbors.path->peers);
1842   GNUNET_free (neighbors.path);
1843   return GNUNET_OK;
1844 }
1845
1846
1847 /**
1848  * Core handler for mesh network traffic
1849  *
1850  * @param cls closure
1851  * @param message message
1852  * @param peer peer identity this notification is about
1853  * @param atsi performance data
1854  *
1855  * @return GNUNET_OK to keep the connection open,
1856  *         GNUNET_SYSERR to close it (signal serious error)
1857  */
1858 static int
1859 handle_mesh_data_to_orig (void *cls, const struct GNUNET_PeerIdentity *peer,
1860                           const struct GNUNET_MessageHeader *message,
1861                           const struct GNUNET_TRANSPORT_ATS_Information *atsi)
1862 {
1863   struct GNUNET_MESH_ToOrigin *msg;
1864   struct GNUNET_PeerIdentity id;
1865   struct MeshPeerInfo *peer_info;
1866   struct MeshTunnel *t;
1867   size_t size;
1868
1869   size = ntohs (message->size);
1870   if (size < sizeof (struct GNUNET_MESH_ToOrigin) +     /* Payload must be */
1871       sizeof (struct GNUNET_MessageHeader))     /* at least a header */
1872   {
1873     GNUNET_break_op (0);
1874     return GNUNET_OK;
1875   }
1876   msg = (struct GNUNET_MESH_ToOrigin *) message;
1877   t = tunnel_get (&msg->oid, ntohl (msg->tid));
1878
1879   if (NULL == t)
1880   {
1881     /* TODO notify that we dont know this tunnel (whom)? */
1882     return GNUNET_OK;
1883   }
1884
1885   if (t->id.oid == myid)
1886   {
1887     if (NULL == t->client)
1888     {
1889       /* got data packet for ownerless tunnel */
1890       GNUNET_break_op (0);
1891       return GNUNET_OK;
1892     }
1893     /* TODO signature verification */
1894     GNUNET_SERVER_notification_context_unicast (nc, t->client->handle, message,
1895                                                 GNUNET_YES);
1896     return GNUNET_OK;
1897   }
1898   peer_info = peer_info_get (&msg->oid);
1899   if (NULL == peer_info)
1900   {
1901     /* unknown origin of tunnel */
1902     GNUNET_break (0);
1903     return GNUNET_OK;
1904   }
1905   GNUNET_PEER_resolve (t->tree->me->parent->peer, &id);
1906   msg = GNUNET_malloc (size);
1907   memcpy (msg, message, size);
1908   GNUNET_CORE_notify_transmit_ready (core_handle, 0, 0,
1909                                      GNUNET_TIME_UNIT_FOREVER_REL, &id, size,
1910                                      &send_core_data_raw, msg);
1911
1912   return GNUNET_OK;
1913 }
1914
1915
1916 /**
1917  * Core handler for path ACKs
1918  *
1919  * @param cls closure
1920  * @param message message
1921  * @param peer peer identity this notification is about
1922  * @param atsi performance data
1923  *
1924  * @return GNUNET_OK to keep the connection open,
1925  *         GNUNET_SYSERR to close it (signal serious error)
1926  *
1927  * FIXME path change state
1928  */
1929 static int
1930 handle_mesh_path_ack (void *cls, const struct GNUNET_PeerIdentity *peer,
1931                       const struct GNUNET_MessageHeader *message,
1932                       const struct GNUNET_TRANSPORT_ATS_Information *atsi)
1933 {
1934   struct GNUNET_MESH_PathACK *msg;
1935   struct MeshTunnel *t;
1936   struct MeshPeerInfo *peer_info;
1937
1938   msg = (struct GNUNET_MESH_PathACK *) message;
1939   t = tunnel_get (&msg->oid, msg->tid);
1940   if (NULL == t)
1941   {
1942     /* TODO notify that we don't know the tunnel */
1943     return GNUNET_OK;
1944   }
1945
1946   /* Message for us? */
1947   if (0 == memcmp (&msg->oid, &my_full_id, sizeof (struct GNUNET_PeerIdentity)))
1948   {
1949
1950     if (NULL == t->client)
1951     {
1952       GNUNET_break (0);
1953       return GNUNET_OK;
1954     }
1955     peer_info = peer_info_get (&msg->peer_id);
1956     if (NULL == peer_info)
1957     {
1958       GNUNET_break_op (0);
1959       return GNUNET_OK;
1960     }
1961     /* FIXME change state of peer */
1962     send_client_peer_connected(t, peer_info->id);
1963     return GNUNET_OK;
1964   }
1965
1966   peer_info = peer_info_get (&msg->oid);
1967   if (NULL == peer_info)
1968   {
1969     /* If we know the tunnel, we should DEFINITELY know the peer */
1970     GNUNET_break (0);
1971     return GNUNET_OK;
1972   }
1973   msg = GNUNET_malloc (sizeof (struct GNUNET_MESH_PathACK));
1974   memcpy (msg, message, sizeof (struct GNUNET_MESH_PathACK));
1975   GNUNET_CORE_notify_transmit_ready (core_handle, 0, 0,
1976                                      GNUNET_TIME_UNIT_FOREVER_REL,
1977                                      path_get_first_hop (t->tree,
1978                                                          peer_info->id),
1979                                      sizeof (struct GNUNET_MESH_PathACK),
1980                                      &send_core_data_raw, msg);
1981   return GNUNET_OK;
1982 }
1983
1984
1985 /**
1986  * Functions to handle messages from core
1987  */
1988 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
1989   {&handle_mesh_path_create, GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE, 0},
1990   {&handle_mesh_data_unicast, GNUNET_MESSAGE_TYPE_MESH_UNICAST, 0},
1991   {&handle_mesh_data_multicast, GNUNET_MESSAGE_TYPE_MESH_MULTICAST, 0},
1992   {&handle_mesh_data_to_orig, GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN, 0},
1993   {&handle_mesh_path_ack, GNUNET_MESSAGE_TYPE_MESH_PATH_ACK,
1994    sizeof (struct GNUNET_MESH_PathACK)},
1995   {NULL, 0, 0}
1996 };
1997
1998
1999
2000 /******************************************************************************/
2001 /****************       MESH LOCAL HANDLER HELPERS      ***********************/
2002 /******************************************************************************/
2003
2004 /**
2005  * deregister_app: iterator for removing each application registered by a client
2006  * 
2007  * @param cls closure
2008  * @param key the hash of the application id (used to access the hashmap)
2009  * @param value the value stored at the key (client)
2010  * 
2011  * @return GNUNET_OK on success
2012  */
2013 static int
2014 deregister_app (void *cls, const GNUNET_HashCode * key, void *value)
2015 {
2016   GNUNET_CONTAINER_multihashmap_remove (applications, key, value);
2017   return GNUNET_OK;
2018 }
2019
2020 #if LATER
2021 /**
2022  * notify_client_connection_failure: notify a client that the connection to the
2023  * requested remote peer is not possible (for instance, no route found)
2024  * Function called when the socket is ready to queue more data. "buf" will be
2025  * NULL and "size" zero if the socket was closed for writing in the meantime.
2026  *
2027  * @param cls closure
2028  * @param size number of bytes available in buf
2029  * @param buf where the callee should write the message
2030  * @return number of bytes written to buf
2031  */
2032 static size_t
2033 notify_client_connection_failure (void *cls, size_t size, void *buf)
2034 {
2035   int size_needed;
2036   struct MeshPeerInfo *peer_info;
2037   struct GNUNET_MESH_PeerControl *msg;
2038   struct GNUNET_PeerIdentity id;
2039
2040   if (0 == size && NULL == buf)
2041   {
2042     // TODO retry? cancel?
2043     return 0;
2044   }
2045
2046   size_needed = sizeof (struct GNUNET_MESH_PeerControl);
2047   peer_info = (struct MeshPeerInfo *) cls;
2048   msg = (struct GNUNET_MESH_PeerControl *) buf;
2049   msg->header.size = htons (sizeof (struct GNUNET_MESH_PeerControl));
2050   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_DISCONNECTED);
2051 //     msg->tunnel_id = htonl(peer_info->t->tid);
2052   GNUNET_PEER_resolve (peer_info->id, &id);
2053   memcpy (&msg->peer, &id, sizeof (struct GNUNET_PeerIdentity));
2054
2055   return size_needed;
2056 }
2057 #endif
2058
2059
2060 /**
2061  * Function to process paths received for a new peer addition. The recorded
2062  * paths form the initial tunnel, which can be optimized later.
2063  * Called on each result obtained for the DHT search.
2064  *
2065  * @param cls closure
2066  * @param exp when will this value expire
2067  * @param key key of the result
2068  * @param get_path NULL-terminated array of pointers
2069  *                 to the peers on reverse GET path (or NULL if not recorded)
2070  * @param put_path NULL-terminated array of pointers
2071  *                 to the peers on the PUT path (or NULL if not recorded)
2072  * @param type type of the result
2073  * @param size number of bytes in data
2074  * @param data pointer to the result data
2075  *
2076  * FIXME path
2077  */
2078 static void
2079 dht_get_id_handler (void *cls, struct GNUNET_TIME_Absolute exp,
2080                     const GNUNET_HashCode * key,
2081                     const struct GNUNET_PeerIdentity *const *get_path,
2082                     const struct GNUNET_PeerIdentity *const *put_path,
2083                     enum GNUNET_BLOCK_Type type, size_t size, const void *data)
2084 {
2085   struct MeshPathInfo *path_info = cls;
2086   struct MeshPeerPath *p;
2087   struct GNUNET_PeerIdentity pi;
2088   int i;
2089
2090   if (NULL == get_path || NULL == put_path)
2091   {
2092     if (NULL == path_info->peer->path_head)
2093     {
2094       // Find ourselves some alternate initial path to the destination: retry
2095       GNUNET_DHT_get_stop (path_info->peer->dhtget);
2096       GNUNET_PEER_resolve (path_info->peer->id, &pi);
2097       path_info->peer->dhtget = GNUNET_DHT_get_start (dht_handle,       /* handle */
2098                                                       GNUNET_TIME_UNIT_FOREVER_REL,     /* timeout */
2099                                                       GNUNET_BLOCK_TYPE_TEST,   /* type */
2100                                                       &pi.hashPubKey,   /*key to search */
2101                                                       4,        /* replication level */
2102                                                       GNUNET_DHT_RO_RECORD_ROUTE, NULL, /* bloom filter */
2103                                                       0,        /* mutator */
2104                                                       NULL,     /* xquery */
2105                                                       0,        /* xquery bits */
2106                                                       dht_get_id_handler,
2107                                                       (void *) path_info);
2108       return;
2109     }
2110   }
2111
2112   p = path_build_from_dht (get_path, put_path);
2113   path_add_to_peer (path_info->peer, p);
2114   for (i = 0; i < path_info->peer->ntunnels; i++)
2115   {
2116     tunnel_add_peer (path_info->peer->tunnels[i], path_info->peer);
2117   }
2118   GNUNET_free (path_info);
2119
2120   return;
2121 }
2122
2123
2124 /**
2125  * Function to process paths received for a new peer addition. The recorded
2126  * paths form the initial tunnel, which can be optimized later.
2127  * Called on each result obtained for the DHT search.
2128  *
2129  * @param cls closure
2130  * @param exp when will this value expire
2131  * @param key key of the result
2132  * @param get_path NULL-terminated array of pointers
2133  *                 to the peers on reverse GET path (or NULL if not recorded)
2134  * @param put_path NULL-terminated array of pointers
2135  *                 to the peers on the PUT path (or NULL if not recorded)
2136  * @param type type of the result
2137  * @param size number of bytes in data
2138  * @param data pointer to the result data
2139  */
2140 static void
2141 dht_get_type_handler (void *cls, struct GNUNET_TIME_Absolute exp,
2142                       const GNUNET_HashCode * key,
2143                       const struct GNUNET_PeerIdentity *const *get_path,
2144                       const struct GNUNET_PeerIdentity *const *put_path,
2145                       enum GNUNET_BLOCK_Type type, size_t size,
2146                       const void *data)
2147 {
2148   const struct GNUNET_PeerIdentity *pi = data;
2149   struct GNUNET_PeerIdentity id;
2150   struct MeshTunnel *t = cls;
2151   struct MeshPeerInfo *peer_info;
2152   struct MeshPathInfo *path_info;
2153   struct MeshPeerPath *p;
2154   int i;
2155
2156   if (size != sizeof (struct GNUNET_PeerIdentity))
2157   {
2158     GNUNET_break_op (0);
2159     return;
2160   }
2161   GNUNET_assert (NULL != t->client);
2162   GNUNET_DHT_get_stop (t->client->dht_get_type);
2163   t->client->dht_get_type = NULL;
2164   peer_info = peer_info_get (pi);
2165   GNUNET_CONTAINER_multihashmap_put (t->peers, &pi->hashPubKey, peer_info,
2166                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
2167
2168   if ((NULL == get_path || NULL == put_path) && NULL == peer_info->path_head &&
2169       NULL == peer_info->dhtget)
2170   {
2171     /* we don't have a route to the peer, let's try a direct lookup */
2172     peer_info->dhtget = GNUNET_DHT_get_start (dht_handle,
2173                                               /* handle */
2174                                               GNUNET_TIME_UNIT_FOREVER_REL,
2175                                               /* timeout */
2176                                               GNUNET_BLOCK_TYPE_TEST,
2177                                               /* block type */
2178                                               &pi->hashPubKey,
2179                                               /* key to look up */
2180                                               10U,
2181                                               /* replication level */
2182                                               GNUNET_DHT_RO_RECORD_ROUTE,
2183                                               /* option to dht: record route */
2184                                               NULL,     /* bloom filter */
2185                                               0,        /* mutator */
2186                                               NULL,     /* xquery */
2187                                               0,        /* xquery bits */
2188                                               dht_get_id_handler,
2189                                               /* callback */
2190                                               peer_info);       /* closure */
2191   }
2192
2193   p = path_build_from_dht (get_path, put_path);
2194   path_add_to_peer (peer_info, p);
2195   tunnel_add_peer(t, peer_info);
2196   p = tree_get_path_to_peer(t->tree, peer_info->id);
2197 #if MESH_DEBUG
2198   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2199               "MESH: new route for tunnel 0x%x found, has %u hops\n",
2200               t->local_tid, p->length);
2201   for (i = 0; i < p->length; i++)
2202   {
2203     GNUNET_PEER_resolve (p->peers[0], &id);
2204     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:\t%d\t%s\n", i,
2205                 GNUNET_h2s_full (&id.hashPubKey));
2206   }
2207 #endif
2208
2209   if (p->length > 1)
2210   {
2211     path_info = GNUNET_malloc(sizeof(struct MeshPathInfo));
2212     path_info->t = t;
2213     path_info->peer = peer_info;
2214     path_info->path = p;
2215     GNUNET_PEER_resolve (p->peers[1], &id);
2216     GNUNET_CORE_notify_transmit_ready (core_handle,
2217                                      /* handle */
2218                                      0,
2219                                      /* cork */
2220                                      0,
2221                                      /* priority */
2222                                      GNUNET_TIME_UNIT_FOREVER_REL,
2223                                      /* timeout */
2224                                      &id,
2225                                      /* target */
2226                                      sizeof (struct GNUNET_MESH_ManipulatePath)
2227                                      +
2228                                      (p->length *
2229                                       sizeof (struct GNUNET_PeerIdentity)),
2230                                      /*size */
2231                                      &send_core_create_path,
2232                                      /* callback */
2233                                      path_info);        /* cls */
2234     return;
2235   }
2236   path_destroy(p);
2237   send_client_peer_connected(t, myid);
2238 }
2239
2240 /******************************************************************************/
2241 /*********************       MESH LOCAL HANDLES      **************************/
2242 /******************************************************************************/
2243
2244
2245 /**
2246  * Handler for client disconnection
2247  *
2248  * @param cls closure
2249  * @param client identification of the client; NULL
2250  *        for the last call when the server is destroyed
2251  */
2252 static void
2253 handle_local_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
2254 {
2255   struct MeshClient *c;
2256   struct MeshClient *next;
2257
2258   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: client disconnected\n");
2259   if (client == NULL)
2260      GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:    (SERVER DOWN)\n");
2261   c = clients;
2262   while (NULL != c)
2263   {
2264     if (c->handle != client && NULL != client)
2265     {
2266       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:    ... searching\n");
2267       c = c->next;
2268       continue;
2269     }
2270     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: matching client found\n");
2271     if (NULL != c->tunnels)
2272     {
2273       GNUNET_CONTAINER_multihashmap_iterate (c->tunnels,
2274                                              &tunnel_destroy_iterator,
2275                                              c);
2276       GNUNET_CONTAINER_multihashmap_destroy (c->tunnels);
2277     }
2278
2279     /* deregister clients applications */
2280     if (NULL != c->apps)
2281     {
2282       GNUNET_CONTAINER_multihashmap_iterate (c->apps, &deregister_app, NULL);
2283       GNUNET_CONTAINER_multihashmap_destroy (c->apps);
2284     }
2285     if (0 == GNUNET_CONTAINER_multihashmap_size (applications) &&
2286         GNUNET_SCHEDULER_NO_TASK != announce_applications_task)
2287     {
2288       GNUNET_SCHEDULER_cancel (announce_applications_task);
2289       announce_applications_task = GNUNET_SCHEDULER_NO_TASK;
2290     }
2291     if (NULL != c->types)
2292       GNUNET_CONTAINER_multihashmap_destroy (c->types);
2293     if (NULL != c->dht_get_type)
2294       GNUNET_DHT_get_stop (c->dht_get_type);
2295     GNUNET_CONTAINER_DLL_remove (clients, clients_tail, c);
2296     next = c->next;
2297     GNUNET_free (c);
2298     c = next;
2299   }
2300
2301   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:    done!\n");
2302   return;
2303 }
2304
2305
2306 /**
2307  * Handler for new clients
2308  *
2309  * @param cls closure
2310  * @param client identification of the client
2311  * @param message the actual message, which includes messages the client wants
2312  */
2313 static void
2314 handle_local_new_client (void *cls, struct GNUNET_SERVER_Client *client,
2315                          const struct GNUNET_MessageHeader *message)
2316 {
2317   struct GNUNET_MESH_ClientConnect *cc_msg;
2318   struct MeshClient *c;
2319   GNUNET_MESH_ApplicationType *a;
2320   unsigned int size;
2321   uint16_t ntypes;
2322   uint16_t *t;
2323   uint16_t napps;
2324   uint16_t i;
2325
2326   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: new client connected\n");
2327   /* Check data sanity */
2328   size = ntohs (message->size) - sizeof (struct GNUNET_MESH_ClientConnect);
2329   cc_msg = (struct GNUNET_MESH_ClientConnect *) message;
2330   ntypes = ntohs (cc_msg->types);
2331   napps = ntohs (cc_msg->applications);
2332   if (size !=
2333       ntypes * sizeof (uint16_t) + napps * sizeof (GNUNET_MESH_ApplicationType))
2334   {
2335     GNUNET_break (0);
2336     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2337     return;
2338   }
2339
2340   /* Create new client structure */
2341   c = GNUNET_malloc (sizeof (struct MeshClient));
2342 #if MESH_DEBUG
2343   c->id = next_client_id++;
2344 #endif
2345   c->handle = client;
2346   a = (GNUNET_MESH_ApplicationType *) &cc_msg[1];
2347   if (napps > 0)
2348   {
2349     GNUNET_MESH_ApplicationType at;
2350     GNUNET_HashCode hc;
2351
2352     c->apps = GNUNET_CONTAINER_multihashmap_create (napps);
2353     for (i = 0; i < napps; i++)
2354     {
2355       at = ntohl (a[i]);
2356       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   app type: %u\n", at);
2357       GNUNET_CRYPTO_hash (&at, sizeof (at), &hc);
2358       /* store in clients hashmap */
2359       GNUNET_CONTAINER_multihashmap_put (c->apps, &hc, c,
2360                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2361       /* store in global hashmap, for announcements */
2362       GNUNET_CONTAINER_multihashmap_put (applications, &hc, c,
2363                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2364     }
2365     if (GNUNET_SCHEDULER_NO_TASK == announce_applications_task)
2366       announce_applications_task =
2367           GNUNET_SCHEDULER_add_now (&announce_applications, NULL);
2368
2369   }
2370   if (ntypes > 0)
2371   {
2372     uint16_t u16;
2373     GNUNET_HashCode hc;
2374
2375     t = (uint16_t *) & a[napps];
2376     c->types = GNUNET_CONTAINER_multihashmap_create (ntypes);
2377     for (i = 0; i < ntypes; i++)
2378     {
2379       u16 = ntohs (t[i]);
2380       GNUNET_CRYPTO_hash (&u16, sizeof (u16), &hc);
2381
2382       /* store in clients hashmap */
2383       GNUNET_CONTAINER_multihashmap_put (c->types, &hc, c,
2384                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2385       /* store in global hashmap */
2386       GNUNET_CONTAINER_multihashmap_put (types, &hc, c,
2387                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2388     }
2389   }
2390   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2391               "MESH:  client has %u+%u subscriptions\n", napps, ntypes);
2392
2393   GNUNET_CONTAINER_DLL_insert (clients, clients_tail, c);
2394   c->tunnels = GNUNET_CONTAINER_multihashmap_create (32);
2395   GNUNET_SERVER_notification_context_add (nc, client);
2396
2397   GNUNET_SERVER_receive_done (client, GNUNET_OK);
2398 #if MESH_DEBUG
2399   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: new client processed\n");
2400 #endif
2401 }
2402
2403
2404 /**
2405  * Handler for requests of new tunnels
2406  *
2407  * @param cls closure
2408  * @param client identification of the client
2409  * @param message the actual message
2410  */
2411 static void
2412 handle_local_tunnel_create (void *cls, struct GNUNET_SERVER_Client *client,
2413                             const struct GNUNET_MessageHeader *message)
2414 {
2415   struct GNUNET_MESH_TunnelMessage *t_msg;
2416   struct MeshTunnel *t;
2417   struct MeshClient *c;
2418   GNUNET_HashCode hash;
2419
2420   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: new tunnel requested\n");
2421
2422   /* Sanity check for client registration */
2423   if (NULL == (c = client_get (client)))
2424   {
2425     GNUNET_break (0);
2426     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2427     return;
2428   }
2429 #if MESH_DEBUG
2430   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   by client %u\n", c->id);
2431 #endif
2432
2433   /* Message sanity check */
2434   if (sizeof (struct GNUNET_MESH_TunnelMessage) != ntohs (message->size))
2435   {
2436     GNUNET_break (0);
2437     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2438     return;
2439   }
2440
2441   t_msg = (struct GNUNET_MESH_TunnelMessage *) message;
2442   /* Sanity check for tunnel numbering */
2443   if (0 == (ntohl (t_msg->tunnel_id) & GNUNET_MESH_LOCAL_TUNNEL_ID_CLI))
2444   {
2445     GNUNET_break (0);
2446     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2447     return;
2448   }
2449   /* Sanity check for duplicate tunnel IDs */
2450   if (NULL != tunnel_get_by_local_id (c, ntohl (t_msg->tunnel_id)))
2451   {
2452     GNUNET_break (0);
2453     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2454     return;
2455   }
2456
2457   t = GNUNET_malloc (sizeof (struct MeshTunnel));
2458   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: CREATED TUNNEL at %p\n", t);
2459   while (NULL != tunnel_get_by_pi (myid, next_tid))
2460     next_tid = (next_tid + 1) & ~GNUNET_MESH_LOCAL_TUNNEL_ID_CLI;
2461   t->id.tid = next_tid++;
2462   t->id.oid = myid;
2463   t->local_tid = ntohl (t_msg->tunnel_id);
2464   t->client = c;
2465   t->peers = GNUNET_CONTAINER_multihashmap_create (32);
2466
2467   GNUNET_CRYPTO_hash (&t->local_tid, sizeof (MESH_TunnelNumber), &hash);
2468   if (GNUNET_OK !=
2469       GNUNET_CONTAINER_multihashmap_put (c->tunnels, &hash, t,
2470                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
2471   {
2472     GNUNET_break (0);
2473     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2474     return;
2475   }
2476
2477   GNUNET_CRYPTO_hash (&t->id, sizeof (struct MESH_TunnelID), &hash);
2478   if (GNUNET_OK !=
2479       GNUNET_CONTAINER_multihashmap_put (tunnels, &hash, t,
2480                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
2481   {
2482     GNUNET_break (0);
2483     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2484     return;
2485   }
2486   t->tree = GNUNET_malloc (sizeof(struct MeshTunnelTree));
2487   t->tree->first_hops = GNUNET_CONTAINER_multihashmap_create(32);
2488   t->tree->t = t;
2489   t->tree->refresh = REFRESH_PATH_TIME;
2490   t->tree->root = GNUNET_malloc(sizeof(struct MeshTunnelTreeNode));
2491   t->tree->root->status = MESH_PEER_READY;
2492   t->tree->root->t = t;
2493   t->tree->root->peer = myid;
2494   t->tree->me = t->tree->root;
2495
2496   GNUNET_SERVER_receive_done (client, GNUNET_OK);
2497   return;
2498 }
2499
2500
2501 /**
2502  * Handler for requests of deleting tunnels
2503  *
2504  * @param cls closure
2505  * @param client identification of the client
2506  * @param message the actual message
2507  */
2508 static void
2509 handle_local_tunnel_destroy (void *cls, struct GNUNET_SERVER_Client *client,
2510                              const struct GNUNET_MessageHeader *message)
2511 {
2512   struct GNUNET_MESH_TunnelMessage *tunnel_msg;
2513   struct MeshClient *c;
2514   struct MeshTunnel *t;
2515   MESH_TunnelNumber tid;
2516   GNUNET_HashCode hash;
2517
2518   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: destroying tunnel\n");
2519
2520   /* Sanity check for client registration */
2521   if (NULL == (c = client_get (client)))
2522   {
2523     GNUNET_break (0);
2524     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2525     return;
2526   }
2527   /* Message sanity check */
2528   if (sizeof (struct GNUNET_MESH_TunnelMessage) != ntohs (message->size))
2529   {
2530     GNUNET_break (0);
2531     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2532     return;
2533   }
2534 #if MESH_DEBUG
2535   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   by client %u\n", c->id);
2536 #endif
2537   tunnel_msg = (struct GNUNET_MESH_TunnelMessage *) message;
2538
2539   /* Retrieve tunnel */
2540   tid = ntohl (tunnel_msg->tunnel_id);
2541
2542   /* Remove from local id hashmap */
2543   GNUNET_CRYPTO_hash (&tid, sizeof (MESH_TunnelNumber), &hash);
2544   t = GNUNET_CONTAINER_multihashmap_get (c->tunnels, &hash);
2545   GNUNET_CONTAINER_multihashmap_remove (c->tunnels, &hash, t);
2546
2547   /* Remove from global id hashmap */
2548   GNUNET_CRYPTO_hash (&t->id, sizeof (struct MESH_TunnelID), &hash);
2549   GNUNET_CONTAINER_multihashmap_remove (tunnels, &hash, t);
2550
2551 //     notify_tunnel_destroy(t); FIXME
2552   tunnel_destroy(t);
2553   GNUNET_SERVER_receive_done (client, GNUNET_OK);
2554   return;
2555 }
2556
2557
2558 /**
2559  * Handler for connection requests to new peers
2560  *
2561  * @param cls closure
2562  * @param client identification of the client
2563  * @param message the actual message (PeerControl)
2564  *
2565  * FIXME path
2566  */
2567 static void
2568 handle_local_connect_add (void *cls, struct GNUNET_SERVER_Client *client,
2569                           const struct GNUNET_MessageHeader *message)
2570 {
2571   struct GNUNET_MESH_PeerControl *peer_msg;
2572   struct MeshClient *c;
2573   struct MeshTunnel *t;
2574   MESH_TunnelNumber tid;
2575   struct MeshPeerInfo *peer_info;
2576
2577
2578   /* Sanity check for client registration */
2579   if (NULL == (c = client_get (client)))
2580   {
2581     GNUNET_break (0);
2582     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2583     return;
2584   }
2585
2586   peer_msg = (struct GNUNET_MESH_PeerControl *) message;
2587   /* Sanity check for message size */
2588   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (peer_msg->header.size))
2589   {
2590     GNUNET_break (0);
2591     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2592     return;
2593   }
2594
2595   /* Tunnel exists? */
2596   tid = ntohl (peer_msg->tunnel_id);
2597   t = tunnel_get_by_local_id (c, tid);
2598   if (NULL == t)
2599   {
2600     GNUNET_break (0);
2601     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2602     return;
2603   }
2604
2605   /* Does client own tunnel? */
2606   if (t->client->handle != client)
2607   {
2608     GNUNET_break (0);
2609     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2610     return;
2611   }
2612
2613   t->peers_total++;
2614   peer_info = peer_info_get (&peer_msg->peer);
2615
2616   /* Start DHT search if needed FIXME: if not already connected */
2617   if (NULL == peer_info->dhtget)
2618   {
2619     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 */
2620                                               GNUNET_DHT_RO_RECORD_ROUTE, NULL, /* bloom filter */
2621                                               0,        /* mutator */
2622                                               NULL,     /* xquery */
2623                                               0,        /* xquery bits */
2624                                               dht_get_id_handler,
2625                                               (void *) peer_info);
2626   }
2627
2628   GNUNET_SERVER_receive_done (client, GNUNET_OK);
2629   return;
2630 }
2631
2632
2633 /**
2634  * Handler for disconnection requests of peers in a tunnel
2635  *
2636  * @param cls closure
2637  * @param client identification of the client
2638  * @param message the actual message (PeerControl)
2639  */
2640 static void
2641 handle_local_connect_del (void *cls, struct GNUNET_SERVER_Client *client,
2642                           const struct GNUNET_MessageHeader *message)
2643 {
2644   struct GNUNET_MESH_PeerControl *peer_msg;
2645   struct MeshClient *c;
2646   struct MeshTunnel *t;
2647   MESH_TunnelNumber tid;
2648
2649   /* Sanity check for client registration */
2650   if (NULL == (c = client_get (client)))
2651   {
2652     GNUNET_break (0);
2653     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2654     return;
2655   }
2656   peer_msg = (struct GNUNET_MESH_PeerControl *) message;
2657   /* Sanity check for message size */
2658   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (peer_msg->header.size))
2659   {
2660     GNUNET_break (0);
2661     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2662     return;
2663   }
2664
2665   /* Tunnel exists? */
2666   tid = ntohl (peer_msg->tunnel_id);
2667   t = tunnel_get_by_local_id (c, tid);
2668   if (NULL == t)
2669   {
2670     GNUNET_break (0);
2671     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2672     return;
2673   }
2674
2675   /* Does client own tunnel? */
2676   if (t->client->handle != client)
2677   {
2678     GNUNET_break (0);
2679     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2680     return;
2681   }
2682
2683   /* Ok, delete peer from tunnel */
2684   GNUNET_CONTAINER_multihashmap_remove_all (t->peers,
2685                                             &peer_msg->peer.hashPubKey);
2686
2687   GNUNET_SERVER_receive_done (client, GNUNET_OK);
2688   return;
2689 }
2690
2691
2692 /**
2693  * Handler for connection requests to new peers by type
2694  *
2695  * @param cls closure
2696  * @param client identification of the client
2697  * @param message the actual message (ConnectPeerByType)
2698  */
2699 static void
2700 handle_local_connect_by_type (void *cls, struct GNUNET_SERVER_Client *client,
2701                               const struct GNUNET_MessageHeader *message)
2702 {
2703   struct GNUNET_MESH_ConnectPeerByType *connect_msg;
2704   struct MeshClient *c;
2705   struct MeshTunnel *t;
2706   GNUNET_HashCode hash;
2707   GNUNET_MESH_ApplicationType type;
2708   MESH_TunnelNumber tid;
2709
2710   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: got connect by type request\n");
2711   /* Sanity check for client registration */
2712   if (NULL == (c = client_get (client)))
2713   {
2714     GNUNET_break (0);
2715     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2716     return;
2717   }
2718
2719   connect_msg = (struct GNUNET_MESH_ConnectPeerByType *) message;
2720   /* Sanity check for message size */
2721   if (sizeof (struct GNUNET_MESH_ConnectPeerByType) !=
2722       ntohs (connect_msg->header.size))
2723   {
2724     GNUNET_break (0);
2725     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2726     return;
2727   }
2728
2729   /* Tunnel exists? */
2730   tid = ntohl (connect_msg->tunnel_id);
2731   t = tunnel_get_by_local_id (c, tid);
2732   if (NULL == t)
2733   {
2734     GNUNET_break (0);
2735     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2736     return;
2737   }
2738
2739   /* Does client own tunnel? */
2740   if (t->client->handle != client)
2741   {
2742     GNUNET_break (0);
2743     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2744     return;
2745   }
2746
2747   /* Do WE have the service? */
2748   type = ntohl (connect_msg->type);
2749   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:  type requested: %u\n", type);
2750   GNUNET_CRYPTO_hash (&type, sizeof (GNUNET_MESH_ApplicationType), &hash);
2751   if (GNUNET_CONTAINER_multihashmap_contains (applications, &hash) ==
2752       GNUNET_YES)
2753   {
2754     /* Yes! Fast forward, add ourselves to the tunnel and send the
2755      * good news to the client
2756      */
2757     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:  available locally\n");
2758     GNUNET_CONTAINER_multihashmap_put (t->peers, &my_full_id.hashPubKey,
2759                                        peer_info_get (&my_full_id),
2760                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
2761
2762     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:  notifying client\n");
2763     send_client_peer_connected(t, myid);
2764     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:  Done\n");
2765     GNUNET_SERVER_receive_done (client, GNUNET_OK);
2766     return;
2767   }
2768   /* Ok, lets find a peer offering the service */
2769   if (c->dht_get_type)
2770   {
2771     GNUNET_DHT_get_stop (c->dht_get_type);
2772   }
2773   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:  looking in DHT for %s\n",
2774               GNUNET_h2s_full (&hash));
2775   c->dht_get_type =
2776       GNUNET_DHT_get_start (dht_handle, GNUNET_TIME_UNIT_FOREVER_REL,
2777                             GNUNET_BLOCK_TYPE_TEST, &hash, 10U,
2778                             GNUNET_DHT_RO_RECORD_ROUTE, NULL, 0, NULL, 0,
2779                             &dht_get_type_handler, t);
2780
2781   GNUNET_SERVER_receive_done (client, GNUNET_OK);
2782   return;
2783 }
2784
2785
2786 /**
2787  * Handler for client traffic directed to one peer
2788  *
2789  * @param cls closure
2790  * @param client identification of the client
2791  * @param message the actual message
2792  */
2793 static void
2794 handle_local_unicast (void *cls, struct GNUNET_SERVER_Client *client,
2795                       const struct GNUNET_MessageHeader *message)
2796 {
2797   struct MeshClient *c;
2798   struct MeshTunnel *t;
2799   struct MeshPeerInfo *pi;
2800   struct GNUNET_MESH_Unicast *data_msg;
2801   struct MeshDataDescriptor *info;
2802   MESH_TunnelNumber tid;
2803   size_t data_size;
2804
2805   /* Sanity check for client registration */
2806   if (NULL == (c = client_get (client)))
2807   {
2808     GNUNET_break (0);
2809     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2810     return;
2811   }
2812   data_msg = (struct GNUNET_MESH_Unicast *) message;
2813   /* Sanity check for message size */
2814   if (sizeof (struct GNUNET_MESH_Unicast) +
2815       sizeof (struct GNUNET_MessageHeader) > ntohs (data_msg->header.size))
2816   {
2817     GNUNET_break (0);
2818     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2819     return;
2820   }
2821
2822   /* Tunnel exists? */
2823   tid = ntohl (data_msg->tid);
2824   t = tunnel_get_by_local_id (c, tid);
2825   if (NULL == t)
2826   {
2827     GNUNET_break (0);
2828     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2829     return;
2830   }
2831
2832   /*  Is it a local tunnel? Then, does client own the tunnel? */
2833   if (t->client->handle != NULL && t->client->handle != client)
2834   {
2835     GNUNET_break (0);
2836     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2837     return;
2838   }
2839
2840   pi = GNUNET_CONTAINER_multihashmap_get (t->peers,
2841                                           &data_msg->destination.hashPubKey);
2842   /* Is the selected peer in the tunnel? */
2843   if (NULL == pi)
2844   {
2845     GNUNET_break (0);
2846     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2847     return;
2848   }
2849   if (pi->id == myid)
2850   {
2851     struct GNUNET_MESH_Unicast copy;
2852
2853     /* Work around const limitation */
2854     memcpy (&copy, data_msg, sizeof (struct GNUNET_MESH_Unicast));
2855     copy.oid = my_full_id;
2856     copy.tid = htonl (t->id.tid);
2857     handle_mesh_data_unicast (NULL, &my_full_id, &copy.header, NULL);
2858     return;
2859   }
2860   data_size = ntohs (message->size) - sizeof (struct GNUNET_MESH_Unicast);
2861   info = GNUNET_malloc (sizeof (struct MeshDataDescriptor) + data_size);
2862   memcpy (&info[1], &data_msg[1], data_size);
2863   info->destination = pi->id;
2864   info->origin = &t->id;
2865   info->size = data_size;
2866   info->client = client;
2867   GNUNET_CORE_notify_transmit_ready (core_handle, 0, 0,
2868                                      GNUNET_TIME_UNIT_FOREVER_REL,
2869                                      path_get_first_hop (t->tree, pi->id),
2870                                      /* FIXME re-check types */
2871                                      data_size +
2872                                      sizeof (struct GNUNET_MESH_Unicast),
2873                                      &send_core_data_unicast, info);
2874   return;
2875 }
2876
2877 /**
2878  * Handler for client traffic directed to all peers in a tunnel
2879  *
2880  * @param cls closure
2881  * @param client identification of the client
2882  * @param message the actual message
2883  */
2884 static void
2885 handle_local_multicast (void *cls, struct GNUNET_SERVER_Client *client,
2886                         const struct GNUNET_MessageHeader *message)
2887 {
2888   struct MeshClient *c;
2889   struct MeshTunnel *t;
2890   struct GNUNET_MESH_Multicast *data_msg;
2891   MESH_TunnelNumber tid;
2892
2893   /* Sanity check for client registration */
2894   if (NULL == (c = client_get (client)))
2895   {
2896     GNUNET_break (0);
2897     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2898     return;
2899   }
2900   data_msg = (struct GNUNET_MESH_Multicast *) message;
2901   /* Sanity check for message size */
2902   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (data_msg->header.size))
2903   {
2904     GNUNET_break (0);
2905     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2906     return;
2907   }
2908
2909   /* Tunnel exists? */
2910   tid = ntohl (data_msg->tid);
2911   t = tunnel_get_by_local_id (c, tid);
2912   if (NULL == t)
2913   {
2914     GNUNET_break (0);
2915     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2916     return;
2917   }
2918
2919   /* Does client own tunnel? */
2920   if (t->client->handle != client)
2921   {
2922     GNUNET_break (0);
2923     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2924     return;
2925   }
2926
2927   /*  TODO */
2928
2929   GNUNET_SERVER_receive_done (client, GNUNET_OK);
2930   return;
2931 }
2932
2933 /**
2934  * Functions to handle messages from clients
2935  */
2936 static struct GNUNET_SERVER_MessageHandler client_handlers[] = {
2937   {&handle_local_new_client, NULL, GNUNET_MESSAGE_TYPE_MESH_LOCAL_CONNECT, 0},
2938   {&handle_local_tunnel_create, NULL,
2939    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_CREATE,
2940    sizeof (struct GNUNET_MESH_TunnelMessage)},
2941   {&handle_local_tunnel_destroy, NULL,
2942    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_DESTROY,
2943    sizeof (struct GNUNET_MESH_TunnelMessage)},
2944   {&handle_local_connect_add, NULL,
2945    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD,
2946    sizeof (struct GNUNET_MESH_PeerControl)},
2947   {&handle_local_connect_del, NULL,
2948    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_DEL,
2949    sizeof (struct GNUNET_MESH_PeerControl)},
2950   {&handle_local_connect_by_type, NULL,
2951    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD_BY_TYPE,
2952    sizeof (struct GNUNET_MESH_ConnectPeerByType)},
2953   {&handle_local_unicast, NULL,
2954    GNUNET_MESSAGE_TYPE_MESH_UNICAST, 0},
2955   {&handle_local_unicast, NULL,
2956    GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN, 0},
2957   {&handle_local_multicast, NULL,
2958    GNUNET_MESSAGE_TYPE_MESH_MULTICAST, 0},
2959   {NULL, NULL, 0, 0}
2960 };
2961
2962
2963 /**
2964  * To be called on core init/fail.
2965  *
2966  * @param cls service closure
2967  * @param server handle to the server for this service
2968  * @param identity the public identity of this peer
2969  * @param publicKey the public key of this peer
2970  */
2971 static void
2972 core_init (void *cls, struct GNUNET_CORE_Handle *server,
2973            const struct GNUNET_PeerIdentity *identity,
2974            const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *publicKey)
2975 {
2976   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: Core init\n");
2977   core_handle = server;
2978   if (0 != memcmp(identity, &my_full_id, sizeof(my_full_id)) || NULL == server)
2979   {
2980     GNUNET_log(GNUNET_ERROR_TYPE_ERROR, _("MESH: Wrong CORE service\n"));
2981     GNUNET_SCHEDULER_shutdown();   
2982   }
2983   return;
2984 }
2985
2986 /**
2987  * Method called whenever a given peer connects.
2988  *
2989  * @param cls closure
2990  * @param peer peer identity this notification is about
2991  * @param atsi performance data for the connection
2992  */
2993 static void
2994 core_connect (void *cls, const struct GNUNET_PeerIdentity *peer,
2995               const struct GNUNET_TRANSPORT_ATS_Information *atsi)
2996 {
2997 //     GNUNET_PEER_Id              pid;
2998   struct MeshPeerInfo *peer_info;
2999   struct MeshPeerPath *path;
3000
3001   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: Peer connected\n");
3002   peer_info = peer_info_get (peer);
3003   if (myid == peer_info->id)
3004   {
3005     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:      (self)\n");
3006     return;
3007   }
3008   path = GNUNET_malloc (sizeof (struct MeshPeerPath));
3009   path->length = 2;
3010   path->peers = GNUNET_malloc (sizeof (GNUNET_PEER_Id) * 2);
3011   path->peers[0] = myid;
3012   path->peers[1] = peer_info->id;
3013   path_add_to_peer (peer_info, path);
3014   return;
3015 }
3016
3017 /**
3018  * Method called whenever a peer disconnects.
3019  *
3020  * @param cls closure
3021  * @param peer peer identity this notification is about
3022  */
3023 static void
3024 core_disconnect (void *cls, const struct GNUNET_PeerIdentity *peer)
3025 {
3026   struct MeshPeerInfo *pi;
3027   unsigned int i;
3028
3029   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: Peer disconnected\n");
3030   pi = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
3031   if (!pi)
3032   {
3033     GNUNET_break (0);
3034     return;
3035   }
3036   for (i = 0; i < CORE_QUEUE_SIZE; i++)
3037   {
3038     if (pi->core_transmit[i])
3039     {
3040       GNUNET_CORE_notify_transmit_ready_cancel (pi->core_transmit[i]);
3041       /* TODO: notify that tranmission has failed */
3042       GNUNET_free (pi->infos[i]);
3043     }
3044   }
3045   path_remove_from_peer (pi, pi->id, myid);
3046   if (myid == pi->id)
3047   {
3048     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:      (self)\n");
3049   }
3050   return;
3051 }
3052
3053
3054 /******************************************************************************/
3055 /************************      MAIN FUNCTIONS      ****************************/
3056 /******************************************************************************/
3057
3058 /**
3059  * Task run during shutdown.
3060  *
3061  * @param cls unused
3062  * @param tc unused
3063  */
3064 static void
3065 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3066 {
3067   struct MeshClient *c;
3068
3069   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: shutting down\n");
3070   if (core_handle != NULL)
3071   {
3072     GNUNET_CORE_disconnect (core_handle);
3073     core_handle = NULL;
3074   }
3075   if (dht_handle != NULL)
3076   {
3077     for (c = clients; NULL != c; c = c->next)
3078       if (NULL != c->dht_get_type)
3079         GNUNET_DHT_get_stop (c->dht_get_type);
3080     GNUNET_DHT_disconnect (dht_handle);
3081     dht_handle = NULL;
3082   }
3083   if (nc != NULL)
3084   {
3085     GNUNET_SERVER_notification_context_destroy (nc);
3086     nc = NULL;
3087   }
3088   if (GNUNET_SCHEDULER_NO_TASK != announce_id_task)
3089   {
3090     GNUNET_SCHEDULER_cancel (announce_id_task);
3091     announce_id_task = GNUNET_SCHEDULER_NO_TASK;
3092   }
3093   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: shut down\n");
3094 }
3095
3096 /**
3097  * Process mesh requests.
3098  *
3099  * @param cls closure
3100  * @param server the initialized server
3101  * @param c configuration to use
3102  */
3103 static void
3104 run (void *cls, struct GNUNET_SERVER_Handle *server,
3105      const struct GNUNET_CONFIGURATION_Handle *c)
3106 {
3107   struct MeshPeerInfo *peer;
3108   struct MeshPeerPath *p;
3109   char *keyfile;
3110
3111   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: starting to run\n");
3112   server_handle = server;
3113   core_handle = GNUNET_CORE_connect (c, /* Main configuration */
3114                                      CORE_QUEUE_SIZE,   /* queue size */
3115                                      NULL,      /* Closure passed to MESH functions */
3116                                      &core_init,        /* Call core_init once connected */
3117                                      &core_connect,     /* Handle connects */
3118                                      &core_disconnect,  /* remove peers on disconnects */
3119                                      NULL,      /* Do we care about "status" updates? */
3120                                      NULL,      /* Don't notify about all incoming messages */
3121                                      GNUNET_NO, /* For header only in notification */
3122                                      NULL,      /* Don't notify about all outbound messages */
3123                                      GNUNET_NO, /* For header-only out notification */
3124                                      core_handlers);    /* Register these handlers */
3125   if (core_handle == NULL)
3126   {
3127     GNUNET_break (0);
3128     GNUNET_SCHEDULER_shutdown ();
3129     return;
3130   }
3131
3132   if (GNUNET_OK !=
3133        GNUNET_CONFIGURATION_get_value_filename (c, "GNUNETD", "HOSTKEY",
3134                                                 &keyfile))
3135   {
3136     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3137                 _
3138                 ("Mesh service is lacking key configuration settings.  Exiting.\n"));
3139     GNUNET_SCHEDULER_shutdown ();
3140     return;
3141   }
3142   my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
3143   GNUNET_free (keyfile);
3144   if (my_private_key == NULL)
3145   {
3146     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3147                 _("Mesh service could not access hostkey.  Exiting.\n"));
3148     GNUNET_SCHEDULER_shutdown ();
3149     return;
3150   }
3151   GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
3152   GNUNET_CRYPTO_hash (&my_public_key, sizeof (my_public_key),
3153                       &my_full_id.hashPubKey);
3154   myid = GNUNET_PEER_intern (&my_full_id);
3155
3156   dht_handle = GNUNET_DHT_connect (c, 64);
3157   if (dht_handle == NULL)
3158   {
3159     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Error connecting to DHT.\
3160                    Running without DHT has a severe\
3161                    impact in MESH capabilities.\n\
3162                    Plase check your configuretion and enable DHT.\n");
3163     GNUNET_break (0);
3164   }
3165
3166   next_tid = 0;
3167
3168   tunnels = GNUNET_CONTAINER_multihashmap_create (32);
3169   peers = GNUNET_CONTAINER_multihashmap_create (32);
3170   applications = GNUNET_CONTAINER_multihashmap_create (32);
3171   types = GNUNET_CONTAINER_multihashmap_create (32);
3172
3173   GNUNET_SERVER_add_handlers (server_handle, client_handlers);
3174   nc = GNUNET_SERVER_notification_context_create (server_handle,
3175                                                   LOCAL_QUEUE_SIZE);
3176   GNUNET_SERVER_disconnect_notify (server_handle,
3177                                    &handle_local_client_disconnect,
3178                                    NULL);
3179
3180
3181   clients = NULL;
3182   clients_tail = NULL;
3183 #if MESH_DEBUG
3184   next_client_id = 0;
3185 #endif
3186
3187   announce_applications_task = GNUNET_SCHEDULER_NO_TASK;
3188   announce_id_task = GNUNET_SCHEDULER_add_now (&announce_id, cls);
3189
3190   /* Create a peer_info for the local peer */
3191   peer = peer_info_get(&my_full_id);
3192   p = GNUNET_malloc (sizeof (struct MeshPeerPath));
3193   p->peers = GNUNET_malloc (sizeof (GNUNET_PEER_Id));
3194   p->length = 1;
3195   p->peers[0] = myid;
3196   path_add_to_peer(peer, p);
3197
3198   /* Scheduled the task to clean up when shutdown is called */
3199   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
3200                                 NULL);
3201
3202   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: end of run()\n");
3203 }
3204
3205 /**
3206  * The main function for the mesh service.
3207  *
3208  * @param argc number of arguments from the command line
3209  * @param argv command line arguments
3210  * @return 0 ok, 1 on error
3211  */
3212 int
3213 main (int argc, char *const *argv)
3214 {
3215   int ret;
3216
3217 #if MESH_DEBUG
3218   fprintf (stderr, "main ()\n");
3219 #endif
3220   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: main()\n");
3221   ret =
3222       (GNUNET_OK ==
3223        GNUNET_SERVICE_run (argc, argv, "mesh", GNUNET_SERVICE_OPTION_NONE, &run,
3224                            NULL)) ? 0 : 1;
3225   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: main() END\n");
3226 #if MESH_DEBUG
3227   fprintf (stderr, "main () END\n");
3228 #endif
3229   return ret;
3230 }