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