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