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