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