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