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