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