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