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