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