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