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