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