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