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