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