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