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