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