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