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