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