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