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