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