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