Small fixes
[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                    NULL));
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   if (own_pos == size - 1)
2368   {
2369     /* It is for us! Send ack. */
2370     struct GNUNET_MESH_TunnelNotification cmsg;
2371     struct MeshDataDescriptor *info;
2372     unsigned int j;
2373
2374     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2375                 "MESH:   It's for us!\n");
2376     path_add_to_origin (orig_peer_info, path);
2377     t->peers = GNUNET_CONTAINER_multihashmap_create(4);
2378     GNUNET_break (GNUNET_OK == GNUNET_CONTAINER_multihashmap_put (
2379         t->peers,
2380         &my_full_id.hashPubKey,
2381         peer_info_get(&my_full_id),
2382         GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST));
2383     info = GNUNET_malloc (sizeof (struct MeshDataDescriptor));
2384     info->origin = &t->id;
2385     info->peer = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
2386     GNUNET_assert (NULL != info->peer);
2387     j = peer_info_transmit_slot(info->peer);
2388     info->handler_n = j;
2389     info->peer->types[j] = GNUNET_MESSAGE_TYPE_MESH_PATH_ACK;
2390     info->peer->infos[j] = info;
2391     info->peer->core_transmit[j] =
2392         GNUNET_CORE_notify_transmit_ready (core_handle, 0, 100,
2393                                            GNUNET_TIME_UNIT_FOREVER_REL, peer,
2394                                            sizeof (struct GNUNET_MESH_PathACK),
2395                                            &send_core_path_ack, info);
2396     cmsg.header.size = htons(sizeof(cmsg));
2397     cmsg.header.type = htons(GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_CREATE);
2398     GNUNET_PEER_resolve(t->id.oid, &cmsg.peer);
2399     cmsg.tunnel_id = htonl(t->local_tid);
2400     GNUNET_SERVER_notification_context_broadcast(nc, &cmsg.header, GNUNET_NO);
2401   }
2402   else
2403   {
2404     struct MeshPeerPath *path2;
2405
2406     /* It's for somebody else! Retransmit. */
2407     path2 = path_duplicate(path);
2408     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2409                 "MESH:   Retransmitting.\n");
2410     path_add_to_peer(dest_peer_info, path);
2411     path = path_duplicate(path2);
2412     path_add_to_origin(orig_peer_info, path2);
2413     send_create_path(dest_peer_info, path, t);
2414   }
2415   return GNUNET_OK;
2416 }
2417
2418
2419 /**
2420  * Core handler for path destruction
2421  *
2422  * @param cls closure
2423  * @param message message
2424  * @param peer peer identity this notification is about
2425  * @param atsi performance data
2426  *
2427  * @return GNUNET_OK to keep the connection open,
2428  *         GNUNET_SYSERR to close it (signal serious error)
2429  */
2430 static int
2431 handle_mesh_path_destroy (void *cls, const struct GNUNET_PeerIdentity *peer,
2432                           const struct GNUNET_MessageHeader *message,
2433                           const struct GNUNET_ATS_Information *atsi)
2434 {
2435   struct GNUNET_MESH_ManipulatePath *msg;
2436   struct GNUNET_PeerIdentity *pi;
2437   struct MeshPeerPath *path;
2438   struct MeshTunnel *t;
2439   unsigned int own_pos;
2440   unsigned int i;
2441   size_t size;
2442
2443   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2444               "MESH: Received a PATH DESTROY msg from %s\n",
2445               GNUNET_i2s(peer));
2446   size = ntohs (message->size);
2447   if (size < sizeof (struct GNUNET_MESH_ManipulatePath))
2448   {
2449     GNUNET_break_op (0);
2450     return GNUNET_OK;
2451   }
2452
2453   size -= sizeof (struct GNUNET_MESH_ManipulatePath);
2454   if (size % sizeof (struct GNUNET_PeerIdentity))
2455   {
2456     GNUNET_break_op (0);
2457     return GNUNET_OK;
2458   }
2459   size /= sizeof (struct GNUNET_PeerIdentity);
2460   if (size < 2)
2461   {
2462     GNUNET_break_op (0);
2463     return GNUNET_OK;
2464   }
2465   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2466               "MESH:     path has %u hops.\n",
2467               size);
2468
2469   msg = (struct GNUNET_MESH_ManipulatePath *) message;
2470   pi = (struct GNUNET_PeerIdentity *) &msg[1];
2471   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2472               "MESH:     path is for tunnel %s [%X].\n",
2473               GNUNET_i2s(pi),
2474               msg->tid);
2475   t = tunnel_get (pi, ntohl (msg->tid));
2476   if (NULL == t)
2477   {
2478     /* TODO notify back: we don't know this tunnel */
2479     GNUNET_break_op (0);
2480     return GNUNET_OK;
2481   }
2482   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   Creating path...\n");
2483   path = path_new (size);
2484   own_pos = 0;
2485   for (i = 0; i < size; i++)
2486   {
2487     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2488                 "MESH:   ... adding %s\n",
2489                 GNUNET_i2s(&pi[i]));
2490     path->peers[i] = GNUNET_PEER_intern (&pi[i]);
2491     if (path->peers[i] == myid)
2492       own_pos = i;
2493   }
2494   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2495                 "MESH:   Own position: %u\n", own_pos);
2496   if (own_pos < path->length - 1)
2497     send_message (message, &pi[own_pos + 1]);
2498   tunnel_delete_path (t, path);
2499   return GNUNET_OK;
2500 }
2501
2502
2503 /**
2504  * Core handler for tunnel destruction
2505  *
2506  * @param cls closure
2507  * @param message message
2508  * @param peer peer identity this notification is about
2509  * @param atsi performance data
2510  *
2511  * @return GNUNET_OK to keep the connection open,
2512  *         GNUNET_SYSERR to close it (signal serious error)
2513  */
2514 static int
2515 handle_mesh_tunnel_destroy (void *cls, const struct GNUNET_PeerIdentity *peer,
2516                             const struct GNUNET_MessageHeader *message,
2517                             const struct GNUNET_ATS_Information *atsi)
2518 {
2519   struct GNUNET_MESH_TunnelDestroy *msg;
2520   struct MeshTunnel *t;
2521
2522   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2523               "MESH: Got a TUNNEL DESTROY packet from %s\n",
2524               GNUNET_i2s (peer));
2525   msg = (struct GNUNET_MESH_TunnelDestroy *) message;
2526   t = tunnel_get (&msg->oid, ntohl (msg->tid));
2527   if (NULL == t)
2528   {
2529     /* TODO notify back: we don't know this tunnel */
2530     GNUNET_break_op (0);
2531     return GNUNET_OK;
2532   }
2533   tunnel_send_destroy (t);
2534   tunnel_destroy (t);
2535   return GNUNET_OK;
2536 }
2537
2538
2539 /**
2540  * Core handler for mesh network traffic going from the origin to a peer
2541  *
2542  * @param cls closure
2543  * @param peer peer identity this notification is about
2544  * @param message message
2545  * @param atsi performance data
2546  * @return GNUNET_OK to keep the connection open,
2547  *         GNUNET_SYSERR to close it (signal serious error)
2548  */
2549 static int
2550 handle_mesh_data_unicast (void *cls, const struct GNUNET_PeerIdentity *peer,
2551                           const struct GNUNET_MessageHeader *message,
2552                           const struct GNUNET_ATS_Information *atsi)
2553 {
2554   struct GNUNET_MESH_Unicast *msg;
2555   struct MeshTunnel *t;
2556   GNUNET_PEER_Id pid;
2557   size_t size;
2558
2559   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2560               "MESH: got a unicast packet from %s\n",
2561               GNUNET_i2s (peer));
2562   size = ntohs (message->size);
2563   if (size <
2564       sizeof (struct GNUNET_MESH_Unicast) +
2565       sizeof (struct GNUNET_MessageHeader))
2566   {
2567     GNUNET_break (0);
2568     return GNUNET_OK;
2569   }
2570   msg = (struct GNUNET_MESH_Unicast *) message;
2571   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2572               "MESH:  of type %u\n",
2573               ntohs (msg[1].header.type));
2574   t = tunnel_get (&msg->oid, ntohl (msg->tid));
2575   if (NULL == t)
2576   {
2577     /* TODO notify back: we don't know this tunnel */
2578     GNUNET_break_op (0);
2579     return GNUNET_OK;
2580   }
2581   tunnel_reset_timeout (t);
2582   pid = GNUNET_PEER_search(&msg->destination);
2583   if (pid == myid)
2584   {
2585     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2586                 "MESH:   it's for us! sending to clients...\n");
2587     send_subscribed_clients (message, (struct GNUNET_MessageHeader *) &msg[1]);
2588     return GNUNET_OK;
2589   }
2590   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2591               "MESH:   not for us, retransmitting...\n");
2592   send_message (message, path_get_first_hop(t->tree, pid));
2593   return GNUNET_OK;
2594 }
2595
2596
2597 /**
2598  * Core handler for mesh network traffic going from the origin to all peers
2599  *
2600  * @param cls closure
2601  * @param message message
2602  * @param peer peer identity this notification is about
2603  * @param atsi performance data
2604  * @return GNUNET_OK to keep the connection open,
2605  *         GNUNET_SYSERR to close it (signal serious error)
2606  *
2607  * TODO: Check who we got this from, to validate route.
2608  */
2609 static int
2610 handle_mesh_data_multicast (void *cls, const struct GNUNET_PeerIdentity *peer,
2611                             const struct GNUNET_MessageHeader *message,
2612                             const struct GNUNET_ATS_Information *atsi)
2613 {
2614   struct GNUNET_MESH_Multicast *msg;
2615   struct MeshTunnel *t;
2616   size_t size;
2617
2618   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2619               "MESH: got a multicast packet from %s\n",
2620               GNUNET_i2s (peer));
2621   size = ntohs (message->size);
2622   if (sizeof (struct GNUNET_MESH_Multicast) +
2623       sizeof (struct GNUNET_MessageHeader) > size)
2624   {
2625     GNUNET_break_op (0);
2626     return GNUNET_OK;
2627   }
2628   msg = (struct GNUNET_MESH_Multicast *) message;
2629   t = tunnel_get (&msg->oid, ntohl (msg->tid));
2630
2631   if (NULL == t)
2632   {
2633     /* TODO notify that we dont know that tunnel */
2634     GNUNET_break_op (0);
2635     return GNUNET_OK;
2636   }
2637   tunnel_reset_timeout (t);
2638
2639   /* Transmit to locally interested clients */
2640   if (NULL != t->peers &&
2641       GNUNET_CONTAINER_multihashmap_contains (t->peers, &my_full_id.hashPubKey))
2642   {
2643     send_subscribed_clients (message, &msg[1].header);
2644   }
2645   tunnel_send_multicast(t, message);
2646   return GNUNET_OK;
2647 }
2648
2649
2650 /**
2651  * Core handler for mesh network traffic toward the owner of a tunnel
2652  *
2653  * @param cls closure
2654  * @param message message
2655  * @param peer peer identity this notification is about
2656  * @param atsi performance data
2657  *
2658  * @return GNUNET_OK to keep the connection open,
2659  *         GNUNET_SYSERR to close it (signal serious error)
2660  */
2661 static int
2662 handle_mesh_data_to_orig (void *cls, const struct GNUNET_PeerIdentity *peer,
2663                           const struct GNUNET_MessageHeader *message,
2664                           const struct GNUNET_ATS_Information *atsi)
2665 {
2666   struct GNUNET_MESH_ToOrigin *msg;
2667   struct GNUNET_PeerIdentity id;
2668   struct MeshPeerInfo *peer_info;
2669   struct MeshTunnel *t;
2670   size_t size;
2671
2672   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2673               "MESH: got a ToOrigin packet from %s\n",
2674               GNUNET_i2s (peer));
2675   size = ntohs (message->size);
2676   if (size < sizeof (struct GNUNET_MESH_ToOrigin) +     /* Payload must be */
2677       sizeof (struct GNUNET_MessageHeader))     /* at least a header */
2678   {
2679     GNUNET_break_op (0);
2680     return GNUNET_OK;
2681   }
2682   msg = (struct GNUNET_MESH_ToOrigin *) message;
2683   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2684               "MESH:  of type %u\n",
2685               ntohs (msg[1].header.type));
2686   t = tunnel_get (&msg->oid, ntohl (msg->tid));
2687
2688   if (NULL == t)
2689   {
2690     /* TODO notify that we dont know this tunnel (whom)? */
2691     GNUNET_break_op (0);
2692     return GNUNET_OK;
2693   }
2694
2695   if (t->id.oid == myid)
2696   {
2697     char cbuf[size];
2698     struct GNUNET_MESH_ToOrigin *copy;
2699
2700     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2701                 "MESH:   it's for us! sending to clients...\n");
2702     if (NULL == t->client)
2703     {
2704       /* got data packet for ownerless tunnel */
2705       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2706                 "MESH:   no clients!\n");
2707       GNUNET_break_op (0);
2708       return GNUNET_OK;
2709     }
2710     /* TODO signature verification */
2711     memcpy (cbuf, message, size);
2712     copy = (struct GNUNET_MESH_ToOrigin *) cbuf;
2713     copy->tid = htonl (t->local_tid);
2714     GNUNET_SERVER_notification_context_unicast (nc,
2715                                                 t->client->handle,
2716                                                 &copy->header,
2717                                                 GNUNET_YES);
2718     return GNUNET_OK;
2719   }
2720   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2721               "MESH:   not for us, retransmitting...\n");
2722
2723   peer_info = peer_info_get (&msg->oid);
2724   if (NULL == peer_info)
2725   {
2726     /* unknown origin of tunnel */
2727     GNUNET_break (0);
2728     return GNUNET_OK;
2729   }
2730   GNUNET_PEER_resolve (t->tree->me->parent->peer, &id);
2731   send_message (message, &id);
2732
2733   return GNUNET_OK;
2734 }
2735
2736
2737 /**
2738  * Core handler for path ACKs
2739  *
2740  * @param cls closure
2741  * @param message message
2742  * @param peer peer identity this notification is about
2743  * @param atsi performance data
2744  *
2745  * @return GNUNET_OK to keep the connection open,
2746  *         GNUNET_SYSERR to close it (signal serious error)
2747  */
2748 static int
2749 handle_mesh_path_ack (void *cls, const struct GNUNET_PeerIdentity *peer,
2750                       const struct GNUNET_MessageHeader *message,
2751                       const struct GNUNET_ATS_Information *atsi)
2752 {
2753   struct GNUNET_MESH_PathACK *msg;
2754   struct GNUNET_PeerIdentity id;
2755   struct MeshTunnelTreeNode *n;
2756   struct MeshPeerInfo *peer_info;
2757   struct MeshTunnel *t;
2758
2759   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2760               "MESH: Received a path ACK msg [%s]\n",
2761               GNUNET_i2s(&my_full_id));
2762   msg = (struct GNUNET_MESH_PathACK *) message;
2763   t = tunnel_get (&msg->oid, msg->tid);
2764   if (NULL == t)
2765   {
2766     /* TODO notify that we don't know the tunnel */
2767     return GNUNET_OK;
2768   }
2769
2770   /* Message for us? */
2771   if (0 == memcmp (&msg->oid, &my_full_id, sizeof (struct GNUNET_PeerIdentity)))
2772   {
2773     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   It's for us!\n");
2774     if (NULL == t->client)
2775     {
2776       GNUNET_break_op (0);
2777       return GNUNET_OK;
2778     }
2779     peer_info = peer_info_get (&msg->peer_id);
2780     if (NULL == peer_info)
2781     {
2782       GNUNET_break_op (0);
2783       return GNUNET_OK;
2784     }
2785     n = tree_find_peer(t->tree->root, peer_info->id);
2786     if (NULL == n)
2787     {
2788       GNUNET_break_op (0);
2789       return GNUNET_OK;
2790     }
2791     n->status = MESH_PEER_READY;
2792     send_client_peer_connected(t, peer_info->id);
2793     return GNUNET_OK;
2794   }
2795   
2796   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2797               "MESH:   not for us, retransmitting...\n");
2798   GNUNET_PEER_resolve(t->tree->me->parent->peer, &id);
2799   peer_info = peer_info_get (&msg->oid);
2800   if (NULL == peer_info)
2801   {
2802     /* If we know the tunnel, we should DEFINITELY know the peer */
2803     GNUNET_break (0);
2804     return GNUNET_OK;
2805   }
2806   send_message (message, &id);
2807   return GNUNET_OK;
2808 }
2809
2810
2811 /**
2812  * Functions to handle messages from core
2813  */
2814 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
2815   {&handle_mesh_path_create, GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE, 0},
2816   {&handle_mesh_path_destroy, GNUNET_MESSAGE_TYPE_MESH_PATH_DESTROY, 0},
2817   {&handle_mesh_tunnel_destroy, GNUNET_MESSAGE_TYPE_MESH_TUNNEL_DESTROY, 0},
2818   {&handle_mesh_data_unicast, GNUNET_MESSAGE_TYPE_MESH_UNICAST, 0},
2819   {&handle_mesh_data_multicast, GNUNET_MESSAGE_TYPE_MESH_MULTICAST, 0},
2820   {&handle_mesh_data_to_orig, GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN, 0},
2821   {&handle_mesh_path_ack, GNUNET_MESSAGE_TYPE_MESH_PATH_ACK,
2822    sizeof (struct GNUNET_MESH_PathACK)},
2823   {NULL, 0, 0}
2824 };
2825
2826
2827
2828 /******************************************************************************/
2829 /****************       MESH LOCAL HANDLER HELPERS      ***********************/
2830 /******************************************************************************/
2831
2832 /**
2833  * deregister_app: iterator for removing each application registered by a client
2834  * 
2835  * @param cls closure
2836  * @param key the hash of the application id (used to access the hashmap)
2837  * @param value the value stored at the key (client)
2838  * 
2839  * @return GNUNET_OK on success
2840  */
2841 static int
2842 deregister_app (void *cls, const GNUNET_HashCode * key, void *value)
2843 {
2844   GNUNET_break (GNUNET_YES == 
2845       GNUNET_CONTAINER_multihashmap_remove (applications, key, value));
2846   return GNUNET_OK;
2847 }
2848
2849 #if LATER
2850 /**
2851  * notify_client_connection_failure: notify a client that the connection to the
2852  * requested remote peer is not possible (for instance, no route found)
2853  * Function called when the socket is ready to queue more data. "buf" will be
2854  * NULL and "size" zero if the socket was closed for writing in the meantime.
2855  *
2856  * @param cls closure
2857  * @param size number of bytes available in buf
2858  * @param buf where the callee should write the message
2859  * @return number of bytes written to buf
2860  */
2861 static size_t
2862 notify_client_connection_failure (void *cls, size_t size, void *buf)
2863 {
2864   int size_needed;
2865   struct MeshPeerInfo *peer_info;
2866   struct GNUNET_MESH_PeerControl *msg;
2867   struct GNUNET_PeerIdentity id;
2868
2869   if (0 == size && NULL == buf)
2870   {
2871     // TODO retry? cancel?
2872     return 0;
2873   }
2874
2875   size_needed = sizeof (struct GNUNET_MESH_PeerControl);
2876   peer_info = (struct MeshPeerInfo *) cls;
2877   msg = (struct GNUNET_MESH_PeerControl *) buf;
2878   msg->header.size = htons (sizeof (struct GNUNET_MESH_PeerControl));
2879   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_DISCONNECTED);
2880 //     msg->tunnel_id = htonl(peer_info->t->tid);
2881   GNUNET_PEER_resolve (peer_info->id, &id);
2882   memcpy (&msg->peer, &id, sizeof (struct GNUNET_PeerIdentity));
2883
2884   return size_needed;
2885 }
2886 #endif
2887
2888
2889 /**
2890  * Send keepalive packets for a peer
2891  *
2892  * @param cls Closure (tunnel for which to send the keepalive).
2893  * @param tc Notification context.
2894  *
2895  * TODO: implement explicit multicast keepalive?
2896  */
2897 static void
2898 path_refresh (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2899 {
2900   struct MeshTunnel *t = cls;
2901   struct GNUNET_MessageHeader *payload;
2902   struct GNUNET_MESH_Multicast *msg;
2903   size_t size = sizeof(struct GNUNET_MESH_Multicast) +
2904                 sizeof(struct GNUNET_MessageHeader);
2905   char cbuf[size];
2906
2907   if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
2908   {
2909     return;
2910   }
2911   t->path_refresh_task = GNUNET_SCHEDULER_NO_TASK;
2912
2913   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2914               "MESH: sending keepalive for tunnel %d\n",
2915               t->id.tid);
2916
2917   msg = (struct GNUNET_MESH_Multicast *) cbuf;
2918   msg->header.size = htons (size);
2919   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_MULTICAST);
2920   msg->oid = my_full_id;
2921   msg->tid = htonl(t->id.tid);
2922   payload = (struct GNUNET_MessageHeader *) &msg[1];
2923   payload->size = htons (sizeof(struct GNUNET_MessageHeader));
2924   payload->type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_KEEPALIVE);
2925   tunnel_send_multicast (t, &msg->header);
2926
2927   t->path_refresh_task =
2928       GNUNET_SCHEDULER_add_delayed (t->tree->refresh, &path_refresh, t);
2929   return;
2930 }
2931
2932
2933 /**
2934  * Function to process paths received for a new peer addition. The recorded
2935  * paths form the initial tunnel, which can be optimized later.
2936  * Called on each result obtained for the DHT search.
2937  *
2938  * @param cls closure
2939  * @param exp when will this value expire
2940  * @param key key of the result
2941  * @param type type of the result
2942  * @param size number of bytes in data
2943  * @param data pointer to the result data
2944  *
2945  * TODO: re-issue the request after certain time? cancel after X results?
2946  */
2947 static void
2948 dht_get_id_handler (void *cls, struct GNUNET_TIME_Absolute exp,
2949                     const GNUNET_HashCode * key,
2950                     const struct GNUNET_PeerIdentity *get_path,
2951                     unsigned int get_path_length,
2952                     const struct GNUNET_PeerIdentity *put_path,
2953                     unsigned int put_path_length,
2954                     enum GNUNET_BLOCK_Type type, size_t size, const void *data)
2955 {
2956   struct MeshPathInfo *path_info = cls;
2957   struct MeshPeerPath *p;
2958   struct GNUNET_PeerIdentity pi;
2959   int i;
2960
2961   GNUNET_PEER_resolve (path_info->peer->id, &pi);
2962   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2963              "MESH: Got results from DHT for %s\n",
2964              GNUNET_h2s_full(&pi.hashPubKey));
2965   GNUNET_DHT_get_stop(path_info->peer->dhtget);
2966   path_info->peer->dhtget = NULL;
2967
2968   p = path_build_from_dht (get_path, get_path_length,
2969                            put_path, put_path_length);
2970   path_add_to_peer (path_info->peer, p);
2971   for (i = 0; i < path_info->peer->ntunnels; i++)
2972   {
2973     tunnel_add_peer (path_info->peer->tunnels[i], path_info->peer);
2974     peer_info_connect(path_info->peer, path_info->t);
2975   }
2976   GNUNET_free (path_info);
2977
2978   return;
2979 }
2980
2981
2982 /**
2983  * Function to process paths received for a new peer addition. The recorded
2984  * paths form the initial tunnel, which can be optimized later.
2985  * Called on each result obtained for the DHT search.
2986  *
2987  * @param cls closure
2988  * @param exp when will this value expire
2989  * @param key key of the result
2990  * @param type type of the result
2991  * @param size number of bytes in data
2992  * @param data pointer to the result data
2993  */
2994 static void
2995 dht_get_type_handler (void *cls, struct GNUNET_TIME_Absolute exp,
2996                       const GNUNET_HashCode * key,
2997                       const struct GNUNET_PeerIdentity *get_path,
2998                       unsigned int get_path_length,
2999                       const struct GNUNET_PeerIdentity *put_path,
3000                       unsigned int put_path_length,
3001                       enum GNUNET_BLOCK_Type type, size_t size,
3002                       const void *data)
3003 {
3004   const struct GNUNET_PeerIdentity *pi = data;
3005   struct GNUNET_PeerIdentity id;
3006   struct MeshTunnel *t = cls;
3007   struct MeshPeerInfo *peer_info;
3008   struct MeshPathInfo *path_info;
3009   struct MeshPeerPath *p;
3010   int i;
3011
3012   if (size != sizeof (struct GNUNET_PeerIdentity))
3013   {
3014     GNUNET_break_op (0);
3015     return;
3016   }
3017   GNUNET_assert (NULL != t->client);
3018   GNUNET_DHT_get_stop (t->dht_get_type);
3019   t->dht_get_type = NULL;
3020   peer_info = peer_info_get (pi);
3021   GNUNET_CONTAINER_multihashmap_put (t->peers, &pi->hashPubKey, peer_info,
3022                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
3023
3024   if ((NULL == get_path || NULL == put_path) && NULL == peer_info->path_head &&
3025       NULL == peer_info->dhtget)
3026   {
3027     path_info = GNUNET_malloc (sizeof (struct MeshPathInfo));
3028     path_info->peer = peer_info;
3029     path_info->t = t;
3030     /* we don't have a route to the peer, let's try a direct lookup */
3031     peer_info->dhtget =
3032         GNUNET_DHT_get_start (dht_handle, /* handle */
3033                               GNUNET_TIME_UNIT_FOREVER_REL, /* timeout */
3034                               GNUNET_BLOCK_TYPE_TEST, /* block type */
3035                               &pi->hashPubKey, /* key to look up */
3036                               10U, /* replication level */
3037                               GNUNET_DHT_RO_RECORD_ROUTE |
3038                                 GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE,
3039                               /* option to dht: record route */
3040                               NULL,     /* xquery */
3041                               0,        /* xquery bits */
3042                               dht_get_id_handler,  /* callback */
3043                               path_info);       /* closure */
3044     return;
3045   }
3046
3047   p = path_build_from_dht (get_path, get_path_length, put_path, put_path_length);
3048   path_add_to_peer (peer_info, p);
3049   tunnel_add_peer(t, peer_info);
3050   p = tree_get_path_to_peer(t->tree, peer_info->id);
3051 #if MESH_DEBUG
3052   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3053               "MESH: new route for tunnel 0x%x found, has %u hops\n",
3054               t->local_tid, p->length);
3055   for (i = 0; i < p->length; i++)
3056   {
3057     GNUNET_PEER_resolve (p->peers[0], &id);
3058     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:\t%d\t%s\n", i,
3059                 GNUNET_h2s_full (&id.hashPubKey));
3060   }
3061 #endif
3062
3063   if (p->length > 1)
3064   {
3065     send_create_path(peer_info, p, t);
3066     return;
3067   }
3068   path_destroy(p);
3069   send_client_peer_connected(t, myid);
3070 }
3071
3072
3073 /******************************************************************************/
3074 /*********************       MESH LOCAL HANDLES      **************************/
3075 /******************************************************************************/
3076
3077
3078 /**
3079  * Handler for client disconnection
3080  *
3081  * @param cls closure
3082  * @param client identification of the client; NULL
3083  *        for the last call when the server is destroyed
3084  */
3085 static void
3086 handle_local_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
3087 {
3088   struct MeshClient *c;
3089   struct MeshClient *next;
3090
3091   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: client disconnected\n");
3092   if (client == NULL)
3093      GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:    (SERVER DOWN)\n");
3094   c = clients;
3095   while (NULL != c)
3096   {
3097     if (c->handle != client && NULL != client)
3098     {
3099       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:    ... searching\n");
3100       c = c->next;
3101       continue;
3102     }
3103     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: matching client found\n");
3104     if (NULL != c->tunnels)
3105     {
3106       GNUNET_CONTAINER_multihashmap_iterate (c->tunnels,
3107                                              &tunnel_destroy_iterator,
3108                                              c);
3109       GNUNET_CONTAINER_multihashmap_destroy (c->tunnels);
3110     }
3111
3112     /* deregister clients applications */
3113     if (NULL != c->apps)
3114     {
3115       GNUNET_CONTAINER_multihashmap_iterate (c->apps, &deregister_app, NULL);
3116       GNUNET_CONTAINER_multihashmap_destroy (c->apps);
3117     }
3118     if (0 == GNUNET_CONTAINER_multihashmap_size (applications) &&
3119         GNUNET_SCHEDULER_NO_TASK != announce_applications_task)
3120     {
3121       GNUNET_SCHEDULER_cancel (announce_applications_task);
3122       announce_applications_task = GNUNET_SCHEDULER_NO_TASK;
3123     }
3124     if (NULL != c->types)
3125       GNUNET_CONTAINER_multihashmap_destroy (c->types);
3126     GNUNET_CONTAINER_DLL_remove (clients, clients_tail, c);
3127     next = c->next;
3128     GNUNET_free (c);
3129     c = next;
3130   }
3131
3132   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:    done!\n");
3133   return;
3134 }
3135
3136
3137 /**
3138  * Handler for new clients
3139  *
3140  * @param cls closure
3141  * @param client identification of the client
3142  * @param message the actual message, which includes messages the client wants
3143  */
3144 static void
3145 handle_local_new_client (void *cls, struct GNUNET_SERVER_Client *client,
3146                          const struct GNUNET_MessageHeader *message)
3147 {
3148   struct GNUNET_MESH_ClientConnect *cc_msg;
3149   struct MeshClient *c;
3150   GNUNET_MESH_ApplicationType *a;
3151   unsigned int size;
3152   uint16_t ntypes;
3153   uint16_t *t;
3154   uint16_t napps;
3155   uint16_t i;
3156
3157   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: new client connected\n");
3158   /* Check data sanity */
3159   size = ntohs (message->size) - sizeof (struct GNUNET_MESH_ClientConnect);
3160   cc_msg = (struct GNUNET_MESH_ClientConnect *) message;
3161   ntypes = ntohs (cc_msg->types);
3162   napps = ntohs (cc_msg->applications);
3163   if (size !=
3164       ntypes * sizeof (uint16_t) + napps * sizeof (GNUNET_MESH_ApplicationType))
3165   {
3166     GNUNET_break (0);
3167     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3168     return;
3169   }
3170
3171   /* Create new client structure */
3172   c = GNUNET_malloc (sizeof (struct MeshClient));
3173 #if MESH_DEBUG
3174   c->id = next_client_id++;
3175 #endif
3176   c->handle = client;
3177   a = (GNUNET_MESH_ApplicationType *) &cc_msg[1];
3178   if (napps > 0)
3179   {
3180     GNUNET_MESH_ApplicationType at;
3181     GNUNET_HashCode hc;
3182
3183     c->apps = GNUNET_CONTAINER_multihashmap_create (napps);
3184     for (i = 0; i < napps; i++)
3185     {
3186       at = ntohl (a[i]);
3187       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   app type: %u\n", at);
3188       GNUNET_CRYPTO_hash (&at, sizeof (at), &hc);
3189       /* store in clients hashmap */
3190       GNUNET_CONTAINER_multihashmap_put (c->apps, &hc, c,
3191                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
3192       /* store in global hashmap, for announcements */
3193       GNUNET_CONTAINER_multihashmap_put (applications, &hc, c,
3194                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
3195     }
3196     if (GNUNET_SCHEDULER_NO_TASK == announce_applications_task)
3197       announce_applications_task =
3198           GNUNET_SCHEDULER_add_now (&announce_applications, NULL);
3199
3200   }
3201   if (ntypes > 0)
3202   {
3203     uint16_t u16;
3204     GNUNET_HashCode hc;
3205
3206     t = (uint16_t *) & a[napps];
3207     c->types = GNUNET_CONTAINER_multihashmap_create (ntypes);
3208     for (i = 0; i < ntypes; i++)
3209     {
3210       u16 = ntohs (t[i]);
3211       GNUNET_CRYPTO_hash (&u16, sizeof (u16), &hc);
3212
3213       /* store in clients hashmap */
3214       GNUNET_CONTAINER_multihashmap_put (c->types, &hc, c,
3215                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
3216       /* store in global hashmap */
3217       GNUNET_CONTAINER_multihashmap_put (types, &hc, c,
3218                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
3219     }
3220   }
3221   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3222               "MESH:  client has %u+%u subscriptions\n", napps, ntypes);
3223
3224   GNUNET_CONTAINER_DLL_insert (clients, clients_tail, c);
3225   c->tunnels = GNUNET_CONTAINER_multihashmap_create (32);
3226   GNUNET_SERVER_notification_context_add (nc, client);
3227
3228   GNUNET_SERVER_receive_done (client, GNUNET_OK);
3229 #if MESH_DEBUG
3230   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: new client processed\n");
3231 #endif
3232 }
3233
3234
3235 /**
3236  * Handler for requests of new tunnels
3237  *
3238  * @param cls closure
3239  * @param client identification of the client
3240  * @param message the actual message
3241  */
3242 static void
3243 handle_local_tunnel_create (void *cls, struct GNUNET_SERVER_Client *client,
3244                             const struct GNUNET_MessageHeader *message)
3245 {
3246   struct GNUNET_MESH_TunnelMessage *t_msg;
3247   struct MeshTunnel *t;
3248   struct MeshClient *c;
3249   GNUNET_HashCode hash;
3250
3251   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: new tunnel requested\n");
3252
3253   /* Sanity check for client registration */
3254   if (NULL == (c = client_get (client)))
3255   {
3256     GNUNET_break (0);
3257     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3258     return;
3259   }
3260 #if MESH_DEBUG
3261   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   by client %u\n", c->id);
3262 #endif
3263
3264   /* Message sanity check */
3265   if (sizeof (struct GNUNET_MESH_TunnelMessage) != ntohs (message->size))
3266   {
3267     GNUNET_break (0);
3268     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3269     return;
3270   }
3271
3272   t_msg = (struct GNUNET_MESH_TunnelMessage *) message;
3273   /* Sanity check for tunnel numbering */
3274   if (0 == (ntohl (t_msg->tunnel_id) & GNUNET_MESH_LOCAL_TUNNEL_ID_CLI))
3275   {
3276     GNUNET_break (0);
3277     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3278     return;
3279   }
3280   /* Sanity check for duplicate tunnel IDs */
3281   if (NULL != tunnel_get_by_local_id (c, ntohl (t_msg->tunnel_id)))
3282   {
3283     GNUNET_break (0);
3284     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3285     return;
3286   }
3287
3288   t = GNUNET_malloc (sizeof (struct MeshTunnel));
3289   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: CREATED TUNNEL at %p\n", t);
3290   while (NULL != tunnel_get_by_pi (myid, next_tid))
3291     next_tid = (next_tid + 1) & ~GNUNET_MESH_LOCAL_TUNNEL_ID_CLI;
3292   t->id.tid = next_tid++;
3293   t->id.oid = myid;
3294   t->local_tid = ntohl (t_msg->tunnel_id);
3295   t->client = c;
3296   t->peers = GNUNET_CONTAINER_multihashmap_create (32);
3297
3298   GNUNET_CRYPTO_hash (&t->local_tid, sizeof (MESH_TunnelNumber), &hash);
3299   if (GNUNET_OK !=
3300       GNUNET_CONTAINER_multihashmap_put (c->tunnels, &hash, t,
3301                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
3302   {
3303     GNUNET_break (0);
3304     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3305     return;
3306   }
3307
3308   GNUNET_CRYPTO_hash (&t->id, sizeof (struct MESH_TunnelID), &hash);
3309   if (GNUNET_OK !=
3310       GNUNET_CONTAINER_multihashmap_put (tunnels, &hash, t,
3311                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
3312   {
3313     GNUNET_break (0);
3314     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3315     return;
3316   }
3317   t->tree = tree_new (t, myid);
3318   t->tree->refresh = REFRESH_PATH_TIME;
3319   t->tree->root->status = MESH_PEER_READY;
3320   t->tree->me = t->tree->root;
3321
3322   GNUNET_SERVER_receive_done (client, GNUNET_OK);
3323   return;
3324 }
3325
3326
3327 /**
3328  * Handler for requests of deleting tunnels
3329  *
3330  * @param cls closure
3331  * @param client identification of the client
3332  * @param message the actual message
3333  */
3334 static void
3335 handle_local_tunnel_destroy (void *cls, struct GNUNET_SERVER_Client *client,
3336                              const struct GNUNET_MessageHeader *message)
3337 {
3338   struct GNUNET_MESH_TunnelMessage *tunnel_msg;
3339   struct MeshClient *c;
3340   struct MeshTunnel *t;
3341   MESH_TunnelNumber tid;
3342   GNUNET_HashCode hash;
3343
3344   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: destroying tunnel\n");
3345
3346   /* Sanity check for client registration */
3347   if (NULL == (c = client_get (client)))
3348   {
3349     GNUNET_break (0);
3350     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3351     return;
3352   }
3353   /* Message sanity check */
3354   if (sizeof (struct GNUNET_MESH_TunnelMessage) != ntohs (message->size))
3355   {
3356     GNUNET_break (0);
3357     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3358     return;
3359   }
3360 #if MESH_DEBUG
3361   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   by client %u\n", c->id);
3362 #endif
3363   tunnel_msg = (struct GNUNET_MESH_TunnelMessage *) message;
3364
3365   /* Retrieve tunnel */
3366   tid = ntohl (tunnel_msg->tunnel_id);
3367
3368   /* Remove from local id hashmap */
3369   GNUNET_CRYPTO_hash (&tid, sizeof (MESH_TunnelNumber), &hash);
3370   t = GNUNET_CONTAINER_multihashmap_get (c->tunnels, &hash);
3371   GNUNET_CONTAINER_multihashmap_remove (c->tunnels, &hash, t);
3372
3373   t->client = NULL;
3374   tunnel_send_destroy (t);
3375   tunnel_destroy(t);
3376   GNUNET_SERVER_receive_done (client, GNUNET_OK);
3377   return;
3378 }
3379
3380
3381 /**
3382  * Handler for connection requests to new peers
3383  *
3384  * @param cls closure
3385  * @param client identification of the client
3386  * @param message the actual message (PeerControl)
3387  */
3388 static void
3389 handle_local_connect_add (void *cls, struct GNUNET_SERVER_Client *client,
3390                           const struct GNUNET_MessageHeader *message)
3391 {
3392   struct GNUNET_MESH_PeerControl *peer_msg;
3393   struct MeshPeerInfo *peer_info;
3394   struct MeshClient *c;
3395   struct MeshTunnel *t;
3396   MESH_TunnelNumber tid;
3397
3398   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "MESH: Got connection request\n");
3399   /* Sanity check for client registration */
3400   if (NULL == (c = client_get (client)))
3401   {
3402     GNUNET_break (0);
3403     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3404     return;
3405   }
3406
3407   peer_msg = (struct GNUNET_MESH_PeerControl *) message;
3408   /* Sanity check for message size */
3409   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (peer_msg->header.size))
3410   {
3411     GNUNET_break (0);
3412     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3413     return;
3414   }
3415
3416   /* Tunnel exists? */
3417   tid = ntohl (peer_msg->tunnel_id);
3418   t = tunnel_get_by_local_id (c, tid);
3419   if (NULL == t)
3420   {
3421     GNUNET_break (0);
3422     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3423     return;
3424   }
3425
3426   /* Does client own tunnel? */
3427   if (t->client->handle != client)
3428   {
3429     GNUNET_break (0);
3430     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3431     return;
3432   }
3433   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "MESH:      for %s\n",
3434              GNUNET_h2s_full(&peer_msg->peer.hashPubKey));
3435   peer_info = peer_info_get (&peer_msg->peer);
3436
3437   tunnel_add_peer(t, peer_info);
3438   peer_info_connect(peer_info, t);
3439
3440   GNUNET_SERVER_receive_done (client, GNUNET_OK);
3441   return;
3442 }
3443
3444
3445 /**
3446  * Handler for disconnection requests of peers in a tunnel
3447  *
3448  * @param cls closure
3449  * @param client identification of the client
3450  * @param message the actual message (PeerControl)
3451  */
3452 static void
3453 handle_local_connect_del (void *cls, struct GNUNET_SERVER_Client *client,
3454                           const struct GNUNET_MessageHeader *message)
3455 {
3456   struct GNUNET_MESH_PeerControl *peer_msg;
3457   struct MeshClient *c;
3458   struct MeshTunnel *t;
3459   MESH_TunnelNumber tid;
3460
3461   /* Sanity check for client registration */
3462   if (NULL == (c = client_get (client)))
3463   {
3464     GNUNET_break (0);
3465     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3466     return;
3467   }
3468   peer_msg = (struct GNUNET_MESH_PeerControl *) message;
3469   /* Sanity check for message size */
3470   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (peer_msg->header.size))
3471   {
3472     GNUNET_break (0);
3473     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3474     return;
3475   }
3476
3477   /* Tunnel exists? */
3478   tid = ntohl (peer_msg->tunnel_id);
3479   t = tunnel_get_by_local_id (c, tid);
3480   if (NULL == t)
3481   {
3482     GNUNET_break (0);
3483     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3484     return;
3485   }
3486
3487   /* Does client own tunnel? */
3488   if (t->client->handle != client)
3489   {
3490     GNUNET_break (0);
3491     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3492     return;
3493   }
3494
3495   /* Ok, delete peer from tunnel */
3496   GNUNET_CONTAINER_multihashmap_remove_all (t->peers,
3497                                             &peer_msg->peer.hashPubKey);
3498
3499   GNUNET_SERVER_receive_done (client, GNUNET_OK);
3500   return;
3501 }
3502
3503
3504 /**
3505  * Handler for connection requests to new peers by type
3506  *
3507  * @param cls closure
3508  * @param client identification of the client
3509  * @param message the actual message (ConnectPeerByType)
3510  */
3511 static void
3512 handle_local_connect_by_type (void *cls, struct GNUNET_SERVER_Client *client,
3513                               const struct GNUNET_MessageHeader *message)
3514 {
3515   struct GNUNET_MESH_ConnectPeerByType *connect_msg;
3516   struct MeshClient *c;
3517   struct MeshTunnel *t;
3518   GNUNET_HashCode hash;
3519   MESH_TunnelNumber tid;
3520
3521   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: got connect by type request\n");
3522   /* Sanity check for client registration */
3523   if (NULL == (c = client_get (client)))
3524   {
3525     GNUNET_break (0);
3526     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3527     return;
3528   }
3529
3530   connect_msg = (struct GNUNET_MESH_ConnectPeerByType *) message;
3531   /* Sanity check for message size */
3532   if (sizeof (struct GNUNET_MESH_ConnectPeerByType) !=
3533       ntohs (connect_msg->header.size))
3534   {
3535     GNUNET_break (0);
3536     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3537     return;
3538   }
3539
3540   /* Tunnel exists? */
3541   tid = ntohl (connect_msg->tunnel_id);
3542   t = tunnel_get_by_local_id (c, tid);
3543   if (NULL == t)
3544   {
3545     GNUNET_break (0);
3546     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3547     return;
3548   }
3549
3550   /* Does client own tunnel? */
3551   if (t->client->handle != client)
3552   {
3553     GNUNET_break (0);
3554     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3555     return;
3556   }
3557
3558   /* Do WE have the service? */
3559   t->type = ntohl (connect_msg->type);
3560   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:  type requested: %u\n", t->type);
3561   GNUNET_CRYPTO_hash (&t->type, sizeof (GNUNET_MESH_ApplicationType), &hash);
3562   if (GNUNET_CONTAINER_multihashmap_contains (applications, &hash) ==
3563       GNUNET_YES)
3564   {
3565     /* Yes! Fast forward, add ourselves to the tunnel and send the
3566      * good news to the client
3567      */
3568     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:  available locally\n");
3569     GNUNET_CONTAINER_multihashmap_put (t->peers, &my_full_id.hashPubKey,
3570                                        peer_info_get (&my_full_id),
3571                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
3572
3573     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:  notifying client\n");
3574     send_client_peer_connected(t, myid);
3575     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:  Done\n");
3576     GNUNET_SERVER_receive_done (client, GNUNET_OK);
3577     return;
3578   }
3579   /* Ok, lets find a peer offering the service */
3580   if (NULL != t->dht_get_type)
3581   {
3582     GNUNET_DHT_get_stop (t->dht_get_type);
3583   }
3584   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:  looking in DHT for %s\n",
3585               GNUNET_h2s_full (&hash));
3586   t->dht_get_type =
3587       GNUNET_DHT_get_start (dht_handle,
3588                             GNUNET_TIME_UNIT_FOREVER_REL,
3589                             GNUNET_BLOCK_TYPE_TEST,
3590                             &hash,
3591                             10U,
3592                             GNUNET_DHT_RO_RECORD_ROUTE |
3593                               GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE,
3594                             NULL, 0,
3595                             &dht_get_type_handler, t);
3596
3597   GNUNET_SERVER_receive_done (client, GNUNET_OK);
3598   return;
3599 }
3600
3601
3602 /**
3603  * Handler for client traffic directed to one peer
3604  *
3605  * @param cls closure
3606  * @param client identification of the client
3607  * @param message the actual message
3608  */
3609 static void
3610 handle_local_unicast (void *cls, struct GNUNET_SERVER_Client *client,
3611                       const struct GNUNET_MessageHeader *message)
3612 {
3613   struct MeshClient *c;
3614   struct MeshTunnel *t;
3615   struct MeshPeerInfo *pi;
3616   struct GNUNET_MESH_Unicast *data_msg;
3617   MESH_TunnelNumber tid;
3618   size_t size;
3619
3620   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3621               "MESH: Got a unicast request from a client!\n");
3622
3623   /* Sanity check for client registration */
3624   if (NULL == (c = client_get (client)))
3625   {
3626     GNUNET_break (0);
3627     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3628     return;
3629   }
3630   data_msg = (struct GNUNET_MESH_Unicast *) message;
3631   /* Sanity check for message size */
3632   size = ntohs (message->size);
3633   if (sizeof (struct GNUNET_MESH_Unicast) +
3634       sizeof (struct GNUNET_MessageHeader) > size)
3635   {
3636     GNUNET_break (0);
3637     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3638     return;
3639   }
3640
3641   /* Tunnel exists? */
3642   tid = ntohl (data_msg->tid);
3643   t = tunnel_get_by_local_id (c, tid);
3644   if (NULL == t)
3645   {
3646     GNUNET_break (0);
3647     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3648     return;
3649   }
3650
3651   /*  Is it a local tunnel? Then, does client own the tunnel? */
3652   if (NULL != t->client &&
3653       NULL != t->client->handle &&
3654       t->client->handle != client)
3655   {
3656     GNUNET_break (0);
3657     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3658     return;
3659   }
3660
3661   pi = GNUNET_CONTAINER_multihashmap_get (t->peers,
3662                                           &data_msg->destination.hashPubKey);
3663   /* Is the selected peer in the tunnel? */
3664   if (NULL == pi)
3665   {
3666     GNUNET_break (0);
3667     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3668     return;
3669   }
3670
3671   /* Ok, everything is correct, send the message
3672    * (pretend we got it from a mesh peer)
3673    */
3674   {
3675     char buf[ntohs (message->size)];
3676     struct GNUNET_MESH_Unicast *copy;
3677
3678     /* Work around const limitation */
3679     copy = (struct GNUNET_MESH_Unicast *) buf;
3680     memcpy (buf, data_msg, size);
3681     copy->oid = my_full_id;
3682     copy->tid = htonl (t->id.tid);
3683     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3684                 "MESH:   calling generic handler...\n");
3685     handle_mesh_data_unicast (NULL, &my_full_id, &copy->header, NULL);
3686   }
3687   GNUNET_SERVER_receive_done (client, GNUNET_OK);
3688   return;
3689 }
3690
3691
3692 /**
3693  * Handler for client traffic directed to the origin
3694  *
3695  * @param cls closure
3696  * @param client identification of the client
3697  * @param message the actual message
3698  */
3699 static void
3700 handle_local_to_origin (void *cls, struct GNUNET_SERVER_Client *client,
3701                         const struct GNUNET_MessageHeader *message)
3702 {
3703   struct GNUNET_MESH_ToOrigin *data_msg;
3704   struct GNUNET_PeerIdentity id;
3705   struct MeshClient *c;
3706   struct MeshTunnel *t;
3707   MESH_TunnelNumber tid;
3708   size_t size;
3709
3710   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3711               "MESH: Got a ToOrigin request from a client!\n");
3712
3713   /* Sanity check for client registration */
3714   if (NULL == (c = client_get (client)))
3715   {
3716     GNUNET_break (0);
3717     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3718     return;
3719   }
3720   data_msg = (struct GNUNET_MESH_ToOrigin *) message;
3721   /* Sanity check for message size */
3722   size = ntohs (message->size);
3723   if (sizeof (struct GNUNET_MESH_ToOrigin) +
3724       sizeof (struct GNUNET_MessageHeader) > size)
3725   {
3726     GNUNET_break (0);
3727     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3728     return;
3729   }
3730
3731   /* Tunnel exists? */
3732   tid = ntohl (data_msg->tid);
3733   if (tid < GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
3734   {
3735     GNUNET_break (0);
3736     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3737     return;
3738   }
3739   t = tunnel_get_by_local_id (c, tid);
3740   if (NULL == t)
3741   {
3742     GNUNET_break (0);
3743     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3744     return;
3745   }
3746
3747   /*  It shouldn't be a local tunnel.  */
3748   if (NULL != t->client)
3749   {
3750     GNUNET_break (0);
3751     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3752     return;
3753   }
3754   GNUNET_PEER_resolve(t->id.oid, &id);
3755
3756   /* Ok, everything is correct, send the message
3757    * (pretend we got it from a mesh peer)
3758    */
3759   {
3760     char buf[ntohs (message->size)];
3761     struct GNUNET_MESH_ToOrigin *copy;
3762
3763     /* Work around const limitation */
3764     copy = (struct GNUNET_MESH_ToOrigin *) buf;
3765     memcpy (buf, data_msg, size);
3766     copy->oid = id;
3767     copy->tid = htonl (t->id.tid);
3768     copy->sender = my_full_id;
3769     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3770                 "MESH:   calling generic handler...\n");
3771     handle_mesh_data_to_orig (NULL, &my_full_id, &copy->header, NULL);
3772   }
3773   GNUNET_SERVER_receive_done (client, GNUNET_OK);
3774   return;
3775 }
3776
3777
3778 /**
3779  * Handler for client traffic directed to all peers in a tunnel
3780  *
3781  * @param cls closure
3782  * @param client identification of the client
3783  * @param message the actual message
3784  */
3785 static void
3786 handle_local_multicast (void *cls, struct GNUNET_SERVER_Client *client,
3787                         const struct GNUNET_MessageHeader *message)
3788 {
3789   struct MeshClient *c;
3790   struct MeshTunnel *t;
3791   struct GNUNET_MESH_Multicast *data_msg;
3792   MESH_TunnelNumber tid;
3793
3794   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3795               "MESH: Got a multicast request from a client!\n");
3796
3797   /* Sanity check for client registration */
3798   if (NULL == (c = client_get (client)))
3799   {
3800     GNUNET_break (0);
3801     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3802     return;
3803   }
3804   data_msg = (struct GNUNET_MESH_Multicast *) message;
3805   /* Sanity check for message size */
3806   if (sizeof (struct GNUNET_MESH_Multicast) +
3807       sizeof (struct GNUNET_MessageHeader) > ntohs (data_msg->header.size))
3808   {
3809     GNUNET_break (0);
3810     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3811     return;
3812   }
3813
3814   /* Tunnel exists? */
3815   tid = ntohl (data_msg->tid);
3816   t = tunnel_get_by_local_id (c, tid);
3817   if (NULL == t)
3818   {
3819     GNUNET_break (0);
3820     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3821     return;
3822   }
3823
3824   /* Does client own tunnel? */
3825   if (t->client->handle != client)
3826   {
3827     GNUNET_break (0);
3828     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3829     return;
3830   }
3831
3832   {
3833     char buf[ntohs(message->size)];
3834     struct GNUNET_MESH_Multicast *copy;
3835
3836     copy = (struct GNUNET_MESH_Multicast *)buf;
3837     memcpy(buf, message, ntohs(message->size));
3838     copy->oid = my_full_id;
3839     copy->tid = htonl(t->id.tid);
3840     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3841                 "MESH:   calling generic handler...\n");
3842     handle_mesh_data_multicast(client, &my_full_id, &copy->header, NULL);
3843   }
3844
3845   /* receive done gets called when last copy is sent to a neighbor */
3846   return;
3847 }
3848
3849 /**
3850  * Functions to handle messages from clients
3851  */
3852 static struct GNUNET_SERVER_MessageHandler client_handlers[] = {
3853   {&handle_local_new_client, NULL,
3854    GNUNET_MESSAGE_TYPE_MESH_LOCAL_CONNECT, 0},
3855   {&handle_local_tunnel_create, NULL,
3856    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_CREATE,
3857    sizeof (struct GNUNET_MESH_TunnelMessage)},
3858   {&handle_local_tunnel_destroy, NULL,
3859    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_DESTROY,
3860    sizeof (struct GNUNET_MESH_TunnelMessage)},
3861   {&handle_local_connect_add, NULL,
3862    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD,
3863    sizeof (struct GNUNET_MESH_PeerControl)},
3864   {&handle_local_connect_del, NULL,
3865    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_DEL,
3866    sizeof (struct GNUNET_MESH_PeerControl)},
3867   {&handle_local_connect_by_type, NULL,
3868    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD_BY_TYPE,
3869    sizeof (struct GNUNET_MESH_ConnectPeerByType)},
3870   {&handle_local_unicast, NULL,
3871    GNUNET_MESSAGE_TYPE_MESH_UNICAST, 0},
3872   {&handle_local_to_origin, NULL,
3873    GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN, 0},
3874   {&handle_local_multicast, NULL,
3875    GNUNET_MESSAGE_TYPE_MESH_MULTICAST, 0},
3876   {NULL, NULL, 0, 0}
3877 };
3878
3879
3880 /**
3881  * To be called on core init/fail.
3882  *
3883  * @param cls service closure
3884  * @param server handle to the server for this service
3885  * @param identity the public identity of this peer
3886  */
3887 static void
3888 core_init (void *cls, struct GNUNET_CORE_Handle *server,
3889            const struct GNUNET_PeerIdentity *identity)
3890 {
3891   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: Core init\n");
3892   core_handle = server;
3893   if (0 != memcmp(identity, &my_full_id, sizeof(my_full_id)) || NULL == server)
3894   {
3895     GNUNET_log(GNUNET_ERROR_TYPE_ERROR, _("MESH: Wrong CORE service\n"));
3896     GNUNET_SCHEDULER_shutdown();   
3897   }
3898   return;
3899 }
3900
3901 /**
3902  * Method called whenever a given peer connects.
3903  *
3904  * @param cls closure
3905  * @param peer peer identity this notification is about
3906  * @param atsi performance data for the connection
3907  */
3908 static void
3909 core_connect (void *cls, const struct GNUNET_PeerIdentity *peer,
3910               const struct GNUNET_ATS_Information *atsi)
3911 {
3912   struct MeshPeerInfo *peer_info;
3913   struct MeshPeerPath *path;
3914
3915 #if MESH_DEBUG_CONNECTION
3916   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: Peer connected\n");
3917   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:      %s\n",
3918               GNUNET_h2s(&my_full_id.hashPubKey));
3919 #endif
3920   peer_info = peer_info_get (peer);
3921   if (myid == peer_info->id)
3922   {
3923 #if MESH_DEBUG_CONNECTION
3924     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:      (self)\n");
3925 #endif
3926     return;
3927   }
3928 #if MESH_DEBUG_CONNECTION
3929   else
3930   {
3931     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:      %s\n",
3932                 GNUNET_h2s(&peer->hashPubKey));
3933   }
3934 #endif
3935   path = path_new (2);
3936   path->peers[0] = myid;
3937   path->peers[1] = peer_info->id;
3938   GNUNET_PEER_change_rc(myid, 1);
3939   GNUNET_PEER_change_rc(peer_info->id, 1);
3940   path_add_to_peer (peer_info, path);
3941   return;
3942 }
3943
3944 /**
3945  * Method called whenever a peer disconnects.
3946  *
3947  * @param cls closure
3948  * @param peer peer identity this notification is about
3949  */
3950 static void
3951 core_disconnect (void *cls, const struct GNUNET_PeerIdentity *peer)
3952 {
3953   struct MeshPeerInfo *pi;
3954   unsigned int i;
3955
3956 #if MESH_DEBUG_CONNECTION
3957   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: Peer disconnected\n");
3958 #endif
3959   pi = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
3960   if (NULL == pi)
3961   {
3962     GNUNET_break (0);
3963     return;
3964   }
3965   for (i = 0; i < CORE_QUEUE_SIZE; i++)
3966   {
3967     peer_info_cancel_transmission(pi, i);
3968   }
3969   path_remove_from_peer (pi, pi->id, myid);
3970 #if MESH_DEBUG_CONNECTION
3971   if (myid == pi->id)
3972   {
3973     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:      (self)\n");
3974   }
3975 #endif
3976   return;
3977 }
3978
3979
3980 /******************************************************************************/
3981 /************************      MAIN FUNCTIONS      ****************************/
3982 /******************************************************************************/
3983
3984 /**
3985  * Iterator over hash map entries.
3986  *
3987  * @param cls closure
3988  * @param key current key code
3989  * @param value value in the hash map
3990  * @return GNUNET_YES if we should continue to
3991  *         iterate,
3992  *         GNUNET_NO if not.
3993  */
3994 int
3995 shutdown_tunnel (void *cls, const GNUNET_HashCode * key, void *value)
3996 {
3997   struct MeshTunnel *t = value;
3998   tunnel_destroy(t);
3999   return GNUNET_YES;
4000 }
4001
4002 /**
4003  * Task run during shutdown.
4004  *
4005  * @param cls unused
4006  * @param tc unused
4007  */
4008 static void
4009 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
4010 {
4011   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: shutting down\n");
4012   /* TODO: destroy tunnels? */
4013   if (core_handle != NULL)
4014   {
4015     GNUNET_CORE_disconnect (core_handle);
4016     core_handle = NULL;
4017   }
4018   GNUNET_CONTAINER_multihashmap_iterate(tunnels, &shutdown_tunnel, NULL);
4019   if (dht_handle != NULL)
4020   {
4021     GNUNET_DHT_disconnect (dht_handle);
4022     dht_handle = NULL;
4023   }
4024   if (nc != NULL)
4025   {
4026     GNUNET_SERVER_notification_context_destroy (nc);
4027     nc = NULL;
4028   }
4029   if (GNUNET_SCHEDULER_NO_TASK != announce_id_task)
4030   {
4031     GNUNET_SCHEDULER_cancel (announce_id_task);
4032     announce_id_task = GNUNET_SCHEDULER_NO_TASK;
4033   }
4034   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: shut down\n");
4035 }
4036
4037 /**
4038  * Process mesh requests.
4039  *
4040  * @param cls closure
4041  * @param server the initialized server
4042  * @param c configuration to use
4043  */
4044 static void
4045 run (void *cls, struct GNUNET_SERVER_Handle *server,
4046      const struct GNUNET_CONFIGURATION_Handle *c)
4047 {
4048   struct MeshPeerInfo *peer;
4049   struct MeshPeerPath *p;
4050   char *keyfile;
4051
4052   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: starting to run\n");
4053   server_handle = server;
4054   core_handle = GNUNET_CORE_connect (c, /* Main configuration */
4055                                      CORE_QUEUE_SIZE,   /* queue size */
4056                                      NULL,      /* Closure passed to MESH functions */
4057                                      &core_init,        /* Call core_init once connected */
4058                                      &core_connect,     /* Handle connects */
4059                                      &core_disconnect,  /* remove peers on disconnects */
4060                                      NULL,      /* Don't notify about all incoming messages */
4061                                      GNUNET_NO, /* For header only in notification */
4062                                      NULL,      /* Don't notify about all outbound messages */
4063                                      GNUNET_NO, /* For header-only out notification */
4064                                      core_handlers);    /* Register these handlers */
4065   if (core_handle == NULL)
4066   {
4067     GNUNET_break (0);
4068     GNUNET_SCHEDULER_shutdown ();
4069     return;
4070   }
4071
4072   if (GNUNET_OK !=
4073        GNUNET_CONFIGURATION_get_value_filename (c, "GNUNETD", "HOSTKEY",
4074                                                 &keyfile))
4075   {
4076     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
4077                 _
4078                 ("Mesh service is lacking key configuration settings.  Exiting.\n"));
4079     GNUNET_SCHEDULER_shutdown ();
4080     return;
4081   }
4082   my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
4083   GNUNET_free (keyfile);
4084   if (my_private_key == NULL)
4085   {
4086     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
4087                 _("Mesh service could not access hostkey.  Exiting.\n"));
4088     GNUNET_SCHEDULER_shutdown ();
4089     return;
4090   }
4091   GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
4092   GNUNET_CRYPTO_hash (&my_public_key, sizeof (my_public_key),
4093                       &my_full_id.hashPubKey);
4094   myid = GNUNET_PEER_intern (&my_full_id);
4095
4096   dht_handle = GNUNET_DHT_connect (c, 64);
4097   if (dht_handle == NULL)
4098   {
4099     GNUNET_break (0);
4100   }
4101
4102   next_tid = 0;
4103   next_local_tid = GNUNET_MESH_LOCAL_TUNNEL_ID_SERV;
4104
4105   tunnels = GNUNET_CONTAINER_multihashmap_create (32);
4106   incoming_tunnels = GNUNET_CONTAINER_multihashmap_create (32);
4107   peers = GNUNET_CONTAINER_multihashmap_create (32);
4108   applications = GNUNET_CONTAINER_multihashmap_create (32);
4109   types = GNUNET_CONTAINER_multihashmap_create (32);
4110
4111   GNUNET_SERVER_add_handlers (server_handle, client_handlers);
4112   nc = GNUNET_SERVER_notification_context_create (server_handle,
4113                                                   LOCAL_QUEUE_SIZE);
4114   GNUNET_SERVER_disconnect_notify (server_handle,
4115                                    &handle_local_client_disconnect,
4116                                    NULL);
4117
4118
4119   clients = NULL;
4120   clients_tail = NULL;
4121 #if MESH_DEBUG
4122   next_client_id = 0;
4123 #endif
4124
4125   announce_applications_task = GNUNET_SCHEDULER_NO_TASK;
4126   announce_id_task = GNUNET_SCHEDULER_add_now (&announce_id, cls);
4127
4128   /* Create a peer_info for the local peer */
4129   peer = peer_info_get(&my_full_id);
4130   p = path_new (1);
4131   p->peers[0] = myid;
4132   path_add_to_peer(peer, p);
4133
4134   /* Scheduled the task to clean up when shutdown is called */
4135   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
4136                                 NULL);
4137
4138   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: end of run()\n");
4139 }
4140
4141 /**
4142  * The main function for the mesh service.
4143  *
4144  * @param argc number of arguments from the command line
4145  * @param argv command line arguments
4146  * @return 0 ok, 1 on error
4147  */
4148 int
4149 main (int argc, char *const *argv)
4150 {
4151   int ret;
4152
4153 #if MESH_DEBUG
4154 //   fprintf (stderr, "main ()\n");
4155 #endif
4156   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: main()\n");
4157   ret =
4158       (GNUNET_OK ==
4159        GNUNET_SERVICE_run (argc, argv, "mesh", GNUNET_SERVICE_OPTION_NONE, &run,
4160                            NULL)) ? 0 : 1;
4161   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: main() END\n");
4162 #if MESH_DEBUG
4163 //   fprintf (stderr, "main () END\n");
4164 #endif
4165   return ret;
4166 }