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