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