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