Mesh adds info about paths to peers as early as possible to avoid unoptimal routes...
[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  * - relay corking down to core
44  * - set ttl relative to tree depth
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 #define UNACKNOWLEDGED_WAIT     GNUNET_TIME_relative_multiply(\
70                                     GNUNET_TIME_UNIT_SECONDS,\
71                                     2)
72 #define DEFAULT_TTL     64
73
74 #define MESH_DEBUG_DHT GNUNET_NO
75
76
77
78 /******************************************************************************/
79 /************************      DATA STRUCTURES     ****************************/
80 /******************************************************************************/
81
82 /** FWD declaration */
83 struct MeshPeerInfo;
84
85 /**
86  * Struct containing all info possibly needed to build a package when called
87  * back by core.
88  */
89 struct MeshDataDescriptor
90 {
91     /** ID of the tunnel this packet travels in */
92   struct MESH_TunnelID *origin;
93
94     /** Data itself */
95   void *data;
96
97     /** Client that asked for the transmission, if any */
98   struct GNUNET_SERVER_Client *client;
99
100     /** Who was this message being sent to */
101   struct MeshPeerInfo *peer;
102
103     /** Ultimate destination of the packet */
104   GNUNET_PEER_Id destination;
105
106     /** Number of identical messages sent to different hops (multicast) */
107   unsigned int *copies;
108
109     /** Which handler was used to request the transmission */
110   unsigned int handler_n;
111
112     /** Size of the data */
113   size_t size;
114
115     /** Used to allow a client send more traffic to the service after a
116      * previous packet was tried to be sent to a neighbor and couldn't */
117   GNUNET_SCHEDULER_TaskIdentifier *timeout_task;
118 };
119
120
121 /**
122  * Struct containing all information regarding a given peer
123  */
124 struct MeshPeerInfo
125 {
126     /**
127      * ID of the peer
128      */
129   GNUNET_PEER_Id id;
130
131     /**
132      * Last time we heard from this peer
133      */
134   struct GNUNET_TIME_Absolute last_contact;
135
136     /**
137      * Number of attempts to reconnect so far
138      */
139   int n_reconnect_attempts;
140
141     /**
142      * Paths to reach the peer, ordered by ascending hop count
143      */
144   struct MeshPeerPath *path_head;
145
146     /**
147      * Paths to reach the peer, ordered by ascending hop count
148      */
149   struct MeshPeerPath *path_tail;
150
151     /**
152      * Handle to stop the DHT search for a path to this peer
153      */
154   struct GNUNET_DHT_GetHandle *dhtget;
155
156     /**
157      * Closure given to the DHT GET
158      */
159   struct MeshPathInfo *dhtgetcls;
160
161     /**
162      * Handles to stop queued transmissions for this peer
163      */
164   struct GNUNET_CORE_TransmitHandle *core_transmit[CORE_QUEUE_SIZE];
165
166     /**
167      * Pointer to info stuctures used as cls for queued transmissions
168      */
169   void *infos[CORE_QUEUE_SIZE];
170
171     /**
172      * Type of message being in each transmission
173      */
174   uint16_t types[CORE_QUEUE_SIZE];
175
176     /**
177      * Array of tunnels this peer participates in
178      * (most probably a small amount, therefore not a hashmap)
179      * When the path to the peer changes, notify these tunnels to let them
180      * re-adjust their path trees.
181      */
182   struct MeshTunnel **tunnels;
183
184     /**
185      * Number of tunnels this peers participates in
186      */
187   unsigned int ntunnels;
188 };
189
190
191 /**
192  * Data scheduled to transmit (to local client or remote peer)
193  */
194 struct MeshQueue
195 {
196     /**
197      * Double linked list
198      */
199   struct MeshQueue *next;
200   struct MeshQueue *prev;
201
202     /**
203      * Target of the data (NULL if target is client)
204      */
205   struct MeshPeerInfo *peer;
206
207     /**
208      * Client to send the data to (NULL if target is peer)
209      */
210   struct MeshClient *client;
211
212     /**
213      * Size of the message to transmit
214      */
215   unsigned int size;
216
217     /**
218      * How old is the data?
219      */
220   struct GNUNET_TIME_Absolute timestamp;
221
222     /**
223      * Data itself
224      */
225   struct GNUNET_MessageHeader *data;
226 };
227
228 /**
229  * Globally unique tunnel identification (owner + number)
230  * DO NOT USE OVER THE NETWORK
231  */
232 struct MESH_TunnelID
233 {
234     /**
235      * Node that owns the tunnel
236      */
237   GNUNET_PEER_Id oid;
238
239     /**
240      * Tunnel number to differentiate all the tunnels owned by the node oid
241      * ( tid < GNUNET_MESH_LOCAL_TUNNEL_ID_CLI )
242      */
243   MESH_TunnelNumber tid;
244 };
245
246
247 struct MeshClient;              /* FWD declaration */
248
249 /**
250  * Struct containing all information regarding a tunnel
251  * For an intermediate node the improtant info used will be:
252  * - id        Tunnel unique identification
253  * - paths[0]  To know where to send it next
254  * - metainfo: ready, speeds, accounting
255  */
256 struct MeshTunnel
257 {
258     /**
259      * Tunnel ID
260      */
261   struct MESH_TunnelID id;
262
263     /**
264      * Local tunnel number ( >= GNUNET_MESH_LOCAL_TUNNEL_ID_CLI or 0 )
265      */
266   MESH_TunnelNumber local_tid;
267
268     /**
269      * ID of the last multicast packet seen/sent.
270      */
271   uint32_t mid;
272
273     /**
274      * Last time the tunnel was used
275      */
276   struct GNUNET_TIME_Absolute timestamp;
277
278     /**
279      * Peers in the tunnel, indexed by PeerIdentity -> (MeshPeerInfo)
280      * containing peers added by id or by type, not intermediate peers.
281      */
282   struct GNUNET_CONTAINER_MultiHashMap *peers;
283
284     /**
285      * Number of peers that are connected and potentially ready to receive data
286      */
287   unsigned int peers_ready;
288
289     /**
290      * Number of peers that have been added to the tunnel
291      */
292   unsigned int peers_total;
293
294     /**
295      * Client owner of the tunnel, if any
296      */
297   struct MeshClient *client;
298
299     /**
300      * Messages ready to transmit
301      */
302   struct MeshQueue *queue_head;
303   struct MeshQueue *queue_tail;
304
305   /**
306    * Tunnel paths
307    */
308   struct MeshTunnelTree *tree;
309
310   /**
311    * Application type we are looking for in this tunnel
312    */
313   GNUNET_MESH_ApplicationType type;
314
315     /**
316      * Used to search peers offering a service
317      */
318   struct GNUNET_DHT_GetHandle *dht_get_type;
319
320   /**
321    * Task to keep the used paths alive
322    */
323   GNUNET_SCHEDULER_TaskIdentifier path_refresh_task;
324
325   /**
326    * Task to destroy the tunnel after timeout
327    *
328    * FIXME: merge the two? a tunnel will have either
329    * a path refresh OR a timeout, never both!
330    */
331   GNUNET_SCHEDULER_TaskIdentifier timeout_task;
332 };
333
334
335 /**
336  * Info needed to work with tunnel paths and peers
337  */
338 struct MeshPathInfo
339 {
340   /**
341    * Tunnel
342    */
343   struct MeshTunnel *t;
344
345   /**
346    * Neighbouring peer to whom we send the packet to
347    */
348   struct MeshPeerInfo *peer;
349
350   /**
351    * Path itself
352    */
353   struct MeshPeerPath *path;
354
355   /**
356    * Position in peer's transmit queue
357    */
358   unsigned int pos;
359 };
360
361
362 /**
363  * Struct containing information about a client of the service
364  */
365 struct MeshClient
366 {
367     /**
368      * Linked list
369      */
370   struct MeshClient *next;
371   struct MeshClient *prev;
372
373     /**
374      * Tunnels that belong to this client, indexed by local id
375      */
376   struct GNUNET_CONTAINER_MultiHashMap *tunnels;
377
378     /**
379      * Handle to communicate with the client
380      */
381   struct GNUNET_SERVER_Client *handle;
382
383     /**
384      * Applications that this client has claimed to provide
385      */
386   struct GNUNET_CONTAINER_MultiHashMap *apps;
387
388     /**
389      * Messages that this client has declared interest in
390      */
391   struct GNUNET_CONTAINER_MultiHashMap *types;
392
393 #if MESH_DEBUG
394     /**
395      * ID of the client, for debug messages
396      */
397   unsigned int id;
398 #endif
399
400 };
401
402
403
404 /******************************************************************************/
405 /************************      DEBUG FUNCTIONS     ****************************/
406 /******************************************************************************/
407
408 #if MESH_DEBUG
409 /**
410  * GNUNET_SCHEDULER_Task for printing a message after some operation is done
411  * @param cls string to print
412  * @param tc task context
413  */
414 static void
415 mesh_debug (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
416 {
417   char *s = cls;
418
419   if (GNUNET_SCHEDULER_REASON_SHUTDOWN == tc->reason)
420   {
421     return;
422   }
423   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: %s\n", s);
424 }
425 #endif
426
427 /******************************************************************************/
428 /***********************      GLOBAL VARIABLES     ****************************/
429 /******************************************************************************/
430
431 /**
432  * All the clients
433  */
434 static struct MeshClient *clients;
435 static struct MeshClient *clients_tail;
436
437 /**
438  * Tunnels known, indexed by MESH_TunnelID (MeshTunnel)
439  */
440 static struct GNUNET_CONTAINER_MultiHashMap *tunnels;
441
442 /**
443  * Tunnels incoming, indexed by MESH_TunnelNumber
444  * (which is greater than GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
445  */
446 static struct GNUNET_CONTAINER_MultiHashMap *incoming_tunnels;
447
448 /**
449  * Peers known, indexed by PeerIdentity (MeshPeerInfo)
450  */
451 static struct GNUNET_CONTAINER_MultiHashMap *peers;
452
453 /**
454  * Handle to communicate with core
455  */
456 static struct GNUNET_CORE_Handle *core_handle;
457
458 /**
459  * Handle to communicate with transport
460  */
461 // static struct GNUNET_TRANSPORT_Handle *transport_handle;
462
463 /**
464  * Handle to use DHT
465  */
466 static struct GNUNET_DHT_Handle *dht_handle;
467
468 /**
469  * Handle to server
470  */
471 static struct GNUNET_SERVER_Handle *server_handle;
472
473 /**
474  * Notification context, to send messages to local clients
475  */
476 static struct GNUNET_SERVER_NotificationContext *nc;
477
478 /**
479  * Local peer own ID (memory efficient handle)
480  */
481 static GNUNET_PEER_Id myid;
482
483 /**
484  * Local peer own ID (full value)
485  */
486 static struct GNUNET_PeerIdentity my_full_id;
487
488 /**
489  * Own private key
490  */
491 static struct GNUNET_CRYPTO_RsaPrivateKey *my_private_key;
492
493 /**
494  * Own public key.
495  */
496 static struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded my_public_key;
497
498 /**
499  * Tunnel ID for the next created tunnel (global tunnel number)
500  */
501 static MESH_TunnelNumber next_tid;
502
503 /**
504  * Tunnel ID for the next incoming tunnel (local tunnel number)
505  */
506 static MESH_TunnelNumber next_local_tid;
507
508 /**
509  * All application types provided by this peer
510  */
511 static struct GNUNET_CONTAINER_MultiHashMap *applications;
512
513 /**
514  * All message types clients of this peer are interested in
515  */
516 static struct GNUNET_CONTAINER_MultiHashMap *types;
517
518 /**
519  * Task to periodically announce provided applications
520  */
521 GNUNET_SCHEDULER_TaskIdentifier announce_applications_task;
522
523 /**
524  * Task to periodically announce itself in the network
525  */
526 GNUNET_SCHEDULER_TaskIdentifier announce_id_task;
527
528 #if MESH_DEBUG
529 unsigned int next_client_id;
530 #endif
531
532
533 /******************************************************************************/
534 /************************         ITERATORS        ****************************/
535 /******************************************************************************/
536
537 /* FIXME move iterators here */
538
539
540 /******************************************************************************/
541 /************************    PERIODIC FUNCTIONS    ****************************/
542 /******************************************************************************/
543
544 /**
545  * Announce iterator over for each application provided by the peer
546  *
547  * @param cls closure
548  * @param key current key code
549  * @param value value in the hash map
550  * @return GNUNET_YES if we should continue to
551  *         iterate,
552  *         GNUNET_NO if not.
553  */
554 static int
555 announce_application (void *cls, const GNUNET_HashCode * key, void *value)
556 {
557   /* FIXME are hashes in multihash map equal on all aquitectures? */
558   GNUNET_DHT_put (dht_handle, key, 10U,
559                   GNUNET_DHT_RO_RECORD_ROUTE |
560                   GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE, GNUNET_BLOCK_TYPE_TEST,
561                   sizeof (struct GNUNET_PeerIdentity),
562                   (const char *) &my_full_id,
563 #if MESH_DEBUG
564                   GNUNET_TIME_UNIT_FOREVER_ABS, GNUNET_TIME_UNIT_FOREVER_REL,
565                   &mesh_debug, "DHT_put for app completed");
566 #else
567                   GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get (),
568                                             APP_ANNOUNCE_TIME),
569                   APP_ANNOUNCE_TIME, NULL, NULL);
570 #endif
571   return GNUNET_OK;
572 }
573
574
575 /**
576  * Periodically announce what applications are provided by local clients
577  *
578  * @param cls closure
579  * @param tc task context
580  */
581 static void
582 announce_applications (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
583 {
584   if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
585   {
586     announce_applications_task = GNUNET_SCHEDULER_NO_TASK;
587     return;
588   }
589 #if MESH_DEBUG_DHT
590   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: Starting PUT for apps\n");
591 #endif
592   GNUNET_CONTAINER_multihashmap_iterate (applications, &announce_application,
593                                          NULL);
594   announce_applications_task =
595       GNUNET_SCHEDULER_add_delayed (APP_ANNOUNCE_TIME, &announce_applications,
596                                     cls);
597 #if MESH_DEBUG_DHT
598   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: Finished PUT for apps\n");
599 #endif
600   return;
601 }
602
603
604 /**
605  * Periodically announce self id in the DHT
606  *
607  * @param cls closure
608  * @param tc task context
609  */
610 static void
611 announce_id (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
612 {
613   if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
614   {
615     announce_id_task = GNUNET_SCHEDULER_NO_TASK;
616     return;
617   }
618   /* TODO
619    * - Set data expiration in function of X
620    * - Adapt X to churn
621    */
622 #if MESH_DEBUG_DHT
623   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: DHT_put for ID %s started.\n",
624               GNUNET_i2s (&my_full_id));
625 #endif
626   GNUNET_DHT_put (dht_handle,   /* DHT handle */
627                   &my_full_id.hashPubKey,       /* Key to use */
628                   10U,          /* Replication level */
629                   GNUNET_DHT_RO_RECORD_ROUTE | GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE,    /* DHT options */
630                   GNUNET_BLOCK_TYPE_TEST,       /* Block type */
631                   sizeof (my_full_id),  /* Size of the data */
632                   (char *) &my_full_id, /* Data itself */
633                   GNUNET_TIME_absolute_get_forever (),  /* Data expiration */
634                   GNUNET_TIME_UNIT_FOREVER_REL, /* Retry time */
635 #if MESH_DEBUG_DHT
636                   &mesh_debug, "DHT_put for id completed");
637 #else
638                   NULL,         /* Continuation */
639                   NULL);        /* Continuation closure */
640 #endif
641   announce_id_task =
642       GNUNET_SCHEDULER_add_delayed (ID_ANNOUNCE_TIME, &announce_id, cls);
643 }
644
645
646 /**
647  * Function to process paths received for a new peer addition. The recorded
648  * paths form the initial tunnel, which can be optimized later.
649  * Called on each result obtained for the DHT search.
650  *
651  * @param cls closure
652  * @param exp when will this value expire
653  * @param key key of the result
654  * @param type type of the result
655  * @param size number of bytes in data
656  * @param data pointer to the result data
657  */
658 static void
659 dht_get_id_handler (void *cls, struct GNUNET_TIME_Absolute exp,
660                     const GNUNET_HashCode * key,
661                     const struct GNUNET_PeerIdentity *get_path,
662                     unsigned int get_path_length,
663                     const struct GNUNET_PeerIdentity *put_path,
664                     unsigned int put_path_length, enum GNUNET_BLOCK_Type type,
665                     size_t size, const void *data);
666
667
668 /******************************************************************************/
669 /******************      GENERAL HELPER FUNCTIONS      ************************/
670 /******************************************************************************/
671
672 /**
673  * Check if client has registered with the service and has not disconnected
674  *
675  * @param client the client to check
676  *
677  * @return non-NULL if client exists in the global DLL
678  */
679 static struct MeshClient *
680 client_get (struct GNUNET_SERVER_Client *client)
681 {
682   struct MeshClient *c;
683
684   c = clients;
685   while (NULL != c)
686   {
687     if (c->handle == client)
688       return c;
689     c = c->next;
690   }
691   return NULL;
692 }
693
694
695 /**
696  * Checks if a given client has subscribed to certain message type
697  *
698  * @param message_type Type of message to check
699  * @param c Client to check
700  *
701  * @return GNUNET_YES or GNUNET_NO, depending on subscription status
702  *
703  * TODO inline?
704  */
705 static int
706 client_is_subscribed (uint16_t message_type, struct MeshClient *c)
707 {
708   GNUNET_HashCode hc;
709
710   GNUNET_CRYPTO_hash (&message_type, sizeof (uint16_t), &hc);
711   return GNUNET_CONTAINER_multihashmap_contains (c->types, &hc);
712 }
713
714
715 /**
716  * Allow a client to send more data after transmitting a multicast message
717  * which some neighbor has not yet accepted altough a reasonable time has
718  * passed.
719  *
720  * @param cls Closure (DataDescriptor containing the task identifier)
721  * @param tc Task Context
722  */
723 static void
724 client_allow_send (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
725 {
726   struct MeshDataDescriptor *info = cls;
727
728   if (GNUNET_SCHEDULER_REASON_SHUTDOWN == tc->reason)
729     return;
730 #if MESH_DEBUG
731   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
732               "MESH: CLIENT ALLOW SEND DESPITE %u COPIES PENDING\n",
733               *(info->copies));
734 #endif
735   *(info->timeout_task) = GNUNET_SCHEDULER_NO_TASK;
736   GNUNET_SERVER_receive_done (info->client, GNUNET_OK);
737 }
738
739
740 /**
741  * Search for a tunnel by global ID using full PeerIdentities
742  *
743  * @param oid owner of the tunnel
744  * @param tid global tunnel number
745  *
746  * @return tunnel handler, NULL if doesn't exist
747  */
748 static struct MeshTunnel *
749 tunnel_get (struct GNUNET_PeerIdentity *oid, MESH_TunnelNumber tid);
750
751
752 /**
753  * Notify a tunnel that a connection has broken that affects at least
754  * some of its peers.
755  *
756  * @param t Tunnel affected.
757  * @param p1 Peer that got disconnected from p2.
758  * @param p2 Peer that got disconnected from p1.
759  *
760  * @return Short ID of the peer disconnected (either p1 or p2).
761  *         0 if the tunnel remained unaffected.
762  */
763 static GNUNET_PEER_Id
764 tunnel_notify_connection_broken (struct MeshTunnel *t, GNUNET_PEER_Id p1,
765                                  GNUNET_PEER_Id p2);
766
767
768 /**
769  * Send the message to all clients that have subscribed to its type
770  *
771  * @param msg Pointer to the message itself
772  * @param payload Pointer to the payload of the message.
773  * @return number of clients this message was sent to
774  */
775 static unsigned int
776 send_subscribed_clients (const struct GNUNET_MessageHeader *msg,
777                          const struct GNUNET_MessageHeader *payload)
778 {
779   struct GNUNET_PeerIdentity *oid;
780   struct MeshClient *c;
781   struct MeshTunnel *t;
782   MESH_TunnelNumber *tid;
783   unsigned int count;
784   uint16_t type;
785   char cbuf[htons (msg->size)];
786
787   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: Sending to clients...\n");
788   type = ntohs (payload->type);
789   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: message of type %u\n", type);
790
791   memcpy (cbuf, msg, sizeof (cbuf));
792   switch (htons (msg->type))
793   {
794     struct GNUNET_MESH_Unicast *uc;
795     struct GNUNET_MESH_Multicast *mc;
796     struct GNUNET_MESH_ToOrigin *to;
797
798   case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
799     uc = (struct GNUNET_MESH_Unicast *) cbuf;
800     tid = &uc->tid;
801     oid = &uc->oid;
802     break;
803   case GNUNET_MESSAGE_TYPE_MESH_MULTICAST:
804     mc = (struct GNUNET_MESH_Multicast *) cbuf;
805     tid = &mc->tid;
806     oid = &mc->oid;
807     break;
808   case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
809     to = (struct GNUNET_MESH_ToOrigin *) cbuf;
810     tid = &to->tid;
811     oid = &to->oid;
812     break;
813   default:
814     GNUNET_break (0);
815     return 0;
816   }
817   t = tunnel_get (oid, ntohl (*tid));
818   if (NULL == t)
819   {
820     GNUNET_break (0);
821     return 0;
822   }
823   *tid = htonl (t->local_tid);
824   for (count = 0, c = clients; c != NULL; c = c->next)
825   {
826 #if MESH_DEBUG
827     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:    client %u\n", c->id);
828 #endif
829     if (client_is_subscribed (type, c))
830     {
831       count++;
832       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:      sending\n");
833       GNUNET_SERVER_notification_context_unicast (nc, c->handle,
834                                                   (struct GNUNET_MessageHeader
835                                                    *) cbuf, GNUNET_YES);
836     }
837   }
838   return count;
839 }
840
841
842 /**
843  * Notify the client that owns the tunnel that a peer has connected to it
844  * (the requested path to it has been confirmed).
845  *
846  * @param t Tunnel whose owner to notify
847  * @param id Short id of the peer that has connected
848  */
849 static void
850 send_client_peer_connected (const struct MeshTunnel *t, const GNUNET_PEER_Id id)
851 {
852   struct GNUNET_MESH_PeerControl pc;
853
854   pc.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD);
855   pc.header.size = htons (sizeof (struct GNUNET_MESH_PeerControl));
856   pc.tunnel_id = htonl (t->local_tid);
857   GNUNET_PEER_resolve (id, &pc.peer);
858   GNUNET_SERVER_notification_context_unicast (nc, t->client->handle, &pc.header,
859                                               GNUNET_NO);
860 }
861
862
863 /**
864  * Notify all clients (not depending on registration status) that the incoming
865  * tunnel is no longer valid.
866  *
867  * @param t Tunnel that was destroyed.
868  */
869 static void
870 send_clients_tunnel_destroy (struct MeshTunnel *t)
871 {
872   struct GNUNET_MESH_TunnelMessage msg;
873
874   msg.header.size = htons (sizeof (msg));
875   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_DESTROY);
876   msg.tunnel_id = htonl (t->local_tid);
877   GNUNET_SERVER_notification_context_broadcast (nc, &msg.header, GNUNET_NO);
878 }
879
880
881 /**
882  * Function called to notify a client about the socket
883  * being ready to queue more data.  "buf" will be
884  * NULL and "size" zero if the socket was closed for
885  * writing in the meantime.
886  *
887  * @param cls closure
888  * @param size number of bytes available in buf
889  * @param buf where the callee should write the message
890  * @return number of bytes written to buf
891  */
892 static size_t
893 send_core_create_path (void *cls, size_t size, void *buf);
894
895
896 /**
897  * Function called to notify a client about the socket
898  * being ready to queue more data.  "buf" will be
899  * NULL and "size" zero if the socket was closed for
900  * writing in the meantime.
901  *
902  * @param cls closure (data itself)
903  * @param size number of bytes available in buf
904  * @param buf where the callee should write the message
905  *
906  * @return number of bytes written to buf
907  */
908 static size_t
909 send_core_data_multicast (void *cls, size_t size, void *buf);
910
911
912 /**
913  * Decrements the reference counter and frees all resources if needed
914  *
915  * @param dd Data Descriptor used in a multicast message
916  */
917 static void
918 data_descriptor_decrement_multicast (struct MeshDataDescriptor *dd)
919 {
920   if (0 == --(*(dd->copies)))
921   {
922     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: Last copy!\n");
923     if (NULL != dd->client)
924     {
925       if (GNUNET_SCHEDULER_NO_TASK != *(dd->timeout_task))
926       {
927         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
928                     "MESH:  cancelling client timeout (%u)...\n",
929                     *(dd->timeout_task));
930         GNUNET_SCHEDULER_cancel (*(dd->timeout_task));
931         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:  notifying client...\n");
932         GNUNET_SERVER_receive_done (dd->client, GNUNET_OK);
933       }
934       GNUNET_free (dd->timeout_task);
935     }
936     GNUNET_free (dd->copies);
937     GNUNET_free (dd->data);
938   }
939 }
940
941
942 /**
943  * Cancel a core transmission that was already requested and free all resources
944  * associated to the request.
945  *
946  * @param peer PeeInfo of the peer whose transmission is cancelled.
947  * @param i Position of the transmission to be cancelled.
948  */
949 static void
950 peer_info_cancel_transmission (struct MeshPeerInfo *peer, unsigned int i)
951 {
952   if (NULL != peer->core_transmit[i])
953   {
954     struct MeshDataDescriptor *dd;
955     struct MeshPathInfo *path_info;
956
957 #if MESH_DEBUG
958     {
959       struct GNUNET_PeerIdentity id;
960
961       GNUNET_PEER_resolve (peer->id, &id);
962       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
963                   "MESH:   Cancelling data transmission at %s [%u]\n",
964                   GNUNET_i2s (&id), i);
965       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:    message type %u\n",
966                   peer->types[i]);
967     }
968 #endif
969     /* TODO: notify that tranmission has failed */
970     switch (peer->types[i])
971     {
972     case GNUNET_MESSAGE_TYPE_MESH_MULTICAST:
973     case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
974     case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
975       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:    type payload\n");
976       dd = peer->infos[i];
977       data_descriptor_decrement_multicast (dd);
978       break;
979     case GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE:
980       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:    type create path\n");
981       path_info = peer->infos[i];
982       path_destroy (path_info->path);
983       break;
984     default:
985       GNUNET_break (0);
986       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:    type unknown!\n");
987     }
988     GNUNET_CORE_notify_transmit_ready_cancel (peer->core_transmit[i]);
989     peer->core_transmit[i] = NULL;
990     GNUNET_free (peer->infos[i]);
991   }
992 }
993
994
995 /**
996  * Get a unused CORE slot to transmit a message to a peer. If all the slots
997  * are used, cancel one and return it's position.
998  *
999  * @param peer PeerInfo of the neighbor we want to transmit to.
1000  *
1001  * @return The index of an available slot to transmit to the neighbor.
1002  */
1003 static unsigned int
1004 peer_info_transmit_slot (struct MeshPeerInfo *peer)
1005 {
1006   unsigned int i;
1007
1008   for (i = 0; peer->core_transmit[i]; i++)
1009   {
1010     if (i == (CORE_QUEUE_SIZE - 1))
1011     {
1012       /* All positions are taken! Overwriting! */
1013       GNUNET_break (0);
1014       peer_info_cancel_transmission (peer, 0);
1015       return 0;
1016     }
1017   }
1018   return i;
1019 }
1020
1021
1022 /**
1023  * Retrieve the MeshPeerInfo stucture associated with the peer, create one
1024  * and insert it in the appropiate structures if the peer is not known yet.
1025  *
1026  * @param peer Full identity of the peer.
1027  *
1028  * @return Existing or newly created peer info.
1029  */
1030 static struct MeshPeerInfo *
1031 peer_info_get (const struct GNUNET_PeerIdentity *peer)
1032 {
1033   struct MeshPeerInfo *peer_info;
1034
1035   peer_info = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
1036   if (NULL == peer_info)
1037   {
1038     peer_info =
1039         (struct MeshPeerInfo *) GNUNET_malloc (sizeof (struct MeshPeerInfo));
1040     GNUNET_CONTAINER_multihashmap_put (peers, &peer->hashPubKey, peer_info,
1041                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
1042     peer_info->id = GNUNET_PEER_intern (peer);
1043   }
1044
1045   return peer_info;
1046 }
1047
1048
1049 /**
1050  * Retrieve the MeshPeerInfo stucture associated with the peer, create one
1051  * and insert it in the appropiate structures if the peer is not known yet.
1052  *
1053  * @param peer Short identity of the peer.
1054  *
1055  * @return Existing or newly created peer info.
1056  */
1057 static struct MeshPeerInfo *
1058 peer_info_get_short (const GNUNET_PEER_Id peer)
1059 {
1060   struct GNUNET_PeerIdentity id;
1061
1062   GNUNET_PEER_resolve (peer, &id);
1063   return peer_info_get (&id);
1064 }
1065
1066
1067 /**
1068  * Iterator to remove the tunnel from the list of tunnels a peer participates
1069  * in.
1070  *
1071  * @param cls Closure (tunnel info)
1072  * @param key GNUNET_PeerIdentity of the peer (unused)
1073  * @param value PeerInfo of the peer
1074  *
1075  * @return always GNUNET_YES, to keep iterating
1076  */
1077 static int
1078 peer_info_delete_tunnel (void *cls, const GNUNET_HashCode * key, void *value)
1079 {
1080   struct MeshTunnel *t = cls;
1081   struct MeshPeerInfo *peer = value;
1082   unsigned int i;
1083
1084   for (i = 0; i < peer->ntunnels; i++)
1085   {
1086     if (0 ==
1087         memcmp (&peer->tunnels[i]->id, &t->id, sizeof (struct MESH_TunnelID)))
1088     {
1089       peer->ntunnels--;
1090       peer->tunnels[i] = peer->tunnels[peer->ntunnels];
1091       peer->tunnels = GNUNET_realloc (peer->tunnels, peer->ntunnels);
1092       return GNUNET_YES;
1093     }
1094   }
1095   return GNUNET_YES;
1096 }
1097
1098
1099 /**
1100   * Core callback to write a
1101   *
1102   * @param cls Closure (MeshDataDescriptor with data in "data" member).
1103   * @param size Number of bytes available in buf.
1104   * @param buf Where the to write the message.
1105   *
1106   * @return number of bytes written to buf
1107   */
1108 static size_t
1109 send_core_data_raw (void *cls, size_t size, void *buf)
1110 {
1111   struct MeshDataDescriptor *info = cls;
1112   struct GNUNET_MessageHeader *msg;
1113   size_t total_size;
1114
1115   GNUNET_assert (NULL != info);
1116   GNUNET_assert (NULL != info->data);
1117   msg = (struct GNUNET_MessageHeader *) info->data;
1118   total_size = ntohs (msg->size);
1119
1120   if (total_size > size)
1121   {
1122     struct GNUNET_PeerIdentity id;
1123
1124     GNUNET_PEER_resolve (info->peer->id, &id);
1125     info->peer->core_transmit[info->handler_n] =
1126         GNUNET_CORE_notify_transmit_ready (core_handle, 0, 100,
1127                                            GNUNET_TIME_UNIT_FOREVER_REL, &id,
1128                                            size, &send_core_data_raw, info);
1129     return 0;
1130   }
1131   info->peer->core_transmit[info->handler_n] = NULL;
1132   memcpy (buf, msg, total_size);
1133   GNUNET_free (info->data);
1134   GNUNET_free (info);
1135   return total_size;
1136 }
1137
1138
1139 /**
1140  * Sends an already built message to a peer, properly registrating
1141  * all used resources.
1142  *
1143  * @param message Message to send. Fucntion makes a copy of it.
1144  * @param peer Short ID of the neighbor whom to send the message.
1145  */
1146 static void
1147 send_message (const struct GNUNET_MessageHeader *message,
1148               const struct GNUNET_PeerIdentity *peer)
1149 {
1150   struct MeshDataDescriptor *info;
1151   struct MeshPeerInfo *neighbor;
1152   struct MeshPeerPath *p;
1153   unsigned int i;
1154   size_t size;
1155
1156 //   GNUNET_TRANSPORT_try_connect();
1157
1158   size = ntohs (message->size);
1159   info = GNUNET_malloc (sizeof (struct MeshDataDescriptor));
1160   info->data = GNUNET_malloc (size);
1161   memcpy (info->data, message, size);
1162   neighbor = peer_info_get (peer);
1163   for (p = neighbor->path_head; NULL != p; p = p->next)
1164   {
1165     if (2 == p->length)
1166     {
1167       break;
1168     }
1169   }
1170   if (NULL == p)
1171   {
1172     GNUNET_break (0);
1173     GNUNET_free (info);
1174     return;
1175   }
1176   i = peer_info_transmit_slot (neighbor);
1177   info->handler_n = i;
1178   info->peer = neighbor;
1179   neighbor->types[i] = GNUNET_MESSAGE_TYPE_MESH_UNICAST;
1180   neighbor->infos[i] = info;
1181   neighbor->core_transmit[i] =
1182       GNUNET_CORE_notify_transmit_ready (core_handle, 0, 100,
1183                                          GNUNET_TIME_UNIT_FOREVER_REL, peer,
1184                                          size, &send_core_data_raw, info);
1185
1186 }
1187
1188
1189 /**
1190  * Sends a CREATE PATH message for a path to a peer, properly registrating
1191  * all used resources.
1192  *
1193  * @param peer PeerInfo of the final peer for whom this path is being created.
1194  * @param p Path itself.
1195  * @param t Tunnel for which the path is created.
1196  */
1197 static void
1198 send_create_path (struct MeshPeerInfo *peer, struct MeshPeerPath *p,
1199                   struct MeshTunnel *t)
1200 {
1201   struct GNUNET_PeerIdentity id;
1202   struct MeshPathInfo *path_info;
1203   struct MeshPeerInfo *neighbor;
1204   unsigned int i;
1205
1206   if (NULL == p)
1207   {
1208     p = tree_get_path_to_peer (t->tree, peer->id);
1209     if (NULL == p)
1210     {
1211       GNUNET_break (0);
1212       return;
1213     }
1214   }
1215   for (i = 0; i < p->length; i++)
1216   {
1217     if (p->peers[i] == myid)
1218       break;
1219   }
1220   if (i >= p->length - 1)
1221   {
1222     path_destroy (p);
1223     GNUNET_break (0);
1224     return;
1225   }
1226   GNUNET_PEER_resolve (p->peers[i + 1], &id);
1227
1228   path_info = GNUNET_malloc (sizeof (struct MeshPathInfo));
1229   path_info->path = p;
1230   path_info->t = t;
1231   neighbor = peer_info_get (&id);
1232   path_info->peer = neighbor;
1233   path_info->pos = peer_info_transmit_slot (neighbor);
1234   neighbor->types[path_info->pos] = GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE;
1235   neighbor->infos[path_info->pos] = path_info;
1236   neighbor->core_transmit[path_info->pos] = GNUNET_CORE_notify_transmit_ready (core_handle,     /* handle */
1237                                                                                0,       /* cork */
1238                                                                                0,       /* priority */
1239                                                                                GNUNET_TIME_UNIT_FOREVER_REL,    /* timeout */
1240                                                                                &id,     /* target */
1241                                                                                sizeof (struct GNUNET_MESH_ManipulatePath) + (p->length * sizeof (struct GNUNET_PeerIdentity)),  /*size */
1242                                                                                &send_core_create_path,  /* callback */
1243                                                                                path_info);      /* cls */
1244 }
1245
1246
1247 /**
1248  * Sends a DESTROY PATH message to free resources for a path in a tunnel
1249  *
1250  * @param t Tunnel whose path to destroy.
1251  * @param destination Short ID of the peer to whom the path to destroy.
1252  */
1253 static void
1254 send_destroy_path (struct MeshTunnel *t, GNUNET_PEER_Id destination)
1255 {
1256   struct MeshPeerPath *p;
1257   size_t size;
1258
1259   p = tree_get_path_to_peer (t->tree, destination);
1260   if (NULL == p)
1261   {
1262     GNUNET_break (0);
1263     return;
1264   }
1265   size = sizeof (struct GNUNET_MESH_ManipulatePath);
1266   size += p->length * sizeof (struct GNUNET_PeerIdentity);
1267   {
1268     struct GNUNET_MESH_ManipulatePath *msg;
1269     struct GNUNET_PeerIdentity *pi;
1270     char cbuf[size];
1271     unsigned int i;
1272
1273     msg = (struct GNUNET_MESH_ManipulatePath *) cbuf;
1274     msg->header.size = htons (size);
1275     msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_DESTROY);
1276     msg->tid = htonl (t->id.tid);
1277     pi = (struct GNUNET_PeerIdentity *) &msg[1];
1278     for (i = 0; i < p->length; i++)
1279     {
1280       GNUNET_PEER_resolve (p->peers[i], &pi[i]);
1281     }
1282     send_message (&msg->header, tree_get_first_hop (t->tree, destination));
1283   }
1284   path_destroy (p);
1285 }
1286
1287
1288 /**
1289  * Try to establish a new connection to this peer.
1290  * Use the best path for the given tunnel.
1291  * If the peer doesn't have any path to it yet, try to get one.
1292  * If the peer already has some path, send a CREATE PATH towards it.
1293  *
1294  * @param peer PeerInfo of the peer.
1295  * @param t Tunnel for which to create the path, if possible.
1296  */
1297 static void
1298 peer_info_connect (struct MeshPeerInfo *peer, struct MeshTunnel *t)
1299 {
1300   struct MeshPeerPath *p;
1301   struct MeshPathInfo *path_info;
1302
1303   if (NULL != peer->path_head)
1304   {
1305     p = tree_get_path_to_peer (t->tree, peer->id);
1306     if (NULL == p)
1307     {
1308       GNUNET_break (0);
1309       return;
1310     }
1311
1312     if (p->length > 1)
1313     {
1314       send_create_path (peer, p, t);
1315     }
1316     else
1317     {
1318       path_destroy (p);
1319       send_client_peer_connected (t, myid);
1320     }
1321   }
1322   else if (NULL == peer->dhtget)
1323   {
1324     struct GNUNET_PeerIdentity id;
1325
1326     GNUNET_PEER_resolve (peer->id, &id);
1327     path_info = GNUNET_malloc (sizeof (struct MeshPathInfo));
1328     path_info->peer = peer;
1329     path_info->t = t;
1330     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1331                 "MESH:   Starting DHT GET for peer %s\n", GNUNET_i2s (&id));
1332     peer->dhtgetcls = path_info;
1333     peer->dhtget = GNUNET_DHT_get_start (dht_handle,    /* handle */
1334                                          GNUNET_TIME_UNIT_FOREVER_REL,  /* timeout */
1335                                          GNUNET_BLOCK_TYPE_TEST,        /* type */
1336                                          &id.hashPubKey,        /* key to search */
1337                                          4,     /* replication level */
1338                                          GNUNET_DHT_RO_RECORD_ROUTE | GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE, NULL,       /* xquery */
1339                                          0,     /* xquery bits */
1340                                          &dht_get_id_handler, path_info);
1341   }
1342   /* Otherwise, there is no path but the DHT get is already started. */
1343 }
1344
1345
1346 /**
1347  * Task to delay the connection of a peer
1348  *
1349  * @param cls Closure (path info with tunnel and peer to connect).
1350  *            Will be free'd on exection.
1351  * @param tc TaskContext
1352  */
1353 static void
1354 peer_info_connect_task (void *cls,
1355                         const struct GNUNET_SCHEDULER_TaskContext *tc)
1356 {
1357   struct MeshPathInfo *path_info = cls;
1358
1359   if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
1360   {
1361     GNUNET_free (cls);
1362     return;
1363   }
1364   peer_info_connect (path_info->peer, path_info->t);
1365   GNUNET_free (cls);
1366 }
1367
1368
1369 /**
1370  * Destroy the peer_info and free any allocated resources linked to it
1371  *
1372  * @param pi The peer_info to destroy.
1373  *
1374  * @return GNUNET_OK on success
1375  */
1376 static int
1377 peer_info_destroy (struct MeshPeerInfo *pi)
1378 {
1379   struct GNUNET_PeerIdentity id;
1380   struct MeshPeerPath *p;
1381   struct MeshPeerPath *nextp;
1382   unsigned int i;
1383
1384   GNUNET_PEER_resolve (pi->id, &id);
1385   GNUNET_PEER_change_rc (pi->id, -1);
1386
1387   if (GNUNET_YES !=
1388       GNUNET_CONTAINER_multihashmap_remove (peers, &id.hashPubKey, pi))
1389   {
1390     GNUNET_break (0);
1391     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1392                 "MESH: removing peer %s, not in hashmap\n", GNUNET_i2s (&id));
1393   }
1394   if (NULL != pi->dhtget)
1395   {
1396     GNUNET_DHT_get_stop (pi->dhtget);
1397     GNUNET_free (pi->dhtgetcls);
1398   }
1399   for (i = 0; i < CORE_QUEUE_SIZE; i++)
1400   {
1401     peer_info_cancel_transmission (pi, i);
1402   }
1403   p = pi->path_head;
1404   while (NULL != p)
1405   {
1406     nextp = p->next;
1407     GNUNET_CONTAINER_DLL_remove (pi->path_head, pi->path_tail, p);
1408     path_destroy (p);
1409     p = nextp;
1410   }
1411   GNUNET_free (pi);
1412   return GNUNET_OK;
1413 }
1414
1415
1416 /**
1417  * Remove all paths that rely on a direct connection between p1 and p2
1418  * from the peer itself and notify all tunnels about it.
1419  *
1420  * @param peer PeerInfo of affected peer.
1421  * @param p1 GNUNET_PEER_Id of one peer.
1422  * @param p2 GNUNET_PEER_Id of another peer that was connected to the first and
1423  *           no longer is.
1424  *
1425  * TODO: optimize (see below)
1426  */
1427 static void
1428 peer_info_remove_path (struct MeshPeerInfo *peer, GNUNET_PEER_Id p1,
1429                        GNUNET_PEER_Id p2)
1430 {
1431   struct MeshPeerPath *p;
1432   struct MeshPeerPath *aux;
1433   struct MeshPeerInfo *peer_d;
1434   GNUNET_PEER_Id d;
1435   unsigned int destroyed;
1436   unsigned int best;
1437   unsigned int cost;
1438   unsigned int i;
1439
1440   destroyed = 0;
1441   p = peer->path_head;
1442   while (NULL != p)
1443   {
1444     aux = p->next;
1445     for (i = 0; i < (p->length - 1); i++)
1446     {
1447       if ((p->peers[i] == p1 && p->peers[i + 1] == p2) ||
1448           (p->peers[i] == p2 && p->peers[i + 1] == p1))
1449       {
1450         GNUNET_CONTAINER_DLL_remove (peer->path_head, peer->path_tail, p);
1451         path_destroy (p);
1452         destroyed++;
1453         break;
1454       }
1455     }
1456     p = aux;
1457   }
1458   if (0 == destroyed)
1459     return;
1460
1461   for (i = 0; i < peer->ntunnels; i++)
1462   {
1463     d = tunnel_notify_connection_broken (peer->tunnels[i], p1, p2);
1464     if (0 == d) continue;
1465     /* TODO
1466      * Problem: one or more peers have been deleted from the tunnel tree.
1467      * We don't know who they are to try to add them again.
1468      * We need to try to find a new path for each of the disconnected peers.
1469      * Some of them might already have a path to reach them that does not
1470      * involve p1 and p2. Adding all anew might render in a better tree than
1471      * the trivial immediate fix.
1472      *
1473      * Trivial immiediate fix: try to reconnect to the disconnected node. All
1474      * its children will be reachable trough him.
1475      */
1476     peer_d = peer_info_get_short (d);
1477     best = UINT_MAX;
1478     aux = NULL;
1479     for (p = peer_d->path_head; NULL != p; p = p->next)
1480     {
1481       if ((cost = tree_get_path_cost (peer->tunnels[i]->tree, p)) < best)
1482       {
1483         best = cost;
1484         aux = p;
1485       }
1486     }
1487     if (NULL != aux)
1488     {
1489       /* No callback, as peer will be already disconnected and a connection
1490        * scheduled by tunnel_notify_connection_broken.
1491        */
1492       tree_add_path (peer->tunnels[i]->tree, aux, NULL, NULL);
1493     }
1494     else
1495     {
1496       peer_info_connect (peer_d, peer->tunnels[i]);
1497     }
1498   }
1499 }
1500
1501
1502 /**
1503  * Add the path to the peer and update the path used to reach it in case this
1504  * is the shortest.
1505  *
1506  * @param peer_info Destination peer to add the path to.
1507  * @param path New path to add. Last peer must be the peer in arg 1.
1508  *             Path will be either used of freed if already known.
1509  * @param trusted Do we trust that this path is real?
1510  */
1511 void
1512 peer_info_add_path (struct MeshPeerInfo *peer_info, struct MeshPeerPath *path,
1513                     int trusted)
1514 {
1515   struct MeshPeerPath *aux;
1516   unsigned int l;
1517   unsigned int l2;
1518
1519   if ((NULL == peer_info) || (NULL == path))
1520   {
1521     GNUNET_break (0);
1522     path_destroy (path);
1523     return;
1524   }
1525   if (path->peers[path->length - 1] != peer_info->id)
1526   {
1527     GNUNET_break (0);
1528     path_destroy (path);
1529     return;
1530   }
1531   if (path->length <= 2 && GNUNET_NO == trusted)
1532   {
1533     /* Only allow CORE to tell us about direct paths */
1534     path_destroy (path);
1535     return;
1536   }
1537   GNUNET_assert (peer_info->id == path->peers[path->length - 1]);
1538   for (l = 1; l < path->length; l++)
1539   {
1540     if (path->peers[l] == myid)
1541     {
1542       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: shortening path by %u\n", l);
1543       for (l2 = 0; l2 < path->length - l; l2++)
1544       {
1545         path->peers[l2] = path->peers[l + l2];
1546       }
1547       path->length -= l;
1548       l = 1;
1549       path->peers =
1550           GNUNET_realloc (path->peers, path->length * sizeof (GNUNET_PEER_Id));
1551     }
1552   }
1553 #if MESH_DEBUG
1554   {
1555     struct GNUNET_PeerIdentity id;
1556
1557     GNUNET_PEER_resolve (peer_info->id, &id);
1558     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: adding path [%u] to peer %s\n",
1559                 path->length, GNUNET_i2s (&id));
1560   }
1561 #endif
1562   l = path_get_length (path);
1563   if (0 == l)
1564   {
1565     GNUNET_free (path);
1566     return;
1567   }
1568
1569   GNUNET_assert (peer_info->id == path->peers[path->length - 1]);
1570   for (aux = peer_info->path_head; aux != NULL; aux = aux->next)
1571   {
1572     l2 = path_get_length (aux);
1573     if (l2 > l)
1574     {
1575       GNUNET_CONTAINER_DLL_insert_before (peer_info->path_head,
1576                                           peer_info->path_tail, aux, path);
1577       return;
1578     }
1579     else
1580     {
1581       if (l2 == l && memcmp (path->peers, aux->peers, l) == 0)
1582       {
1583         path_destroy (path);
1584         return;
1585       }
1586     }
1587   }
1588   GNUNET_CONTAINER_DLL_insert_tail (peer_info->path_head, peer_info->path_tail,
1589                                     path);
1590   return;
1591 }
1592
1593
1594 /**
1595  * Add the path to the origin peer and update the path used to reach it in case
1596  * this is the shortest.
1597  * The path is given in peer_info -> destination, therefore we turn the path
1598  * upside down first.
1599  *
1600  * @param peer_info Peer to add the path to, being the origin of the path.
1601  * @param path New path to add after being inversed.
1602  * @param trusted Do we trust that this path is real?
1603  */
1604 static void
1605 peer_info_add_path_to_origin (struct MeshPeerInfo *peer_info,
1606                               struct MeshPeerPath *path, int trusted)
1607 {
1608   path_invert (path);
1609   peer_info_add_path (peer_info, path, trusted);
1610 }
1611
1612
1613 /**
1614  * Build a PeerPath from the paths returned from the DHT, reversing the paths
1615  * to obtain a local peer -> destination path and interning the peer ids.
1616  *
1617  * @return Newly allocated and created path
1618  */
1619 static struct MeshPeerPath *
1620 path_build_from_dht (const struct GNUNET_PeerIdentity *get_path,
1621                      unsigned int get_path_length,
1622                      const struct GNUNET_PeerIdentity *put_path,
1623                      unsigned int put_path_length)
1624 {
1625   struct MeshPeerPath *p;
1626   GNUNET_PEER_Id id;
1627   int i;
1628
1629   p = path_new (1);
1630   p->peers[0] = myid;
1631   GNUNET_PEER_change_rc (myid, 1);
1632   i = get_path_length;
1633   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:    GET has %d hops.\n", i);
1634   for (i--; i >= 0; i--)
1635   {
1636     id = GNUNET_PEER_intern (&get_path[i]);
1637     if (p->length > 0 && id == p->peers[p->length - 1])
1638     {
1639       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:    Optimizing 1 hop out.\n");
1640       GNUNET_PEER_change_rc (id, -1);
1641     }
1642     else
1643     {
1644       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:    Adding from GET: %s.\n",
1645                   GNUNET_i2s (&get_path[i]));
1646       p->length++;
1647       p->peers = GNUNET_realloc (p->peers, sizeof (GNUNET_PEER_Id) * p->length);
1648       p->peers[p->length - 1] = id;
1649     }
1650   }
1651   i = put_path_length;
1652   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:    PUT has %d hops.\n", i);
1653   for (i--; i >= 0; i--)
1654   {
1655     id = GNUNET_PEER_intern (&put_path[i]);
1656     if (id == myid)
1657     {
1658       /* PUT path went through us, so discard the path up until now and start
1659        * from here to get a much shorter (and loop-free) path.
1660        */
1661       path_destroy (p);
1662       p = path_new (0);
1663     }
1664     if (p->length > 0 && id == p->peers[p->length - 1])
1665     {
1666       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:    Optimizing 1 hop out.\n");
1667       GNUNET_PEER_change_rc (id, -1);
1668     }
1669     else
1670     {
1671       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:    Adding from PUT: %s.\n",
1672                   GNUNET_i2s (&put_path[i]));
1673       p->length++;
1674       p->peers = GNUNET_realloc (p->peers, sizeof (GNUNET_PEER_Id) * p->length);
1675       p->peers[p->length - 1] = id;
1676     }
1677   }
1678 #if MESH_DEBUG
1679   if (get_path_length > 0)
1680     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:    (first of GET: %s)\n",
1681                 GNUNET_i2s (&get_path[0]));
1682   if (put_path_length > 0)
1683     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:    (first of PUT: %s)\n",
1684                 GNUNET_i2s (&put_path[0]));
1685   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:    In total: %d hops\n",
1686               p->length);
1687   for (i = 0; i < p->length; i++)
1688   {
1689     struct GNUNET_PeerIdentity peer_id;
1690
1691     GNUNET_PEER_resolve (p->peers[i], &peer_id);
1692     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:        %u: %s\n", p->peers[i],
1693                 GNUNET_i2s (&peer_id));
1694   }
1695 #endif
1696   return p;
1697 }
1698
1699
1700 /**
1701  * Adds a path to the peer_infos of all the peers in the path
1702  * 
1703  * @param p Path to process.
1704  * @param confirmed Whether we know if the path works or not. FIXME use
1705  */
1706 static void
1707 path_add_to_peers (struct MeshPeerPath *p, int confirmed)
1708 {
1709   unsigned int i;
1710
1711   /* TODO: invert and add */
1712   for (i = 1; i < p->length && p->peers[i] != myid; i++) /* skip'em */;
1713   for (i++; i < p->length; i++)
1714   {
1715     struct MeshPeerInfo *aux;
1716     struct MeshPeerPath *copy;
1717
1718     aux = peer_info_get_short(p->peers[i]);
1719     copy = path_duplicate(p);
1720     copy->length = i;
1721     peer_info_add_path(aux, copy, GNUNET_NO);
1722   }
1723 }
1724
1725
1726 /**
1727  * Send keepalive packets for a peer
1728  *
1729  * @param cls Closure (tunnel for which to send the keepalive).
1730  * @param tc Notification context.
1731  *
1732  * TODO: implement explicit multicast keepalive?
1733  */
1734 static void
1735 path_refresh (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
1736
1737
1738 /**
1739  * Search for a tunnel among the incoming tunnels
1740  *
1741  * @param tid the local id of the tunnel
1742  *
1743  * @return tunnel handler, NULL if doesn't exist
1744  */
1745 static struct MeshTunnel *
1746 tunnel_get_incoming (MESH_TunnelNumber tid)
1747 {
1748   GNUNET_HashCode hash;
1749
1750   GNUNET_assert (tid >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV);
1751   GNUNET_CRYPTO_hash (&tid, sizeof (MESH_TunnelNumber), &hash);
1752   return GNUNET_CONTAINER_multihashmap_get (incoming_tunnels, &hash);
1753 }
1754
1755
1756 /**
1757  * Search for a tunnel among the tunnels for a client
1758  *
1759  * @param c the client whose tunnels to search in
1760  * @param tid the local id of the tunnel
1761  *
1762  * @return tunnel handler, NULL if doesn't exist
1763  */
1764 static struct MeshTunnel *
1765 tunnel_get_by_local_id (struct MeshClient *c, MESH_TunnelNumber tid)
1766 {
1767   if (tid >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
1768   {
1769     return tunnel_get_incoming (tid);
1770   }
1771   else
1772   {
1773     GNUNET_HashCode hash;
1774
1775     GNUNET_CRYPTO_hash (&tid, sizeof (MESH_TunnelNumber), &hash);
1776     return GNUNET_CONTAINER_multihashmap_get (c->tunnels, &hash);
1777   }
1778 }
1779
1780
1781 /**
1782  * Search for a tunnel by global ID using PEER_ID
1783  *
1784  * @param pi owner of the tunnel
1785  * @param tid global tunnel number
1786  *
1787  * @return tunnel handler, NULL if doesn't exist
1788  */
1789 static struct MeshTunnel *
1790 tunnel_get_by_pi (GNUNET_PEER_Id pi, MESH_TunnelNumber tid)
1791 {
1792   struct MESH_TunnelID id;
1793   GNUNET_HashCode hash;
1794
1795   id.oid = pi;
1796   id.tid = tid;
1797
1798   GNUNET_CRYPTO_hash (&id, sizeof (struct MESH_TunnelID), &hash);
1799   return GNUNET_CONTAINER_multihashmap_get (tunnels, &hash);
1800 }
1801
1802
1803 /**
1804  * Search for a tunnel by global ID using full PeerIdentities
1805  *
1806  * @param oid owner of the tunnel
1807  * @param tid global tunnel number
1808  *
1809  * @return tunnel handler, NULL if doesn't exist
1810  */
1811 static struct MeshTunnel *
1812 tunnel_get (struct GNUNET_PeerIdentity *oid, MESH_TunnelNumber tid)
1813 {
1814   return tunnel_get_by_pi (GNUNET_PEER_search (oid), tid);
1815 }
1816
1817
1818 /**
1819  * Callback used to notify a client owner of a tunnel that a peer has
1820  * disconnected, most likely because of a path change.
1821  *
1822  * @param cls Closure (tunnel this notification is about).
1823  * @param peer_id Short ID of disconnected peer.
1824  */
1825 void
1826 notify_peer_disconnected (void *cls, GNUNET_PEER_Id peer_id)
1827 {
1828   struct MeshTunnel *t = cls;
1829   struct MeshPeerInfo *peer;
1830   struct MeshPathInfo *path_info;
1831
1832   if (NULL != t->client && NULL != nc)
1833   {
1834     struct GNUNET_MESH_PeerControl msg;
1835
1836     msg.header.size = htons (sizeof (msg));
1837     msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_DEL);
1838     msg.tunnel_id = htonl (t->local_tid);
1839     GNUNET_PEER_resolve (peer_id, &msg.peer);
1840     GNUNET_SERVER_notification_context_unicast (nc, t->client->handle,
1841                                                 &msg.header, GNUNET_NO);
1842   }
1843   peer = peer_info_get_short (peer_id);
1844   path_info = GNUNET_malloc (sizeof (struct MeshPathInfo));
1845   path_info->peer = peer;
1846   path_info->t = t;
1847   GNUNET_SCHEDULER_add_now (&peer_info_connect_task, path_info);
1848 }
1849
1850
1851 /**
1852  * Add a peer to a tunnel, accomodating paths accordingly and initializing all
1853  * needed rescources.
1854  * If peer already exists, reevaluate shortest path and change if different.
1855  *
1856  * @param t Tunnel we want to add a new peer to
1857  * @param peer PeerInfo of the peer being added
1858  *
1859  */
1860 static void
1861 tunnel_add_peer (struct MeshTunnel *t, struct MeshPeerInfo *peer)
1862 {
1863   struct GNUNET_PeerIdentity id;
1864   struct MeshPeerPath *best_p;
1865   struct MeshPeerPath *p;
1866   unsigned int best_cost;
1867   unsigned int cost;
1868
1869   GNUNET_PEER_resolve (peer->id, &id);
1870   if (GNUNET_NO ==
1871       GNUNET_CONTAINER_multihashmap_contains (t->peers, &id.hashPubKey))
1872   {
1873     t->peers_total++;
1874     GNUNET_array_append (peer->tunnels, peer->ntunnels, t);
1875     GNUNET_assert (GNUNET_OK ==
1876                    GNUNET_CONTAINER_multihashmap_put (t->peers, &id.hashPubKey,
1877                                                       peer,
1878                                                       GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST));
1879   }
1880
1881   if (NULL != (p = peer->path_head))
1882   {
1883     best_p = p;
1884     best_cost = tree_get_path_cost (t->tree, p);
1885     while (NULL != p)
1886     {
1887       if ((cost = tree_get_path_cost (t->tree, p)) < best_cost)
1888       {
1889         best_cost = cost;
1890         best_p = p;
1891       }
1892       p = p->next;
1893     }
1894     tree_add_path (t->tree, best_p, &notify_peer_disconnected, t);
1895     if (GNUNET_SCHEDULER_NO_TASK == t->path_refresh_task)
1896       t->path_refresh_task =
1897           GNUNET_SCHEDULER_add_delayed (REFRESH_PATH_TIME, &path_refresh, t);
1898   }
1899   else
1900   {
1901     /* Start a DHT get */
1902     peer_info_connect (peer, t);
1903   }
1904 }
1905
1906 /**
1907  * Add a path to a tunnel which we don't own, just to remember the next hop.
1908  * If destination node was already in the tunnel, the first hop information
1909  * will be replaced with the new path.
1910  *
1911  * @param t Tunnel we want to add a new peer to
1912  * @param p Path to add
1913  * @param own_pos Position of local node in path.
1914  *
1915  */
1916 static void
1917 tunnel_add_path (struct MeshTunnel *t, struct MeshPeerPath *p,
1918                  unsigned int own_pos)
1919 {
1920   struct GNUNET_PeerIdentity id;
1921
1922   GNUNET_assert (0 != own_pos);
1923   tree_add_path (t->tree, p, NULL, NULL);
1924   if (own_pos < p->length - 1)
1925   {
1926     GNUNET_PEER_resolve (p->peers[own_pos + 1], &id);
1927     tree_update_first_hops (t->tree, myid, &id);
1928   }
1929 }
1930
1931
1932 /**
1933  * Notifies a tunnel that a connection has broken that affects at least
1934  * some of its peers. Sends a notification towards the root of the tree.
1935  * In case the peer is the owner of the tree, notifies the client that owns
1936  * the tunnel and tries to reconnect.
1937  *
1938  * @param t Tunnel affected.
1939  * @param p1 Peer that got disconnected from p2.
1940  * @param p2 Peer that got disconnected from p1.
1941  *
1942  * @return Short ID of the peer disconnected (either p1 or p2).
1943  *         0 if the tunnel remained unaffected.
1944  */
1945 static GNUNET_PEER_Id
1946 tunnel_notify_connection_broken (struct MeshTunnel *t, GNUNET_PEER_Id p1,
1947                                  GNUNET_PEER_Id p2)
1948 {
1949   GNUNET_PEER_Id pid;
1950
1951   pid =
1952       tree_notify_connection_broken (t->tree, p1, p2, &notify_peer_disconnected,
1953                                      t);
1954   if (myid != p1 && myid != p2)
1955   {
1956     return pid;
1957   }
1958   if (pid != myid)
1959   {
1960     if (tree_get_predecessor (t->tree) != 0)
1961     {
1962       /* We are the peer still connected, notify owner of the disconnection. */
1963       struct GNUNET_MESH_PathBroken msg;
1964       struct GNUNET_PeerIdentity neighbor;
1965
1966       msg.header.size = htons (sizeof (msg));
1967       msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_BROKEN);
1968       GNUNET_PEER_resolve (t->id.oid, &msg.oid);
1969       msg.tid = htonl (t->id.tid);
1970       msg.peer1 = my_full_id;
1971       GNUNET_PEER_resolve (pid, &msg.peer2);
1972       GNUNET_PEER_resolve (tree_get_predecessor (t->tree), &neighbor);
1973       send_message (&msg.header, &neighbor);
1974     }
1975   }
1976   return pid;
1977 }
1978
1979
1980 struct MeshMulticastData
1981 {
1982   struct MeshTunnel *t;
1983
1984   GNUNET_SCHEDULER_TaskIdentifier *task;
1985
1986   unsigned int *reference_counter;
1987
1988   size_t data_len;
1989
1990   void *data;
1991 };
1992
1993
1994 /**
1995  * Send a multicast packet to a neighbor.
1996  */
1997 static void
1998 tunnel_send_multicast_iterator (void *cls, GNUNET_PEER_Id neighbor_id)
1999 {
2000   struct MeshMulticastData *mdata = cls;
2001   struct MeshDataDescriptor *info;
2002   struct GNUNET_PeerIdentity neighbor;
2003   unsigned int i;
2004
2005   info = GNUNET_malloc (sizeof (struct MeshDataDescriptor));
2006
2007   info->data = mdata->data;
2008   info->size = mdata->data_len;
2009   info->copies = mdata->reference_counter;
2010   (*(mdata->reference_counter))++;
2011
2012   if (NULL != mdata->t->client)
2013   {
2014     info->client = mdata->t->client->handle;
2015     info->timeout_task = mdata->task;
2016   }
2017   info->destination = neighbor_id;
2018   GNUNET_PEER_resolve (neighbor_id, &neighbor);
2019 #if MESH_DEBUG
2020   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:    sending to %s...\n",
2021               GNUNET_i2s (&neighbor));
2022 #endif
2023   info->peer = peer_info_get (&neighbor);
2024   GNUNET_assert (NULL != info->peer);
2025   i = peer_info_transmit_slot (info->peer);
2026   info->handler_n = i;
2027   info->peer->infos[i] = info;
2028   info->peer->types[i] = GNUNET_MESSAGE_TYPE_MESH_MULTICAST;
2029   info->peer->core_transmit[i] =
2030       GNUNET_CORE_notify_transmit_ready (core_handle, 0, 0,
2031                                          GNUNET_TIME_UNIT_FOREVER_REL,
2032                                          &neighbor, info->size,
2033                                          &send_core_data_multicast, info);
2034 }
2035
2036 /**
2037  * Send a message in a tunnel in multicast, sending a copy to each child node
2038  * down the local one in the tunnel tree.
2039  *
2040  * @param t Tunnel in which to send the data.
2041  * @param msg Message to be sent
2042  */
2043 static void
2044 tunnel_send_multicast (struct MeshTunnel *t,
2045                        const struct GNUNET_MessageHeader *msg)
2046 {
2047   struct MeshMulticastData *mdata;
2048
2049 #if MESH_DEBUG
2050   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2051               "MESH:  sending a multicast packet...\n");
2052 #endif
2053   mdata = GNUNET_malloc (sizeof (struct MeshMulticastData));
2054   mdata->data_len = ntohs (msg->size);
2055   mdata->reference_counter = GNUNET_malloc (sizeof (unsigned int));
2056   mdata->t = t;
2057   mdata->data = GNUNET_malloc (mdata->data_len);
2058   memcpy (mdata->data, msg, mdata->data_len);
2059   if (ntohs (msg->type) == GNUNET_MESSAGE_TYPE_MESH_MULTICAST)
2060   {
2061     struct GNUNET_MESH_Multicast *mcast;
2062
2063     mcast = (struct GNUNET_MESH_Multicast *) mdata->data;
2064     mcast->ttl = htonl (ntohl (mcast->ttl) - 1);
2065 #if MESH_DEBUG
2066     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2067                 "MESH:   data packet, ttl: %u\n",
2068                 ntohl (mcast->ttl));
2069   }
2070   else
2071   {
2072     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2073                 "MESH:   not a data packet, no ttl\n");
2074 #endif
2075   }
2076   if (NULL != t->client)
2077   {
2078     mdata->task = GNUNET_malloc (sizeof (GNUNET_SCHEDULER_TaskIdentifier));
2079     *(mdata->task) =
2080         GNUNET_SCHEDULER_add_delayed (UNACKNOWLEDGED_WAIT, &client_allow_send,
2081                                       t->client->handle);
2082   }
2083
2084   tree_iterate_children (t->tree, &tunnel_send_multicast_iterator, mdata);
2085   if (*(mdata->reference_counter) == 0)
2086   {
2087     GNUNET_free (mdata->data);
2088     GNUNET_free (mdata->reference_counter);
2089     if (NULL != mdata->task)
2090     {
2091       GNUNET_free (mdata->task);
2092     }
2093   }
2094   GNUNET_free (mdata);
2095 #if MESH_DEBUG
2096   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2097               "MESH:  sending a multicast packet done\n");
2098 #endif
2099   return;
2100 }
2101
2102
2103 /**
2104  * Send a message to all peers in this tunnel that the tunnel is no longer
2105  * valid.
2106  *
2107  * @param t The tunnel whose peers to notify.
2108  */
2109 static void
2110 tunnel_send_destroy (struct MeshTunnel *t)
2111 {
2112   struct GNUNET_MESH_TunnelDestroy msg;
2113
2114   msg.header.size = htons (sizeof (msg));
2115   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_TUNNEL_DESTROY);
2116   GNUNET_PEER_resolve (t->id.oid, &msg.oid);
2117   msg.tid = htonl (t->id.tid);
2118   tunnel_send_multicast (t, &msg.header);
2119 }
2120
2121
2122
2123 /**
2124  * Destroy the tunnel and free any allocated resources linked to it
2125  *
2126  * @param t the tunnel to destroy
2127  *
2128  * @return GNUNET_OK on success
2129  */
2130 static int
2131 tunnel_destroy (struct MeshTunnel *t)
2132 {
2133   struct MeshClient *c;
2134   struct MeshQueue *q;
2135   struct MeshQueue *qn;
2136   GNUNET_HashCode hash;
2137   int r;
2138
2139   if (NULL == t)
2140     return GNUNET_OK;
2141
2142   c = t->client;
2143 #if MESH_DEBUG
2144   {
2145     struct GNUNET_PeerIdentity id;
2146
2147     GNUNET_PEER_resolve (t->id.oid, &id);
2148     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: destroying tunnel %s [%x]\n",
2149                 GNUNET_i2s (&id), t->id.tid);
2150     if (NULL != c)
2151       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   by client %u\n", c->id);
2152   }
2153 #endif
2154
2155   GNUNET_CRYPTO_hash (&t->id, sizeof (struct MESH_TunnelID), &hash);
2156   if (GNUNET_YES != GNUNET_CONTAINER_multihashmap_remove (tunnels, &hash, t))
2157   {
2158     r = GNUNET_SYSERR;
2159   }
2160
2161   GNUNET_CRYPTO_hash (&t->local_tid, sizeof (MESH_TunnelNumber), &hash);
2162   if (NULL != c &&
2163       GNUNET_YES != GNUNET_CONTAINER_multihashmap_remove (c->tunnels, &hash, t))
2164   {
2165     r = GNUNET_SYSERR;
2166   }
2167   if (t->local_tid >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
2168   {
2169     GNUNET_CRYPTO_hash (&t->local_tid, sizeof (MESH_TunnelNumber), &hash);
2170     GNUNET_break (GNUNET_YES ==
2171                   GNUNET_CONTAINER_multihashmap_remove (incoming_tunnels, &hash,
2172                                                         t));
2173   }
2174   if (NULL != t->peers)
2175   {
2176     GNUNET_CONTAINER_multihashmap_iterate (t->peers, &peer_info_delete_tunnel,
2177                                            t);
2178     GNUNET_CONTAINER_multihashmap_destroy (t->peers);
2179   }
2180   q = t->queue_head;
2181   while (NULL != q)
2182   {
2183     if (NULL != q->data)
2184       GNUNET_free (q->data);
2185     qn = q->next;
2186     GNUNET_free (q);
2187     q = qn;
2188     /* TODO cancel core transmit ready in case it was active */
2189   }
2190   tree_destroy (t->tree);
2191   if (NULL != t->dht_get_type)
2192     GNUNET_DHT_get_stop (t->dht_get_type);
2193   if (GNUNET_SCHEDULER_NO_TASK != t->timeout_task)
2194     GNUNET_SCHEDULER_cancel (t->timeout_task);
2195   if (GNUNET_SCHEDULER_NO_TASK != t->path_refresh_task)
2196     GNUNET_SCHEDULER_cancel (t->path_refresh_task);
2197   GNUNET_free (t);
2198   return r;
2199 }
2200
2201
2202 /**
2203  * Removes an explicit path from a tunnel, freeing all intermediate nodes
2204  * that are no longer needed, as well as nodes of no longer reachable peers.
2205  * The tunnel itself is also destoyed if results in a remote empty tunnel.
2206  *
2207  * @param t Tunnel from which to remove the path.
2208  * @param peer Short id of the peer which should be removed.
2209  */
2210 static void
2211 tunnel_delete_peer (struct MeshTunnel *t, GNUNET_PEER_Id peer)
2212 {
2213   if (GNUNET_NO == tree_del_peer (t->tree, peer, NULL, NULL))
2214     tunnel_destroy (t);
2215 }
2216
2217
2218 /**
2219  * tunnel_destroy_iterator: iterator for deleting each tunnel that belongs to a
2220  * client when the client disconnects.
2221  *
2222  * @param cls closure (client that is disconnecting)
2223  * @param key the hash of the local tunnel id (used to access the hashmap)
2224  * @param value the value stored at the key (tunnel to destroy)
2225  *
2226  * @return GNUNET_OK on success
2227  */
2228 static int
2229 tunnel_destroy_iterator (void *cls, const GNUNET_HashCode * key, void *value)
2230 {
2231   struct MeshTunnel *t = value;
2232   int r;
2233
2234   r = tunnel_destroy (t);
2235   return r;
2236 }
2237
2238
2239 /**
2240  * Timeout function, destroys tunnel if called
2241  *
2242  * @param cls Closure (tunnel to destroy).
2243  * @param tc TaskContext
2244  */
2245 static void
2246 tunnel_timeout (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2247 {
2248   struct MeshTunnel *t = cls;
2249
2250   if (GNUNET_SCHEDULER_REASON_SHUTDOWN == tc->reason)
2251     return;
2252   t->timeout_task = GNUNET_SCHEDULER_NO_TASK;
2253   tunnel_destroy (t);
2254 }
2255
2256 /**
2257  * Resets the tunnel timeout. Starts it if no timeout was running.
2258  *
2259  * @param t Tunnel whose timeout to reset.
2260  */
2261 static void
2262 tunnel_reset_timeout (struct MeshTunnel *t)
2263 {
2264   if (GNUNET_SCHEDULER_NO_TASK != t->timeout_task)
2265     GNUNET_SCHEDULER_cancel (t->timeout_task);
2266   t->timeout_task =
2267       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply
2268                                     (REFRESH_PATH_TIME, 4), &tunnel_timeout, t);
2269 }
2270
2271
2272 /******************************************************************************/
2273 /****************      MESH NETWORK HANDLER HELPERS     ***********************/
2274 /******************************************************************************/
2275
2276 /**
2277  * Function called to notify a client about the socket
2278  * being ready to queue more data.  "buf" will be
2279  * NULL and "size" zero if the socket was closed for
2280  * writing in the meantime.
2281  *
2282  * @param cls closure
2283  * @param size number of bytes available in buf
2284  * @param buf where the callee should write the message
2285  * @return number of bytes written to buf
2286  */
2287 static size_t
2288 send_core_create_path (void *cls, size_t size, void *buf)
2289 {
2290   struct MeshPathInfo *info = cls;
2291   struct GNUNET_MESH_ManipulatePath *msg;
2292   struct GNUNET_PeerIdentity *peer_ptr;
2293   struct MeshPeerInfo *peer = info->peer;
2294   struct MeshTunnel *t = info->t;
2295   struct MeshPeerPath *p = info->path;
2296   size_t size_needed;
2297   int i;
2298
2299   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: CREATE PATH sending...\n");
2300   size_needed =
2301       sizeof (struct GNUNET_MESH_ManipulatePath) +
2302       p->length * sizeof (struct GNUNET_PeerIdentity);
2303
2304   if (size < size_needed || NULL == buf)
2305   {
2306     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: create path retransmit!\n");
2307     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   buf:  %p\n", buf);
2308     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   size: (%u/%u)\n", size,
2309                 size_needed);
2310     info->peer->core_transmit[info->pos] =
2311         GNUNET_CORE_notify_transmit_ready (core_handle, 0, 0,
2312                                            GNUNET_TIME_UNIT_FOREVER_REL,
2313                                            tree_get_first_hop (t->tree,
2314                                                                peer->id),
2315                                            size_needed, &send_core_create_path,
2316                                            info);
2317     return 0;
2318   }
2319   info->peer->core_transmit[info->pos] = NULL;
2320 #if MESH_DEBUG
2321   {
2322     struct GNUNET_PeerIdentity id;
2323
2324     GNUNET_PEER_resolve (peer->id, &id);
2325     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2326                 "MESH:   setting core_transmit %s [%u] to NULL\n",
2327                 GNUNET_i2s (&id), info->pos);
2328   }
2329 #endif
2330   msg = (struct GNUNET_MESH_ManipulatePath *) buf;
2331   msg->header.size = htons (size_needed);
2332   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE);
2333   msg->tid = ntohl (t->id.tid);
2334
2335   peer_ptr = (struct GNUNET_PeerIdentity *) &msg[1];
2336   for (i = 0; i < p->length; i++)
2337   {
2338     GNUNET_PEER_resolve (p->peers[i], peer_ptr++);
2339   }
2340
2341   path_destroy (p);
2342   GNUNET_free (info);
2343
2344   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2345               "MESH: CREATE PATH (%u bytes long) sent!\n", size_needed);
2346   return size_needed;
2347 }
2348
2349
2350 /**
2351  * Function called to notify a client about the socket
2352  * being ready to queue more data.  "buf" will be
2353  * NULL and "size" zero if the socket was closed for
2354  * writing in the meantime.
2355  *
2356  * @param cls closure (data itself)
2357  * @param size number of bytes available in buf
2358  * @param buf where the callee should write the message
2359  *
2360  * @return number of bytes written to buf
2361  */
2362 static size_t
2363 send_core_data_multicast (void *cls, size_t size, void *buf)
2364 {
2365   struct MeshDataDescriptor *info = cls;
2366   size_t total_size;
2367
2368   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: Multicast callback.\n");
2369   GNUNET_assert (NULL != info);
2370   GNUNET_assert (NULL != info->peer);
2371   total_size = info->size;
2372   GNUNET_assert (total_size < GNUNET_SERVER_MAX_MESSAGE_SIZE);
2373
2374   if (total_size > size)
2375   {
2376     /* Retry */
2377     struct GNUNET_PeerIdentity id;
2378
2379     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2380                 "MESH: Multicast: retransmitting... (%u/%u)\n", size,
2381                 total_size);
2382     GNUNET_PEER_resolve (info->peer->id, &id);
2383     info->peer->core_transmit[info->handler_n] =
2384         GNUNET_CORE_notify_transmit_ready (core_handle, 0, 0,
2385                                            GNUNET_TIME_UNIT_FOREVER_REL, &id,
2386                                            total_size,
2387                                            &send_core_data_multicast, info);
2388     return 0;
2389   }
2390   info->peer->core_transmit[info->handler_n] = NULL;
2391   info->peer->infos[info->handler_n] = NULL;
2392   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:  copying data...\n");
2393   memcpy (buf, info->data, total_size);
2394 #if MESH_DEBUG
2395   {
2396     struct GNUNET_MESH_Multicast *mc;
2397     struct GNUNET_MessageHeader *mh;
2398
2399     mh = buf;
2400     if (ntohs (mh->type) == GNUNET_MESSAGE_TYPE_MESH_MULTICAST)
2401     {
2402       mc = (struct GNUNET_MESH_Multicast *) mh;
2403       mh = (struct GNUNET_MessageHeader *) &mc[1];
2404       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2405                   "MESH:  multicast, payload type %u\n", ntohs (mh->type));
2406       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2407                   "MESH:  multicast, payload size %u\n", ntohs (mh->size));
2408     }
2409     else
2410     {
2411       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:  type %u\n",
2412                   ntohs (mh->type));
2413     }
2414   }
2415 #endif
2416   data_descriptor_decrement_multicast (info);
2417   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: freeing info...\n");
2418   GNUNET_free (info);
2419   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: return %u\n", total_size);
2420   return total_size;
2421 }
2422
2423
2424 /**
2425  * Function called to notify a client about the socket
2426  * being ready to queue more data.  "buf" will be
2427  * NULL and "size" zero if the socket was closed for
2428  * writing in the meantime.
2429  *
2430  * @param cls closure (MeshDataDescriptor)
2431  * @param size number of bytes available in buf
2432  * @param buf where the callee should write the message
2433  * @return number of bytes written to buf
2434  */
2435 static size_t
2436 send_core_path_ack (void *cls, size_t size, void *buf)
2437 {
2438   struct MeshDataDescriptor *info = cls;
2439   struct GNUNET_MESH_PathACK *msg = buf;
2440
2441   GNUNET_assert (NULL != info);
2442   if (info->peer)
2443   {
2444     info->peer->core_transmit[info->handler_n] = NULL;
2445   }
2446   if (sizeof (struct GNUNET_MESH_PathACK) > size)
2447   {
2448     GNUNET_break (0);
2449     return 0;
2450   }
2451   msg->header.size = htons (sizeof (struct GNUNET_MESH_PathACK));
2452   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_ACK);
2453   GNUNET_PEER_resolve (info->origin->oid, &msg->oid);
2454   msg->tid = htonl (info->origin->tid);
2455   msg->peer_id = my_full_id;
2456   GNUNET_free (info);
2457   /* TODO add signature */
2458
2459   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: PATH ACK sent!\n");
2460   return sizeof (struct GNUNET_MESH_PathACK);
2461 }
2462
2463
2464 /******************************************************************************/
2465 /********************      MESH NETWORK HANDLERS     **************************/
2466 /******************************************************************************/
2467
2468
2469 /**
2470  * Core handler for path creation
2471  *
2472  * @param cls closure
2473  * @param message message
2474  * @param peer peer identity this notification is about
2475  * @param atsi performance data
2476  * @param atsi_count number of records in 'atsi'
2477  *
2478  * @return GNUNET_OK to keep the connection open,
2479  *         GNUNET_SYSERR to close it (signal serious error)
2480  */
2481 static int
2482 handle_mesh_path_create (void *cls, const struct GNUNET_PeerIdentity *peer,
2483                          const struct GNUNET_MessageHeader *message,
2484                          const struct GNUNET_ATS_Information *atsi,
2485                          unsigned int atsi_count)
2486 {
2487   unsigned int own_pos;
2488   uint16_t size;
2489   uint16_t i;
2490   MESH_TunnelNumber tid;
2491   struct GNUNET_MESH_ManipulatePath *msg;
2492   struct GNUNET_PeerIdentity *pi;
2493   GNUNET_HashCode hash;
2494   struct MeshPeerPath *path;
2495   struct MeshPeerInfo *dest_peer_info;
2496   struct MeshPeerInfo *orig_peer_info;
2497   struct MeshTunnel *t;
2498
2499   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2500               "MESH: Received a path create msg [%s]\n",
2501               GNUNET_i2s (&my_full_id));
2502   size = ntohs (message->size);
2503   if (size < sizeof (struct GNUNET_MESH_ManipulatePath))
2504   {
2505     GNUNET_break_op (0);
2506     return GNUNET_OK;
2507   }
2508
2509   size -= sizeof (struct GNUNET_MESH_ManipulatePath);
2510   if (size % sizeof (struct GNUNET_PeerIdentity))
2511   {
2512     GNUNET_break_op (0);
2513     return GNUNET_OK;
2514   }
2515   size /= sizeof (struct GNUNET_PeerIdentity);
2516   if (size < 2)
2517   {
2518     GNUNET_break_op (0);
2519     return GNUNET_OK;
2520   }
2521   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:     path has %u hops.\n", size);
2522   msg = (struct GNUNET_MESH_ManipulatePath *) message;
2523
2524   tid = ntohl (msg->tid);
2525   pi = (struct GNUNET_PeerIdentity *) &msg[1];
2526   t = tunnel_get (pi, tid);
2527   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2528               "MESH:     path is for tunnel %s [%X].\n", GNUNET_i2s (pi), tid);
2529   if (NULL == t)
2530   {
2531     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   Creating tunnel\n");
2532     t = GNUNET_malloc (sizeof (struct MeshTunnel));
2533     t->id.oid = GNUNET_PEER_intern (pi);
2534     t->id.tid = tid;
2535     while (NULL != tunnel_get_incoming (next_local_tid))
2536       next_local_tid = (next_local_tid + 1) | GNUNET_MESH_LOCAL_TUNNEL_ID_SERV;
2537     t->local_tid = next_local_tid++;
2538     next_local_tid = next_local_tid | GNUNET_MESH_LOCAL_TUNNEL_ID_SERV;
2539     t->tree = tree_new (t->id.oid);
2540
2541     GNUNET_CRYPTO_hash (&t->id, sizeof (struct MESH_TunnelID), &hash);
2542     if (GNUNET_OK !=
2543         GNUNET_CONTAINER_multihashmap_put (tunnels, &hash, t,
2544                                            GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
2545     {
2546       tunnel_destroy (t);
2547       GNUNET_break (0);
2548       return GNUNET_OK;
2549     }
2550     tunnel_reset_timeout (t);
2551     GNUNET_CRYPTO_hash (&t->local_tid, sizeof (MESH_TunnelNumber), &hash);
2552     if (GNUNET_OK !=
2553         GNUNET_CONTAINER_multihashmap_put (incoming_tunnels, &hash, t,
2554                                            GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
2555     {
2556       tunnel_destroy (t);
2557       GNUNET_break (0);
2558       return GNUNET_OK;
2559     }
2560   }
2561   dest_peer_info =
2562       GNUNET_CONTAINER_multihashmap_get (peers, &pi[size - 1].hashPubKey);
2563   if (NULL == dest_peer_info)
2564   {
2565     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2566                 "MESH:   Creating PeerInfo for destination.\n");
2567     dest_peer_info = GNUNET_malloc (sizeof (struct MeshPeerInfo));
2568     dest_peer_info->id = GNUNET_PEER_intern (&pi[size - 1]);
2569     GNUNET_CONTAINER_multihashmap_put (peers, &pi[size - 1].hashPubKey,
2570                                        dest_peer_info,
2571                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
2572   }
2573   orig_peer_info = GNUNET_CONTAINER_multihashmap_get (peers, &pi->hashPubKey);
2574   if (NULL == orig_peer_info)
2575   {
2576     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2577                 "MESH:   Creating PeerInfo for origin.\n");
2578     orig_peer_info = GNUNET_malloc (sizeof (struct MeshPeerInfo));
2579     orig_peer_info->id = GNUNET_PEER_intern (pi);
2580     GNUNET_CONTAINER_multihashmap_put (peers, &pi->hashPubKey, orig_peer_info,
2581                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
2582   }
2583   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   Creating path...\n");
2584   path = path_new (size);
2585   own_pos = 0;
2586   for (i = 0; i < size; i++)
2587   {
2588     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   ... adding %s\n",
2589                 GNUNET_i2s (&pi[i]));
2590     path->peers[i] = GNUNET_PEER_intern (&pi[i]);
2591     if (path->peers[i] == myid)
2592       own_pos = i;
2593   }
2594   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   Own position: %u\n", own_pos);
2595   if (own_pos == 0)
2596   {
2597     /* cannot be self, must be 'not found' */
2598     /* create path: self not found in path through self */
2599     GNUNET_break_op (0);
2600     path_destroy (path);
2601     /* FIXME error. destroy tunnel? leave for timeout? */
2602     return 0;
2603   }
2604   path_add_to_peers(path, GNUNET_NO);
2605   tunnel_add_path (t, path, own_pos);
2606   if (own_pos == size - 1)
2607   {
2608     /* It is for us! Send ack. */
2609     struct MeshDataDescriptor *info;
2610     unsigned int j;
2611
2612     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   It's for us!\n");
2613     peer_info_add_path_to_origin (orig_peer_info, path, GNUNET_NO);
2614     if (NULL == t->peers)
2615     {
2616       /* New tunnel! Notify clients! */
2617       struct GNUNET_MESH_TunnelNotification cmsg;
2618
2619       cmsg.header.size = htons (sizeof (cmsg));
2620       cmsg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_CREATE);
2621       GNUNET_PEER_resolve (t->id.oid, &cmsg.peer);
2622       cmsg.tunnel_id = htonl (t->local_tid);
2623       GNUNET_SERVER_notification_context_broadcast (nc, &cmsg.header,
2624                                                     GNUNET_NO);
2625
2626       t->peers = GNUNET_CONTAINER_multihashmap_create (4);
2627     }
2628     GNUNET_break (GNUNET_OK ==
2629                   GNUNET_CONTAINER_multihashmap_put (t->peers,
2630                                                      &my_full_id.hashPubKey,
2631                                                      peer_info_get
2632                                                      (&my_full_id),
2633                                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE));
2634     /* FIXME use send_message */
2635     info = GNUNET_malloc (sizeof (struct MeshDataDescriptor));
2636     info->origin = &t->id;
2637     info->peer = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
2638     GNUNET_assert (NULL != info->peer);
2639     j = peer_info_transmit_slot (info->peer);
2640     info->handler_n = j;
2641     info->peer->types[j] = GNUNET_MESSAGE_TYPE_MESH_PATH_ACK;
2642     info->peer->infos[j] = info;
2643     info->peer->core_transmit[j] =
2644         GNUNET_CORE_notify_transmit_ready (core_handle, 0, 100,
2645                                            GNUNET_TIME_UNIT_FOREVER_REL, peer,
2646                                            sizeof (struct GNUNET_MESH_PathACK),
2647                                            &send_core_path_ack, info);
2648   }
2649   else
2650   {
2651     struct MeshPeerPath *path2;
2652
2653     /* It's for somebody else! Retransmit. */
2654     path2 = path_duplicate (path);
2655     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   Retransmitting.\n");
2656     peer_info_add_path (dest_peer_info, path2, GNUNET_NO);
2657     path2 = path_duplicate (path);
2658     peer_info_add_path_to_origin (orig_peer_info, path2, GNUNET_NO);
2659     send_create_path (dest_peer_info, path, t);
2660   }
2661   return GNUNET_OK;
2662 }
2663
2664
2665 /**
2666  * Core handler for path destruction
2667  *
2668  * @param cls closure
2669  * @param message message
2670  * @param peer peer identity this notification is about
2671  * @param atsi performance data
2672  * @param atsi_count number of records in 'atsi'
2673  *
2674  * @return GNUNET_OK to keep the connection open,
2675  *         GNUNET_SYSERR to close it (signal serious error)
2676  */
2677 static int
2678 handle_mesh_path_destroy (void *cls, const struct GNUNET_PeerIdentity *peer,
2679                           const struct GNUNET_MessageHeader *message,
2680                           const struct GNUNET_ATS_Information *atsi,
2681                           unsigned int atsi_count)
2682 {
2683   struct GNUNET_MESH_ManipulatePath *msg;
2684   struct GNUNET_PeerIdentity *pi;
2685   struct MeshPeerPath *path;
2686   struct MeshTunnel *t;
2687   unsigned int own_pos;
2688   unsigned int i;
2689   size_t size;
2690
2691   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2692               "MESH: Received a PATH DESTROY msg from %s\n", GNUNET_i2s (peer));
2693   size = ntohs (message->size);
2694   if (size < sizeof (struct GNUNET_MESH_ManipulatePath))
2695   {
2696     GNUNET_break_op (0);
2697     return GNUNET_OK;
2698   }
2699
2700   size -= sizeof (struct GNUNET_MESH_ManipulatePath);
2701   if (size % sizeof (struct GNUNET_PeerIdentity))
2702   {
2703     GNUNET_break_op (0);
2704     return GNUNET_OK;
2705   }
2706   size /= sizeof (struct GNUNET_PeerIdentity);
2707   if (size < 2)
2708   {
2709     GNUNET_break_op (0);
2710     return GNUNET_OK;
2711   }
2712   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:     path has %u hops.\n", size);
2713
2714   msg = (struct GNUNET_MESH_ManipulatePath *) message;
2715   pi = (struct GNUNET_PeerIdentity *) &msg[1];
2716   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2717               "MESH:     path is for tunnel %s [%X].\n", GNUNET_i2s (pi),
2718               msg->tid);
2719   t = tunnel_get (pi, ntohl (msg->tid));
2720   if (NULL == t)
2721   {
2722     /* TODO notify back: we don't know this tunnel */
2723     GNUNET_break_op (0);
2724     return GNUNET_OK;
2725   }
2726   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   Creating path...\n");
2727   path = path_new (size);
2728   own_pos = 0;
2729   for (i = 0; i < size; i++)
2730   {
2731     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   ... adding %s\n",
2732                 GNUNET_i2s (&pi[i]));
2733     path->peers[i] = GNUNET_PEER_intern (&pi[i]);
2734     if (path->peers[i] == myid)
2735       own_pos = i;
2736   }
2737   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   Own position: %u\n", own_pos);
2738   if (own_pos < path->length - 1)
2739     send_message (message, &pi[own_pos + 1]);
2740   tunnel_delete_peer (t, path->peers[path->length - 1]);
2741   path_destroy (path);
2742   return GNUNET_OK;
2743 }
2744
2745
2746 /**
2747  * Core handler for notifications of broken paths
2748  *
2749  * @param cls closure
2750  * @param message message
2751  * @param peer peer identity this notification is about
2752  * @param atsi performance data
2753  * @param atsi_count number of records in 'atsi'
2754  *
2755  * @return GNUNET_OK to keep the connection open,
2756  *         GNUNET_SYSERR to close it (signal serious error)
2757  */
2758 static int
2759 handle_mesh_path_broken (void *cls, const struct GNUNET_PeerIdentity *peer,
2760                          const struct GNUNET_MessageHeader *message,
2761                          const struct GNUNET_ATS_Information *atsi,
2762                          unsigned int atsi_count)
2763 {
2764   struct GNUNET_MESH_PathBroken *msg;
2765   struct MeshTunnel *t;
2766
2767   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2768               "MESH: Received a PATH BROKEN msg from %s\n", GNUNET_i2s (peer));
2769   msg = (struct GNUNET_MESH_PathBroken *) message;
2770   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   regarding %s\n",
2771               GNUNET_i2s (&msg->peer1));
2772   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   regarding %s\n",
2773               GNUNET_i2s (&msg->peer2));
2774   t = tunnel_get (&msg->oid, ntohl (msg->tid));
2775   if (NULL == t)
2776   {
2777     GNUNET_break_op (0);
2778     return GNUNET_OK;
2779   }
2780   tunnel_notify_connection_broken (t, GNUNET_PEER_search (&msg->peer1),
2781                                    GNUNET_PEER_search (&msg->peer2));
2782   return GNUNET_OK;
2783
2784 }
2785
2786
2787 /**
2788  * Core handler for tunnel destruction
2789  *
2790  * @param cls closure
2791  * @param message message
2792  * @param peer peer identity this notification is about
2793  * @param atsi performance data
2794  * @param atsi_count number of records in 'atsi'
2795  *
2796  * @return GNUNET_OK to keep the connection open,
2797  *         GNUNET_SYSERR to close it (signal serious error)
2798  */
2799 static int
2800 handle_mesh_tunnel_destroy (void *cls, const struct GNUNET_PeerIdentity *peer,
2801                             const struct GNUNET_MessageHeader *message,
2802                             const struct GNUNET_ATS_Information *atsi,
2803                             unsigned int atsi_count)
2804 {
2805   struct GNUNET_MESH_TunnelDestroy *msg;
2806   struct MeshTunnel *t;
2807
2808   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2809               "MESH: Got a TUNNEL DESTROY packet from %s\n", GNUNET_i2s (peer));
2810   msg = (struct GNUNET_MESH_TunnelDestroy *) message;
2811   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   for tunnel %s [%u]\n",
2812               GNUNET_i2s (&msg->oid), ntohl (msg->tid));
2813   t = tunnel_get (&msg->oid, ntohl (msg->tid));
2814   if (NULL == t)
2815   {
2816     /* Probably already got the message from another path,
2817      * destroyed the tunnel and retransmitted to children.
2818      * Safe to ignore.
2819      */
2820     return GNUNET_OK;
2821   }
2822   if (t->id.oid == myid)
2823   {
2824     GNUNET_break_op (0);
2825     return GNUNET_OK;
2826   }
2827   if (t->local_tid >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
2828   {
2829     /* Tunnel was incoming, notify clients */
2830     send_clients_tunnel_destroy (t);
2831   }
2832   tunnel_send_destroy (t);
2833   tunnel_destroy (t);
2834   return GNUNET_OK;
2835 }
2836
2837
2838 /**
2839  * Core handler for mesh network traffic going from the origin to a peer
2840  *
2841  * @param cls closure
2842  * @param peer peer identity this notification is about
2843  * @param message message
2844  * @param atsi performance data
2845  * @param atsi_count number of records in 'atsi'
2846  * @return GNUNET_OK to keep the connection open,
2847  *         GNUNET_SYSERR to close it (signal serious error)
2848  */
2849 static int
2850 handle_mesh_data_unicast (void *cls, const struct GNUNET_PeerIdentity *peer,
2851                           const struct GNUNET_MessageHeader *message,
2852                           const struct GNUNET_ATS_Information *atsi,
2853                           unsigned int atsi_count)
2854 {
2855   struct GNUNET_MESH_Unicast *msg;
2856   struct MeshTunnel *t;
2857   GNUNET_PEER_Id pid;
2858   size_t size;
2859
2860   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: got a unicast packet from %s\n",
2861               GNUNET_i2s (peer));
2862   size = ntohs (message->size);
2863   if (size <
2864       sizeof (struct GNUNET_MESH_Unicast) +
2865       sizeof (struct GNUNET_MessageHeader))
2866   {
2867     GNUNET_break (0);
2868     return GNUNET_OK;
2869   }
2870   msg = (struct GNUNET_MESH_Unicast *) message;
2871   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:  of type %u\n",
2872               ntohs (msg[1].header.type));
2873   t = tunnel_get (&msg->oid, ntohl (msg->tid));
2874   if (NULL == t)
2875   {
2876     /* TODO notify back: we don't know this tunnel */
2877     GNUNET_break_op (0);
2878     return GNUNET_OK;
2879   }
2880   tunnel_reset_timeout (t);
2881   pid = GNUNET_PEER_search (&msg->destination);
2882   if (pid == myid)
2883   {
2884     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2885                 "MESH:   it's for us! sending to clients...\n");
2886     send_subscribed_clients (message, (struct GNUNET_MessageHeader *) &msg[1]);
2887     return GNUNET_OK;
2888   }
2889   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2890               "MESH:   not for us, retransmitting...\n");
2891   send_message (message, tree_get_first_hop (t->tree, pid));
2892   return GNUNET_OK;
2893 }
2894
2895
2896 /**
2897  * Core handler for mesh network traffic going from the origin to all peers
2898  *
2899  * @param cls closure
2900  * @param message message
2901  * @param peer peer identity this notification is about
2902  * @param atsi performance data
2903  * @param atsi_count number of records in 'atsi'
2904  * @return GNUNET_OK to keep the connection open,
2905  *         GNUNET_SYSERR to close it (signal serious error)
2906  *
2907  * TODO: Check who we got this from, to validate route.
2908  */
2909 static int
2910 handle_mesh_data_multicast (void *cls, const struct GNUNET_PeerIdentity *peer,
2911                             const struct GNUNET_MessageHeader *message,
2912                             const struct GNUNET_ATS_Information *atsi,
2913                             unsigned int atsi_count)
2914 {
2915   struct GNUNET_MESH_Multicast *msg;
2916   struct MeshTunnel *t;
2917   size_t size;
2918
2919   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: got a multicast packet from %s\n",
2920               GNUNET_i2s (peer));
2921   size = ntohs (message->size);
2922   if (sizeof (struct GNUNET_MESH_Multicast) +
2923       sizeof (struct GNUNET_MessageHeader) > size)
2924   {
2925     GNUNET_break_op (0);
2926     return GNUNET_OK;
2927   }
2928   msg = (struct GNUNET_MESH_Multicast *) message;
2929   t = tunnel_get (&msg->oid, ntohl (msg->tid));
2930
2931   if (NULL == t)
2932   {
2933     /* TODO notify that we dont know that tunnel */
2934     GNUNET_break_op (0);
2935     return GNUNET_OK;
2936   }
2937   if (t->mid == ntohl (msg->mid))
2938   {
2939     /* FIXME: already seen this packet, log dropping */
2940     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2941                 "MESH:  Already seen mid %u, DROPPING!\n",
2942                 t->mid);
2943     return GNUNET_OK;
2944   }
2945 #if MESH_DEBUG
2946   else
2947   {
2948     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2949                 "MESH:  mid %u not seen yet, forwarding\n",
2950                 ntohl (msg->mid));
2951   }
2952 #endif
2953   t->mid = ntohl (msg->mid);
2954   tunnel_reset_timeout (t);
2955
2956   /* Transmit to locally interested clients */
2957   if (NULL != t->peers &&
2958       GNUNET_CONTAINER_multihashmap_contains (t->peers, &my_full_id.hashPubKey))
2959   {
2960     send_subscribed_clients (message, &msg[1].header);
2961   }
2962 #if MESH_DEBUG
2963   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2964               "MESH:    ttl: %u\n",
2965               ntohl (msg->ttl));
2966 #endif
2967   if (ntohl (msg->ttl) == 0)
2968   {
2969     /* FIXME: ttl is 0, log dropping */
2970     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2971                 "MESH:  TTL is 0, DROPPING!\n");
2972     return GNUNET_OK;
2973   }
2974   tunnel_send_multicast (t, message);
2975   return GNUNET_OK;
2976 }
2977
2978
2979 /**
2980  * Core handler for mesh network traffic toward the owner of a tunnel
2981  *
2982  * @param cls closure
2983  * @param message message
2984  * @param peer peer identity this notification is about
2985  * @param atsi performance data
2986  * @param atsi_count number of records in 'atsi'
2987  *
2988  * @return GNUNET_OK to keep the connection open,
2989  *         GNUNET_SYSERR to close it (signal serious error)
2990  */
2991 static int
2992 handle_mesh_data_to_orig (void *cls, const struct GNUNET_PeerIdentity *peer,
2993                           const struct GNUNET_MessageHeader *message,
2994                           const struct GNUNET_ATS_Information *atsi,
2995                           unsigned int atsi_count)
2996 {
2997   struct GNUNET_MESH_ToOrigin *msg;
2998   struct GNUNET_PeerIdentity id;
2999   struct MeshPeerInfo *peer_info;
3000   struct MeshTunnel *t;
3001   size_t size;
3002
3003   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: got a ToOrigin packet from %s\n",
3004               GNUNET_i2s (peer));
3005   size = ntohs (message->size);
3006   if (size < sizeof (struct GNUNET_MESH_ToOrigin) +     /* Payload must be */
3007       sizeof (struct GNUNET_MessageHeader))     /* at least a header */
3008   {
3009     GNUNET_break_op (0);
3010     return GNUNET_OK;
3011   }
3012   msg = (struct GNUNET_MESH_ToOrigin *) message;
3013   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:  of type %u\n",
3014               ntohs (msg[1].header.type));
3015   t = tunnel_get (&msg->oid, ntohl (msg->tid));
3016
3017   if (NULL == t)
3018   {
3019     /* TODO notify that we dont know this tunnel (whom)? */
3020     GNUNET_break_op (0);
3021     return GNUNET_OK;
3022   }
3023
3024   if (t->id.oid == myid)
3025   {
3026     char cbuf[size];
3027     struct GNUNET_MESH_ToOrigin *copy;
3028
3029     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3030                 "MESH:   it's for us! sending to clients...\n");
3031     if (NULL == t->client)
3032     {
3033       /* got data packet for ownerless tunnel */
3034       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   no clients!\n");
3035       GNUNET_break_op (0);
3036       return GNUNET_OK;
3037     }
3038     /* TODO signature verification */
3039     memcpy (cbuf, message, size);
3040     copy = (struct GNUNET_MESH_ToOrigin *) cbuf;
3041     copy->tid = htonl (t->local_tid);
3042     GNUNET_SERVER_notification_context_unicast (nc, t->client->handle,
3043                                                 &copy->header, GNUNET_YES);
3044     return GNUNET_OK;
3045   }
3046   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3047               "MESH:   not for us, retransmitting...\n");
3048
3049   peer_info = peer_info_get (&msg->oid);
3050   if (NULL == peer_info)
3051   {
3052     /* unknown origin of tunnel */
3053     GNUNET_break (0);
3054     return GNUNET_OK;
3055   }
3056   GNUNET_PEER_resolve (tree_get_predecessor (t->tree), &id);
3057   send_message (message, &id);
3058
3059   return GNUNET_OK;
3060 }
3061
3062
3063 /**
3064  * Core handler for path ACKs
3065  *
3066  * @param cls closure
3067  * @param message message
3068  * @param peer peer identity this notification is about
3069  * @param atsi performance data
3070  * @param atsi_count number of records in 'atsi'
3071  *
3072  * @return GNUNET_OK to keep the connection open,
3073  *         GNUNET_SYSERR to close it (signal serious error)
3074  */
3075 static int
3076 handle_mesh_path_ack (void *cls, const struct GNUNET_PeerIdentity *peer,
3077                       const struct GNUNET_MessageHeader *message,
3078                       const struct GNUNET_ATS_Information *atsi,
3079                       unsigned int atsi_count)
3080 {
3081   struct GNUNET_MESH_PathACK *msg;
3082   struct GNUNET_PeerIdentity id;
3083   struct MeshPeerInfo *peer_info;
3084   struct MeshPeerPath *p;
3085   struct MeshTunnel *t;
3086
3087   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: Received a path ACK msg [%s]\n",
3088               GNUNET_i2s (&my_full_id));
3089   msg = (struct GNUNET_MESH_PathACK *) message;
3090   t = tunnel_get (&msg->oid, msg->tid);
3091   if (NULL == t)
3092   {
3093     /* TODO notify that we don't know the tunnel */
3094     return GNUNET_OK;
3095   }
3096
3097   peer_info = peer_info_get (&msg->peer_id);
3098
3099   /* Add paths to peers? */
3100   p = tree_get_path_to_peer(t->tree, peer_info->id);
3101   if (NULL != p)
3102   {
3103     path_add_to_peers (p, GNUNET_YES);
3104     path_destroy(p);
3105   }
3106   else
3107   {
3108     GNUNET_break (0);
3109   }
3110
3111   /* Message for us? */
3112   if (0 == memcmp (&msg->oid, &my_full_id, sizeof (struct GNUNET_PeerIdentity)))
3113   {
3114     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   It's for us!\n");
3115     if (NULL == t->client)
3116     {
3117       GNUNET_break_op (0);
3118       return GNUNET_OK;
3119     }
3120     if (NULL != t->dht_get_type)
3121     {
3122       GNUNET_DHT_get_stop (t->dht_get_type);
3123       t->dht_get_type = NULL;
3124     }
3125     if (tree_get_status(t->tree, peer_info->id) != MESH_PEER_READY)
3126     {
3127       tree_set_status (t->tree, peer_info->id, MESH_PEER_READY);
3128       send_client_peer_connected (t, peer_info->id);
3129     }
3130     return GNUNET_OK;
3131   }
3132
3133   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3134               "MESH:   not for us, retransmitting...\n");
3135   GNUNET_PEER_resolve (tree_get_predecessor (t->tree), &id);
3136   peer_info = peer_info_get (&msg->oid);
3137   if (NULL == peer_info)
3138   {
3139     /* If we know the tunnel, we should DEFINITELY know the peer */
3140     GNUNET_break (0);
3141     return GNUNET_OK;
3142   }
3143   send_message (message, &id);
3144   return GNUNET_OK;
3145 }
3146
3147
3148 /**
3149  * Functions to handle messages from core
3150  */
3151 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
3152   {&handle_mesh_path_create, GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE, 0},
3153   {&handle_mesh_path_destroy, GNUNET_MESSAGE_TYPE_MESH_PATH_DESTROY, 0},
3154   {&handle_mesh_path_broken, GNUNET_MESSAGE_TYPE_MESH_PATH_BROKEN,
3155    sizeof (struct GNUNET_MESH_PathBroken)},
3156   {&handle_mesh_tunnel_destroy, GNUNET_MESSAGE_TYPE_MESH_TUNNEL_DESTROY, 0},
3157   {&handle_mesh_data_unicast, GNUNET_MESSAGE_TYPE_MESH_UNICAST, 0},
3158   {&handle_mesh_data_multicast, GNUNET_MESSAGE_TYPE_MESH_MULTICAST, 0},
3159   {&handle_mesh_data_to_orig, GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN, 0},
3160   {&handle_mesh_path_ack, GNUNET_MESSAGE_TYPE_MESH_PATH_ACK,
3161    sizeof (struct GNUNET_MESH_PathACK)},
3162   {NULL, 0, 0}
3163 };
3164
3165
3166
3167 /******************************************************************************/
3168 /****************       MESH LOCAL HANDLER HELPERS      ***********************/
3169 /******************************************************************************/
3170
3171 /**
3172  * deregister_app: iterator for removing each application registered by a client
3173  *
3174  * @param cls closure
3175  * @param key the hash of the application id (used to access the hashmap)
3176  * @param value the value stored at the key (client)
3177  *
3178  * @return GNUNET_OK on success
3179  */
3180 static int
3181 deregister_app (void *cls, const GNUNET_HashCode * key, void *value)
3182 {
3183   GNUNET_break (GNUNET_YES ==
3184                 GNUNET_CONTAINER_multihashmap_remove (applications, key,
3185                                                       value));
3186   return GNUNET_OK;
3187 }
3188
3189 #if LATER
3190 /**
3191  * notify_client_connection_failure: notify a client that the connection to the
3192  * requested remote peer is not possible (for instance, no route found)
3193  * Function called when the socket is ready to queue more data. "buf" will be
3194  * NULL and "size" zero if the socket was closed for writing in the meantime.
3195  *
3196  * @param cls closure
3197  * @param size number of bytes available in buf
3198  * @param buf where the callee should write the message
3199  * @return number of bytes written to buf
3200  */
3201 static size_t
3202 notify_client_connection_failure (void *cls, size_t size, void *buf)
3203 {
3204   int size_needed;
3205   struct MeshPeerInfo *peer_info;
3206   struct GNUNET_MESH_PeerControl *msg;
3207   struct GNUNET_PeerIdentity id;
3208
3209   if (0 == size && NULL == buf)
3210   {
3211     // TODO retry? cancel?
3212     return 0;
3213   }
3214
3215   size_needed = sizeof (struct GNUNET_MESH_PeerControl);
3216   peer_info = (struct MeshPeerInfo *) cls;
3217   msg = (struct GNUNET_MESH_PeerControl *) buf;
3218   msg->header.size = htons (sizeof (struct GNUNET_MESH_PeerControl));
3219   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_DISCONNECTED);
3220 //     msg->tunnel_id = htonl(peer_info->t->tid);
3221   GNUNET_PEER_resolve (peer_info->id, &id);
3222   memcpy (&msg->peer, &id, sizeof (struct GNUNET_PeerIdentity));
3223
3224   return size_needed;
3225 }
3226 #endif
3227
3228
3229 /**
3230  * Send keepalive packets for a peer
3231  *
3232  * @param cls Closure (tunnel for which to send the keepalive).
3233  * @param tc Notification context.
3234  *
3235  * TODO: implement explicit multicast keepalive?
3236  */
3237 static void
3238 path_refresh (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3239 {
3240   struct MeshTunnel *t = cls;
3241   struct GNUNET_MessageHeader *payload;
3242   struct GNUNET_MESH_Multicast *msg;
3243   size_t size =
3244       sizeof (struct GNUNET_MESH_Multicast) +
3245       sizeof (struct GNUNET_MessageHeader);
3246   char cbuf[size];
3247
3248   if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3249   {
3250     return;
3251   }
3252   t->path_refresh_task = GNUNET_SCHEDULER_NO_TASK;
3253
3254   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3255               "MESH: sending keepalive for tunnel %d\n", t->id.tid);
3256
3257   msg = (struct GNUNET_MESH_Multicast *) cbuf;
3258   msg->header.size = htons (size);
3259   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_MULTICAST);
3260   msg->oid = my_full_id;
3261   msg->tid = htonl (t->id.tid);
3262   payload = (struct GNUNET_MessageHeader *) &msg[1];
3263   payload->size = htons (sizeof (struct GNUNET_MessageHeader));
3264   payload->type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_KEEPALIVE);
3265   tunnel_send_multicast (t, &msg->header);
3266
3267   t->path_refresh_task =
3268       GNUNET_SCHEDULER_add_delayed (REFRESH_PATH_TIME, &path_refresh, t);
3269   return;
3270 }
3271
3272
3273 /**
3274  * Function to process paths received for a new peer addition. The recorded
3275  * paths form the initial tunnel, which can be optimized later.
3276  * Called on each result obtained for the DHT search.
3277  *
3278  * @param cls closure
3279  * @param exp when will this value expire
3280  * @param key key of the result
3281  * @param get_path path of the get request
3282  * @param get_path_length lenght of get_path
3283  * @param put_path path of the put request
3284  * @param put_path_length length of the put_path
3285  * @param type type of the result
3286  * @param size number of bytes in data
3287  * @param data pointer to the result data
3288  *
3289  * TODO: re-issue the request after certain time? cancel after X results?
3290  */
3291 static void
3292 dht_get_id_handler (void *cls, struct GNUNET_TIME_Absolute exp,
3293                     const GNUNET_HashCode * key,
3294                     const struct GNUNET_PeerIdentity *get_path,
3295                     unsigned int get_path_length,
3296                     const struct GNUNET_PeerIdentity *put_path,
3297                     unsigned int put_path_length, enum GNUNET_BLOCK_Type type,
3298                     size_t size, const void *data)
3299 {
3300   struct MeshPathInfo *path_info = cls;
3301   struct MeshPeerPath *p;
3302   struct GNUNET_PeerIdentity pi;
3303   int i;
3304
3305   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: Got results from DHT!\n");
3306   GNUNET_PEER_resolve (path_info->peer->id, &pi);
3307   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   for %s\n", GNUNET_i2s (&pi));
3308
3309   p = path_build_from_dht (get_path, get_path_length, put_path,
3310                            put_path_length);
3311   path_add_to_peers(p, GNUNET_NO);
3312   for (i = 0; i < path_info->peer->ntunnels; i++)
3313   {
3314     tunnel_add_peer (path_info->peer->tunnels[i], path_info->peer);
3315     peer_info_connect (path_info->peer, path_info->t);
3316   }
3317
3318   return;
3319 }
3320
3321
3322 /**
3323  * Function to process paths received for a new peer addition. The recorded
3324  * paths form the initial tunnel, which can be optimized later.
3325  * Called on each result obtained for the DHT search.
3326  *
3327  * @param cls closure
3328  * @param exp when will this value expire
3329  * @param key key of the result
3330  * @param get_path path of the get request
3331  * @param get_path_length lenght of get_path
3332  * @param put_path path of the put request
3333  * @param put_path_length length of the put_path
3334  * @param type type of the result
3335  * @param size number of bytes in data
3336  * @param data pointer to the result data
3337  */
3338 static void
3339 dht_get_type_handler (void *cls, struct GNUNET_TIME_Absolute exp,
3340                       const GNUNET_HashCode * key,
3341                       const struct GNUNET_PeerIdentity *get_path,
3342                       unsigned int get_path_length,
3343                       const struct GNUNET_PeerIdentity *put_path,
3344                       unsigned int put_path_length, enum GNUNET_BLOCK_Type type,
3345                       size_t size, const void *data)
3346 {
3347   const struct GNUNET_PeerIdentity *pi = data;
3348   struct MeshTunnel *t = cls;
3349   struct MeshPeerInfo *peer_info;
3350   struct MeshPeerPath *p;
3351
3352   if (size != sizeof (struct GNUNET_PeerIdentity))
3353   {
3354     GNUNET_break_op (0);
3355     return;
3356   }
3357   GNUNET_assert (NULL != t->client);
3358   peer_info = peer_info_get (pi);
3359   (void) GNUNET_CONTAINER_multihashmap_put (t->peers, &pi->hashPubKey,
3360                                             peer_info,
3361                                             GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE);
3362
3363   p = path_build_from_dht (get_path, get_path_length, put_path,
3364                            put_path_length);
3365   path_add_to_peers(p, GNUNET_NO);
3366   tunnel_add_peer (t, peer_info);
3367   peer_info_connect (peer_info, t);
3368 }
3369
3370
3371 /******************************************************************************/
3372 /*********************       MESH LOCAL HANDLES      **************************/
3373 /******************************************************************************/
3374
3375
3376 /**
3377  * Handler for client disconnection
3378  *
3379  * @param cls closure
3380  * @param client identification of the client; NULL
3381  *        for the last call when the server is destroyed
3382  */
3383 static void
3384 handle_local_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
3385 {
3386   struct MeshClient *c;
3387   struct MeshClient *next;
3388
3389   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: client disconnected\n");
3390   if (client == NULL)
3391   {
3392     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:    (SERVER DOWN)\n");
3393     return;
3394   }
3395   c = clients;
3396   while (NULL != c)
3397   {
3398     if (c->handle != client && NULL != client)
3399     {
3400       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:    ... searching\n");
3401       c = c->next;
3402       continue;
3403     }
3404     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: matching client found\n");
3405     GNUNET_SERVER_client_drop (c->handle);
3406     if (NULL != c->tunnels)
3407     {
3408       GNUNET_CONTAINER_multihashmap_iterate (c->tunnels,
3409                                              &tunnel_destroy_iterator, c);
3410       GNUNET_CONTAINER_multihashmap_destroy (c->tunnels);
3411     }
3412
3413     /* deregister clients applications */
3414     if (NULL != c->apps)
3415     {
3416       GNUNET_CONTAINER_multihashmap_iterate (c->apps, &deregister_app, NULL);
3417       GNUNET_CONTAINER_multihashmap_destroy (c->apps);
3418     }
3419     if (0 == GNUNET_CONTAINER_multihashmap_size (applications) &&
3420         GNUNET_SCHEDULER_NO_TASK != announce_applications_task)
3421     {
3422       GNUNET_SCHEDULER_cancel (announce_applications_task);
3423       announce_applications_task = GNUNET_SCHEDULER_NO_TASK;
3424     }
3425     if (NULL != c->types)
3426       GNUNET_CONTAINER_multihashmap_destroy (c->types);
3427     next = c->next;
3428     GNUNET_CONTAINER_DLL_remove (clients, clients_tail, c);
3429     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   CLIENT FREE at %p\n", c);
3430     GNUNET_free (c);
3431     c = next;
3432   }
3433
3434   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:    done!\n");
3435   return;
3436 }
3437
3438
3439 /**
3440  * Handler for new clients
3441  *
3442  * @param cls closure
3443  * @param client identification of the client
3444  * @param message the actual message, which includes messages the client wants
3445  */
3446 static void
3447 handle_local_new_client (void *cls, struct GNUNET_SERVER_Client *client,
3448                          const struct GNUNET_MessageHeader *message)
3449 {
3450   struct GNUNET_MESH_ClientConnect *cc_msg;
3451   struct MeshClient *c;
3452   GNUNET_MESH_ApplicationType *a;
3453   unsigned int size;
3454   uint16_t ntypes;
3455   uint16_t *t;
3456   uint16_t napps;
3457   uint16_t i;
3458
3459   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: new client connected\n");
3460   /* Check data sanity */
3461   size = ntohs (message->size) - sizeof (struct GNUNET_MESH_ClientConnect);
3462   cc_msg = (struct GNUNET_MESH_ClientConnect *) message;
3463   ntypes = ntohs (cc_msg->types);
3464   napps = ntohs (cc_msg->applications);
3465   if (size !=
3466       ntypes * sizeof (uint16_t) + napps * sizeof (GNUNET_MESH_ApplicationType))
3467   {
3468     GNUNET_break (0);
3469     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3470     return;
3471   }
3472
3473   /* Create new client structure */
3474   c = GNUNET_malloc (sizeof (struct MeshClient));
3475 #if MESH_DEBUG
3476   c->id = next_client_id++;
3477   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   CLIENT NEW %u at %p\n", c->id,
3478               c);
3479 #endif
3480   c->handle = client;
3481   GNUNET_SERVER_client_keep (client);
3482   a = (GNUNET_MESH_ApplicationType *) &cc_msg[1];
3483   if (napps > 0)
3484   {
3485     GNUNET_MESH_ApplicationType at;
3486     GNUNET_HashCode hc;
3487
3488     c->apps = GNUNET_CONTAINER_multihashmap_create (napps);
3489     for (i = 0; i < napps; i++)
3490     {
3491       at = ntohl (a[i]);
3492       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   app type: %u\n", at);
3493       GNUNET_CRYPTO_hash (&at, sizeof (at), &hc);
3494       /* store in clients hashmap */
3495       GNUNET_CONTAINER_multihashmap_put (c->apps, &hc, c,
3496                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
3497       /* store in global hashmap, for announcements */
3498       GNUNET_CONTAINER_multihashmap_put (applications, &hc, c,
3499                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
3500     }
3501     if (GNUNET_SCHEDULER_NO_TASK == announce_applications_task)
3502       announce_applications_task =
3503           GNUNET_SCHEDULER_add_now (&announce_applications, NULL);
3504
3505   }
3506   if (ntypes > 0)
3507   {
3508     uint16_t u16;
3509     GNUNET_HashCode hc;
3510
3511     t = (uint16_t *) & a[napps];
3512     c->types = GNUNET_CONTAINER_multihashmap_create (ntypes);
3513     for (i = 0; i < ntypes; i++)
3514     {
3515       u16 = ntohs (t[i]);
3516       GNUNET_CRYPTO_hash (&u16, sizeof (u16), &hc);
3517
3518       /* store in clients hashmap */
3519       GNUNET_CONTAINER_multihashmap_put (c->types, &hc, c,
3520                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
3521       /* store in global hashmap */
3522       GNUNET_CONTAINER_multihashmap_put (types, &hc, c,
3523                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
3524     }
3525   }
3526   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3527               "MESH:  client has %u+%u subscriptions\n", napps, ntypes);
3528
3529   GNUNET_CONTAINER_DLL_insert (clients, clients_tail, c);
3530   c->tunnels = GNUNET_CONTAINER_multihashmap_create (32);
3531   GNUNET_SERVER_notification_context_add (nc, client);
3532
3533   GNUNET_SERVER_receive_done (client, GNUNET_OK);
3534 #if MESH_DEBUG
3535   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: new client processed\n");
3536 #endif
3537 }
3538
3539
3540 /**
3541  * Handler for requests of new tunnels
3542  *
3543  * @param cls closure
3544  * @param client identification of the client
3545  * @param message the actual message
3546  */
3547 static void
3548 handle_local_tunnel_create (void *cls, struct GNUNET_SERVER_Client *client,
3549                             const struct GNUNET_MessageHeader *message)
3550 {
3551   struct GNUNET_MESH_TunnelMessage *t_msg;
3552   struct MeshTunnel *t;
3553   struct MeshClient *c;
3554   GNUNET_HashCode hash;
3555
3556   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: new tunnel requested\n");
3557
3558   /* Sanity check for client registration */
3559   if (NULL == (c = client_get (client)))
3560   {
3561     GNUNET_break (0);
3562     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3563     return;
3564   }
3565 #if MESH_DEBUG
3566   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   by client %u\n", c->id);
3567 #endif
3568
3569   /* Message sanity check */
3570   if (sizeof (struct GNUNET_MESH_TunnelMessage) != ntohs (message->size))
3571   {
3572     GNUNET_break (0);
3573     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3574     return;
3575   }
3576
3577   t_msg = (struct GNUNET_MESH_TunnelMessage *) message;
3578   /* Sanity check for tunnel numbering */
3579   if (0 == (ntohl (t_msg->tunnel_id) & GNUNET_MESH_LOCAL_TUNNEL_ID_CLI))
3580   {
3581     GNUNET_break (0);
3582     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3583     return;
3584   }
3585   /* Sanity check for duplicate tunnel IDs */
3586   if (NULL != tunnel_get_by_local_id (c, ntohl (t_msg->tunnel_id)))
3587   {
3588     GNUNET_break (0);
3589     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3590     return;
3591   }
3592
3593   t = GNUNET_malloc (sizeof (struct MeshTunnel));
3594   while (NULL != tunnel_get_by_pi (myid, next_tid))
3595     next_tid = (next_tid + 1) & ~GNUNET_MESH_LOCAL_TUNNEL_ID_CLI;
3596   t->id.tid = next_tid++;
3597   next_tid = next_tid & ~GNUNET_MESH_LOCAL_TUNNEL_ID_CLI;
3598   t->id.oid = myid;
3599   t->local_tid = ntohl (t_msg->tunnel_id);
3600 #if MESH_DEBUG
3601   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: CREATED TUNNEL %s [%x] (%x)\n",
3602               GNUNET_i2s (&my_full_id), t->id.tid, t->local_tid);
3603 #endif
3604   t->client = c;
3605   t->peers = GNUNET_CONTAINER_multihashmap_create (32);
3606
3607   GNUNET_CRYPTO_hash (&t->local_tid, sizeof (MESH_TunnelNumber), &hash);
3608   if (GNUNET_OK !=
3609       GNUNET_CONTAINER_multihashmap_put (c->tunnels, &hash, t,
3610                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
3611   {
3612     GNUNET_break (0);
3613     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3614     return;
3615   }
3616
3617   GNUNET_CRYPTO_hash (&t->id, sizeof (struct MESH_TunnelID), &hash);
3618   if (GNUNET_OK !=
3619       GNUNET_CONTAINER_multihashmap_put (tunnels, &hash, t,
3620                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
3621   {
3622     GNUNET_break (0);
3623     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3624     return;
3625   }
3626   t->tree = tree_new (myid);
3627
3628   GNUNET_SERVER_receive_done (client, GNUNET_OK);
3629   return;
3630 }
3631
3632
3633 /**
3634  * Handler for requests of deleting tunnels
3635  *
3636  * @param cls closure
3637  * @param client identification of the client
3638  * @param message the actual message
3639  */
3640 static void
3641 handle_local_tunnel_destroy (void *cls, struct GNUNET_SERVER_Client *client,
3642                              const struct GNUNET_MessageHeader *message)
3643 {
3644   struct GNUNET_MESH_TunnelMessage *tunnel_msg;
3645   struct MeshClient *c;
3646   struct MeshTunnel *t;
3647   MESH_TunnelNumber tid;
3648   GNUNET_HashCode hash;
3649
3650   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3651               "MESH: Got a DESTROY TUNNEL from client!\n");
3652
3653   /* Sanity check for client registration */
3654   if (NULL == (c = client_get (client)))
3655   {
3656     GNUNET_break (0);
3657     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3658     return;
3659   }
3660   /* Message sanity check */
3661   if (sizeof (struct GNUNET_MESH_TunnelMessage) != ntohs (message->size))
3662   {
3663     GNUNET_break (0);
3664     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3665     return;
3666   }
3667 #if MESH_DEBUG
3668   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   by client %u\n", c->id);
3669 #endif
3670   tunnel_msg = (struct GNUNET_MESH_TunnelMessage *) message;
3671
3672   /* Retrieve tunnel */
3673   tid = ntohl (tunnel_msg->tunnel_id);
3674
3675   /* Remove from local id hashmap */
3676   GNUNET_CRYPTO_hash (&tid, sizeof (MESH_TunnelNumber), &hash);
3677   t = GNUNET_CONTAINER_multihashmap_get (c->tunnels, &hash);
3678   GNUNET_assert (GNUNET_YES ==
3679                  GNUNET_CONTAINER_multihashmap_remove (c->tunnels, &hash, t));
3680
3681   t->client = NULL;
3682   tunnel_send_destroy (t);
3683   tunnel_destroy (t);
3684   GNUNET_SERVER_receive_done (client, GNUNET_OK);
3685   return;
3686 }
3687
3688
3689 /**
3690  * Handler for connection requests to new peers
3691  *
3692  * @param cls closure
3693  * @param client identification of the client
3694  * @param message the actual message (PeerControl)
3695  */
3696 static void
3697 handle_local_connect_add (void *cls, struct GNUNET_SERVER_Client *client,
3698                           const struct GNUNET_MessageHeader *message)
3699 {
3700   struct GNUNET_MESH_PeerControl *peer_msg;
3701   struct MeshPeerInfo *peer_info;
3702   struct MeshClient *c;
3703   struct MeshTunnel *t;
3704   MESH_TunnelNumber tid;
3705
3706   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: Got connection request\n");
3707   /* Sanity check for client registration */
3708   if (NULL == (c = client_get (client)))
3709   {
3710     GNUNET_break (0);
3711     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3712     return;
3713   }
3714
3715   peer_msg = (struct GNUNET_MESH_PeerControl *) message;
3716   /* Sanity check for message size */
3717   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (peer_msg->header.size))
3718   {
3719     GNUNET_break (0);
3720     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3721     return;
3722   }
3723
3724   /* Tunnel exists? */
3725   tid = ntohl (peer_msg->tunnel_id);
3726   t = tunnel_get_by_local_id (c, tid);
3727   if (NULL == t)
3728   {
3729     GNUNET_break (0);
3730     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3731     return;
3732   }
3733
3734   /* Does client own tunnel? */
3735   if (t->client->handle != client)
3736   {
3737     GNUNET_break (0);
3738     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3739     return;
3740   }
3741   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:      for %s\n",
3742               GNUNET_i2s (&peer_msg->peer));
3743   peer_info = peer_info_get (&peer_msg->peer);
3744
3745   tunnel_add_peer (t, peer_info);
3746   peer_info_connect (peer_info, t);
3747
3748   GNUNET_SERVER_receive_done (client, GNUNET_OK);
3749   return;
3750 }
3751
3752
3753 /**
3754  * Handler for disconnection requests of peers in a tunnel
3755  *
3756  * @param cls closure
3757  * @param client identification of the client
3758  * @param message the actual message (PeerControl)
3759  */
3760 static void
3761 handle_local_connect_del (void *cls, struct GNUNET_SERVER_Client *client,
3762                           const struct GNUNET_MessageHeader *message)
3763 {
3764   struct GNUNET_MESH_PeerControl *peer_msg;
3765   struct MeshPeerInfo *peer_info;
3766   struct MeshClient *c;
3767   struct MeshTunnel *t;
3768   MESH_TunnelNumber tid;
3769
3770   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: Got a PEER DEL request\n");
3771   /* Sanity check for client registration */
3772   if (NULL == (c = client_get (client)))
3773   {
3774     GNUNET_break (0);
3775     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3776     return;
3777   }
3778   peer_msg = (struct GNUNET_MESH_PeerControl *) message;
3779   /* Sanity check for message size */
3780   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (peer_msg->header.size))
3781   {
3782     GNUNET_break (0);
3783     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3784     return;
3785   }
3786
3787   /* Tunnel exists? */
3788   tid = ntohl (peer_msg->tunnel_id);
3789   t = tunnel_get_by_local_id (c, tid);
3790   if (NULL == t)
3791   {
3792     GNUNET_break (0);
3793     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3794     return;
3795   }
3796   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   on tunnel %X\n", t->id.tid);
3797
3798   /* Does client own tunnel? */
3799   if (t->client->handle != client)
3800   {
3801     GNUNET_break (0);
3802     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3803     return;
3804   }
3805
3806   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   for peer %s\n",
3807               GNUNET_i2s (&peer_msg->peer));
3808   /* Is the peer in the tunnel? */
3809   peer_info =
3810       GNUNET_CONTAINER_multihashmap_get (t->peers, &peer_msg->peer.hashPubKey);
3811   if (NULL == peer_info)
3812   {
3813     GNUNET_break (0);
3814     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3815     return;
3816   }
3817
3818   /* Ok, delete peer from tunnel */
3819   GNUNET_CONTAINER_multihashmap_remove_all (t->peers,
3820                                             &peer_msg->peer.hashPubKey);
3821
3822   send_destroy_path (t, peer_info->id);
3823   tunnel_delete_peer (t, peer_info->id);
3824   GNUNET_SERVER_receive_done (client, GNUNET_OK);
3825   return;
3826 }
3827
3828
3829 /**
3830  * Handler for connection requests to new peers by type
3831  *
3832  * @param cls closure
3833  * @param client identification of the client
3834  * @param message the actual message (ConnectPeerByType)
3835  */
3836 static void
3837 handle_local_connect_by_type (void *cls, struct GNUNET_SERVER_Client *client,
3838                               const struct GNUNET_MessageHeader *message)
3839 {
3840   struct GNUNET_MESH_ConnectPeerByType *connect_msg;
3841   struct MeshClient *c;
3842   struct MeshTunnel *t;
3843   GNUNET_HashCode hash;
3844   MESH_TunnelNumber tid;
3845
3846   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: got connect by type request\n");
3847   /* Sanity check for client registration */
3848   if (NULL == (c = client_get (client)))
3849   {
3850     GNUNET_break (0);
3851     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3852     return;
3853   }
3854
3855   connect_msg = (struct GNUNET_MESH_ConnectPeerByType *) message;
3856   /* Sanity check for message size */
3857   if (sizeof (struct GNUNET_MESH_ConnectPeerByType) !=
3858       ntohs (connect_msg->header.size))
3859   {
3860     GNUNET_break (0);
3861     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3862     return;
3863   }
3864
3865   /* Tunnel exists? */
3866   tid = ntohl (connect_msg->tunnel_id);
3867   t = tunnel_get_by_local_id (c, tid);
3868   if (NULL == t)
3869   {
3870     GNUNET_break (0);
3871     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3872     return;
3873   }
3874
3875   /* Does client own tunnel? */
3876   if (t->client->handle != client)
3877   {
3878     GNUNET_break (0);
3879     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3880     return;
3881   }
3882
3883   /* Do WE have the service? */
3884   t->type = ntohl (connect_msg->type);
3885   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:  type requested: %u\n", t->type);
3886   GNUNET_CRYPTO_hash (&t->type, sizeof (GNUNET_MESH_ApplicationType), &hash);
3887   if (GNUNET_CONTAINER_multihashmap_contains (applications, &hash) ==
3888       GNUNET_YES)
3889   {
3890     /* Yes! Fast forward, add ourselves to the tunnel and send the
3891      * good news to the client
3892      */
3893     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:  available locally\n");
3894     GNUNET_CONTAINER_multihashmap_put (t->peers, &my_full_id.hashPubKey,
3895                                        peer_info_get (&my_full_id),
3896                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
3897
3898     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:  notifying client\n");
3899     send_client_peer_connected (t, myid);
3900     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:  Done\n");
3901     GNUNET_SERVER_receive_done (client, GNUNET_OK);
3902     return;
3903   }
3904   /* Ok, lets find a peer offering the service */
3905   if (NULL != t->dht_get_type)
3906   {
3907     GNUNET_DHT_get_stop (t->dht_get_type);
3908   }
3909   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:  looking in DHT for %s\n",
3910               GNUNET_h2s (&hash));
3911   t->dht_get_type =
3912       GNUNET_DHT_get_start (dht_handle, GNUNET_TIME_UNIT_FOREVER_REL,
3913                             GNUNET_BLOCK_TYPE_TEST, &hash, 10U,
3914                             GNUNET_DHT_RO_RECORD_ROUTE |
3915                             GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE, NULL, 0,
3916                             &dht_get_type_handler, t);
3917
3918   GNUNET_SERVER_receive_done (client, GNUNET_OK);
3919   return;
3920 }
3921
3922
3923 /**
3924  * Handler for client traffic directed to one peer
3925  *
3926  * @param cls closure
3927  * @param client identification of the client
3928  * @param message the actual message
3929  */
3930 static void
3931 handle_local_unicast (void *cls, struct GNUNET_SERVER_Client *client,
3932                       const struct GNUNET_MessageHeader *message)
3933 {
3934   struct MeshClient *c;
3935   struct MeshTunnel *t;
3936   struct MeshPeerInfo *pi;
3937   struct GNUNET_MESH_Unicast *data_msg;
3938   MESH_TunnelNumber tid;
3939   size_t size;
3940
3941   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3942               "MESH: Got a unicast request from a client!\n");
3943
3944   /* Sanity check for client registration */
3945   if (NULL == (c = client_get (client)))
3946   {
3947     GNUNET_break (0);
3948     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3949     return;
3950   }
3951   data_msg = (struct GNUNET_MESH_Unicast *) message;
3952   /* Sanity check for message size */
3953   size = ntohs (message->size);
3954   if (sizeof (struct GNUNET_MESH_Unicast) +
3955       sizeof (struct GNUNET_MessageHeader) > size)
3956   {
3957     GNUNET_break (0);
3958     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3959     return;
3960   }
3961
3962   /* Tunnel exists? */
3963   tid = ntohl (data_msg->tid);
3964   t = tunnel_get_by_local_id (c, tid);
3965   if (NULL == t)
3966   {
3967     GNUNET_break (0);
3968     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3969     return;
3970   }
3971
3972   /*  Is it a local tunnel? Then, does client own the tunnel? */
3973   if (NULL != t->client && NULL != t->client->handle &&
3974       t->client->handle != client)
3975   {
3976     GNUNET_break (0);
3977     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3978     return;
3979   }
3980
3981   pi = GNUNET_CONTAINER_multihashmap_get (t->peers,
3982                                           &data_msg->destination.hashPubKey);
3983   /* Is the selected peer in the tunnel? */
3984   if (NULL == pi)
3985   {
3986     GNUNET_break (0);
3987     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3988     return;
3989   }
3990
3991   /* Ok, everything is correct, send the message
3992    * (pretend we got it from a mesh peer)
3993    */
3994   {
3995     char buf[ntohs (message->size)];
3996     struct GNUNET_MESH_Unicast *copy;
3997
3998     /* Work around const limitation */
3999     copy = (struct GNUNET_MESH_Unicast *) buf;
4000     memcpy (buf, data_msg, size);
4001     copy->oid = my_full_id;
4002     copy->tid = htonl (t->id.tid);
4003     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4004                 "MESH:   calling generic handler...\n");
4005     handle_mesh_data_unicast (NULL, &my_full_id, &copy->header, NULL, 0);
4006   }
4007   GNUNET_SERVER_receive_done (client, GNUNET_OK);
4008   return;
4009 }
4010
4011
4012 /**
4013  * Handler for client traffic directed to the origin
4014  *
4015  * @param cls closure
4016  * @param client identification of the client
4017  * @param message the actual message
4018  */
4019 static void
4020 handle_local_to_origin (void *cls, struct GNUNET_SERVER_Client *client,
4021                         const struct GNUNET_MessageHeader *message)
4022 {
4023   struct GNUNET_MESH_ToOrigin *data_msg;
4024   struct GNUNET_PeerIdentity id;
4025   struct MeshClient *c;
4026   struct MeshTunnel *t;
4027   MESH_TunnelNumber tid;
4028   size_t size;
4029
4030   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4031               "MESH: Got a ToOrigin request from a client!\n");
4032
4033   /* Sanity check for client registration */
4034   if (NULL == (c = client_get (client)))
4035   {
4036     GNUNET_break (0);
4037     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4038     return;
4039   }
4040   data_msg = (struct GNUNET_MESH_ToOrigin *) message;
4041   /* Sanity check for message size */
4042   size = ntohs (message->size);
4043   if (sizeof (struct GNUNET_MESH_ToOrigin) +
4044       sizeof (struct GNUNET_MessageHeader) > size)
4045   {
4046     GNUNET_break (0);
4047     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4048     return;
4049   }
4050
4051   /* Tunnel exists? */
4052   tid = ntohl (data_msg->tid);
4053   if (tid < GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
4054   {
4055     GNUNET_break (0);
4056     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4057     return;
4058   }
4059   t = tunnel_get_by_local_id (c, tid);
4060   if (NULL == t)
4061   {
4062     GNUNET_break (0);
4063     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4064     return;
4065   }
4066
4067   /*  It shouldn't be a local tunnel.  */
4068   if (NULL != t->client)
4069   {
4070     GNUNET_break (0);
4071     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4072     return;
4073   }
4074   GNUNET_PEER_resolve (t->id.oid, &id);
4075
4076   /* Ok, everything is correct, send the message
4077    * (pretend we got it from a mesh peer)
4078    */
4079   {
4080     char buf[ntohs (message->size)];
4081     struct GNUNET_MESH_ToOrigin *copy;
4082
4083     /* Work around const limitation */
4084     copy = (struct GNUNET_MESH_ToOrigin *) buf;
4085     memcpy (buf, data_msg, size);
4086     copy->oid = id;
4087     copy->tid = htonl (t->id.tid);
4088     copy->sender = my_full_id;
4089     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4090                 "MESH:   calling generic handler...\n");
4091     handle_mesh_data_to_orig (NULL, &my_full_id, &copy->header, NULL, 0);
4092   }
4093   GNUNET_SERVER_receive_done (client, GNUNET_OK);
4094   return;
4095 }
4096
4097
4098 /**
4099  * Handler for client traffic directed to all peers in a tunnel
4100  *
4101  * @param cls closure
4102  * @param client identification of the client
4103  * @param message the actual message
4104  */
4105 static void
4106 handle_local_multicast (void *cls, struct GNUNET_SERVER_Client *client,
4107                         const struct GNUNET_MessageHeader *message)
4108 {
4109   struct MeshClient *c;
4110   struct MeshTunnel *t;
4111   struct GNUNET_MESH_Multicast *data_msg;
4112   MESH_TunnelNumber tid;
4113
4114   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4115               "MESH: Got a multicast request from a client!\n");
4116
4117   /* Sanity check for client registration */
4118   if (NULL == (c = client_get (client)))
4119   {
4120     GNUNET_break (0);
4121     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4122     return;
4123   }
4124   data_msg = (struct GNUNET_MESH_Multicast *) message;
4125   /* Sanity check for message size */
4126   if (sizeof (struct GNUNET_MESH_Multicast) +
4127       sizeof (struct GNUNET_MessageHeader) > ntohs (data_msg->header.size))
4128   {
4129     GNUNET_break (0);
4130     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4131     return;
4132   }
4133
4134   /* Tunnel exists? */
4135   tid = ntohl (data_msg->tid);
4136   t = tunnel_get_by_local_id (c, tid);
4137   if (NULL == t)
4138   {
4139     GNUNET_break (0);
4140     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4141     return;
4142   }
4143
4144   /* Does client own tunnel? */
4145   if (t->client->handle != client)
4146   {
4147     GNUNET_break (0);
4148     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4149     return;
4150   }
4151
4152   {
4153     char buf[ntohs (message->size)];
4154     struct GNUNET_MESH_Multicast *copy;
4155
4156     copy = (struct GNUNET_MESH_Multicast *) buf;
4157     memcpy (buf, message, ntohs (message->size));
4158     copy->oid = my_full_id;
4159     copy->tid = htonl (t->id.tid);
4160     copy->ttl = htonl (DEFAULT_TTL);
4161     copy->mid = htonl (t->mid + 1);
4162     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4163                 "MESH:   calling generic handler...\n");
4164     handle_mesh_data_multicast (client, &my_full_id, &copy->header, NULL, 0);
4165   }
4166
4167   /* receive done gets called when last copy is sent to a neighbor */
4168   return;
4169 }
4170
4171 /**
4172  * Functions to handle messages from clients
4173  */
4174 static struct GNUNET_SERVER_MessageHandler client_handlers[] = {
4175   {&handle_local_new_client, NULL,
4176    GNUNET_MESSAGE_TYPE_MESH_LOCAL_CONNECT, 0},
4177   {&handle_local_tunnel_create, NULL,
4178    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_CREATE,
4179    sizeof (struct GNUNET_MESH_TunnelMessage)},
4180   {&handle_local_tunnel_destroy, NULL,
4181    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_DESTROY,
4182    sizeof (struct GNUNET_MESH_TunnelMessage)},
4183   {&handle_local_connect_add, NULL,
4184    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD,
4185    sizeof (struct GNUNET_MESH_PeerControl)},
4186   {&handle_local_connect_del, NULL,
4187    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_DEL,
4188    sizeof (struct GNUNET_MESH_PeerControl)},
4189   {&handle_local_connect_by_type, NULL,
4190    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD_BY_TYPE,
4191    sizeof (struct GNUNET_MESH_ConnectPeerByType)},
4192   {&handle_local_unicast, NULL,
4193    GNUNET_MESSAGE_TYPE_MESH_UNICAST, 0},
4194   {&handle_local_to_origin, NULL,
4195    GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN, 0},
4196   {&handle_local_multicast, NULL,
4197    GNUNET_MESSAGE_TYPE_MESH_MULTICAST, 0},
4198   {NULL, NULL, 0, 0}
4199 };
4200
4201
4202 /**
4203  * To be called on core init/fail.
4204  *
4205  * @param cls service closure
4206  * @param server handle to the server for this service
4207  * @param identity the public identity of this peer
4208  */
4209 static void
4210 core_init (void *cls, struct GNUNET_CORE_Handle *server,
4211            const struct GNUNET_PeerIdentity *identity)
4212 {
4213   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: Core init\n");
4214   core_handle = server;
4215   if (0 != memcmp (identity, &my_full_id, sizeof (my_full_id)) ||
4216       NULL == server)
4217   {
4218     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _("MESH: Wrong CORE service\n"));
4219     GNUNET_SCHEDULER_shutdown ();
4220   }
4221   return;
4222 }
4223
4224 /**
4225  * Method called whenever a given peer connects.
4226  *
4227  * @param cls closure
4228  * @param peer peer identity this notification is about
4229  * @param atsi performance data for the connection
4230  * @param atsi_count number of records in 'atsi'
4231  */
4232 static void
4233 core_connect (void *cls, const struct GNUNET_PeerIdentity *peer,
4234               const struct GNUNET_ATS_Information *atsi,
4235               unsigned int atsi_count)
4236 {
4237   struct MeshPeerInfo *peer_info;
4238   struct MeshPeerPath *path;
4239
4240 #if MESH_DEBUG_CONNECTION
4241   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: Peer connected\n");
4242   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:      %s\n",
4243               GNUNET_i2s (&my_full_id));
4244 #endif
4245   peer_info = peer_info_get (peer);
4246   if (myid == peer_info->id)
4247   {
4248 #if MESH_DEBUG_CONNECTION
4249     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:      (self)\n");
4250 #endif
4251     return;
4252   }
4253 #if MESH_DEBUG_CONNECTION
4254   else
4255   {
4256     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:      %s\n", GNUNET_i2s (peer));
4257   }
4258 #endif
4259   path = path_new (2);
4260   path->peers[0] = myid;
4261   path->peers[1] = peer_info->id;
4262   GNUNET_PEER_change_rc (myid, 1);
4263   GNUNET_PEER_change_rc (peer_info->id, 1);
4264   peer_info_add_path (peer_info, path, GNUNET_YES);
4265   return;
4266 }
4267
4268 /**
4269  * Method called whenever a peer disconnects.
4270  *
4271  * @param cls closure
4272  * @param peer peer identity this notification is about
4273  */
4274 static void
4275 core_disconnect (void *cls, const struct GNUNET_PeerIdentity *peer)
4276 {
4277   struct MeshPeerInfo *pi;
4278   unsigned int i;
4279
4280 #if MESH_DEBUG_CONNECTION
4281   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: Peer disconnected\n");
4282 #endif
4283   pi = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
4284   if (NULL == pi)
4285   {
4286     GNUNET_break (0);
4287     return;
4288   }
4289   for (i = 0; i < CORE_QUEUE_SIZE; i++)
4290   {
4291     /* TODO: notify that the transmission failed */
4292     peer_info_cancel_transmission (pi, i);
4293   }
4294   peer_info_remove_path (pi, pi->id, myid);
4295 #if MESH_DEBUG_CONNECTION
4296   if (myid == pi->id)
4297   {
4298     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:      (self)\n");
4299   }
4300 #endif
4301   return;
4302 }
4303
4304
4305 /******************************************************************************/
4306 /************************      MAIN FUNCTIONS      ****************************/
4307 /******************************************************************************/
4308
4309 /**
4310  * Iterator over tunnel hash map entries to destroy the tunnel during shutdown.
4311  *
4312  * @param cls closure
4313  * @param key current key code
4314  * @param value value in the hash map
4315  * @return GNUNET_YES if we should continue to iterate,
4316  *         GNUNET_NO if not.
4317  */
4318 static int
4319 shutdown_tunnel (void *cls, const GNUNET_HashCode * key, void *value)
4320 {
4321   struct MeshTunnel *t = value;
4322
4323   tunnel_destroy (t);
4324   return GNUNET_YES;
4325 }
4326
4327 /**
4328  * Iterator over peer hash map entries to destroy the tunnel during shutdown.
4329  *
4330  * @param cls closure
4331  * @param key current key code
4332  * @param value value in the hash map
4333  * @return GNUNET_YES if we should continue to iterate,
4334  *         GNUNET_NO if not.
4335  */
4336 static int
4337 shutdown_peer (void *cls, const GNUNET_HashCode * key, void *value)
4338 {
4339   struct MeshPeerInfo *p = value;
4340
4341   peer_info_destroy (p);
4342   return GNUNET_YES;
4343 }
4344
4345 /**
4346  * Task run during shutdown.
4347  *
4348  * @param cls unused
4349  * @param tc unused
4350  */
4351 static void
4352 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
4353 {
4354   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: shutting down\n");
4355   /* TODO: destroy tunnels? */
4356   if (core_handle != NULL)
4357   {
4358     GNUNET_CORE_disconnect (core_handle);
4359     core_handle = NULL;
4360   }
4361   GNUNET_CONTAINER_multihashmap_iterate (tunnels, &shutdown_tunnel, NULL);
4362   GNUNET_CONTAINER_multihashmap_iterate (peers, &shutdown_peer, NULL);
4363   if (dht_handle != NULL)
4364   {
4365     GNUNET_DHT_disconnect (dht_handle);
4366     dht_handle = NULL;
4367   }
4368   if (nc != NULL)
4369   {
4370     GNUNET_SERVER_notification_context_destroy (nc);
4371     nc = NULL;
4372   }
4373   if (GNUNET_SCHEDULER_NO_TASK != announce_id_task)
4374   {
4375     GNUNET_SCHEDULER_cancel (announce_id_task);
4376     announce_id_task = GNUNET_SCHEDULER_NO_TASK;
4377   }
4378   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: shut down\n");
4379 }
4380
4381 /**
4382  * Process mesh requests.
4383  *
4384  * @param cls closure
4385  * @param server the initialized server
4386  * @param c configuration to use
4387  */
4388 static void
4389 run (void *cls, struct GNUNET_SERVER_Handle *server,
4390      const struct GNUNET_CONFIGURATION_Handle *c)
4391 {
4392   struct MeshPeerInfo *peer;
4393   struct MeshPeerPath *p;
4394   char *keyfile;
4395
4396   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: starting to run\n");
4397   server_handle = server;
4398   core_handle = GNUNET_CORE_connect (c, /* Main configuration */
4399                                      CORE_QUEUE_SIZE,   /* queue size */
4400                                      NULL,      /* Closure passed to MESH functions */
4401                                      &core_init,        /* Call core_init once connected */
4402                                      &core_connect,     /* Handle connects */
4403                                      &core_disconnect,  /* remove peers on disconnects */
4404                                      NULL,      /* Don't notify about all incoming messages */
4405                                      GNUNET_NO, /* For header only in notification */
4406                                      NULL,      /* Don't notify about all outbound messages */
4407                                      GNUNET_NO, /* For header-only out notification */
4408                                      core_handlers);    /* Register these handlers */
4409
4410   if (core_handle == NULL)
4411   {
4412     GNUNET_break (0);
4413     GNUNET_SCHEDULER_shutdown ();
4414     return;
4415   }
4416
4417   if (GNUNET_OK !=
4418       GNUNET_CONFIGURATION_get_value_filename (c, "GNUNETD", "HOSTKEY",
4419                                                &keyfile))
4420   {
4421     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
4422                 _
4423                 ("Mesh service is lacking key configuration settings.  Exiting.\n"));
4424     GNUNET_SCHEDULER_shutdown ();
4425     return;
4426   }
4427   my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
4428   GNUNET_free (keyfile);
4429   if (my_private_key == NULL)
4430   {
4431     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
4432                 _("Mesh service could not access hostkey.  Exiting.\n"));
4433     GNUNET_SCHEDULER_shutdown ();
4434     return;
4435   }
4436   GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
4437   GNUNET_CRYPTO_hash (&my_public_key, sizeof (my_public_key),
4438                       &my_full_id.hashPubKey);
4439   myid = GNUNET_PEER_intern (&my_full_id);
4440
4441 // //   transport_handle = GNUNET_TRANSPORT_connect(c,
4442 // //                                               &my_full_id,
4443 // //                                               NULL,
4444 // //                                               NULL,
4445 // //                                               NULL,
4446 // //                                               NULL);
4447
4448   dht_handle = GNUNET_DHT_connect (c, 64);
4449   if (dht_handle == NULL)
4450   {
4451     GNUNET_break (0);
4452   }
4453
4454   next_tid = 0;
4455   next_local_tid = GNUNET_MESH_LOCAL_TUNNEL_ID_SERV;
4456
4457   tunnels = GNUNET_CONTAINER_multihashmap_create (32);
4458   incoming_tunnels = GNUNET_CONTAINER_multihashmap_create (32);
4459   peers = GNUNET_CONTAINER_multihashmap_create (32);
4460   applications = GNUNET_CONTAINER_multihashmap_create (32);
4461   types = GNUNET_CONTAINER_multihashmap_create (32);
4462
4463   GNUNET_SERVER_add_handlers (server_handle, client_handlers);
4464   nc = GNUNET_SERVER_notification_context_create (server_handle,
4465                                                   LOCAL_QUEUE_SIZE);
4466   GNUNET_SERVER_disconnect_notify (server_handle,
4467                                    &handle_local_client_disconnect, NULL);
4468
4469
4470   clients = NULL;
4471   clients_tail = NULL;
4472 #if MESH_DEBUG
4473   next_client_id = 0;
4474 #endif
4475
4476   announce_applications_task = GNUNET_SCHEDULER_NO_TASK;
4477   announce_id_task = GNUNET_SCHEDULER_add_now (&announce_id, cls);
4478
4479   /* Create a peer_info for the local peer */
4480   peer = peer_info_get (&my_full_id);
4481   p = path_new (1);
4482   p->peers[0] = myid;
4483   GNUNET_PEER_change_rc (myid, 1);
4484   peer_info_add_path (peer, p, GNUNET_YES);
4485
4486   /* Scheduled the task to clean up when shutdown is called */
4487   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
4488                                 NULL);
4489
4490   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: end of run()\n");
4491 }
4492
4493 /**
4494  * The main function for the mesh service.
4495  *
4496  * @param argc number of arguments from the command line
4497  * @param argv command line arguments
4498  * @return 0 ok, 1 on error
4499  */
4500 int
4501 main (int argc, char *const *argv)
4502 {
4503   int ret;
4504
4505   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: main()\n");
4506   ret =
4507       (GNUNET_OK ==
4508        GNUNET_SERVICE_run (argc, argv, "mesh", GNUNET_SERVICE_OPTION_NONE, &run,
4509                            NULL)) ? 0 : 1;
4510   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: main() END\n");
4511
4512   return ret;
4513 }