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