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