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