Disable DHT debug of MESH separately
[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 path_remove_from_peer (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 path_add_to_peer (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   for (l = 1; l < path->length; l++)
1548   {
1549     if (path->peers[l] == myid)
1550     {
1551       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1552                   "MESH: shortening path by %u\n",
1553                   l);
1554       for (l2 = 0; l2 < path->length - l - 1 ; l2++)
1555       {
1556         path->peers[l2] = path->peers[l + l2];
1557       }
1558       path->length -= l;
1559       l = 0;
1560       path->peers = GNUNET_realloc (path->peers,
1561                                     path->length * sizeof (GNUNET_PEER_Id));
1562     }
1563   }
1564 #if MESH_DEBUG
1565   { 
1566     struct GNUNET_PeerIdentity id;
1567
1568     GNUNET_PEER_resolve (peer_info->id, &id);
1569     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1570                 "MESH: adding path [%u] to peer %s\n",
1571                 path->length,
1572                 GNUNET_i2s (&id));
1573   }
1574 #endif
1575   l = path_get_length (path);
1576   if (0 == l)
1577   {
1578     GNUNET_free (path);
1579     return;
1580   }
1581
1582   for (aux = peer_info->path_head; aux != NULL; aux = aux->next)
1583   {
1584     l2 = path_get_length (aux);
1585     if (l2 > l)
1586     {
1587       GNUNET_CONTAINER_DLL_insert_before (peer_info->path_head,
1588                                           peer_info->path_tail,
1589                                           aux,
1590                                           path);
1591       return;
1592     }
1593     else
1594     {
1595       if (l2 == l && memcmp(path->peers, aux->peers, l) == 0)
1596       {
1597         path_destroy(path);
1598         return;
1599       }
1600     }
1601   }
1602   GNUNET_CONTAINER_DLL_insert_tail (peer_info->path_head,
1603                                     peer_info->path_tail,
1604                                     path);
1605   return;
1606 }
1607
1608
1609 /**
1610  * Add the path to the origin peer and update the path used to reach it in case
1611  * this is the shortest.
1612  * The path is given in peer_info -> destination, therefore we turn the path
1613  * upside down first.
1614  *
1615  * @param peer_info Peer to add the path to, being the origin of the path.
1616  * @param path New path to add after being inversed.
1617  * @param trusted Do we trust that this path is real?
1618  */
1619 static void
1620 path_add_to_origin (struct MeshPeerInfo *peer_info,
1621                     struct MeshPeerPath *path,
1622                     int trusted)
1623 {
1624   path_invert(path);
1625   path_add_to_peer (peer_info, path, trusted);
1626 }
1627
1628
1629 /**
1630  * Build a PeerPath from the paths returned from the DHT, reversing the paths
1631  * to obtain a local peer -> destination path and interning the peer ids.
1632  *
1633  * @return Newly allocated and created path
1634  */
1635 static struct MeshPeerPath *
1636 path_build_from_dht (const struct GNUNET_PeerIdentity *get_path,
1637                      unsigned int get_path_length,
1638                      const struct GNUNET_PeerIdentity *put_path,
1639                      unsigned int put_path_length)
1640 {
1641   struct MeshPeerPath *p;
1642   GNUNET_PEER_Id id;
1643   int i;
1644
1645   p = path_new (1);
1646   p->peers[0] = myid;
1647   GNUNET_PEER_change_rc(myid, 1);
1648   i = get_path_length;
1649   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "MESH:    GET has %d hops.\n", i);
1650   for (i--; i >= 0; i--)
1651   {
1652     id = GNUNET_PEER_intern (&get_path[i]);
1653     if (p->length > 0 && id == p->peers[p->length - 1])
1654     {
1655       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "MESH:    Optimizing 1 hop out.\n");
1656       GNUNET_PEER_change_rc(id, -1);
1657     }
1658     else
1659     {
1660       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1661                  "MESH:    Adding from GET: %s.\n",
1662                  GNUNET_i2s(&get_path[i]));
1663       p->length++;
1664       p->peers = GNUNET_realloc (p->peers, sizeof (GNUNET_PEER_Id) * p->length);
1665       p->peers[p->length - 1] = id;
1666     }
1667   }
1668   i = put_path_length;
1669   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "MESH:    PUT has %d hops.\n", i);
1670   for (i--; i >= 0; i--)
1671   {
1672     id = GNUNET_PEER_intern (&put_path[i]);
1673     if (id == myid)
1674     {
1675       /* PUT path went through us, so discard the path up until now and start
1676        * from here to get a much shorter (and loop-free) path.
1677        */
1678       path_destroy (p);
1679       p = path_new (0);
1680     }
1681     if (p->length > 0 && id == p->peers[p->length - 1])
1682     {
1683       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "MESH:    Optimizing 1 hop out.\n");
1684       GNUNET_PEER_change_rc(id, -1);
1685     }
1686     else
1687     {
1688       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1689             "MESH:    Adding from PUT: %s.\n",
1690             GNUNET_i2s(&put_path[i]));
1691       p->length++;
1692       p->peers = GNUNET_realloc (p->peers, sizeof (GNUNET_PEER_Id) * p->length);
1693       p->peers[p->length - 1] = id;
1694     }
1695   }
1696 #if MESH_DEBUG
1697   if (get_path_length > 0)
1698     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1699                 "MESH:    (first of GET: %s)\n",
1700                 GNUNET_i2s(&get_path[0]));
1701   if (put_path_length > 0)
1702     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1703                 "MESH:    (first of PUT: %s)\n",
1704                 GNUNET_i2s(&put_path[0]));
1705   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1706               "MESH:    In total: %d hops\n",
1707               p->length);
1708   for (i = 0; i < p->length; i++)
1709   {
1710     struct GNUNET_PeerIdentity peer_id;
1711
1712     GNUNET_PEER_resolve(p->peers[i], &peer_id);
1713     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1714               "MESH:        %u: %s\n",
1715               p->peers[i],
1716               GNUNET_i2s(&peer_id));
1717   }
1718 #endif
1719   return p;
1720 }
1721
1722
1723 /**
1724  * Send keepalive packets for a peer
1725  *
1726  * @param cls Closure (tunnel for which to send the keepalive).
1727  * @param tc Notification context.
1728  *
1729  * TODO: implement explicit multicast keepalive?
1730  */
1731 static void
1732 path_refresh (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
1733
1734
1735 /**
1736  * Search for a tunnel among the incoming tunnels
1737  *
1738  * @param tid the local id of the tunnel
1739  *
1740  * @return tunnel handler, NULL if doesn't exist
1741  */
1742 static struct MeshTunnel *
1743 tunnel_get_incoming (MESH_TunnelNumber tid)
1744 {
1745   GNUNET_HashCode hash;
1746
1747   GNUNET_assert (tid >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV);
1748   GNUNET_CRYPTO_hash (&tid, sizeof (MESH_TunnelNumber), &hash);
1749   return GNUNET_CONTAINER_multihashmap_get (incoming_tunnels, &hash);
1750 }
1751
1752
1753 /**
1754  * Search for a tunnel among the tunnels for a client
1755  *
1756  * @param c the client whose tunnels to search in
1757  * @param tid the local id of the tunnel
1758  *
1759  * @return tunnel handler, NULL if doesn't exist
1760  */
1761 static struct MeshTunnel *
1762 tunnel_get_by_local_id (struct MeshClient *c, MESH_TunnelNumber tid)
1763 {
1764   if (tid >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
1765   {
1766     return tunnel_get_incoming (tid);
1767   }
1768   else
1769   {
1770     GNUNET_HashCode hash;
1771
1772     GNUNET_CRYPTO_hash (&tid, sizeof (MESH_TunnelNumber), &hash);
1773     return GNUNET_CONTAINER_multihashmap_get (c->tunnels, &hash);
1774   }
1775 }
1776
1777
1778 /**
1779  * Search for a tunnel by global ID using PEER_ID
1780  *
1781  * @param pi owner of the tunnel
1782  * @param tid global tunnel number
1783  *
1784  * @return tunnel handler, NULL if doesn't exist
1785  */
1786 static struct MeshTunnel *
1787 tunnel_get_by_pi (GNUNET_PEER_Id pi, MESH_TunnelNumber tid)
1788 {
1789   struct MESH_TunnelID id;
1790   GNUNET_HashCode hash;
1791
1792   id.oid = pi;
1793   id.tid = tid;
1794
1795   GNUNET_CRYPTO_hash (&id, sizeof (struct MESH_TunnelID), &hash);
1796   return GNUNET_CONTAINER_multihashmap_get (tunnels, &hash);
1797 }
1798
1799
1800 /**
1801  * Search for a tunnel by global ID using full PeerIdentities
1802  *
1803  * @param oid owner of the tunnel
1804  * @param tid global tunnel number
1805  *
1806  * @return tunnel handler, NULL if doesn't exist
1807  */
1808 static struct MeshTunnel *
1809 tunnel_get (struct GNUNET_PeerIdentity *oid, MESH_TunnelNumber tid)
1810 {
1811   return tunnel_get_by_pi (GNUNET_PEER_search (oid), tid);
1812 }
1813
1814
1815 /**
1816  * Callback used to notify a client owner of a tunnel that a peer has
1817  * disconnected, most likely because of a path change.
1818  *
1819  * @param cls Closure (tunnel this notification is about).
1820  * @param peer_id Short ID of disconnected peer.
1821  */
1822 void
1823 notify_peer_disconnected (void *cls, GNUNET_PEER_Id peer_id)
1824 {
1825   struct MeshTunnel *t = cls;
1826   struct MeshPeerInfo *peer;
1827   struct MeshPathInfo *path_info;
1828
1829   if (NULL != t->client && NULL != nc)
1830   {
1831     struct GNUNET_MESH_PeerControl msg;
1832     msg.header.size = htons (sizeof (msg));
1833     msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_DEL);
1834     msg.tunnel_id = htonl (t->local_tid);
1835     GNUNET_PEER_resolve (peer_id, &msg.peer);
1836     GNUNET_SERVER_notification_context_unicast (nc, t->client->handle,
1837                                                 &msg.header, GNUNET_NO);
1838   }
1839   peer = peer_info_get_short(peer_id);
1840   path_info = GNUNET_malloc (sizeof (struct MeshPathInfo));
1841   path_info->peer = peer;
1842   path_info->t = t;
1843   GNUNET_SCHEDULER_add_now(&peer_info_connect_task, path_info);
1844 }
1845
1846
1847 /**
1848  * Add a peer to a tunnel, accomodating paths accordingly and initializing all
1849  * needed rescources.
1850  * If peer already exists, reevaluate shortest path and change if different.
1851  *
1852  * @param t Tunnel we want to add a new peer to
1853  * @param peer PeerInfo of the peer being added
1854  *
1855  */
1856 static void
1857 tunnel_add_peer (struct MeshTunnel *t, struct MeshPeerInfo *peer)
1858 {
1859   struct GNUNET_PeerIdentity id;
1860   struct MeshPeerPath *best_p;
1861   struct MeshPeerPath *p;
1862   unsigned int best_cost;
1863   unsigned int cost;
1864
1865   GNUNET_PEER_resolve(peer->id, &id);
1866   if (GNUNET_NO ==
1867       GNUNET_CONTAINER_multihashmap_contains(t->peers, &id.hashPubKey))
1868   {
1869     t->peers_total++;
1870     GNUNET_array_append (peer->tunnels, peer->ntunnels, t);
1871     GNUNET_assert (GNUNET_OK == GNUNET_CONTAINER_multihashmap_put(
1872       t->peers,
1873       &id.hashPubKey,
1874       peer,
1875       GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST));
1876   }
1877
1878   if (NULL != (p = peer->path_head))
1879   {
1880     best_p = p;
1881     best_cost = path_get_cost(t->tree, p);
1882     while (NULL != p)
1883     {
1884       if ((cost = path_get_cost (t->tree, p)) < best_cost)
1885       {
1886         best_cost = cost;
1887         best_p = p;
1888       }
1889       p = p->next;
1890     }
1891     tree_add_path (t->tree, best_p, &notify_peer_disconnected, t);
1892     if (GNUNET_SCHEDULER_NO_TASK == t->path_refresh_task)
1893       t->path_refresh_task =
1894           GNUNET_SCHEDULER_add_delayed (REFRESH_PATH_TIME, &path_refresh, t);
1895   }
1896   else
1897   {
1898     /* Start a DHT get if necessary */
1899     peer_info_connect(peer, t);
1900   }
1901 }
1902
1903 /**
1904  * Add a path to a tunnel which we don't own, just to remember the next hop.
1905  * If destination node was already in the tunnel, the first hop information
1906  * will be replaced with the new path.
1907  *
1908  * @param t Tunnel we want to add a new peer to
1909  * @param p Path to add
1910  * @param own_pos Position of local node in path.
1911  *
1912  */
1913 static void
1914 tunnel_add_path (struct MeshTunnel *t,
1915                  struct MeshPeerPath *p,
1916                  unsigned int own_pos)
1917 {
1918   struct GNUNET_PeerIdentity id;
1919
1920   GNUNET_assert (0 != own_pos);
1921   tree_add_path(t->tree, p, NULL, NULL);
1922   if (tree_get_me (t->tree) == 0)
1923     tree_set_me (t->tree, p->peers[own_pos]);
1924   if (own_pos < p->length - 1)
1925   {
1926     GNUNET_PEER_resolve (p->peers[own_pos + 1], &id);
1927     tree_update_first_hops(t->tree,
1928                            tree_get_me (t->tree),
1929                            &id);
1930   }
1931 }
1932
1933
1934 /**
1935  * Notifies a tunnel that a connection has broken that affects at least
1936  * some of its peers. Sends a notification towards the root of the tree.
1937  * In case the peer is the owner of the tree, notifies the client that owns
1938  * the tunnel and tries to reconnect.
1939  *
1940  * @param t Tunnel affected.
1941  * @param p1 Peer that got disconnected from p2.
1942  * @param p2 Peer that got disconnected from p1.
1943  *
1944  * @return Short ID of the peer disconnected (either p1 or p2).
1945  *         0 if the tunnel remained unaffected.
1946  */
1947 static GNUNET_PEER_Id
1948 tunnel_notify_connection_broken (struct MeshTunnel *t,
1949                                  GNUNET_PEER_Id p1,
1950                                  GNUNET_PEER_Id p2)
1951 {
1952   GNUNET_PEER_Id pid;
1953
1954   pid = tree_notify_connection_broken (t->tree,
1955                                        p1,
1956                                        p2,
1957                                        &notify_peer_disconnected,
1958                                        t);
1959   if (myid != p1 && myid != p2)
1960   {
1961     return pid;
1962   }
1963   if (pid != myid)
1964   {
1965     if (tree_get_predecessor(t->tree) != 0)
1966     {
1967       /* We are the peer still connected, notify owner of the disconnection. */
1968       struct GNUNET_MESH_PathBroken msg;
1969       struct GNUNET_PeerIdentity neighbor;
1970
1971       msg.header.size = htons (sizeof (msg));
1972       msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_BROKEN);
1973       GNUNET_PEER_resolve (t->id.oid, &msg.oid);
1974       msg.tid = htonl (t->id.tid);
1975       msg.peer1 = my_full_id;
1976       GNUNET_PEER_resolve (pid, &msg.peer2);
1977       GNUNET_PEER_resolve (tree_get_predecessor (t->tree), &neighbor);
1978       send_message (&msg.header, &neighbor);
1979     }
1980   }
1981   return pid;
1982 }
1983
1984
1985 struct MeshMulticastData
1986 {
1987   struct MeshTunnel *t;
1988
1989   GNUNET_SCHEDULER_TaskIdentifier *task;
1990
1991   unsigned int *reference_counter;
1992
1993   size_t data_len;
1994
1995   void *data;
1996 };
1997
1998
1999 /**
2000  * Send a multicast packet to a neighbor.
2001  */
2002 static void
2003 tunnel_send_multicast_iterator (void *cls,
2004                                 GNUNET_PEER_Id neighbor_id)
2005 {
2006   struct MeshMulticastData *mdata = cls;
2007   struct MeshDataDescriptor *info;
2008   struct GNUNET_PeerIdentity neighbor;
2009   unsigned int i;
2010
2011   info = GNUNET_malloc (sizeof (struct MeshDataDescriptor));
2012
2013   info->data = mdata->data;
2014   info->size = mdata->data_len;
2015   info->copies = mdata->reference_counter;
2016   (*(mdata->reference_counter))++;
2017
2018   if (NULL != mdata->t->client)
2019   {
2020     info->client = mdata->t->client->handle;
2021     info->timeout_task = mdata->task;
2022   }
2023   info->destination = neighbor_id;
2024   GNUNET_PEER_resolve (neighbor_id, &neighbor);
2025 #if MESH_DEBUG
2026   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2027             "MESH:    sending to %s...\n",
2028             GNUNET_i2s (&neighbor));
2029 #endif
2030   info->peer = peer_info_get(&neighbor);
2031   GNUNET_assert (NULL != info->peer);
2032   i = peer_info_transmit_slot(info->peer);
2033   info->handler_n = i;
2034   info->peer->infos[i] = info;
2035   info->peer->types[i] = GNUNET_MESSAGE_TYPE_MESH_MULTICAST;
2036   info->peer->core_transmit[i] =
2037       GNUNET_CORE_notify_transmit_ready (core_handle,
2038                                           0,
2039                                           0,
2040                                           GNUNET_TIME_UNIT_FOREVER_REL,
2041                                           &neighbor,
2042                                           info->size,
2043                                           &send_core_data_multicast, info);
2044 }
2045
2046 /**
2047  * Send a message in a tunnel in multicast, sending a copy to each child node
2048  * down the local one in the tunnel tree.
2049  *
2050  * @param t Tunnel in which to send the data.
2051  * @param msg Message to be sent
2052  */
2053 static void
2054 tunnel_send_multicast (struct MeshTunnel *t,
2055                        const struct GNUNET_MessageHeader *msg)
2056 {
2057   struct MeshMulticastData *mdata;
2058
2059 #if MESH_DEBUG
2060   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2061               "MESH:  sending a multicast packet...\n");
2062 #endif
2063   GNUNET_assert (tree_get_me (t->tree) != 0);
2064   mdata = GNUNET_malloc (sizeof (struct MeshMulticastData));
2065   mdata->data_len = ntohs (msg->size);
2066   mdata->reference_counter = GNUNET_malloc (sizeof (unsigned int));
2067   mdata->data = GNUNET_malloc (mdata->data_len);
2068   mdata->t = t;
2069   memcpy (mdata->data, msg, mdata->data_len);
2070   if (NULL != t->client)
2071   {
2072     mdata->task = GNUNET_malloc (sizeof (GNUNET_SCHEDULER_TaskIdentifier));
2073     *(mdata->task) = GNUNET_SCHEDULER_add_delayed (UNACKNOWLEDGED_WAIT,
2074                                                    &client_allow_send,
2075                                                    t->client->handle);
2076   }
2077
2078   tree_iterate_children (t->tree, &tunnel_send_multicast_iterator, mdata);
2079   if (*(mdata->reference_counter) == 0)
2080   {
2081     GNUNET_free (mdata->data);
2082     GNUNET_free (mdata->reference_counter);
2083     if (NULL != mdata->task)
2084     {
2085       GNUNET_free (mdata->task);
2086     }
2087   }
2088   GNUNET_free (mdata);
2089 #if MESH_DEBUG
2090   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2091               "MESH:  sending a multicast packet done\n");
2092 #endif
2093   return;
2094 }
2095
2096
2097 /**
2098  * Send a message to all peers in this tunnel that the tunnel is no longer
2099  * valid.
2100  *
2101  * @param t The tunnel whose peers to notify.
2102  */
2103 static void
2104 tunnel_send_destroy (struct MeshTunnel *t)
2105 {
2106   struct GNUNET_MESH_TunnelDestroy msg;
2107
2108   msg.header.size = htons (sizeof (msg));
2109   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_TUNNEL_DESTROY);
2110   GNUNET_PEER_resolve (t->id.oid, &msg.oid);
2111   msg.tid = htonl (t->id.tid);
2112   tunnel_send_multicast (t, &msg.header);
2113 }
2114
2115
2116
2117 /**
2118  * Destroy the tunnel and free any allocated resources linked to it
2119  *
2120  * @param t the tunnel to destroy
2121  *
2122  * @return GNUNET_OK on success
2123  */
2124 static int
2125 tunnel_destroy (struct MeshTunnel *t)
2126 {
2127   struct MeshClient *c;
2128   struct MeshQueue *q;
2129   struct MeshQueue *qn;
2130   GNUNET_HashCode hash;
2131   int r;
2132
2133   if (NULL == t)
2134     return GNUNET_OK;
2135
2136   c = t->client;
2137 #if MESH_DEBUG
2138   {
2139     struct GNUNET_PeerIdentity id;
2140
2141     GNUNET_PEER_resolve(t->id.oid, &id);
2142     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2143                 "MESH: destroying tunnel %s [%x]\n",
2144                 GNUNET_i2s (&id),
2145                 t->id.tid);
2146     if (NULL != c)
2147       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   by client %u\n", c->id);
2148   }
2149 #endif
2150
2151   GNUNET_CRYPTO_hash (&t->id, sizeof (struct MESH_TunnelID), &hash);
2152   if (GNUNET_YES != GNUNET_CONTAINER_multihashmap_remove (tunnels, &hash, t))
2153   {
2154     r = GNUNET_SYSERR;
2155   }
2156
2157   GNUNET_CRYPTO_hash (&t->local_tid, sizeof (MESH_TunnelNumber), &hash);
2158   if (NULL != c &&
2159       GNUNET_YES != GNUNET_CONTAINER_multihashmap_remove (c->tunnels, &hash, t))
2160   {
2161     r = GNUNET_SYSERR;
2162   }
2163   if (t->local_tid >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
2164   {
2165     GNUNET_CRYPTO_hash (&t->local_tid, sizeof (MESH_TunnelNumber), &hash);
2166     GNUNET_break (GNUNET_YES ==
2167       GNUNET_CONTAINER_multihashmap_remove (incoming_tunnels, &hash, t));
2168   }
2169   if (NULL != t->peers)
2170   {
2171     GNUNET_CONTAINER_multihashmap_iterate(t->peers,
2172                                           &peer_info_delete_tunnel, t);
2173     GNUNET_CONTAINER_multihashmap_destroy (t->peers);
2174   }
2175   q = t->queue_head;
2176   while (NULL != q)
2177   {
2178     if (NULL != q->data)
2179       GNUNET_free (q->data);
2180     qn = q->next;
2181     GNUNET_free (q);
2182     q = qn;
2183     /* TODO cancel core transmit ready in case it was active */
2184   }
2185   tree_destroy(t->tree);
2186   if (NULL != t->dht_get_type)
2187     GNUNET_DHT_get_stop(t->dht_get_type);
2188   if (GNUNET_SCHEDULER_NO_TASK != t->timeout_task)
2189     GNUNET_SCHEDULER_cancel(t->timeout_task);
2190   if (GNUNET_SCHEDULER_NO_TASK != t->path_refresh_task)
2191     GNUNET_SCHEDULER_cancel(t->path_refresh_task);
2192   GNUNET_free (t);
2193   return r;
2194 }
2195
2196
2197 /**
2198  * Removes an explicit path from a tunnel, freeing all intermediate nodes
2199  * that are no longer needed, as well as nodes of no longer reachable peers.
2200  * The tunnel itself is also destoyed if results in a remote empty tunnel.
2201  *
2202  * @param t Tunnel from which to remove the path.
2203  * @param p Peer which should be removed.
2204  */
2205 static void
2206 tunnel_delete_peer (struct MeshTunnel *t,
2207                     GNUNET_PEER_Id peer)
2208 {
2209   if (GNUNET_NO == tree_del_peer (t->tree, peer, NULL, NULL))
2210     tunnel_destroy (t);
2211 }
2212
2213
2214 /**
2215  * tunnel_destroy_iterator: iterator for deleting each tunnel that belongs to a
2216  * client when the client disconnects.
2217  * 
2218  * @param cls closure (client that is disconnecting)
2219  * @param key the hash of the local tunnel id (used to access the hashmap)
2220  * @param value the value stored at the key (tunnel to destroy)
2221  * 
2222  * @return GNUNET_OK on success
2223  */
2224 static int
2225 tunnel_destroy_iterator (void *cls, const GNUNET_HashCode * key, void *value)
2226 {
2227   struct MeshTunnel *t = value;
2228   int r;
2229
2230   r = tunnel_destroy (t);
2231   return r;
2232 }
2233
2234
2235 /**
2236  * Timeout function, destroys tunnel if called
2237  *
2238  * @param cls Closure (tunnel to destroy).
2239  * @param tc TaskContext
2240  */
2241 static void
2242 tunnel_timeout (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2243 {
2244   struct MeshTunnel *t = cls;
2245
2246   if (GNUNET_SCHEDULER_REASON_SHUTDOWN == tc->reason)
2247     return;
2248   t->timeout_task = GNUNET_SCHEDULER_NO_TASK;
2249   tunnel_destroy (t);
2250 }
2251
2252 /**
2253  * Resets the tunnel timeout. Starts it if no timeout was running.
2254  *
2255  * @param t Tunnel whose timeout to reset.
2256  */
2257 static void
2258 tunnel_reset_timeout (struct MeshTunnel *t)
2259 {
2260   if (GNUNET_SCHEDULER_NO_TASK != t->timeout_task)
2261     GNUNET_SCHEDULER_cancel (t->timeout_task);
2262   t->timeout_task = GNUNET_SCHEDULER_add_delayed (
2263       GNUNET_TIME_relative_multiply(REFRESH_PATH_TIME, 4),
2264       &tunnel_timeout,
2265       t);
2266 }
2267
2268
2269 /******************************************************************************/
2270 /****************      MESH NETWORK HANDLER HELPERS     ***********************/
2271 /******************************************************************************/
2272
2273 /**
2274  * Function called to notify a client about the socket
2275  * being ready to queue more data.  "buf" will be
2276  * NULL and "size" zero if the socket was closed for
2277  * writing in the meantime.
2278  *
2279  * @param cls closure
2280  * @param size number of bytes available in buf
2281  * @param buf where the callee should write the message
2282  * @return number of bytes written to buf
2283  */
2284 static size_t
2285 send_core_create_path (void *cls, size_t size, void *buf)
2286 {
2287   struct MeshPathInfo *info = cls;
2288   struct GNUNET_MESH_ManipulatePath *msg;
2289   struct GNUNET_PeerIdentity *peer_ptr;
2290   struct MeshPeerInfo *peer = info->peer;
2291   struct MeshTunnel *t = info->t;
2292   struct MeshPeerPath *p = info->path;
2293   size_t size_needed;
2294   int i;
2295
2296   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2297               "MESH: CREATE PATH sending...\n");
2298   size_needed =
2299       sizeof (struct GNUNET_MESH_ManipulatePath) +
2300       p->length * sizeof (struct GNUNET_PeerIdentity);
2301
2302   if (size < size_needed || NULL == buf)
2303   {
2304     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: create path retransmit!\n");
2305     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   buf:  %p\n", buf);
2306     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   size: (%u/%u)\n",
2307                 size, size_needed);
2308     info->peer->core_transmit[info->pos] = 
2309       GNUNET_CORE_notify_transmit_ready (core_handle, 0, 0,
2310                                         GNUNET_TIME_UNIT_FOREVER_REL,
2311                                         path_get_first_hop (t->tree, peer->id),
2312                                         size_needed,
2313                                         &send_core_create_path,
2314                                         info);
2315     return 0;
2316   }
2317   info->peer->core_transmit[info->pos] = NULL;
2318 #if MESH_DEBUG
2319   {
2320     struct GNUNET_PeerIdentity id;
2321
2322     GNUNET_PEER_resolve (peer->id, &id);
2323     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2324                 "MESH:   setting core_transmit %s [%u] to NULL\n",
2325                 GNUNET_i2s (&id),
2326                 info->pos);
2327   }
2328 #endif
2329   msg = (struct GNUNET_MESH_ManipulatePath *) buf;
2330   msg->header.size = htons (size_needed);
2331   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE);
2332   msg->tid = ntohl (t->id.tid);
2333
2334   peer_ptr = (struct GNUNET_PeerIdentity *) &msg[1];
2335   for (i = 0; i < p->length; i++)
2336   {
2337     GNUNET_PEER_resolve (p->peers[i], peer_ptr++);
2338   }
2339
2340   path_destroy (p);
2341   GNUNET_free (info);
2342
2343   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2344               "MESH: CREATE PATH (%u bytes long) sent!\n",
2345               size_needed);
2346   return size_needed;
2347 }
2348
2349
2350 /**
2351  * Function called to notify a client about the socket
2352  * being ready to queue more data.  "buf" will be
2353  * NULL and "size" zero if the socket was closed for
2354  * writing in the meantime.
2355  *
2356  * @param cls closure (data itself)
2357  * @param size number of bytes available in buf
2358  * @param buf where the callee should write the message
2359  * 
2360  * @return number of bytes written to buf
2361  */
2362 static size_t
2363 send_core_data_multicast (void *cls, size_t size, void *buf)
2364 {
2365   struct MeshDataDescriptor *info = cls;
2366   size_t total_size;
2367
2368   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: Multicast callback.\n");
2369   GNUNET_assert (NULL != info);
2370   GNUNET_assert (NULL != info->peer);
2371   total_size = info->size;
2372   GNUNET_assert (total_size < GNUNET_SERVER_MAX_MESSAGE_SIZE);
2373
2374   if (total_size > size)
2375   {
2376     /* Retry */
2377     struct GNUNET_PeerIdentity id;
2378
2379     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2380                 "MESH: Multicast: retransmitting... (%u/%u)\n",
2381                 size, total_size);
2382     GNUNET_PEER_resolve(info->peer->id, &id);
2383     info->peer->core_transmit[info->handler_n] =
2384       GNUNET_CORE_notify_transmit_ready (core_handle,
2385                                          0,
2386                                          0,
2387                                          GNUNET_TIME_UNIT_FOREVER_REL,
2388                                          &id,
2389                                          total_size,
2390                                          &send_core_data_multicast,
2391                                          info);
2392     return 0;
2393   }
2394   info->peer->core_transmit[info->handler_n] = NULL;
2395   info->peer->infos[info->handler_n] = NULL;
2396   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:  copying data...\n");
2397   memcpy (buf, info->data, total_size);
2398 #if MESH_DEBUG
2399   {
2400     struct GNUNET_MESH_Multicast *mc;
2401     struct GNUNET_MessageHeader *mh;
2402
2403     mh = buf;
2404     if (ntohs (mh->type) == GNUNET_MESSAGE_TYPE_MESH_MULTICAST)
2405     {
2406       mc = (struct GNUNET_MESH_Multicast *) mh;
2407       mh = (struct GNUNET_MessageHeader *) &mc[1];
2408       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2409                   "MESH:  multicast, payload type %u\n",
2410                   ntohs (mh->type));
2411       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2412                   "MESH:  multicast, payload size %u\n",
2413                   ntohs (mh->size));
2414     }
2415     else
2416     {
2417       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2418                   "MESH:  type %u\n",
2419                   ntohs (mh->type));
2420     }
2421   }
2422 #endif
2423   data_descriptor_decrement_multicast (info);
2424   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: freeing info...\n");
2425   GNUNET_free (info);
2426   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: return %u\n", total_size);
2427   return total_size;
2428 }
2429
2430
2431 /**
2432  * Function called to notify a client about the socket
2433  * being ready to queue more data.  "buf" will be
2434  * NULL and "size" zero if the socket was closed for
2435  * writing in the meantime.
2436  *
2437  * @param cls closure (MeshDataDescriptor)
2438  * @param size number of bytes available in buf
2439  * @param buf where the callee should write the message
2440  * @return number of bytes written to buf
2441  */
2442 static size_t
2443 send_core_path_ack (void *cls, size_t size, void *buf)
2444 {
2445   struct MeshDataDescriptor *info = cls;
2446   struct GNUNET_MESH_PathACK *msg = buf;
2447
2448   GNUNET_assert (NULL != info);
2449   if (info->peer)
2450   {
2451     info->peer->core_transmit[info->handler_n] = NULL;
2452   }
2453   if (sizeof (struct GNUNET_MESH_PathACK) > size)
2454   {
2455     GNUNET_break (0);
2456     return 0;
2457   }
2458   msg->header.size = htons (sizeof (struct GNUNET_MESH_PathACK));
2459   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_ACK);
2460   GNUNET_PEER_resolve (info->origin->oid, &msg->oid);
2461   msg->tid = htonl (info->origin->tid);
2462   msg->peer_id = my_full_id;
2463   GNUNET_free (info);
2464   /* TODO add signature */
2465
2466   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: PATH ACK sent!\n");
2467   return sizeof (struct GNUNET_MESH_PathACK);
2468 }
2469
2470
2471 /******************************************************************************/
2472 /********************      MESH NETWORK HANDLERS     **************************/
2473 /******************************************************************************/
2474
2475
2476 /**
2477  * Core handler for path creation
2478  *
2479  * @param cls closure
2480  * @param message message
2481  * @param peer peer identity this notification is about
2482  * @param atsi performance data
2483  * @param atsi_count number of records in 'atsi'
2484  * 
2485  * @return GNUNET_OK to keep the connection open,
2486  *         GNUNET_SYSERR to close it (signal serious error)
2487  */
2488 static int
2489 handle_mesh_path_create (void *cls, const struct GNUNET_PeerIdentity *peer,
2490                          const struct GNUNET_MessageHeader *message,
2491                          const struct GNUNET_ATS_Information *atsi,
2492                          unsigned int atsi_count)
2493 {
2494   unsigned int own_pos;
2495   uint16_t size;
2496   uint16_t i;
2497   MESH_TunnelNumber tid;
2498   struct GNUNET_MESH_ManipulatePath *msg;
2499   struct GNUNET_PeerIdentity *pi;
2500   GNUNET_HashCode hash;
2501   struct MeshPeerPath *path;
2502   struct MeshPeerInfo *dest_peer_info;
2503   struct MeshPeerInfo *orig_peer_info;
2504   struct MeshTunnel *t;
2505
2506   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2507               "MESH: Received a path create msg [%s]\n",
2508               GNUNET_i2s(&my_full_id));
2509   size = ntohs (message->size);
2510   if (size < sizeof (struct GNUNET_MESH_ManipulatePath))
2511   {
2512     GNUNET_break_op (0);
2513     return GNUNET_OK;
2514   }
2515
2516   size -= sizeof (struct GNUNET_MESH_ManipulatePath);
2517   if (size % sizeof (struct GNUNET_PeerIdentity))
2518   {
2519     GNUNET_break_op (0);
2520     return GNUNET_OK;
2521   }
2522   size /= sizeof (struct GNUNET_PeerIdentity);
2523   if (size < 2)
2524   {
2525     GNUNET_break_op (0);
2526     return GNUNET_OK;
2527   }
2528   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2529               "MESH:     path has %u hops.\n",
2530               size);
2531   msg = (struct GNUNET_MESH_ManipulatePath *) message;
2532
2533   tid = ntohl (msg->tid);
2534   pi = (struct GNUNET_PeerIdentity *) &msg[1];
2535   t = tunnel_get (pi, tid);
2536   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2537               "MESH:     path is for tunnel %s [%X].\n",
2538               GNUNET_i2s(pi),
2539               tid);
2540   if (NULL == t)
2541   {
2542     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   Creating tunnel\n");
2543     t = GNUNET_malloc (sizeof (struct MeshTunnel));
2544     t->id.oid = GNUNET_PEER_intern (pi);
2545     t->id.tid = tid;
2546     while (NULL != tunnel_get_incoming (next_local_tid))
2547       next_local_tid = (next_local_tid + 1) | GNUNET_MESH_LOCAL_TUNNEL_ID_SERV;
2548     t->local_tid = next_local_tid++;
2549     next_local_tid = next_local_tid | GNUNET_MESH_LOCAL_TUNNEL_ID_SERV;
2550     t->tree = tree_new(t->id.oid);
2551
2552     GNUNET_CRYPTO_hash (&t->id, sizeof (struct MESH_TunnelID), &hash);
2553     if (GNUNET_OK !=
2554         GNUNET_CONTAINER_multihashmap_put (
2555             tunnels,
2556             &hash,
2557             t,
2558             GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
2559     {
2560       tunnel_destroy (t);
2561       GNUNET_break (0);
2562       return GNUNET_OK;
2563     }
2564     tunnel_reset_timeout (t);
2565     GNUNET_CRYPTO_hash (&t->local_tid, sizeof (MESH_TunnelNumber), &hash);
2566     if (GNUNET_OK !=
2567         GNUNET_CONTAINER_multihashmap_put (
2568             incoming_tunnels,
2569             &hash,
2570             t,
2571             GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
2572     {
2573       tunnel_destroy (t);
2574       GNUNET_break (0);
2575       return GNUNET_OK;
2576     }
2577   }
2578   dest_peer_info =
2579       GNUNET_CONTAINER_multihashmap_get (peers, &pi[size - 1].hashPubKey);
2580   if (NULL == dest_peer_info)
2581   {
2582     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2583                 "MESH:   Creating PeerInfo for destination.\n");
2584     dest_peer_info = GNUNET_malloc (sizeof (struct MeshPeerInfo));
2585     dest_peer_info->id = GNUNET_PEER_intern (&pi[size - 1]);
2586     GNUNET_CONTAINER_multihashmap_put (peers, &pi[size - 1].hashPubKey,
2587                                        dest_peer_info,
2588                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
2589   }
2590   orig_peer_info = GNUNET_CONTAINER_multihashmap_get (peers, &pi->hashPubKey);
2591   if (NULL == orig_peer_info)
2592   {
2593     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2594                 "MESH:   Creating PeerInfo for origin.\n");
2595     orig_peer_info = GNUNET_malloc (sizeof (struct MeshPeerInfo));
2596     orig_peer_info->id = GNUNET_PEER_intern (pi);
2597     GNUNET_CONTAINER_multihashmap_put (peers, &pi->hashPubKey, orig_peer_info,
2598                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
2599   }
2600   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   Creating path...\n");
2601   path = path_new (size);
2602   own_pos = 0;
2603   for (i = 0; i < size; i++)
2604   {
2605     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2606                 "MESH:   ... adding %s\n",
2607                 GNUNET_i2s(&pi[i]));
2608     path->peers[i] = GNUNET_PEER_intern (&pi[i]);
2609     if (path->peers[i] == myid)
2610       own_pos = i;
2611   }
2612   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2613               "MESH:   Own position: %u\n", own_pos);
2614   if (own_pos == 0)
2615   {
2616     /* cannot be self, must be 'not found' */
2617     /* create path: self not found in path through self */
2618     GNUNET_break_op (0);
2619     path_destroy (path);
2620     /* FIXME error. destroy tunnel? leave for timeout? */
2621     return 0;
2622   }
2623   tunnel_add_path (t, path, own_pos);
2624   if (own_pos == size - 1)
2625   {
2626     /* It is for us! Send ack. */
2627     struct GNUNET_MESH_TunnelNotification cmsg;
2628     struct MeshDataDescriptor *info;
2629     unsigned int j;
2630
2631     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2632                 "MESH:   It's for us!\n");
2633     path_add_to_origin (orig_peer_info, path, GNUNET_NO);
2634     if (NULL == t->peers)
2635       t->peers = GNUNET_CONTAINER_multihashmap_create(4);
2636     GNUNET_break (GNUNET_OK == GNUNET_CONTAINER_multihashmap_put (
2637         t->peers,
2638         &my_full_id.hashPubKey,
2639         peer_info_get(&my_full_id),
2640         GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST));
2641     /* FIXME use send_message */
2642     info = GNUNET_malloc (sizeof (struct MeshDataDescriptor));
2643     info->origin = &t->id;
2644     info->peer = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
2645     GNUNET_assert (NULL != info->peer);
2646     j = peer_info_transmit_slot(info->peer);
2647     info->handler_n = j;
2648     info->peer->types[j] = GNUNET_MESSAGE_TYPE_MESH_PATH_ACK;
2649     info->peer->infos[j] = info;
2650     info->peer->core_transmit[j] =
2651         GNUNET_CORE_notify_transmit_ready (core_handle, 0, 100,
2652                                            GNUNET_TIME_UNIT_FOREVER_REL, peer,
2653                                            sizeof (struct GNUNET_MESH_PathACK),
2654                                            &send_core_path_ack, info);
2655     cmsg.header.size = htons(sizeof(cmsg));
2656     cmsg.header.type = htons(GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_CREATE);
2657     GNUNET_PEER_resolve(t->id.oid, &cmsg.peer);
2658     cmsg.tunnel_id = htonl(t->local_tid);
2659     GNUNET_SERVER_notification_context_broadcast(nc, &cmsg.header, GNUNET_NO);
2660   }
2661   else
2662   {
2663     struct MeshPeerPath *path2;
2664
2665     /* It's for somebody else! Retransmit. */
2666     path2 = path_duplicate(path);
2667     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2668                 "MESH:   Retransmitting.\n");
2669     path_add_to_peer(dest_peer_info, path2, GNUNET_NO);
2670     path2 = path_duplicate(path);
2671     path_add_to_origin(orig_peer_info, path2, GNUNET_NO);
2672     send_create_path(dest_peer_info, path, t);
2673   }
2674   return GNUNET_OK;
2675 }
2676
2677
2678 /**
2679  * Core handler for path destruction
2680  *
2681  * @param cls closure
2682  * @param message message
2683  * @param peer peer identity this notification is about
2684  * @param atsi performance data
2685  * @param atsi_count number of records in 'atsi'
2686  *
2687  * @return GNUNET_OK to keep the connection open,
2688  *         GNUNET_SYSERR to close it (signal serious error)
2689  */
2690 static int
2691 handle_mesh_path_destroy (void *cls, const struct GNUNET_PeerIdentity *peer,
2692                           const struct GNUNET_MessageHeader *message,
2693                           const struct GNUNET_ATS_Information *atsi,
2694                           unsigned int atsi_count)
2695 {
2696   struct GNUNET_MESH_ManipulatePath *msg;
2697   struct GNUNET_PeerIdentity *pi;
2698   struct MeshPeerPath *path;
2699   struct MeshTunnel *t;
2700   unsigned int own_pos;
2701   unsigned int i;
2702   size_t size;
2703
2704   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2705               "MESH: Received a PATH DESTROY msg from %s\n",
2706               GNUNET_i2s(peer));
2707   size = ntohs (message->size);
2708   if (size < sizeof (struct GNUNET_MESH_ManipulatePath))
2709   {
2710     GNUNET_break_op (0);
2711     return GNUNET_OK;
2712   }
2713
2714   size -= sizeof (struct GNUNET_MESH_ManipulatePath);
2715   if (size % sizeof (struct GNUNET_PeerIdentity))
2716   {
2717     GNUNET_break_op (0);
2718     return GNUNET_OK;
2719   }
2720   size /= sizeof (struct GNUNET_PeerIdentity);
2721   if (size < 2)
2722   {
2723     GNUNET_break_op (0);
2724     return GNUNET_OK;
2725   }
2726   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2727               "MESH:     path has %u hops.\n",
2728               size);
2729
2730   msg = (struct GNUNET_MESH_ManipulatePath *) message;
2731   pi = (struct GNUNET_PeerIdentity *) &msg[1];
2732   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2733               "MESH:     path is for tunnel %s [%X].\n",
2734               GNUNET_i2s(pi),
2735               msg->tid);
2736   t = tunnel_get (pi, ntohl (msg->tid));
2737   if (NULL == t)
2738   {
2739     /* TODO notify back: we don't know this tunnel */
2740     GNUNET_break_op (0);
2741     return GNUNET_OK;
2742   }
2743   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   Creating path...\n");
2744   path = path_new (size);
2745   own_pos = 0;
2746   for (i = 0; i < size; i++)
2747   {
2748     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2749                 "MESH:   ... adding %s\n",
2750                 GNUNET_i2s(&pi[i]));
2751     path->peers[i] = GNUNET_PEER_intern (&pi[i]);
2752     if (path->peers[i] == myid)
2753       own_pos = i;
2754   }
2755   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2756                 "MESH:   Own position: %u\n", own_pos);
2757   if (own_pos < path->length - 1)
2758     send_message (message, &pi[own_pos + 1]);
2759   tunnel_delete_peer (t, path->peers[path->length - 1]);
2760   path_destroy (path);
2761   return GNUNET_OK;
2762 }
2763
2764
2765 /**
2766  * Core handler for notifications of broken paths
2767  *
2768  * @param cls closure
2769  * @param message message
2770  * @param peer peer identity this notification is about
2771  * @param atsi performance data
2772  * @param atsi_count number of records in 'atsi'
2773  *
2774  * @return GNUNET_OK to keep the connection open,
2775  *         GNUNET_SYSERR to close it (signal serious error)
2776  */
2777 static int
2778 handle_mesh_path_broken (void *cls, const struct GNUNET_PeerIdentity *peer,
2779                           const struct GNUNET_MessageHeader *message,
2780                           const struct GNUNET_ATS_Information *atsi,
2781                           unsigned int atsi_count)
2782 {
2783   struct GNUNET_MESH_PathBroken *msg;
2784   struct MeshTunnel *t;
2785
2786   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2787               "MESH: Received a PATH BROKEN msg from %s\n",
2788               GNUNET_i2s(peer));
2789   msg = (struct GNUNET_MESH_PathBroken *) message;
2790   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2791               "MESH:   regarding %s\n",
2792               GNUNET_i2s(&msg->peer1));
2793   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2794               "MESH:   regarding %s\n",
2795               GNUNET_i2s(&msg->peer2));
2796   t = tunnel_get(&msg->oid, ntohl (msg->tid));
2797   if (NULL == t)
2798   {
2799     GNUNET_break_op (0);
2800     return GNUNET_OK;
2801   }
2802   tunnel_notify_connection_broken(t,
2803                                   GNUNET_PEER_search(&msg->peer1),
2804                                   GNUNET_PEER_search(&msg->peer2));
2805   return GNUNET_OK;
2806
2807 }
2808
2809
2810 /**
2811  * Core handler for tunnel destruction
2812  *
2813  * @param cls closure
2814  * @param message message
2815  * @param peer peer identity this notification is about
2816  * @param atsi performance data
2817  * @param atsi_count number of records in 'atsi'
2818  *
2819  * @return GNUNET_OK to keep the connection open,
2820  *         GNUNET_SYSERR to close it (signal serious error)
2821  */
2822 static int
2823 handle_mesh_tunnel_destroy (void *cls, const struct GNUNET_PeerIdentity *peer,
2824                             const struct GNUNET_MessageHeader *message,
2825                             const struct GNUNET_ATS_Information *atsi,
2826                             unsigned int atsi_count)
2827 {
2828   struct GNUNET_MESH_TunnelDestroy *msg;
2829   struct MeshTunnel *t;
2830
2831   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2832               "MESH: Got a TUNNEL DESTROY packet from %s\n",
2833               GNUNET_i2s (peer));
2834   msg = (struct GNUNET_MESH_TunnelDestroy *) message;
2835   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2836               "MESH:   for tunnel %s [%u]\n",
2837               GNUNET_i2s (&msg->oid),
2838               ntohl (msg->tid));
2839   t = tunnel_get (&msg->oid, ntohl (msg->tid));
2840   if (NULL == t)
2841   {
2842     /* Probably already got the message from another path,
2843      * destroyed the tunnel and retransmitted to children.
2844      * Safe to ignore.
2845      */
2846     return GNUNET_OK;
2847   }
2848   if (t->id.oid == myid)
2849   {
2850     GNUNET_break_op (0);
2851     return GNUNET_OK;
2852   }
2853   if (t->local_tid >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
2854   {
2855     /* Tunnel was incoming, notify clients */
2856     send_clients_tunnel_destroy (t);
2857   }
2858   tunnel_send_destroy (t);
2859   tunnel_destroy (t);
2860   return GNUNET_OK;
2861 }
2862
2863
2864 /**
2865  * Core handler for mesh network traffic going from the origin to a peer
2866  *
2867  * @param cls closure
2868  * @param peer peer identity this notification is about
2869  * @param message message
2870  * @param atsi performance data
2871  * @param atsi_count number of records in 'atsi'
2872  * @return GNUNET_OK to keep the connection open,
2873  *         GNUNET_SYSERR to close it (signal serious error)
2874  */
2875 static int
2876 handle_mesh_data_unicast (void *cls, const struct GNUNET_PeerIdentity *peer,
2877                           const struct GNUNET_MessageHeader *message,
2878                           const struct GNUNET_ATS_Information *atsi,
2879                           unsigned int atsi_count)
2880 {
2881   struct GNUNET_MESH_Unicast *msg;
2882   struct MeshTunnel *t;
2883   GNUNET_PEER_Id pid;
2884   size_t size;
2885
2886   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2887               "MESH: got a unicast packet from %s\n",
2888               GNUNET_i2s (peer));
2889   size = ntohs (message->size);
2890   if (size <
2891       sizeof (struct GNUNET_MESH_Unicast) +
2892       sizeof (struct GNUNET_MessageHeader))
2893   {
2894     GNUNET_break (0);
2895     return GNUNET_OK;
2896   }
2897   msg = (struct GNUNET_MESH_Unicast *) message;
2898   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2899               "MESH:  of type %u\n",
2900               ntohs (msg[1].header.type));
2901   t = tunnel_get (&msg->oid, ntohl (msg->tid));
2902   if (NULL == t)
2903   {
2904     /* TODO notify back: we don't know this tunnel */
2905     GNUNET_break_op (0);
2906     return GNUNET_OK;
2907   }
2908   tunnel_reset_timeout (t);
2909   pid = GNUNET_PEER_search(&msg->destination);
2910   if (pid == myid)
2911   {
2912     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2913                 "MESH:   it's for us! sending to clients...\n");
2914     send_subscribed_clients (message, (struct GNUNET_MessageHeader *) &msg[1]);
2915     return GNUNET_OK;
2916   }
2917   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2918               "MESH:   not for us, retransmitting...\n");
2919   send_message (message, path_get_first_hop(t->tree, pid));
2920   return GNUNET_OK;
2921 }
2922
2923
2924 /**
2925  * Core handler for mesh network traffic going from the origin to all peers
2926  *
2927  * @param cls closure
2928  * @param message message
2929  * @param peer peer identity this notification is about
2930  * @param atsi performance data
2931  * @param atsi_count number of records in 'atsi'
2932  * @return GNUNET_OK to keep the connection open,
2933  *         GNUNET_SYSERR to close it (signal serious error)
2934  *
2935  * TODO: Check who we got this from, to validate route.
2936  */
2937 static int
2938 handle_mesh_data_multicast (void *cls, const struct GNUNET_PeerIdentity *peer,
2939                             const struct GNUNET_MessageHeader *message,
2940                             const struct GNUNET_ATS_Information *atsi,
2941                             unsigned int atsi_count)
2942 {
2943   struct GNUNET_MESH_Multicast *msg;
2944   struct MeshTunnel *t;
2945   size_t size;
2946
2947   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2948               "MESH: got a multicast packet from %s\n",
2949               GNUNET_i2s (peer));
2950   size = ntohs (message->size);
2951   if (sizeof (struct GNUNET_MESH_Multicast) +
2952       sizeof (struct GNUNET_MessageHeader) > size)
2953   {
2954     GNUNET_break_op (0);
2955     return GNUNET_OK;
2956   }
2957   msg = (struct GNUNET_MESH_Multicast *) message;
2958   t = tunnel_get (&msg->oid, ntohl (msg->tid));
2959
2960   if (NULL == t)
2961   {
2962     /* TODO notify that we dont know that tunnel */
2963     GNUNET_break_op (0);
2964     return GNUNET_OK;
2965   }
2966   tunnel_reset_timeout (t);
2967
2968   /* Transmit to locally interested clients */
2969   if (NULL != t->peers &&
2970       GNUNET_CONTAINER_multihashmap_contains (t->peers, &my_full_id.hashPubKey))
2971   {
2972     send_subscribed_clients (message, &msg[1].header);
2973   }
2974   tunnel_send_multicast(t, message);
2975   return GNUNET_OK;
2976 }
2977
2978
2979 /**
2980  * Core handler for mesh network traffic toward the owner of a tunnel
2981  *
2982  * @param cls closure
2983  * @param message message
2984  * @param peer peer identity this notification is about
2985  * @param atsi performance data
2986  * @param atsi_count number of records in 'atsi'
2987  *
2988  * @return GNUNET_OK to keep the connection open,
2989  *         GNUNET_SYSERR to close it (signal serious error)
2990  */
2991 static int
2992 handle_mesh_data_to_orig (void *cls, const struct GNUNET_PeerIdentity *peer,
2993                           const struct GNUNET_MessageHeader *message,
2994                           const struct GNUNET_ATS_Information *atsi,
2995                           unsigned int atsi_count)
2996 {
2997   struct GNUNET_MESH_ToOrigin *msg;
2998   struct GNUNET_PeerIdentity id;
2999   struct MeshPeerInfo *peer_info;
3000   struct MeshTunnel *t;
3001   size_t size;
3002
3003   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3004               "MESH: got a ToOrigin packet from %s\n",
3005               GNUNET_i2s (peer));
3006   size = ntohs (message->size);
3007   if (size < sizeof (struct GNUNET_MESH_ToOrigin) +     /* Payload must be */
3008       sizeof (struct GNUNET_MessageHeader))     /* at least a header */
3009   {
3010     GNUNET_break_op (0);
3011     return GNUNET_OK;
3012   }
3013   msg = (struct GNUNET_MESH_ToOrigin *) message;
3014   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3015               "MESH:  of type %u\n",
3016               ntohs (msg[1].header.type));
3017   t = tunnel_get (&msg->oid, ntohl (msg->tid));
3018
3019   if (NULL == t)
3020   {
3021     /* TODO notify that we dont know this tunnel (whom)? */
3022     GNUNET_break_op (0);
3023     return GNUNET_OK;
3024   }
3025
3026   if (t->id.oid == myid)
3027   {
3028     char cbuf[size];
3029     struct GNUNET_MESH_ToOrigin *copy;
3030
3031     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3032                 "MESH:   it's for us! sending to clients...\n");
3033     if (NULL == t->client)
3034     {
3035       /* got data packet for ownerless tunnel */
3036       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3037                 "MESH:   no clients!\n");
3038       GNUNET_break_op (0);
3039       return GNUNET_OK;
3040     }
3041     /* TODO signature verification */
3042     memcpy (cbuf, message, size);
3043     copy = (struct GNUNET_MESH_ToOrigin *) cbuf;
3044     copy->tid = htonl (t->local_tid);
3045     GNUNET_SERVER_notification_context_unicast (nc,
3046                                                 t->client->handle,
3047                                                 &copy->header,
3048                                                 GNUNET_YES);
3049     return GNUNET_OK;
3050   }
3051   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3052               "MESH:   not for us, retransmitting...\n");
3053
3054   peer_info = peer_info_get (&msg->oid);
3055   if (NULL == peer_info)
3056   {
3057     /* unknown origin of tunnel */
3058     GNUNET_break (0);
3059     return GNUNET_OK;
3060   }
3061   GNUNET_PEER_resolve (tree_get_predecessor(t->tree), &id);
3062   send_message (message, &id);
3063
3064   return GNUNET_OK;
3065 }
3066
3067
3068 /**
3069  * Core handler for path ACKs
3070  *
3071  * @param cls closure
3072  * @param message message
3073  * @param peer peer identity this notification is about
3074  * @param atsi performance data
3075  * @param atsi_count number of records in 'atsi'
3076  *
3077  * @return GNUNET_OK to keep the connection open,
3078  *         GNUNET_SYSERR to close it (signal serious error)
3079  */
3080 static int
3081 handle_mesh_path_ack (void *cls, const struct GNUNET_PeerIdentity *peer,
3082                       const struct GNUNET_MessageHeader *message,
3083                       const struct GNUNET_ATS_Information *atsi,
3084                       unsigned int atsi_count)
3085 {
3086   struct GNUNET_MESH_PathACK *msg;
3087   struct GNUNET_PeerIdentity id;
3088   struct MeshPeerInfo *peer_info;
3089   struct MeshTunnel *t;
3090
3091   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3092               "MESH: Received a path ACK msg [%s]\n",
3093               GNUNET_i2s(&my_full_id));
3094   msg = (struct GNUNET_MESH_PathACK *) message;
3095   t = tunnel_get (&msg->oid, msg->tid);
3096   if (NULL == t)
3097   {
3098     /* TODO notify that we don't know the tunnel */
3099     return GNUNET_OK;
3100   }
3101
3102   /* Message for us? */
3103   if (0 == memcmp (&msg->oid, &my_full_id, sizeof (struct GNUNET_PeerIdentity)))
3104   {
3105     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   It's for us!\n");
3106     if (NULL == t->client)
3107     {
3108       GNUNET_break_op (0);
3109       return GNUNET_OK;
3110     }
3111     if (NULL != t->dht_get_type)
3112     {
3113       GNUNET_DHT_get_stop (t->dht_get_type);
3114       t->dht_get_type = NULL;
3115     }
3116     peer_info = peer_info_get (&msg->peer_id);
3117     tree_set_status(t->tree, peer_info->id, MESH_PEER_READY);
3118     send_client_peer_connected(t, peer_info->id);
3119     return GNUNET_OK;
3120   }
3121
3122   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3123               "MESH:   not for us, retransmitting...\n");
3124   GNUNET_PEER_resolve(tree_get_predecessor(t->tree), &id);
3125   peer_info = peer_info_get (&msg->oid);
3126   if (NULL == peer_info)
3127   {
3128     /* If we know the tunnel, we should DEFINITELY know the peer */
3129     GNUNET_break (0);
3130     return GNUNET_OK;
3131   }
3132   send_message (message, &id);
3133   return GNUNET_OK;
3134 }
3135
3136
3137 /**
3138  * Functions to handle messages from core
3139  */
3140 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
3141   {&handle_mesh_path_create, GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE, 0},
3142   {&handle_mesh_path_destroy, GNUNET_MESSAGE_TYPE_MESH_PATH_DESTROY, 0},
3143   {&handle_mesh_path_broken, GNUNET_MESSAGE_TYPE_MESH_PATH_BROKEN,
3144     sizeof (struct GNUNET_MESH_PathBroken)},
3145   {&handle_mesh_tunnel_destroy, GNUNET_MESSAGE_TYPE_MESH_TUNNEL_DESTROY, 0},
3146   {&handle_mesh_data_unicast, GNUNET_MESSAGE_TYPE_MESH_UNICAST, 0},
3147   {&handle_mesh_data_multicast, GNUNET_MESSAGE_TYPE_MESH_MULTICAST, 0},
3148   {&handle_mesh_data_to_orig, GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN, 0},
3149   {&handle_mesh_path_ack, GNUNET_MESSAGE_TYPE_MESH_PATH_ACK,
3150     sizeof (struct GNUNET_MESH_PathACK)},
3151   {NULL, 0, 0}
3152 };
3153
3154
3155
3156 /******************************************************************************/
3157 /****************       MESH LOCAL HANDLER HELPERS      ***********************/
3158 /******************************************************************************/
3159
3160 /**
3161  * deregister_app: iterator for removing each application registered by a client
3162  * 
3163  * @param cls closure
3164  * @param key the hash of the application id (used to access the hashmap)
3165  * @param value the value stored at the key (client)
3166  * 
3167  * @return GNUNET_OK on success
3168  */
3169 static int
3170 deregister_app (void *cls, const GNUNET_HashCode * key, void *value)
3171 {
3172   GNUNET_break (GNUNET_YES == 
3173       GNUNET_CONTAINER_multihashmap_remove (applications, key, value));
3174   return GNUNET_OK;
3175 }
3176
3177 #if LATER
3178 /**
3179  * notify_client_connection_failure: notify a client that the connection to the
3180  * requested remote peer is not possible (for instance, no route found)
3181  * Function called when the socket is ready to queue more data. "buf" will be
3182  * NULL and "size" zero if the socket was closed for writing in the meantime.
3183  *
3184  * @param cls closure
3185  * @param size number of bytes available in buf
3186  * @param buf where the callee should write the message
3187  * @return number of bytes written to buf
3188  */
3189 static size_t
3190 notify_client_connection_failure (void *cls, size_t size, void *buf)
3191 {
3192   int size_needed;
3193   struct MeshPeerInfo *peer_info;
3194   struct GNUNET_MESH_PeerControl *msg;
3195   struct GNUNET_PeerIdentity id;
3196
3197   if (0 == size && NULL == buf)
3198   {
3199     // TODO retry? cancel?
3200     return 0;
3201   }
3202
3203   size_needed = sizeof (struct GNUNET_MESH_PeerControl);
3204   peer_info = (struct MeshPeerInfo *) cls;
3205   msg = (struct GNUNET_MESH_PeerControl *) buf;
3206   msg->header.size = htons (sizeof (struct GNUNET_MESH_PeerControl));
3207   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_DISCONNECTED);
3208 //     msg->tunnel_id = htonl(peer_info->t->tid);
3209   GNUNET_PEER_resolve (peer_info->id, &id);
3210   memcpy (&msg->peer, &id, sizeof (struct GNUNET_PeerIdentity));
3211
3212   return size_needed;
3213 }
3214 #endif
3215
3216
3217 /**
3218  * Send keepalive packets for a peer
3219  *
3220  * @param cls Closure (tunnel for which to send the keepalive).
3221  * @param tc Notification context.
3222  *
3223  * TODO: implement explicit multicast keepalive?
3224  */
3225 static void
3226 path_refresh (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3227 {
3228   struct MeshTunnel *t = cls;
3229   struct GNUNET_MessageHeader *payload;
3230   struct GNUNET_MESH_Multicast *msg;
3231   size_t size = sizeof(struct GNUNET_MESH_Multicast) +
3232                 sizeof(struct GNUNET_MessageHeader);
3233   char cbuf[size];
3234
3235   if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3236   {
3237     return;
3238   }
3239   t->path_refresh_task = GNUNET_SCHEDULER_NO_TASK;
3240
3241   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3242               "MESH: sending keepalive for tunnel %d\n",
3243               t->id.tid);
3244
3245   msg = (struct GNUNET_MESH_Multicast *) cbuf;
3246   msg->header.size = htons (size);
3247   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_MULTICAST);
3248   msg->oid = my_full_id;
3249   msg->tid = htonl(t->id.tid);
3250   payload = (struct GNUNET_MessageHeader *) &msg[1];
3251   payload->size = htons (sizeof(struct GNUNET_MessageHeader));
3252   payload->type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_KEEPALIVE);
3253   tunnel_send_multicast (t, &msg->header);
3254
3255   t->path_refresh_task =
3256       GNUNET_SCHEDULER_add_delayed (REFRESH_PATH_TIME, &path_refresh, t);
3257   return;
3258 }
3259
3260
3261 /**
3262  * Function to process paths received for a new peer addition. The recorded
3263  * paths form the initial tunnel, which can be optimized later.
3264  * Called on each result obtained for the DHT search.
3265  *
3266  * @param cls closure
3267  * @param exp when will this value expire
3268  * @param key key of the result
3269  * @param type type of the result
3270  * @param size number of bytes in data
3271  * @param data pointer to the result data
3272  *
3273  * TODO: re-issue the request after certain time? cancel after X results?
3274  */
3275 static void
3276 dht_get_id_handler (void *cls, struct GNUNET_TIME_Absolute exp,
3277                     const GNUNET_HashCode * key,
3278                     const struct GNUNET_PeerIdentity *get_path,
3279                     unsigned int get_path_length,
3280                     const struct GNUNET_PeerIdentity *put_path,
3281                     unsigned int put_path_length,
3282                     enum GNUNET_BLOCK_Type type, size_t size, const void *data)
3283 {
3284   struct MeshPathInfo *path_info = cls;
3285   struct MeshPeerPath *p;
3286   struct GNUNET_PeerIdentity pi;
3287   int i;
3288
3289   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3290              "MESH: Got results from DHT!\n");
3291   GNUNET_PEER_resolve (path_info->peer->id, &pi);
3292   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3293              "MESH:   for %s\n",
3294              GNUNET_i2s(&pi));
3295 //   GNUNET_DHT_get_stop(path_info->peer->dhtget);
3296 //   path_info->peer->dhtget = NULL;
3297
3298   p = path_build_from_dht (get_path, get_path_length,
3299                            put_path, put_path_length);
3300   path_add_to_peer (path_info->peer, p, GNUNET_NO);
3301   for (i = 0; i < path_info->peer->ntunnels; i++)
3302   {
3303     tunnel_add_peer (path_info->peer->tunnels[i], path_info->peer);
3304     peer_info_connect(path_info->peer, path_info->t);
3305   }
3306 //   GNUNET_free (path_info);
3307
3308   return;
3309 }
3310
3311
3312 /**
3313  * Function to process paths received for a new peer addition. The recorded
3314  * paths form the initial tunnel, which can be optimized later.
3315  * Called on each result obtained for the DHT search.
3316  *
3317  * @param cls closure
3318  * @param exp when will this value expire
3319  * @param key key of the result
3320  * @param type type of the result
3321  * @param size number of bytes in data
3322  * @param data pointer to the result data
3323  */
3324 static void
3325 dht_get_type_handler (void *cls, struct GNUNET_TIME_Absolute exp,
3326                       const GNUNET_HashCode * key,
3327                       const struct GNUNET_PeerIdentity *get_path,
3328                       unsigned int get_path_length,
3329                       const struct GNUNET_PeerIdentity *put_path,
3330                       unsigned int put_path_length,
3331                       enum GNUNET_BLOCK_Type type, size_t size,
3332                       const void *data)
3333 {
3334   const struct GNUNET_PeerIdentity *pi = data;
3335   struct MeshTunnel *t = cls;
3336   struct MeshPeerInfo *peer_info;
3337   struct MeshPeerPath *p;
3338
3339   if (size != sizeof (struct GNUNET_PeerIdentity))
3340   {
3341     GNUNET_break_op (0);
3342     return;
3343   }
3344   GNUNET_assert (NULL != t->client);
3345   peer_info = peer_info_get (pi);
3346   (void) GNUNET_CONTAINER_multihashmap_put (
3347       t->peers,
3348       &pi->hashPubKey,
3349       peer_info,
3350       GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE);
3351
3352   p = path_build_from_dht (get_path, get_path_length,
3353                            put_path, put_path_length);
3354   path_add_to_peer (peer_info, p, GNUNET_NO);
3355   tunnel_add_peer(t, peer_info);
3356   peer_info_connect (peer_info, t);
3357 }
3358
3359
3360 /******************************************************************************/
3361 /*********************       MESH LOCAL HANDLES      **************************/
3362 /******************************************************************************/
3363
3364
3365 /**
3366  * Handler for client disconnection
3367  *
3368  * @param cls closure
3369  * @param client identification of the client; NULL
3370  *        for the last call when the server is destroyed
3371  */
3372 static void
3373 handle_local_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
3374 {
3375   struct MeshClient *c;
3376   struct MeshClient *next;
3377
3378   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: client disconnected\n");
3379   if (client == NULL)
3380   {
3381     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:    (SERVER DOWN)\n");
3382     return;
3383   }
3384   c = clients;
3385   while (NULL != c)
3386   {
3387     if (c->handle != client && NULL != client)
3388     {
3389       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:    ... searching\n");
3390       c = c->next;
3391       continue;
3392     }
3393     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: matching client found\n");
3394     GNUNET_SERVER_client_drop (c->handle);
3395     if (NULL != c->tunnels)
3396     {
3397       GNUNET_CONTAINER_multihashmap_iterate (c->tunnels,
3398                                              &tunnel_destroy_iterator,
3399                                              c);
3400       GNUNET_CONTAINER_multihashmap_destroy (c->tunnels);
3401     }
3402
3403     /* deregister clients applications */
3404     if (NULL != c->apps)
3405     {
3406       GNUNET_CONTAINER_multihashmap_iterate (c->apps, &deregister_app, NULL);
3407       GNUNET_CONTAINER_multihashmap_destroy (c->apps);
3408     }
3409     if (0 == GNUNET_CONTAINER_multihashmap_size (applications) &&
3410         GNUNET_SCHEDULER_NO_TASK != announce_applications_task)
3411     {
3412       GNUNET_SCHEDULER_cancel (announce_applications_task);
3413       announce_applications_task = GNUNET_SCHEDULER_NO_TASK;
3414     }
3415     if (NULL != c->types)
3416       GNUNET_CONTAINER_multihashmap_destroy (c->types);
3417     next = c->next;
3418     GNUNET_CONTAINER_DLL_remove (clients, clients_tail, c);
3419     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   CLIENT FREE at %p\n", c);
3420     GNUNET_free (c);
3421     c = next;
3422   }
3423
3424   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:    done!\n");
3425   return;
3426 }
3427
3428
3429 /**
3430  * Handler for new clients
3431  *
3432  * @param cls closure
3433  * @param client identification of the client
3434  * @param message the actual message, which includes messages the client wants
3435  */
3436 static void
3437 handle_local_new_client (void *cls, struct GNUNET_SERVER_Client *client,
3438                          const struct GNUNET_MessageHeader *message)
3439 {
3440   struct GNUNET_MESH_ClientConnect *cc_msg;
3441   struct MeshClient *c;
3442   GNUNET_MESH_ApplicationType *a;
3443   unsigned int size;
3444   uint16_t ntypes;
3445   uint16_t *t;
3446   uint16_t napps;
3447   uint16_t i;
3448
3449   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: new client connected\n");
3450   /* Check data sanity */
3451   size = ntohs (message->size) - sizeof (struct GNUNET_MESH_ClientConnect);
3452   cc_msg = (struct GNUNET_MESH_ClientConnect *) message;
3453   ntypes = ntohs (cc_msg->types);
3454   napps = ntohs (cc_msg->applications);
3455   if (size !=
3456       ntypes * sizeof (uint16_t) + napps * sizeof (GNUNET_MESH_ApplicationType))
3457   {
3458     GNUNET_break (0);
3459     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3460     return;
3461   }
3462
3463   /* Create new client structure */
3464   c = GNUNET_malloc (sizeof (struct MeshClient));
3465 #if MESH_DEBUG
3466   c->id = next_client_id++;
3467 #endif
3468   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   CLIENT NEW %u at %p\n", c->id, c);
3469   c->handle = client;
3470   GNUNET_SERVER_client_keep (client);
3471   a = (GNUNET_MESH_ApplicationType *) &cc_msg[1];
3472   if (napps > 0)
3473   {
3474     GNUNET_MESH_ApplicationType at;
3475     GNUNET_HashCode hc;
3476
3477     c->apps = GNUNET_CONTAINER_multihashmap_create (napps);
3478     for (i = 0; i < napps; i++)
3479     {
3480       at = ntohl (a[i]);
3481       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   app type: %u\n", at);
3482       GNUNET_CRYPTO_hash (&at, sizeof (at), &hc);
3483       /* store in clients hashmap */
3484       GNUNET_CONTAINER_multihashmap_put (c->apps, &hc, c,
3485                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
3486       /* store in global hashmap, for announcements */
3487       GNUNET_CONTAINER_multihashmap_put (applications, &hc, c,
3488                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
3489     }
3490     if (GNUNET_SCHEDULER_NO_TASK == announce_applications_task)
3491       announce_applications_task =
3492           GNUNET_SCHEDULER_add_now (&announce_applications, NULL);
3493
3494   }
3495   if (ntypes > 0)
3496   {
3497     uint16_t u16;
3498     GNUNET_HashCode hc;
3499
3500     t = (uint16_t *) & a[napps];
3501     c->types = GNUNET_CONTAINER_multihashmap_create (ntypes);
3502     for (i = 0; i < ntypes; i++)
3503     {
3504       u16 = ntohs (t[i]);
3505       GNUNET_CRYPTO_hash (&u16, sizeof (u16), &hc);
3506
3507       /* store in clients hashmap */
3508       GNUNET_CONTAINER_multihashmap_put (c->types, &hc, c,
3509                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
3510       /* store in global hashmap */
3511       GNUNET_CONTAINER_multihashmap_put (types, &hc, c,
3512                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
3513     }
3514   }
3515   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3516               "MESH:  client has %u+%u subscriptions\n", napps, ntypes);
3517
3518   GNUNET_CONTAINER_DLL_insert (clients, clients_tail, c);
3519   c->tunnels = GNUNET_CONTAINER_multihashmap_create (32);
3520   GNUNET_SERVER_notification_context_add (nc, client);
3521
3522   GNUNET_SERVER_receive_done (client, GNUNET_OK);
3523 #if MESH_DEBUG
3524   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: new client processed\n");
3525 #endif
3526 }
3527
3528
3529 /**
3530  * Handler for requests of new tunnels
3531  *
3532  * @param cls closure
3533  * @param client identification of the client
3534  * @param message the actual message
3535  */
3536 static void
3537 handle_local_tunnel_create (void *cls, struct GNUNET_SERVER_Client *client,
3538                             const struct GNUNET_MessageHeader *message)
3539 {
3540   struct GNUNET_MESH_TunnelMessage *t_msg;
3541   struct MeshTunnel *t;
3542   struct MeshClient *c;
3543   GNUNET_HashCode hash;
3544
3545   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: new tunnel requested\n");
3546
3547   /* Sanity check for client registration */
3548   if (NULL == (c = client_get (client)))
3549   {
3550     GNUNET_break (0);
3551     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3552     return;
3553   }
3554 #if MESH_DEBUG
3555   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   by client %u\n", c->id);
3556 #endif
3557
3558   /* Message sanity check */
3559   if (sizeof (struct GNUNET_MESH_TunnelMessage) != ntohs (message->size))
3560   {
3561     GNUNET_break (0);
3562     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3563     return;
3564   }
3565
3566   t_msg = (struct GNUNET_MESH_TunnelMessage *) message;
3567   /* Sanity check for tunnel numbering */
3568   if (0 == (ntohl (t_msg->tunnel_id) & GNUNET_MESH_LOCAL_TUNNEL_ID_CLI))
3569   {
3570     GNUNET_break (0);
3571     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3572     return;
3573   }
3574   /* Sanity check for duplicate tunnel IDs */
3575   if (NULL != tunnel_get_by_local_id (c, ntohl (t_msg->tunnel_id)))
3576   {
3577     GNUNET_break (0);
3578     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3579     return;
3580   }
3581
3582   t = GNUNET_malloc (sizeof (struct MeshTunnel));
3583   while (NULL != tunnel_get_by_pi (myid, next_tid))
3584     next_tid = (next_tid + 1) & ~GNUNET_MESH_LOCAL_TUNNEL_ID_CLI;
3585   t->id.tid = next_tid++;
3586   next_tid = next_tid & ~GNUNET_MESH_LOCAL_TUNNEL_ID_CLI;
3587   t->id.oid = myid;
3588   t->local_tid = ntohl (t_msg->tunnel_id);
3589 #if MESH_DEBUG
3590   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3591               "MESH: CREATED TUNNEL %s [%x] (%x)\n",
3592               GNUNET_i2s (&my_full_id),
3593               t->id.tid,
3594               t->local_tid);
3595 #endif
3596   t->client = c;
3597   t->peers = GNUNET_CONTAINER_multihashmap_create (32);
3598
3599   GNUNET_CRYPTO_hash (&t->local_tid, sizeof (MESH_TunnelNumber), &hash);
3600   if (GNUNET_OK !=
3601       GNUNET_CONTAINER_multihashmap_put (
3602         c->tunnels, &hash, t,
3603         GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
3604   {
3605     GNUNET_break (0);
3606     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3607     return;
3608   }
3609
3610   GNUNET_CRYPTO_hash (&t->id, sizeof (struct MESH_TunnelID), &hash);
3611   if (GNUNET_OK !=
3612       GNUNET_CONTAINER_multihashmap_put (
3613         tunnels, &hash, t,
3614         GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
3615   {
3616     GNUNET_break (0);
3617     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3618     return;
3619   }
3620   t->tree = tree_new (myid);
3621   tree_set_me(t->tree, myid);
3622
3623   GNUNET_SERVER_receive_done (client, GNUNET_OK);
3624   return;
3625 }
3626
3627
3628 /**
3629  * Handler for requests of deleting tunnels
3630  *
3631  * @param cls closure
3632  * @param client identification of the client
3633  * @param message the actual message
3634  */
3635 static void
3636 handle_local_tunnel_destroy (void *cls, struct GNUNET_SERVER_Client *client,
3637                              const struct GNUNET_MessageHeader *message)
3638 {
3639   struct GNUNET_MESH_TunnelMessage *tunnel_msg;
3640   struct MeshClient *c;
3641   struct MeshTunnel *t;
3642   MESH_TunnelNumber tid;
3643   GNUNET_HashCode hash;
3644
3645   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3646               "MESH: Got a DESTROY TUNNEL from client!\n");
3647
3648   /* Sanity check for client registration */
3649   if (NULL == (c = client_get (client)))
3650   {
3651     GNUNET_break (0);
3652     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3653     return;
3654   }
3655   /* Message sanity check */
3656   if (sizeof (struct GNUNET_MESH_TunnelMessage) != ntohs (message->size))
3657   {
3658     GNUNET_break (0);
3659     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3660     return;
3661   }
3662 #if MESH_DEBUG
3663   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   by client %u\n", c->id);
3664 #endif
3665   tunnel_msg = (struct GNUNET_MESH_TunnelMessage *) message;
3666
3667   /* Retrieve tunnel */
3668   tid = ntohl (tunnel_msg->tunnel_id);
3669
3670   /* Remove from local id hashmap */
3671   GNUNET_CRYPTO_hash (&tid, sizeof (MESH_TunnelNumber), &hash);
3672   t = GNUNET_CONTAINER_multihashmap_get (c->tunnels, &hash);
3673   GNUNET_assert (GNUNET_YES ==
3674                  GNUNET_CONTAINER_multihashmap_remove (c->tunnels, &hash, t));
3675
3676   t->client = NULL;
3677   tunnel_send_destroy (t);
3678   tunnel_destroy(t);
3679   GNUNET_SERVER_receive_done (client, GNUNET_OK);
3680   return;
3681 }
3682
3683
3684 /**
3685  * Handler for connection requests to new peers
3686  *
3687  * @param cls closure
3688  * @param client identification of the client
3689  * @param message the actual message (PeerControl)
3690  */
3691 static void
3692 handle_local_connect_add (void *cls, struct GNUNET_SERVER_Client *client,
3693                           const struct GNUNET_MessageHeader *message)
3694 {
3695   struct GNUNET_MESH_PeerControl *peer_msg;
3696   struct MeshPeerInfo *peer_info;
3697   struct MeshClient *c;
3698   struct MeshTunnel *t;
3699   MESH_TunnelNumber tid;
3700
3701   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "MESH: Got connection request\n");
3702   /* Sanity check for client registration */
3703   if (NULL == (c = client_get (client)))
3704   {
3705     GNUNET_break (0);
3706     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3707     return;
3708   }
3709
3710   peer_msg = (struct GNUNET_MESH_PeerControl *) message;
3711   /* Sanity check for message size */
3712   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (peer_msg->header.size))
3713   {
3714     GNUNET_break (0);
3715     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3716     return;
3717   }
3718
3719   /* Tunnel exists? */
3720   tid = ntohl (peer_msg->tunnel_id);
3721   t = tunnel_get_by_local_id (c, tid);
3722   if (NULL == t)
3723   {
3724     GNUNET_break (0);
3725     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3726     return;
3727   }
3728
3729   /* Does client own tunnel? */
3730   if (t->client->handle != client)
3731   {
3732     GNUNET_break (0);
3733     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3734     return;
3735   }
3736   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "MESH:      for %s\n",
3737              GNUNET_i2s(&peer_msg->peer));
3738   peer_info = peer_info_get (&peer_msg->peer);
3739
3740   tunnel_add_peer(t, peer_info);
3741   peer_info_connect(peer_info, t);
3742
3743   GNUNET_SERVER_receive_done (client, GNUNET_OK);
3744   return;
3745 }
3746
3747
3748 /**
3749  * Handler for disconnection requests of peers in a tunnel
3750  *
3751  * @param cls closure
3752  * @param client identification of the client
3753  * @param message the actual message (PeerControl)
3754  */
3755 static void
3756 handle_local_connect_del (void *cls, struct GNUNET_SERVER_Client *client,
3757                           const struct GNUNET_MessageHeader *message)
3758 {
3759   struct GNUNET_MESH_PeerControl *peer_msg;
3760   struct MeshPeerInfo *peer_info;
3761   struct MeshClient *c;
3762   struct MeshTunnel *t;
3763   MESH_TunnelNumber tid;
3764
3765   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: Got a PEER DEL request\n");
3766   /* Sanity check for client registration */
3767   if (NULL == (c = client_get (client)))
3768   {
3769     GNUNET_break (0);
3770     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3771     return;
3772   }
3773   peer_msg = (struct GNUNET_MESH_PeerControl *) message;
3774   /* Sanity check for message size */
3775   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (peer_msg->header.size))
3776   {
3777     GNUNET_break (0);
3778     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3779     return;
3780   }
3781
3782   /* Tunnel exists? */
3783   tid = ntohl (peer_msg->tunnel_id);
3784   t = tunnel_get_by_local_id (c, tid);
3785   if (NULL == t)
3786   {
3787     GNUNET_break (0);
3788     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3789     return;
3790   }
3791   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   on tunnel %X\n", t->id.tid);
3792
3793   /* Does client own tunnel? */
3794   if (t->client->handle != client)
3795   {
3796     GNUNET_break (0);
3797     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3798     return;
3799   }
3800
3801   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3802               "MESH:   for peer %s\n",
3803               GNUNET_i2s(&peer_msg->peer));
3804   /* Is the peer in the tunnel? */
3805   peer_info = GNUNET_CONTAINER_multihashmap_get(t->peers,
3806                                                 &peer_msg->peer.hashPubKey);
3807   if (NULL == peer_info)
3808   {
3809     GNUNET_break (0);
3810     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3811     return;
3812   }
3813
3814   /* Ok, delete peer from tunnel */
3815   GNUNET_CONTAINER_multihashmap_remove_all (t->peers,
3816                                             &peer_msg->peer.hashPubKey);
3817
3818   send_destroy_path (t, peer_info->id);
3819   tunnel_delete_peer(t, peer_info->id);
3820   GNUNET_SERVER_receive_done (client, GNUNET_OK);
3821   return;
3822 }
3823
3824
3825 /**
3826  * Handler for connection requests to new peers by type
3827  *
3828  * @param cls closure
3829  * @param client identification of the client
3830  * @param message the actual message (ConnectPeerByType)
3831  */
3832 static void
3833 handle_local_connect_by_type (void *cls, struct GNUNET_SERVER_Client *client,
3834                               const struct GNUNET_MessageHeader *message)
3835 {
3836   struct GNUNET_MESH_ConnectPeerByType *connect_msg;
3837   struct MeshClient *c;
3838   struct MeshTunnel *t;
3839   GNUNET_HashCode hash;
3840   MESH_TunnelNumber tid;
3841
3842   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: got connect by type request\n");
3843   /* Sanity check for client registration */
3844   if (NULL == (c = client_get (client)))
3845   {
3846     GNUNET_break (0);
3847     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3848     return;
3849   }
3850
3851   connect_msg = (struct GNUNET_MESH_ConnectPeerByType *) message;
3852   /* Sanity check for message size */
3853   if (sizeof (struct GNUNET_MESH_ConnectPeerByType) !=
3854       ntohs (connect_msg->header.size))
3855   {
3856     GNUNET_break (0);
3857     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3858     return;
3859   }
3860
3861   /* Tunnel exists? */
3862   tid = ntohl (connect_msg->tunnel_id);
3863   t = tunnel_get_by_local_id (c, tid);
3864   if (NULL == t)
3865   {
3866     GNUNET_break (0);
3867     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3868     return;
3869   }
3870
3871   /* Does client own tunnel? */
3872   if (t->client->handle != client)
3873   {
3874     GNUNET_break (0);
3875     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3876     return;
3877   }
3878
3879   /* Do WE have the service? */
3880   t->type = ntohl (connect_msg->type);
3881   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:  type requested: %u\n", t->type);
3882   GNUNET_CRYPTO_hash (&t->type, sizeof (GNUNET_MESH_ApplicationType), &hash);
3883   if (GNUNET_CONTAINER_multihashmap_contains (applications, &hash) ==
3884       GNUNET_YES)
3885   {
3886     /* Yes! Fast forward, add ourselves to the tunnel and send the
3887      * good news to the client
3888      */
3889     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:  available locally\n");
3890     GNUNET_CONTAINER_multihashmap_put (t->peers, &my_full_id.hashPubKey,
3891                                        peer_info_get (&my_full_id),
3892                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
3893
3894     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:  notifying client\n");
3895     send_client_peer_connected(t, myid);
3896     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:  Done\n");
3897     GNUNET_SERVER_receive_done (client, GNUNET_OK);
3898     return;
3899   }
3900   /* Ok, lets find a peer offering the service */
3901   if (NULL != t->dht_get_type)
3902   {
3903     GNUNET_DHT_get_stop (t->dht_get_type);
3904   }
3905   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:  looking in DHT for %s\n",
3906               GNUNET_h2s (&hash));
3907   t->dht_get_type =
3908       GNUNET_DHT_get_start (dht_handle,
3909                             GNUNET_TIME_UNIT_FOREVER_REL,
3910                             GNUNET_BLOCK_TYPE_TEST,
3911                             &hash,
3912                             10U,
3913                             GNUNET_DHT_RO_RECORD_ROUTE |
3914                               GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE,
3915                             NULL, 0,
3916                             &dht_get_type_handler, t);
3917
3918   GNUNET_SERVER_receive_done (client, GNUNET_OK);
3919   return;
3920 }
3921
3922
3923 /**
3924  * Handler for client traffic directed to one peer
3925  *
3926  * @param cls closure
3927  * @param client identification of the client
3928  * @param message the actual message
3929  */
3930 static void
3931 handle_local_unicast (void *cls, struct GNUNET_SERVER_Client *client,
3932                       const struct GNUNET_MessageHeader *message)
3933 {
3934   struct MeshClient *c;
3935   struct MeshTunnel *t;
3936   struct MeshPeerInfo *pi;
3937   struct GNUNET_MESH_Unicast *data_msg;
3938   MESH_TunnelNumber tid;
3939   size_t size;
3940
3941   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3942               "MESH: Got a unicast request from a client!\n");
3943
3944   /* Sanity check for client registration */
3945   if (NULL == (c = client_get (client)))
3946   {
3947     GNUNET_break (0);
3948     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3949     return;
3950   }
3951   data_msg = (struct GNUNET_MESH_Unicast *) message;
3952   /* Sanity check for message size */
3953   size = ntohs (message->size);
3954   if (sizeof (struct GNUNET_MESH_Unicast) +
3955       sizeof (struct GNUNET_MessageHeader) > size)
3956   {
3957     GNUNET_break (0);
3958     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3959     return;
3960   }
3961
3962   /* Tunnel exists? */
3963   tid = ntohl (data_msg->tid);
3964   t = tunnel_get_by_local_id (c, tid);
3965   if (NULL == t)
3966   {
3967     GNUNET_break (0);
3968     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3969     return;
3970   }
3971
3972   /*  Is it a local tunnel? Then, does client own the tunnel? */
3973   if (NULL != t->client &&
3974       NULL != t->client->handle &&
3975       t->client->handle != client)
3976   {
3977     GNUNET_break (0);
3978     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3979     return;
3980   }
3981
3982   pi = GNUNET_CONTAINER_multihashmap_get (t->peers,
3983                                           &data_msg->destination.hashPubKey);
3984   /* Is the selected peer in the tunnel? */
3985   if (NULL == pi)
3986   {
3987     GNUNET_break (0);
3988     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3989     return;
3990   }
3991
3992   /* Ok, everything is correct, send the message
3993    * (pretend we got it from a mesh peer)
3994    */
3995   {
3996     char buf[ntohs (message->size)];
3997     struct GNUNET_MESH_Unicast *copy;
3998
3999     /* Work around const limitation */
4000     copy = (struct GNUNET_MESH_Unicast *) buf;
4001     memcpy (buf, data_msg, size);
4002     copy->oid = my_full_id;
4003     copy->tid = htonl (t->id.tid);
4004     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4005                 "MESH:   calling generic handler...\n");
4006     handle_mesh_data_unicast (NULL, &my_full_id, &copy->header, NULL, 0);
4007   }
4008   GNUNET_SERVER_receive_done (client, GNUNET_OK);
4009   return;
4010 }
4011
4012
4013 /**
4014  * Handler for client traffic directed to the origin
4015  *
4016  * @param cls closure
4017  * @param client identification of the client
4018  * @param message the actual message
4019  */
4020 static void
4021 handle_local_to_origin (void *cls, struct GNUNET_SERVER_Client *client,
4022                         const struct GNUNET_MessageHeader *message)
4023 {
4024   struct GNUNET_MESH_ToOrigin *data_msg;
4025   struct GNUNET_PeerIdentity id;
4026   struct MeshClient *c;
4027   struct MeshTunnel *t;
4028   MESH_TunnelNumber tid;
4029   size_t size;
4030
4031   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4032               "MESH: Got a ToOrigin request from a client!\n");
4033
4034   /* Sanity check for client registration */
4035   if (NULL == (c = client_get (client)))
4036   {
4037     GNUNET_break (0);
4038     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4039     return;
4040   }
4041   data_msg = (struct GNUNET_MESH_ToOrigin *) message;
4042   /* Sanity check for message size */
4043   size = ntohs (message->size);
4044   if (sizeof (struct GNUNET_MESH_ToOrigin) +
4045       sizeof (struct GNUNET_MessageHeader) > size)
4046   {
4047     GNUNET_break (0);
4048     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4049     return;
4050   }
4051
4052   /* Tunnel exists? */
4053   tid = ntohl (data_msg->tid);
4054   if (tid < GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
4055   {
4056     GNUNET_break (0);
4057     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4058     return;
4059   }
4060   t = tunnel_get_by_local_id (c, tid);
4061   if (NULL == t)
4062   {
4063     GNUNET_break (0);
4064     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4065     return;
4066   }
4067
4068   /*  It shouldn't be a local tunnel.  */
4069   if (NULL != t->client)
4070   {
4071     GNUNET_break (0);
4072     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4073     return;
4074   }
4075   GNUNET_PEER_resolve(t->id.oid, &id);
4076
4077   /* Ok, everything is correct, send the message
4078    * (pretend we got it from a mesh peer)
4079    */
4080   {
4081     char buf[ntohs (message->size)];
4082     struct GNUNET_MESH_ToOrigin *copy;
4083
4084     /* Work around const limitation */
4085     copy = (struct GNUNET_MESH_ToOrigin *) buf;
4086     memcpy (buf, data_msg, size);
4087     copy->oid = id;
4088     copy->tid = htonl (t->id.tid);
4089     copy->sender = my_full_id;
4090     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4091                 "MESH:   calling generic handler...\n");
4092     handle_mesh_data_to_orig (NULL, &my_full_id, &copy->header, NULL, 0);
4093   }
4094   GNUNET_SERVER_receive_done (client, GNUNET_OK);
4095   return;
4096 }
4097
4098
4099 /**
4100  * Handler for client traffic directed to all peers in a tunnel
4101  *
4102  * @param cls closure
4103  * @param client identification of the client
4104  * @param message the actual message
4105  */
4106 static void
4107 handle_local_multicast (void *cls, struct GNUNET_SERVER_Client *client,
4108                         const struct GNUNET_MessageHeader *message)
4109 {
4110   struct MeshClient *c;
4111   struct MeshTunnel *t;
4112   struct GNUNET_MESH_Multicast *data_msg;
4113   MESH_TunnelNumber tid;
4114
4115   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4116               "MESH: Got a multicast request from a client!\n");
4117
4118   /* Sanity check for client registration */
4119   if (NULL == (c = client_get (client)))
4120   {
4121     GNUNET_break (0);
4122     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4123     return;
4124   }
4125   data_msg = (struct GNUNET_MESH_Multicast *) message;
4126   /* Sanity check for message size */
4127   if (sizeof (struct GNUNET_MESH_Multicast) +
4128       sizeof (struct GNUNET_MessageHeader) > ntohs (data_msg->header.size))
4129   {
4130     GNUNET_break (0);
4131     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4132     return;
4133   }
4134
4135   /* Tunnel exists? */
4136   tid = ntohl (data_msg->tid);
4137   t = tunnel_get_by_local_id (c, tid);
4138   if (NULL == t)
4139   {
4140     GNUNET_break (0);
4141     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4142     return;
4143   }
4144
4145   /* Does client own tunnel? */
4146   if (t->client->handle != client)
4147   {
4148     GNUNET_break (0);
4149     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4150     return;
4151   }
4152
4153   {
4154     char buf[ntohs(message->size)];
4155     struct GNUNET_MESH_Multicast *copy;
4156
4157     copy = (struct GNUNET_MESH_Multicast *)buf;
4158     memcpy(buf, message, ntohs(message->size));
4159     copy->oid = my_full_id;
4160     copy->tid = htonl(t->id.tid);
4161     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4162                 "MESH:   calling generic handler...\n");
4163     handle_mesh_data_multicast(client, &my_full_id, &copy->header, NULL, 0);
4164   }
4165
4166   /* receive done gets called when last copy is sent to a neighbor */
4167   return;
4168 }
4169
4170 /**
4171  * Functions to handle messages from clients
4172  */
4173 static struct GNUNET_SERVER_MessageHandler client_handlers[] = {
4174   {&handle_local_new_client, NULL,
4175    GNUNET_MESSAGE_TYPE_MESH_LOCAL_CONNECT, 0},
4176   {&handle_local_tunnel_create, NULL,
4177    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_CREATE,
4178    sizeof (struct GNUNET_MESH_TunnelMessage)},
4179   {&handle_local_tunnel_destroy, NULL,
4180    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_DESTROY,
4181    sizeof (struct GNUNET_MESH_TunnelMessage)},
4182   {&handle_local_connect_add, NULL,
4183    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD,
4184    sizeof (struct GNUNET_MESH_PeerControl)},
4185   {&handle_local_connect_del, NULL,
4186    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_DEL,
4187    sizeof (struct GNUNET_MESH_PeerControl)},
4188   {&handle_local_connect_by_type, NULL,
4189    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD_BY_TYPE,
4190    sizeof (struct GNUNET_MESH_ConnectPeerByType)},
4191   {&handle_local_unicast, NULL,
4192    GNUNET_MESSAGE_TYPE_MESH_UNICAST, 0},
4193   {&handle_local_to_origin, NULL,
4194    GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN, 0},
4195   {&handle_local_multicast, NULL,
4196    GNUNET_MESSAGE_TYPE_MESH_MULTICAST, 0},
4197   {NULL, NULL, 0, 0}
4198 };
4199
4200
4201 /**
4202  * To be called on core init/fail.
4203  *
4204  * @param cls service closure
4205  * @param server handle to the server for this service
4206  * @param identity the public identity of this peer
4207  */
4208 static void
4209 core_init (void *cls, struct GNUNET_CORE_Handle *server,
4210            const struct GNUNET_PeerIdentity *identity)
4211 {
4212   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: Core init\n");
4213   core_handle = server;
4214   if (0 != memcmp(identity, &my_full_id, sizeof(my_full_id)) || NULL == server)
4215   {
4216     GNUNET_log(GNUNET_ERROR_TYPE_ERROR, _("MESH: Wrong CORE service\n"));
4217     GNUNET_SCHEDULER_shutdown();   
4218   }
4219   return;
4220 }
4221
4222 /**
4223  * Method called whenever a given peer connects.
4224  *
4225  * @param cls closure
4226  * @param peer peer identity this notification is about
4227  * @param atsi performance data for the connection
4228  * @param atsi_count number of records in 'atsi'
4229  */
4230 static void
4231 core_connect (void *cls, const struct GNUNET_PeerIdentity *peer,
4232               const struct GNUNET_ATS_Information *atsi,
4233               unsigned int atsi_count)
4234 {
4235   struct MeshPeerInfo *peer_info;
4236   struct MeshPeerPath *path;
4237
4238 #if MESH_DEBUG_CONNECTION
4239   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: Peer connected\n");
4240   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:      %s\n",
4241               GNUNET_i2s(&my_full_id));
4242 #endif
4243   peer_info = peer_info_get (peer);
4244   if (myid == peer_info->id)
4245   {
4246 #if MESH_DEBUG_CONNECTION
4247     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:      (self)\n");
4248 #endif
4249     return;
4250   }
4251 #if MESH_DEBUG_CONNECTION
4252   else
4253   {
4254     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:      %s\n",
4255                 GNUNET_i2s(peer));
4256   }
4257 #endif
4258   path = path_new (2);
4259   path->peers[0] = myid;
4260   path->peers[1] = peer_info->id;
4261   GNUNET_PEER_change_rc(myid, 1);
4262   GNUNET_PEER_change_rc(peer_info->id, 1);
4263   path_add_to_peer (peer_info, path, GNUNET_YES);
4264   return;
4265 }
4266
4267 /**
4268  * Method called whenever a peer disconnects.
4269  *
4270  * @param cls closure
4271  * @param peer peer identity this notification is about
4272  */
4273 static void
4274 core_disconnect (void *cls, const struct GNUNET_PeerIdentity *peer)
4275 {
4276   struct MeshPeerInfo *pi;
4277   unsigned int i;
4278
4279 #if MESH_DEBUG_CONNECTION
4280   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: Peer disconnected\n");
4281 #endif
4282   pi = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
4283   if (NULL == pi)
4284   {
4285     GNUNET_break (0);
4286     return;
4287   }
4288   for (i = 0; i < CORE_QUEUE_SIZE; i++)
4289   {
4290     /* TODO: notify that the transmission failed */
4291     peer_info_cancel_transmission(pi, i);
4292   }
4293   path_remove_from_peer (pi, pi->id, myid);
4294 #if MESH_DEBUG_CONNECTION
4295   if (myid == pi->id)
4296   {
4297     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:      (self)\n");
4298   }
4299 #endif
4300   return;
4301 }
4302
4303
4304 /******************************************************************************/
4305 /************************      MAIN FUNCTIONS      ****************************/
4306 /******************************************************************************/
4307
4308 /**
4309  * Iterator over tunnel hash map entries to destroy the tunnel during shutdown.
4310  *
4311  * @param cls closure
4312  * @param key current key code
4313  * @param value value in the hash map
4314  * @return GNUNET_YES if we should continue to iterate,
4315  *         GNUNET_NO if not.
4316  */
4317 static int
4318 shutdown_tunnel (void *cls, const GNUNET_HashCode * key, void *value)
4319 {
4320   struct MeshTunnel *t = value;
4321   tunnel_destroy(t);
4322   return GNUNET_YES;
4323 }
4324
4325 /**
4326  * Iterator over peer hash map entries to destroy the tunnel during shutdown.
4327  *
4328  * @param cls closure
4329  * @param key current key code
4330  * @param value value in the hash map
4331  * @return GNUNET_YES if we should continue to iterate,
4332  *         GNUNET_NO if not.
4333  */
4334 static int
4335 shutdown_peer (void *cls, const GNUNET_HashCode * key, void *value)
4336 {
4337   struct MeshPeerInfo *p = value;
4338   peer_info_destroy (p);
4339   return GNUNET_YES;
4340 }
4341
4342 /**
4343  * Task run during shutdown.
4344  *
4345  * @param cls unused
4346  * @param tc unused
4347  */
4348 static void
4349 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
4350 {
4351   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: shutting down\n");
4352   /* TODO: destroy tunnels? */
4353   if (core_handle != NULL)
4354   {
4355     GNUNET_CORE_disconnect (core_handle);
4356     core_handle = NULL;
4357   }
4358   GNUNET_CONTAINER_multihashmap_iterate(tunnels, &shutdown_tunnel, NULL);
4359   GNUNET_CONTAINER_multihashmap_iterate(peers, &shutdown_peer, NULL);
4360   if (dht_handle != NULL)
4361   {
4362     GNUNET_DHT_disconnect (dht_handle);
4363     dht_handle = NULL;
4364   }
4365   if (nc != NULL)
4366   {
4367     GNUNET_SERVER_notification_context_destroy (nc);
4368     nc = NULL;
4369   }
4370   if (GNUNET_SCHEDULER_NO_TASK != announce_id_task)
4371   {
4372     GNUNET_SCHEDULER_cancel (announce_id_task);
4373     announce_id_task = GNUNET_SCHEDULER_NO_TASK;
4374   }
4375   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: shut down\n");
4376 }
4377
4378 /**
4379  * Process mesh requests.
4380  *
4381  * @param cls closure
4382  * @param server the initialized server
4383  * @param c configuration to use
4384  */
4385 static void
4386 run (void *cls, struct GNUNET_SERVER_Handle *server,
4387      const struct GNUNET_CONFIGURATION_Handle *c)
4388 {
4389   struct MeshPeerInfo *peer;
4390   struct MeshPeerPath *p;
4391   char *keyfile;
4392
4393   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: starting to run\n");
4394   server_handle = server;
4395   core_handle = GNUNET_CORE_connect (c, /* Main configuration */
4396                                      CORE_QUEUE_SIZE,   /* queue size */
4397                                      NULL,      /* Closure passed to MESH functions */
4398                                      &core_init,        /* Call core_init once connected */
4399                                      &core_connect,     /* Handle connects */
4400                                      &core_disconnect,  /* remove peers on disconnects */
4401                                      NULL,      /* Don't notify about all incoming messages */
4402                                      GNUNET_NO, /* For header only in notification */
4403                                      NULL,      /* Don't notify about all outbound messages */
4404                                      GNUNET_NO, /* For header-only out notification */
4405                                      core_handlers);    /* Register these handlers */
4406
4407   if (core_handle == NULL)
4408   {
4409     GNUNET_break (0);
4410     GNUNET_SCHEDULER_shutdown ();
4411     return;
4412   }
4413
4414   if (GNUNET_OK !=
4415        GNUNET_CONFIGURATION_get_value_filename (c, "GNUNETD", "HOSTKEY",
4416                                                 &keyfile))
4417   {
4418     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
4419                 _
4420                 ("Mesh service is lacking key configuration settings.  Exiting.\n"));
4421     GNUNET_SCHEDULER_shutdown ();
4422     return;
4423   }
4424   my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
4425   GNUNET_free (keyfile);
4426   if (my_private_key == NULL)
4427   {
4428     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
4429                 _("Mesh service could not access hostkey.  Exiting.\n"));
4430     GNUNET_SCHEDULER_shutdown ();
4431     return;
4432   }
4433   GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
4434   GNUNET_CRYPTO_hash (&my_public_key, sizeof (my_public_key),
4435                       &my_full_id.hashPubKey);
4436   myid = GNUNET_PEER_intern (&my_full_id);
4437
4438 // //   transport_handle = GNUNET_TRANSPORT_connect(c,
4439 // //                                               &my_full_id,
4440 // //                                               NULL,
4441 // //                                               NULL,
4442 // //                                               NULL,
4443 // //                                               NULL);
4444
4445   dht_handle = GNUNET_DHT_connect (c, 64);
4446   if (dht_handle == NULL)
4447   {
4448     GNUNET_break (0);
4449   }
4450
4451   next_tid = 0;
4452   next_local_tid = GNUNET_MESH_LOCAL_TUNNEL_ID_SERV;
4453
4454   tunnels = GNUNET_CONTAINER_multihashmap_create (32);
4455   incoming_tunnels = GNUNET_CONTAINER_multihashmap_create (32);
4456   peers = GNUNET_CONTAINER_multihashmap_create (32);
4457   applications = GNUNET_CONTAINER_multihashmap_create (32);
4458   types = GNUNET_CONTAINER_multihashmap_create (32);
4459
4460   GNUNET_SERVER_add_handlers (server_handle, client_handlers);
4461   nc = GNUNET_SERVER_notification_context_create (server_handle,
4462                                                   LOCAL_QUEUE_SIZE);
4463   GNUNET_SERVER_disconnect_notify (server_handle,
4464                                    &handle_local_client_disconnect,
4465                                    NULL);
4466
4467
4468   clients = NULL;
4469   clients_tail = NULL;
4470 #if MESH_DEBUG
4471   next_client_id = 0;
4472 #endif
4473
4474   announce_applications_task = GNUNET_SCHEDULER_NO_TASK;
4475   announce_id_task = GNUNET_SCHEDULER_add_now (&announce_id, cls);
4476
4477   /* Create a peer_info for the local peer */
4478   peer = peer_info_get(&my_full_id);
4479   p = path_new (1);
4480   p->peers[0] = myid;
4481   GNUNET_PEER_change_rc (myid, 1);
4482   path_add_to_peer(peer, p, GNUNET_YES);
4483
4484   /* Scheduled the task to clean up when shutdown is called */
4485   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
4486                                 NULL);
4487
4488   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: end of run()\n");
4489 }
4490
4491 /**
4492  * The main function for the mesh service.
4493  *
4494  * @param argc number of arguments from the command line
4495  * @param argv command line arguments
4496  * @return 0 ok, 1 on error
4497  */
4498 int
4499 main (int argc, char *const *argv)
4500 {
4501   int ret;
4502
4503   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: main()\n");
4504   ret =
4505       (GNUNET_OK ==
4506        GNUNET_SERVICE_run (argc, argv, "mesh", GNUNET_SERVICE_OPTION_NONE, &run,
4507                            NULL)) ? 0 : 1;
4508   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: main() END\n");
4509
4510   return ret;
4511 }