WiP (adding paths)
[oweals/gnunet.git] / src / mesh / gnunet-service-mesh.c
1 /*
2      This file is part of GNUnet.
3      (C) 2001 - 2011 Christian Grothoff (and other contributing authors)
4
5      GNUnet is free software; you can redistribute it and/or modify
6      it under the terms of the GNU General Public License as published
7      by the Free Software Foundation; either version 3, or (at your
8      option) any later version.
9
10      GNUnet is distributed in the hope that it will be useful, but
11      WITHOUT ANY WARRANTY; without even the implied warranty of
12      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13      General Public License for more details.
14
15      You should have received a copy of the GNU General Public License
16      along with GNUnet; see the file COPYING.  If not, write to the
17      Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18      Boston, MA 02111-1307, USA.
19 */
20
21 /**
22  * @file mesh/gnunet-service-mesh.c
23  * @brief GNUnet MESH service
24  * @author Bartlomiej Polot
25  *
26  * STRUCTURE:
27  * - DATA STRUCTURES
28  * - GLOBAL VARIABLES
29  * - MESH NETWORK HANDLER HELPERS
30  * - MESH NETWORK HANDLES
31  * - MESH LOCAL HANDLER HELPERS
32  * - MESH LOCAL HANDLES
33  * - PERIODIC FUNCTIONS
34  * - MAIN FUNCTIONS (main & run)
35  * 
36  * TODO:
37  * - error reporting (CREATE/CHANGE/ADD/DEL?) -- new message!
38  * - partial disconnect reporting -- same as error reporting?
39  * - add vs create? change vs. keep-alive? same msg or different ones? -- thinking...
40  * - speed requirement specification (change?) in mesh API -- API call
41  * - add ping message (connection confirmation, others?)
42  */
43
44 #include "platform.h"
45 #include "gnunet_common.h"
46 #include "gnunet_util_lib.h"
47 #include "gnunet_peer_lib.h"
48 #include "gnunet_core_service.h"
49 #include "gnunet_protocols.h"
50
51 #include "mesh.h"
52 #include "mesh_protocol.h"
53 #include "gnunet_dht_service.h"
54
55 #define REFRESH_PATH_TIME GNUNET_TIME_relative_multiply(\
56                                     GNUNET_TIME_UNIT_SECONDS,\
57                                     300)
58
59
60 /******************************************************************************/
61 /************************      DATA STRUCTURES     ****************************/
62 /******************************************************************************/
63
64 /**
65  * Information regarding a path
66  */
67 struct MeshPath
68 {
69
70     /**
71      * Linked list
72      */
73     struct MeshPath             *next;
74     struct MeshPath             *prev;
75
76     /**
77      * Whether the path is serving traffic in a tunnel or is a backup
78      */
79     int                         in_use;
80
81     /**
82      * List of all the peers that form the path from origin to target
83      */
84     GNUNET_PEER_Id              *peers;
85
86     /**
87      * Number of peers (hops) in the path
88      */
89     unsigned int                length;
90 };
91
92
93 /**
94  * All the states a peer participating in a tunnel can be in.
95  */
96 enum MeshPeerState
97 {
98     /**
99      * Path to the peer not known yet
100      */
101     MESH_PEER_SEARCHING,
102
103     /**
104      * Request sent, not yet answered.
105      */
106     MESH_PEER_WAITING,
107
108     /**
109      * Peer connected and ready to accept data
110      */
111     MESH_PEER_READY,
112
113     /**
114      * Peer connected previosly but not responding
115      */
116     MESH_PEER_RECONNECTING
117 };
118
119
120 /**
121  * Struct containing all information regarding a given peer
122  */
123 struct MeshPeerInfo
124 {
125     /**
126      * ID of the peer
127      */
128     GNUNET_PEER_Id              id;
129
130     /**
131      * Is the peer reachable? Is the peer even connected?
132      */
133     enum MeshPeerState          state;
134
135     /**
136      * Last time we heard from this peer
137      */
138     struct GNUNET_TIME_Absolute last_contact;
139
140     /**
141      * Number of attempts to reconnect so far
142      */
143     int                         n_reconnect_attempts;
144
145     /**
146      * Paths to reach the peer
147      */
148     struct MeshPath             *path;
149     struct MeshPath             *path_tail;
150
151     /**
152      * Handle to stop the DHT search for a path to this peer
153      */
154     struct GNUNET_DHT_GetHandle *dhtget;
155 };
156
157
158 /**
159  * Data scheduled to transmit (to local client or remote peer)
160  */
161 struct MeshQueue
162 {
163     /**
164      * Double linked list
165      */
166     struct MeshQueue            *next;
167     struct MeshQueue            *prev;
168
169     /**
170      * Target of the data (NULL if target is client)
171      */
172     struct MeshPeerInfo         *peer;
173
174     /**
175      * Client to send the data to (NULL if target is peer)
176      */
177     struct MeshClient           *client;
178
179     /**
180      * Size of the message to transmit
181      */
182     unsigned int                size;
183
184     /**
185      * How old is the data?
186      */
187     struct GNUNET_TIME_Absolute timestamp;
188
189     /**
190      * Data itself
191      */
192     struct GNUNET_MessageHeader *data;
193 };
194
195 /**
196  * Globally unique tunnel identification (owner + number)
197  * DO NOT USE OVER THE NETWORK
198  */
199 struct MESH_TunnelID {
200     /**
201      * Node that owns the tunnel
202      */
203     GNUNET_PEER_Id      oid;
204
205     /**
206      * Tunnel number to differentiate all the tunnels owned by the node oid
207      * ( tid < GNUNET_MESH_LOCAL_TUNNEL_ID_MARK )
208      */
209     MESH_TunnelNumber   tid;
210 };
211
212
213 struct MeshClient; /* FWD declaration */
214 /**
215  * Struct containing all information regarding a tunnel
216  * For an intermediate node the improtant info used will be:
217  * - id        Tunnel unique identification
218  * - paths[0]  To know where to send it next
219  * - metainfo: ready, speeds, accounting
220  */
221 struct MeshTunnel
222 {
223     /**
224      * Tunnel ID
225      */
226     struct MESH_TunnelID        id;
227
228     /**
229      * Local tunnel number ( >= GNUNET_MESH_LOCAL_TUNNEL_ID_MARK or 0 )
230      */
231     MESH_TunnelNumber           local_tid;
232
233     /**
234      * Last time the tunnel was used
235      */
236     struct GNUNET_TIME_Absolute timestamp;
237
238     /**
239      * Peers in the tunnelindexed by PeerIdentity (MeshPeerInfo)
240      */
241     struct GNUNET_CONTAINER_MultiHashMap* peers;
242
243     /**
244      * Number of peers that are connected and potentially ready to receive data
245      */
246     unsigned int                peers_ready;
247
248     /**
249      * Number of peers that have been added to the tunnel
250      */
251     unsigned int                peers_total;
252
253
254     /**
255      * Client owner of the tunnel, if any
256      */
257     struct MeshClient           *client;
258
259     /**
260      * Messages ready to transmit
261      */
262     struct MeshQueue            *queue_head;
263     struct MeshQueue            *queue_tail;
264
265 };
266
267 /**
268  * Struct containing information about a client of the service
269  */
270 struct MeshClient
271 {
272     /**
273      * Linked list
274      */
275     struct MeshClient           *next;
276     struct MeshClient           *prev;
277
278     /**
279      * Tunnels that belong to this client, indexed by local id
280      */
281     struct GNUNET_CONTAINER_MultiHashMap* tunnels;
282
283     /**
284      * Handle to communicate with the client
285      */
286     struct GNUNET_SERVER_Client *handle;
287
288     /**
289      * Applications that this client has claimed to provide
290      */
291     GNUNET_MESH_ApplicationType *apps;
292     unsigned int                app_counter;
293
294     /**
295      * Messages that this client has declared interest in
296      */
297     uint16_t                    *types;
298     unsigned int                type_counter;
299
300 };
301
302 /******************************************************************************/
303 /***********************      GLOBAL VARIABLES     ****************************/
304 /******************************************************************************/
305
306 /**
307  * All the clients
308  */
309 static struct MeshClient                *clients;
310 static struct MeshClient                *clients_tail;
311
312 /**
313  * Tunnels known, indexed by MESH_TunnelID (MeshTunnel)
314  */
315 struct GNUNET_CONTAINER_MultiHashMap    *tunnels;
316
317 /**
318  * Peers known, indexed by PeerIdentity (MeshPeerInfo)
319  */
320 struct GNUNET_CONTAINER_MultiHashMap    *peers;
321
322 /**
323  * Handle to communicate with core
324  */
325 static struct GNUNET_CORE_Handle        *core_handle;
326
327 /**
328  * Handle to use DHT
329  */
330 static struct GNUNET_DHT_Handle         *dht_handle;
331
332 /**
333  * Local peer own ID (memory efficient handle)
334  */
335 static GNUNET_PEER_Id                   myid;
336
337 /**
338  * Tunnel ID for the next created tunnel (global tunnel number)
339  */
340 static MESH_TunnelNumber                next_tid;
341
342 /******************************************************************************/
343 /******************      GENERAL HELPER FUNCTIONS      ************************/
344 /******************************************************************************/
345
346 /**
347  * Retrieve the MeshPeerInfo stucture associated with the peer, create one
348  * and inster it in the appropiate structures if the peer is not known yet.
349  * @param peer Identity of the peer
350  * @return Existing or newly created peer info
351  */
352 static struct MeshPeerInfo *
353 retireve_peer_info (const struct GNUNET_PeerIdentity *peer)
354 {
355     struct MeshPeerInfo *       peer_info;
356
357     peer_info = GNUNET_CONTAINER_multihashmap_get(peers,
358                                                   &peer->hashPubKey);
359     if (NULL == peer_info) {
360         peer_info = (struct MeshPeerInfo *)
361                     GNUNET_malloc(sizeof(struct MeshPeerInfo));
362         GNUNET_CONTAINER_multihashmap_put(peers,
363                             &peer->hashPubKey,
364                             peer_info,
365                             GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
366         peer_info->id = GNUNET_PEER_intern(peer);
367         peer_info->state = MESH_PEER_SEARCHING;
368     }
369
370     return peer_info;
371 }
372
373 /**
374  * find the first peer whom to send a packet to go down this path
375  * @param path The path to use
376  * @return short id of the next peer, myid in case of local delivery,
377  * or 0 in case of error
378  */
379 static GNUNET_PEER_Id
380 retrieve_first_hop (struct MeshPath *path)
381 {
382     unsigned int        i;
383
384     if (NULL == path) return 0;
385     if (path->in_use == 0) return 0;
386
387     for (i = 0; i < path->length; i++) {
388         if (path->peers[i] == myid) {
389             if (i < path->length - 1) {
390                 return path->peers[i+1];
391             } else {
392                 return myid;
393             }
394         }
395     }
396     return 0;
397 }
398
399 static void
400 add_path_to_peer(struct MeshPeerInfo *peer_info, struct MeshPath *path)
401 {
402     return;
403 }
404
405
406 /**
407  * Check if client has registered with the service and has not disconnected
408  * @param client the client to check
409  * @return non-NULL if client exists in the global DLL
410  */
411 static struct MeshClient *
412 retrieve_client (struct GNUNET_SERVER_Client *client)
413 {
414     struct MeshClient       *c;
415
416     c = clients; 
417     while (NULL != c) {
418         if (c->handle == client) return c;
419         c = c->next;
420     }
421     return NULL;
422 }
423
424
425 /**
426  * Search for a tunnel among the tunnels for a client
427  * @param client the client whose tunnels to search in
428  * @param tid the local id of the tunnel
429  * @return tunnel handler, NULL if doesn't exist
430  */
431 static struct MeshTunnel *
432 retrieve_tunnel_by_local_id (struct MeshClient *c, MESH_TunnelNumber tid)
433 {
434     GNUNET_HashCode hash;
435
436     GNUNET_CRYPTO_hash(&tid, sizeof(MESH_TunnelNumber), &hash);
437     return GNUNET_CONTAINER_multihashmap_get(c->tunnels, &hash);
438 }
439
440 /**
441  * Search for a tunnel by global ID using PEER_ID
442  * @param pi owner of the tunnel
443  * @param tid global tunnel number
444  * @return tunnel handler, NULL if doesn't exist
445  */
446 static struct MeshTunnel *
447 retrieve_tunnel_by_pi (GNUNET_PEER_Id pi, MESH_TunnelNumber tid)
448 {
449     struct MESH_TunnelID        id;
450     GNUNET_HashCode             hash;
451
452     id.oid = pi;
453     id.tid = tid;
454
455     GNUNET_CRYPTO_hash(&id, sizeof(struct MESH_TunnelID), &hash);
456     return GNUNET_CONTAINER_multihashmap_get(tunnels, &hash);
457 }
458
459
460 #if LATER
461 /**
462  * Search for a tunnel by global ID using full PeerIdentities
463  * @param oid owner of the tunnel
464  * @param tid global tunnel number
465  * @return tunnel handler, NULL if doesn't exist
466  */
467 static struct MeshTunnel *
468 retrieve_tunnel (struct GNUNET_PeerIdentity *oid, MESH_TunnelNumber tid)
469 {
470     GNUNET_PEER_Id              pi;
471
472     pi = GNUNET_PEER_intern(oid);
473     GNUNET_PEER_change_rc(pi, -1);
474     return retrieve_tunnel_by_pi(pi, tid);
475 }
476
477
478 /**
479  * Destroy the path and free any allocated resources linked to it
480  * @param t tunnel the path belongs to
481  * @param p the path to destroy
482  * @return GNUNET_OK on success
483  */
484 static int
485 destroy_path(struct MeshTunnel  *t, struct MeshPath *p)
486 {
487     GNUNET_PEER_decrement_rcs(p->peers, p->length);
488     GNUNET_free(p->peers);
489     GNUNET_free(p);
490     return GNUNET_OK;
491 }
492
493
494 /**
495  * Destroy the peer_info and free any allocated resources linked to it
496  * @param t tunnel the path belongs to
497  * @param pi the peer_info to destroy
498  * @return GNUNET_OK on success
499  */
500 // static int
501 // destroy_peer_info(struct MeshTunnel  *t, struct MeshPeerInfo *pi)
502 // {
503 //     GNUNET_PEER_change_rc(pi->id, -1);
504 //     /* FIXME delete from list */
505 //     GNUNET_free(pi);
506 //     return GNUNET_OK;
507 // }
508 #endif
509
510
511 /**
512  * Destroy the tunnel and free any allocated resources linked to it
513  * @param c client the tunnel belongs to
514  * @param t the tunnel to destroy
515  * @return GNUNET_OK on success
516  */
517 static int
518 destroy_tunnel(struct MeshClient *c, struct MeshTunnel  *t)
519 {
520 //     struct MeshPath         *path;
521     GNUNET_HashCode         hash;
522     int                     r;
523
524     if (NULL == t) return GNUNET_OK;
525
526     // FIXME
527 //     for (path = t->paths_head; path != NULL; path = t->paths_head) {
528 //         if(GNUNET_OK != destroy_path(t, path)) r = GNUNET_SYSERR;
529 //     }
530
531     GNUNET_CRYPTO_hash(&t->id, sizeof(struct MESH_TunnelID), &hash);
532     if(GNUNET_YES != GNUNET_CONTAINER_multihashmap_remove(tunnels, &hash, t)) {
533         r = GNUNET_SYSERR;
534     }
535
536     GNUNET_CRYPTO_hash(&t->local_tid, sizeof(MESH_TunnelNumber), &hash);
537     if(GNUNET_YES !=
538         GNUNET_CONTAINER_multihashmap_remove(c->tunnels, &hash, t))
539     {
540         r = GNUNET_SYSERR;
541     }
542     GNUNET_free(t);
543     return r;
544 }
545
546 /******************************************************************************/
547 /****************      MESH NETWORK HANDLER HELPERS     ***********************/
548 /******************************************************************************/
549
550 /**
551  * Function called to notify a client about the socket
552  * being ready to queue more data.  "buf" will be
553  * NULL and "size" zero if the socket was closed for
554  * writing in the meantime.
555  *
556  * @param cls closure
557  * @param size number of bytes available in buf
558  * @param buf where the callee should write the message
559  * @return number of bytes written to buf
560  */
561 static size_t
562 send_core_create_path_for_peer (void *cls, size_t size, void *buf)
563 {
564     struct MeshPeerInfo                 *peer_info = cls;
565     struct GNUNET_MESH_ManipulatePath   *msg;
566     struct MeshPath                     *p;
567     struct GNUNET_PeerIdentity          *peer_ptr;
568     struct GNUNET_PeerIdentity          id;
569     size_t                              size_needed;
570     int                                 i;
571
572     if (0 == size && NULL == buf) {
573         GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Retransmitting create path\n");
574         GNUNET_PEER_resolve(retrieve_first_hop(peer_info->path), &id);
575         GNUNET_CORE_notify_transmit_ready(core_handle,
576                             0,
577                             0,
578                             GNUNET_TIME_UNIT_FOREVER_REL,
579                             &id,
580                             sizeof(struct GNUNET_MESH_ManipulatePath)
581                             + (peer_info->path->length
582                             * sizeof (struct GNUNET_PeerIdentity)),
583                             &send_core_create_path_for_peer,
584                             peer_info);
585         return 0;
586     }
587     p = peer_info->path;
588     while (NULL != p) {
589         if (p->in_use) {
590             break;
591         }
592         p = p->next;
593     }
594     if (p == NULL) return 0; // TODO Notify ERROR Path not found
595
596     size_needed = sizeof(struct GNUNET_MESH_ManipulatePath)
597                   + p->length * sizeof(struct GNUNET_PeerIdentity);
598     if (size < size_needed) {
599         // TODO retry? cancel?
600         return 0;
601     }
602
603     msg = (struct GNUNET_MESH_ManipulatePath *) buf;
604     msg->header.size = htons(size_needed);
605     msg->header.type = htons(GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE);
606
607     peer_ptr = (struct GNUNET_PeerIdentity *) &msg[1];
608     for (i = 0; i < p->length; i++) {
609         GNUNET_PEER_resolve(p->peers[i], peer_ptr++);
610     }
611
612     peer_info->state = MESH_PEER_WAITING; // TODO maybe already ready?
613
614     return size_needed;
615 }
616
617 #if LATER
618 /**
619  * Send another peer a notification to destroy a tunnel
620  * @param cls The tunnel to destroy
621  * @param size Size in the buffer
622  * @param buf Memory where to put the data to transmit
623  * @return Size of data put in buffer
624  */
625 static size_t
626 send_p2p_tunnel_destroy(void *cls, size_t size, void *buf)
627 {
628     struct MeshTunnel                   *t = cls;
629     struct MeshClient                   *c;
630     struct GNUNET_MESH_TunnelMessage    *msg;
631
632     c = t->client;
633     msg = buf;
634     msg->header.type = htons(GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_DESTROY); /*FIXME*/
635     msg->header.size = htons(sizeof(struct GNUNET_MESH_TunnelMessage));
636     msg->tunnel_id = htonl(t->id.tid);
637
638     destroy_tunnel(c, t);
639     return sizeof(struct GNUNET_MESH_TunnelMessage);
640 }
641 #endif
642
643
644 /******************************************************************************/
645 /********************      MESH NETWORK HANDLERS     **************************/
646 /******************************************************************************/
647
648
649 /**
650  * Core handler for path creation
651  * struct GNUNET_CORE_MessageHandler
652  *
653  * @param cls closure
654  * @param message message
655  * @param peer peer identity this notification is about
656  * @param atsi performance data
657  * @return GNUNET_OK to keep the connection open,
658  *         GNUNET_SYSERR to close it (signal serious error)
659  *
660  */
661 static int
662 handle_mesh_path_create (void *cls,
663                               const struct GNUNET_PeerIdentity *peer,
664                               const struct GNUNET_MessageHeader *message,
665                               const struct GNUNET_TRANSPORT_ATS_Information
666                               *atsi)
667 {
668     /* Extract path */
669     /* Find origin & self */
670     /* Search for origin in local tunnels */
671     /* Create tunnel / add path */
672     /* Retransmit to next link in chain, if any (core_notify + callback) */
673     return GNUNET_OK;
674 }
675
676
677 /**
678  * Core handler for mesh network traffic
679  *
680  * @param cls closure
681  * @param message message
682  * @param peer peer identity this notification is about
683  * @param atsi performance data
684  * @return GNUNET_OK to keep the connection open,
685  *         GNUNET_SYSERR to close it (signal serious error)
686  */
687 static int
688 handle_mesh_network_traffic (void *cls,
689                              const struct GNUNET_PeerIdentity *peer,
690                              const struct GNUNET_MessageHeader *message,
691                              const struct GNUNET_TRANSPORT_ATS_Information
692                              *atsi)
693 {
694     if (GNUNET_MESSAGE_TYPE_MESH_DATA_GO == ntohs(message->type)) {
695         /* Retransmit to next in path of tunnel identified by message */
696         return GNUNET_OK;
697     } else { /* GNUNET_MESSAGE_TYPE_MESH_DATA_BACK */
698         /* Retransmit to previous in path of tunnel identified by message */
699         return GNUNET_OK;
700     }
701 }
702
703
704 /**
705  * Functions to handle messages from core
706  */
707 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
708   {&handle_mesh_path_create, GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE, 0},
709   {&handle_mesh_network_traffic, GNUNET_MESSAGE_TYPE_MESH_DATA_GO, 0},
710   {&handle_mesh_network_traffic, GNUNET_MESSAGE_TYPE_MESH_DATA_BACK, 0},
711   {NULL, 0, 0}
712 };
713
714
715
716 /******************************************************************************/
717 /****************       MESH LOCAL HANDLER HELPERS      ***********************/
718 /******************************************************************************/
719
720 /**
721  * delete_tunnel_entry: iterator for deleting each tunnel that belongs to a
722  * client when the client disconnects.
723  * @param cls closure (client that is disconnecting)
724  * @param key the hash of the local tunnel id (used to access the hashmap)
725  * @param value the value stored at the key (tunnel to destroy)
726  * @return GNUNET_OK on success
727  */
728 static int
729 delete_tunnel_entry (void *cls, const GNUNET_HashCode * key, void *value) {
730     int r;
731     r = destroy_tunnel((struct MeshClient *) cls, (struct MeshTunnel *) value);
732     return r;
733 }
734
735 #if LATER
736 /**
737  * notify_client_connection_failure: notify a client that the connection to the
738  * requested remote peer is not possible (for instance, no route found)
739  * Function called when the socket is ready to queue more data. "buf" will be
740  * NULL and "size" zero if the socket was closed for writing in the meantime.
741  *
742  * @param cls closure
743  * @param size number of bytes available in buf
744  * @param buf where the callee should write the message
745  * @return number of bytes written to buf
746  */
747 static size_t
748 notify_client_connection_failure (void *cls, size_t size, void *buf)
749 {
750     int                                 size_needed;
751     struct MeshPeerInfo                 *peer_info;
752     struct GNUNET_MESH_PeerControl      *msg;
753     struct GNUNET_PeerIdentity          id;
754
755     if (0 == size && NULL == buf) {
756         // TODO retry? cancel?
757         return 0;
758     }
759
760     size_needed = sizeof(struct GNUNET_MESH_PeerControl);
761     peer_info = (struct MeshPeerInfo *) cls;
762     msg = (struct GNUNET_MESH_PeerControl *) buf;
763     msg->header.size = htons(sizeof(struct GNUNET_MESH_PeerControl));
764     msg->header.type = htons(GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_DISCONNECTED);
765 //     msg->tunnel_id = htonl(peer_info->t->tid);
766     GNUNET_PEER_resolve(peer_info->id, &id);
767     memcpy(&msg->peer, &id, sizeof(struct GNUNET_PeerIdentity));
768
769     return size_needed;
770 }
771 #endif
772
773 /**
774  * Function to process paths received for a new peer addition. The recorded
775  * paths form the initial tunnel, which can be optimized later.
776  * Called on each result obtained for the DHT search.
777  *
778  * @param cls closure
779  * @param exp when will this value expire
780  * @param key key of the result
781  * @param get_path NULL-terminated array of pointers
782  *                 to the peers on reverse GET path (or NULL if not recorded)
783  * @param put_path NULL-terminated array of pointers
784  *                 to the peers on the PUT path (or NULL if not recorded)
785  * @param type type of the result
786  * @param size number of bytes in data
787  * @param data pointer to the result data
788  */
789 static void
790 dht_get_response_handler(void *cls,
791                         struct GNUNET_TIME_Absolute exp,
792                         const GNUNET_HashCode * key,
793                         const struct GNUNET_PeerIdentity * const *get_path,
794                         const struct GNUNET_PeerIdentity * const *put_path,
795                         enum GNUNET_BLOCK_Type type,
796                         size_t size,
797                         const void *data)
798 {
799     struct MeshPeerInfo         *peer_info = cls;
800     struct MeshPath             *p;
801     struct GNUNET_PeerIdentity  pi;
802     int                         i;
803
804     if ((NULL == get_path || NULL == put_path) && NULL == peer_info->path) {
805         // Find ourselves some alternate initial path to the destination: retry
806         GNUNET_DHT_get_stop(peer_info->dhtget);
807         GNUNET_PEER_resolve(peer_info->id, &pi);
808         peer_info->dhtget = GNUNET_DHT_get_start(dht_handle,
809                                     GNUNET_TIME_UNIT_FOREVER_REL,
810                                     GNUNET_BLOCK_TYPE_ANY,
811                                     &pi.hashPubKey,
812                                     4,    /* replication level */
813                                     GNUNET_DHT_RO_RECORD_ROUTE,
814                                     NULL, /* bloom filter */
815                                     0,    /* mutator */
816                                     NULL, /* xquery */
817                                     0,    /* xquery bits */
818                                     dht_get_response_handler,
819                                     (void *)peer_info);
820     }
821
822     p = GNUNET_malloc(sizeof(struct MeshPath));
823     for (i = 0; get_path[i] != NULL; i++);
824     for (i--; i >= 0; i--) {
825         p->peers = GNUNET_realloc(p->peers,
826                                    sizeof(GNUNET_PEER_Id) * (p->length + 1));
827         p->peers[p->length] = GNUNET_PEER_intern(get_path[i]);
828         p->length++;
829     }
830     for (i = 0; put_path[i] != NULL; i++);
831     for (i--; i >= 0; i--) {
832         p->peers = GNUNET_realloc(p->peers,
833                                   sizeof(GNUNET_PEER_Id) * (p->length + 1));
834         p->peers[p->length] = GNUNET_PEER_intern(put_path[i]);
835         p->length++;
836     }
837     add_path_to_peer(peer_info, p);
838     GNUNET_CORE_notify_transmit_ready(core_handle,
839                                       0,
840                                       0,
841                                       GNUNET_TIME_UNIT_FOREVER_REL,
842                                       get_path[1],
843                                       sizeof(struct GNUNET_MESH_ManipulatePath)
844                                         + (p->length
845                                         * sizeof (struct GNUNET_PeerIdentity)),
846                                       &send_core_create_path_for_peer,
847                                       peer_info);
848     return;
849 }
850
851
852 /******************************************************************************/
853 /*********************       MESH LOCAL HANDLES      **************************/
854 /******************************************************************************/
855
856
857 /**
858  * Handler for client disconnection
859  *
860  * @param cls closure
861  * @param client identification of the client; NULL
862  *        for the last call when the server is destroyed
863  */
864 static void
865 handle_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
866 {
867     struct MeshClient   *c;
868     struct MeshClient   *next;
869
870     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
871                "client disconnected\n");
872     c = clients;
873     while (NULL != c) {
874         if (c->handle == client) {
875             GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
876                " matching client found, cleaning\n");
877             GNUNET_CONTAINER_multihashmap_iterate(c->tunnels,
878                                                   &delete_tunnel_entry,
879                                                   c);
880             GNUNET_CONTAINER_multihashmap_destroy(c->tunnels);
881             if(0 != c->app_counter) GNUNET_free (c->apps);
882             if(0 != c->type_counter) GNUNET_free (c->types);
883             GNUNET_CONTAINER_DLL_remove(clients, clients_tail, c);
884             next = c->next;
885             GNUNET_free (c);
886             c = next;
887         } else {
888             GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
889                "   ... searching\n");
890             c = c->next;
891         }
892     }
893     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
894                "   done!\n");
895     return;
896 }
897
898
899 /**
900  * Handler for new clients
901  * 
902  * @param cls closure
903  * @param client identification of the client
904  * @param message the actual message, which includes messages the client wants
905  */
906 static void
907 handle_local_new_client (void *cls,
908                          struct GNUNET_SERVER_Client *client,
909                          const struct GNUNET_MessageHeader *message)
910 {
911     struct GNUNET_MESH_ClientConnect    *cc_msg;
912     struct MeshClient                   *c;
913     unsigned int                        size;
914     uint16_t                            types;
915     uint16_t                            apps;
916
917     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "new client connected\n");
918     /* Check data sanity */
919     size = ntohs(message->size) - sizeof(struct GNUNET_MESH_ClientConnect);
920     cc_msg = (struct GNUNET_MESH_ClientConnect *) message;
921     types = ntohs(cc_msg->types);
922     apps = ntohs(cc_msg->applications);
923     if (size !=
924         types * sizeof(uint16_t) + apps * sizeof(GNUNET_MESH_ApplicationType))
925     {
926         GNUNET_break(0);
927         GNUNET_SERVER_receive_done(client, GNUNET_SYSERR);
928         return;
929     }
930
931     /* Create new client structure */
932     c = GNUNET_malloc(sizeof(struct MeshClient));
933     c->handle = client;
934     if (types != 0) {
935         c->type_counter = types;
936         c->types = GNUNET_malloc(types * sizeof(uint16_t));
937         memcpy(c->types, &message[1], types * sizeof(uint16_t));
938     }
939     if (apps != 0) {
940         c->app_counter = apps;
941         c->apps = GNUNET_malloc(apps * sizeof(GNUNET_MESH_ApplicationType));
942         memcpy(c->apps,
943                &message[1] + types * sizeof(uint16_t),
944                apps * sizeof(GNUNET_MESH_ApplicationType));
945     }
946     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
947                " client has %u+%u subscriptions\n",
948                c->type_counter,
949                c->app_counter);
950
951     GNUNET_CONTAINER_DLL_insert(clients, clients_tail, c);
952     c->tunnels = GNUNET_CONTAINER_multihashmap_create(32);
953
954     GNUNET_SERVER_receive_done(client, GNUNET_OK);
955
956 }
957
958
959 /**
960  * Handler for requests of new tunnels
961  * 
962  * @param cls closure
963  * @param client identification of the client
964  * @param message the actual message
965  */
966 static void
967 handle_local_tunnel_create (void *cls,
968                             struct GNUNET_SERVER_Client *client,
969                             const struct GNUNET_MessageHeader *message)
970 {
971     struct GNUNET_MESH_TunnelMessage    *t_msg;
972     struct MeshTunnel                   *t;
973     struct MeshClient                   *c;
974     GNUNET_HashCode                     hash;
975
976     /* Sanity check for client registration */
977     if (NULL == (c = retrieve_client(client))) {
978         GNUNET_break(0);
979         GNUNET_SERVER_receive_done(client, GNUNET_SYSERR);
980         return;
981     }
982
983     /* Message sanity check */
984     if (sizeof(struct GNUNET_MESH_TunnelMessage) != ntohs(message->size)) {
985         GNUNET_break(0);
986         GNUNET_SERVER_receive_done(client, GNUNET_SYSERR);
987         return;
988     }
989
990     t_msg = (struct GNUNET_MESH_TunnelMessage *) message;
991     /* Sanity check for tunnel numbering */
992     if (0 == (ntohl(t_msg->tunnel_id) & GNUNET_MESH_LOCAL_TUNNEL_ID_MARK)) {
993         GNUNET_break(0);
994         GNUNET_SERVER_receive_done(client, GNUNET_SYSERR);
995         return;
996     }
997     /* Sanity check for duplicate tunnel IDs */
998     if(NULL != retrieve_tunnel_by_local_id(c, ntohl(t_msg->tunnel_id))) {
999         GNUNET_break(0);
1000         GNUNET_SERVER_receive_done(client, GNUNET_SYSERR);
1001         return;
1002     }
1003
1004     t = GNUNET_malloc(sizeof(struct MeshTunnel));
1005     while (NULL != retrieve_tunnel_by_pi(myid, next_tid))
1006         next_tid = (next_tid + 1) % GNUNET_MESH_LOCAL_TUNNEL_ID_MARK;
1007     t->id.tid = next_tid++;
1008     t->id.oid = myid;
1009     t->local_tid = ntohl(t_msg->tunnel_id);
1010     t->client = c;
1011     t->peers = GNUNET_CONTAINER_multihashmap_create(32);
1012
1013     GNUNET_CRYPTO_hash(&t->local_tid, sizeof(MESH_TunnelNumber), &hash);
1014     if (GNUNET_OK !=
1015         GNUNET_CONTAINER_multihashmap_put(c->tunnels, &hash, t,
1016                             GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
1017     {
1018         GNUNET_break(0);
1019         GNUNET_SERVER_receive_done(client, GNUNET_SYSERR);
1020         return;
1021     }
1022
1023     GNUNET_CRYPTO_hash(&t->id, sizeof(struct MESH_TunnelID), &hash);
1024     if (GNUNET_OK !=
1025         GNUNET_CONTAINER_multihashmap_put(tunnels, &hash, t,
1026                             GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
1027     {
1028         GNUNET_break(0);
1029         GNUNET_SERVER_receive_done(client, GNUNET_SYSERR);
1030         return;
1031     }
1032
1033     GNUNET_SERVER_receive_done(client, GNUNET_OK);
1034     return;
1035 }
1036
1037
1038 /**
1039  * Handler for requests of deleting tunnels
1040  * 
1041  * @param cls closure
1042  * @param client identification of the client
1043  * @param message the actual message
1044  */
1045 static void
1046 handle_local_tunnel_destroy (void *cls,
1047                              struct GNUNET_SERVER_Client *client,
1048                              const struct GNUNET_MessageHeader *message)
1049 {
1050     struct GNUNET_MESH_TunnelMessage    *tunnel_msg;
1051     struct MeshClient                   *c;
1052     struct MeshTunnel                   *t;
1053     MESH_TunnelNumber                   tid;
1054     GNUNET_HashCode                     hash;
1055
1056
1057     /* Sanity check for client registration */
1058     if (NULL == (c = retrieve_client(client))) {
1059         GNUNET_break(0);
1060         GNUNET_SERVER_receive_done(client, GNUNET_SYSERR);
1061         return;
1062     }
1063     /* Message sanity check */
1064     if (sizeof(struct GNUNET_MESH_TunnelMessage) != ntohs(message->size)) {
1065         GNUNET_break(0);
1066         GNUNET_SERVER_receive_done(client, GNUNET_SYSERR);
1067         return;
1068     }
1069
1070     tunnel_msg = (struct GNUNET_MESH_TunnelMessage *) message;
1071
1072     /* Retrieve tunnel */
1073     tid = ntohl(tunnel_msg->tunnel_id);
1074
1075     /* Remove from local id hashmap */
1076     GNUNET_CRYPTO_hash(&tid, sizeof(MESH_TunnelNumber), &hash);
1077     t = GNUNET_CONTAINER_multihashmap_get(c->tunnels, &hash);
1078     GNUNET_CONTAINER_multihashmap_remove(c->tunnels, &hash, t);
1079
1080     /* Remove from global id hashmap */
1081     GNUNET_CRYPTO_hash(&t->id, sizeof(struct MESH_TunnelID), &hash);
1082     GNUNET_CONTAINER_multihashmap_remove(tunnels, &hash, t);
1083
1084 //     notify_tunnel_destroy(t);
1085     GNUNET_SERVER_receive_done(client, GNUNET_OK);
1086     return;
1087 }
1088
1089
1090 /**
1091  * Handler for connection requests to new peers
1092  * 
1093  * @param cls closure
1094  * @param client identification of the client
1095  * @param message the actual message (PeerControl)
1096  */
1097 static void
1098 handle_local_connect_add (void *cls,
1099                           struct GNUNET_SERVER_Client *client,
1100                           const struct GNUNET_MessageHeader *message)
1101 {
1102     struct GNUNET_MESH_PeerControl      *peer_msg;
1103     struct MeshClient                   *c;
1104     struct MeshTunnel                   *t;
1105     MESH_TunnelNumber                   tid;
1106     struct MeshPeerInfo                 *peer_info;
1107
1108
1109     /* Sanity check for client registration */
1110     if (NULL == (c = retrieve_client(client))) {
1111         GNUNET_break(0);
1112         GNUNET_SERVER_receive_done(client, GNUNET_SYSERR);
1113         return;
1114     }
1115
1116     peer_msg = (struct GNUNET_MESH_PeerControl *)message;
1117     /* Sanity check for message size */
1118     if (sizeof(struct GNUNET_MESH_PeerControl)
1119         != ntohs(peer_msg->header.size))
1120     {
1121         GNUNET_break(0);
1122         GNUNET_SERVER_receive_done(client, GNUNET_SYSERR);
1123         return;
1124     }
1125
1126     /* Tunnel exists? */
1127     tid = ntohl(peer_msg->tunnel_id);
1128     t = retrieve_tunnel_by_local_id(c, tid);
1129     if (NULL == t) {
1130         GNUNET_break(0);
1131         GNUNET_SERVER_receive_done(client, GNUNET_SYSERR);
1132         return;
1133     }
1134
1135     /* Does client own tunnel? */
1136     if (t->client->handle != client) {
1137         GNUNET_break(0);
1138         GNUNET_SERVER_receive_done(client, GNUNET_SYSERR);
1139         return;
1140     }
1141
1142     t->peers_total++;
1143     peer_info = retireve_peer_info(&peer_msg->peer);
1144
1145     /* Start DHT search if needed */
1146     if(MESH_PEER_READY != peer_info->state && NULL == peer_info->dhtget) {
1147         peer_info->dhtget = GNUNET_DHT_get_start(dht_handle,
1148                                             GNUNET_TIME_UNIT_FOREVER_REL,
1149                                             GNUNET_BLOCK_TYPE_ANY,
1150                                             &peer_msg->peer.hashPubKey,
1151                                             4,    /* replication level */
1152                                             GNUNET_DHT_RO_RECORD_ROUTE,
1153                                             NULL, /* bloom filter */
1154                                             0,    /* mutator */
1155                                             NULL, /* xquery */
1156                                             0,    /* xquery bits */
1157                                             dht_get_response_handler,
1158                                             (void *)peer_info);
1159     }
1160
1161     GNUNET_SERVER_receive_done(client, GNUNET_OK);
1162     return;
1163 }
1164
1165
1166 /**
1167  * Handler for disconnection requests of peers in a tunnel
1168  * 
1169  * @param cls closure
1170  * @param client identification of the client
1171  * @param message the actual message (PeerControl)
1172  */
1173 static void
1174 handle_local_connect_del (void *cls,
1175                           struct GNUNET_SERVER_Client *client,
1176                           const struct GNUNET_MessageHeader *message)
1177 {
1178     struct GNUNET_MESH_PeerControl      *peer_msg;
1179     struct MeshClient                   *c;
1180     struct MeshTunnel                   *t;
1181     MESH_TunnelNumber                   tid;
1182     GNUNET_PEER_Id                      peer_id;
1183
1184     /* Sanity check for client registration */
1185     if (NULL == (c = retrieve_client(client))) {
1186         GNUNET_break(0);
1187         GNUNET_SERVER_receive_done(client, GNUNET_SYSERR);
1188         return;
1189     }
1190     peer_msg = (struct GNUNET_MESH_PeerControl *)message;
1191     /* Sanity check for message size */
1192     if (sizeof(struct GNUNET_MESH_PeerControl)
1193         != ntohs(peer_msg->header.size))
1194     {
1195         GNUNET_break(0);
1196         GNUNET_SERVER_receive_done(client, GNUNET_SYSERR);
1197         return;
1198     }
1199
1200     /* Tunnel exists? */
1201     tid = ntohl(peer_msg->tunnel_id);
1202     t = retrieve_tunnel_by_local_id(c, tid);
1203     if (NULL == t) {
1204             GNUNET_break(0);
1205             GNUNET_SERVER_receive_done(client, GNUNET_SYSERR);
1206             return;
1207         }
1208
1209     /* Does client own tunnel? */
1210     if (t->client->handle != client) {
1211         GNUNET_break(0);
1212         GNUNET_SERVER_receive_done(client, GNUNET_SYSERR);
1213         return;
1214     }
1215
1216     /* Ok, delete peer from tunnel */
1217     peer_id = GNUNET_PEER_intern(&peer_msg->peer);
1218
1219     /* FIXME Delete paths */
1220     /* FIXME Delete peer info */
1221
1222     GNUNET_PEER_change_rc(peer_id, -1);
1223
1224     GNUNET_SERVER_receive_done(client, GNUNET_OK);
1225     return;
1226 }
1227
1228
1229 /**
1230  * Handler for connection requests to new peers by type
1231  * 
1232  * @param cls closure
1233  * @param client identification of the client
1234  * @param message the actual message (ConnectPeerByType)
1235  */
1236 static void
1237 handle_local_connect_by_type (void *cls,
1238                               struct GNUNET_SERVER_Client *client,
1239                               const struct GNUNET_MessageHeader *message)
1240 {
1241     struct GNUNET_MESH_ConnectPeerByType        *connect_msg;
1242     MESH_TunnelNumber                           tid;
1243     GNUNET_MESH_ApplicationType                 application;
1244     struct MeshClient                           *c;
1245     struct MeshTunnel                           *t;
1246
1247     /* Sanity check for client registration */
1248     if (NULL == (c = retrieve_client(client))) {
1249         GNUNET_break(0);
1250         GNUNET_SERVER_receive_done(client, GNUNET_SYSERR);
1251         return;
1252     }
1253
1254     connect_msg = (struct GNUNET_MESH_ConnectPeerByType *)message;
1255     /* Sanity check for message size */
1256     if (sizeof(struct GNUNET_MESH_PeerControl) !=
1257             ntohs(connect_msg->header.size))
1258     {
1259         GNUNET_break(0);
1260         GNUNET_SERVER_receive_done(client, GNUNET_SYSERR);
1261         return;
1262     }
1263
1264     /* Tunnel exists? */
1265     tid = ntohl(connect_msg->tunnel_id);
1266     t = retrieve_tunnel_by_local_id(c, tid);
1267     if (NULL == t) {
1268         GNUNET_break(0);
1269         GNUNET_SERVER_receive_done(client, GNUNET_SYSERR);
1270         return;
1271     }
1272
1273     /* Does client own tunnel? */
1274     if (t->client->handle != client) {
1275         GNUNET_break(0);
1276         GNUNET_SERVER_receive_done(client, GNUNET_SYSERR);
1277         return;
1278     }
1279
1280     /* Ok, lets find a peer offering the service */
1281     application = ntohl(connect_msg->type);
1282     application++; // FIXME silence warnings
1283
1284     GNUNET_SERVER_receive_done(client, GNUNET_OK);
1285     return;
1286 }
1287
1288
1289 /**
1290  * Handler for client traffic directed to one peer
1291  * 
1292  * @param cls closure
1293  * @param client identification of the client
1294  * @param message the actual message
1295  */
1296 static void
1297 handle_local_network_traffic (void *cls,
1298                          struct GNUNET_SERVER_Client *client,
1299                          const struct GNUNET_MessageHeader *message)
1300 {
1301     struct MeshClient                           *c;
1302     struct MeshTunnel                           *t;
1303     struct GNUNET_MESH_Data                     *data_msg;
1304     MESH_TunnelNumber                           tid;
1305
1306     /* Sanity check for client registration */
1307     if (NULL == (c = retrieve_client(client))) {
1308         GNUNET_break(0);
1309         GNUNET_SERVER_receive_done(client, GNUNET_SYSERR);
1310         return;
1311     }
1312     data_msg = (struct GNUNET_MESH_Data *)message;
1313     /* Sanity check for message size */
1314     if (sizeof(struct GNUNET_MESH_PeerControl) !=
1315             ntohs(data_msg->header.size))
1316     {
1317         GNUNET_break(0);
1318         GNUNET_SERVER_receive_done(client, GNUNET_SYSERR);
1319         return;
1320     }
1321
1322     /* Tunnel exists? */
1323     tid = ntohl(data_msg->tunnel_id);
1324     t = retrieve_tunnel_by_local_id(c, tid);
1325     if (NULL == t) {
1326         GNUNET_break(0);
1327         GNUNET_SERVER_receive_done(client, GNUNET_SYSERR);
1328         return;
1329     }
1330
1331     /* Does client own tunnel? */
1332     if (t->client->handle != client) {
1333         GNUNET_break(0);
1334         GNUNET_SERVER_receive_done(client, GNUNET_SYSERR);
1335         return;
1336     }
1337
1338     /* TODO */
1339
1340     GNUNET_SERVER_receive_done(client, GNUNET_OK);
1341     return;
1342 }
1343
1344 /**
1345  * Handler for client traffic directed to all peers in a tunnel
1346  * 
1347  * @param cls closure
1348  * @param client identification of the client
1349  * @param message the actual message
1350  */
1351 static void
1352 handle_local_network_traffic_bcast (void *cls,
1353                                     struct GNUNET_SERVER_Client *client,
1354                                     const struct GNUNET_MessageHeader *message)
1355 {
1356     struct MeshClient                           *c;
1357     struct MeshTunnel                           *t;
1358     struct GNUNET_MESH_DataBroadcast            *data_msg;
1359     MESH_TunnelNumber                           tid;
1360
1361     /* Sanity check for client registration */
1362     if (NULL == (c = retrieve_client(client))) {
1363         GNUNET_break(0);
1364         GNUNET_SERVER_receive_done(client, GNUNET_SYSERR);
1365         return;
1366     }
1367     data_msg = (struct GNUNET_MESH_DataBroadcast *)message;
1368     /* Sanity check for message size */
1369     if (sizeof(struct GNUNET_MESH_PeerControl)
1370         != ntohs(data_msg->header.size))
1371     {
1372         GNUNET_break(0);
1373         GNUNET_SERVER_receive_done(client, GNUNET_SYSERR);
1374         return;
1375     }
1376
1377     /* Tunnel exists? */
1378     tid = ntohl(data_msg->tunnel_id);
1379     t = retrieve_tunnel_by_local_id(c, tid);
1380     if (NULL == t) {
1381         GNUNET_break(0);
1382         GNUNET_SERVER_receive_done(client, GNUNET_SYSERR);
1383         return;
1384     }
1385
1386     /* Does client own tunnel? */
1387     if (t->client->handle != client) {
1388         GNUNET_break(0);
1389         GNUNET_SERVER_receive_done(client, GNUNET_SYSERR);
1390         return;
1391     }
1392
1393     /*  TODO */
1394
1395     GNUNET_SERVER_receive_done(client, GNUNET_OK);
1396     return;
1397 }
1398
1399 /**
1400  * Functions to handle messages from clients
1401  */
1402 static struct GNUNET_SERVER_MessageHandler plugin_handlers[] = {
1403   {&handle_local_new_client, NULL, GNUNET_MESSAGE_TYPE_MESH_LOCAL_CONNECT, 0},
1404   {&handle_local_tunnel_create, NULL,
1405    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_CREATE,
1406    sizeof(struct GNUNET_MESH_TunnelMessage)},
1407   {&handle_local_tunnel_destroy, NULL,
1408    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_DESTROY,
1409    sizeof(struct GNUNET_MESH_TunnelMessage)},
1410   {&handle_local_connect_add, NULL,
1411    GNUNET_MESSAGE_TYPE_MESH_LOCAL_CONNECT_PEER_ADD,
1412    sizeof(struct GNUNET_MESH_PeerControl)},
1413   {&handle_local_connect_del, NULL,
1414    GNUNET_MESSAGE_TYPE_MESH_LOCAL_CONNECT_PEER_DEL,
1415    sizeof(struct GNUNET_MESH_PeerControl)},
1416   {&handle_local_connect_by_type, NULL,
1417    GNUNET_MESSAGE_TYPE_MESH_LOCAL_CONNECT_PEER_BY_TYPE,
1418    sizeof(struct GNUNET_MESH_ConnectPeerByType)},
1419   {&handle_local_network_traffic, NULL,
1420    GNUNET_MESSAGE_TYPE_MESH_LOCAL_DATA, 0},
1421   {&handle_local_network_traffic_bcast, NULL,
1422    GNUNET_MESSAGE_TYPE_MESH_LOCAL_DATA_BROADCAST, 0},
1423   {NULL, NULL, 0, 0}
1424 };
1425
1426
1427 /**
1428  * To be called on core init/fail.
1429  *
1430  * @param cls service closure
1431  * @param server handle to the server for this service
1432  * @param identity the public identity of this peer
1433  * @param publicKey the public key of this peer
1434  */
1435 static void
1436 core_init (void *cls,
1437            struct GNUNET_CORE_Handle *server,
1438            const struct GNUNET_PeerIdentity *identity,
1439            const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *publicKey)
1440 {
1441     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1442                 "Core init\n");
1443     core_handle = server;
1444     myid = GNUNET_PEER_intern(identity);
1445     return;
1446 }
1447
1448 /**
1449  * Method called whenever a given peer connects.
1450  *
1451  * @param cls closure
1452  * @param peer peer identity this notification is about
1453  * @param atsi performance data for the connection
1454  */
1455 static void
1456 core_connect (void *cls,
1457               const struct GNUNET_PeerIdentity *peer,
1458               const struct GNUNET_TRANSPORT_ATS_Information *atsi)
1459 {
1460 //     GNUNET_PEER_Id              pid;
1461     struct MeshPeerInfo         *peer_info;
1462     struct MeshPath             *path;
1463
1464     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1465                 "Peer connected\n");
1466     peer_info = retireve_peer_info(peer);
1467     if (myid == peer_info->id) {
1468         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1469                 "     (self)\n");
1470     }
1471     path = GNUNET_malloc(sizeof(struct MeshPath));
1472     path->length = 2;
1473     path->peers = GNUNET_malloc(sizeof(GNUNET_PEER_Id) * 2);
1474     path->peers[0] = myid;
1475     path->peers[1] = peer_info->id;
1476     add_path_to_peer(peer_info, path);
1477     return;
1478 }
1479
1480 /**
1481  * Method called whenever a peer disconnects.
1482  *
1483  * @param cls closure
1484  * @param peer peer identity this notification is about
1485  */
1486 static void
1487 core_disconnect (void *cls,
1488                 const struct
1489                 GNUNET_PeerIdentity *peer)
1490 {
1491     GNUNET_PEER_Id      pid;
1492     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1493                 "Peer disconnected\n");
1494     pid = GNUNET_PEER_intern(peer);
1495     GNUNET_PEER_change_rc(pid, -1);
1496     if (myid == pid) {
1497         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1498                 "     (self)\n");
1499     }
1500     return;
1501 }
1502
1503
1504 /******************************************************************************/
1505 /**********************      PERIODIC FUNCTIONS      **************************/
1506 /******************************************************************************/
1507
1508 /**
1509  * Iterator over peers to send keepalive packets when needed.
1510  *
1511  * @param cls unused
1512  * @param key current key code
1513  * @param value value in the hash map
1514  * @return GNUNET_YES if we should continue to iterate, GNUNET_NO if not.
1515  */
1516 int
1517 path_refresh_peer (void *cls, const GNUNET_HashCode * key, void *value)
1518 {
1519     struct MeshPeerInfo         *pi = cls;
1520     struct GNUNET_TIME_Absolute threshold;
1521     struct GNUNET_PeerIdentity  id;
1522
1523     threshold = GNUNET_TIME_absolute_subtract(GNUNET_TIME_absolute_get(),
1524                                               REFRESH_PATH_TIME);
1525
1526     if (pi->last_contact.abs_value < threshold.abs_value) {
1527         GNUNET_PEER_resolve(pi->path->peers[1], &id);
1528         GNUNET_CORE_notify_transmit_ready(core_handle,
1529                                     0,
1530                                     0,
1531                                     GNUNET_TIME_UNIT_FOREVER_REL,
1532                                     &id,
1533                                     sizeof(struct GNUNET_MESH_ManipulatePath)
1534                                     + (pi->path->length
1535                                     * sizeof (struct GNUNET_PeerIdentity)),
1536                                     &send_core_create_path_for_peer,
1537                                     pi);
1538     }
1539     return GNUNET_YES;
1540 }
1541
1542
1543 /**
1544  * Send keepalive packets for all routes
1545  *
1546  * @param cls unused
1547  * @param tc unused
1548  */
1549 static void
1550 path_refresh (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1551 {
1552     if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN) return;
1553     GNUNET_CONTAINER_multihashmap_iterate(peers, path_refresh_peer, NULL);
1554     GNUNET_SCHEDULER_add_delayed(REFRESH_PATH_TIME,
1555                                  &path_refresh,
1556                                  NULL);
1557     return;
1558 }
1559
1560
1561 /******************************************************************************/
1562 /************************      MAIN FUNCTIONS      ****************************/
1563 /******************************************************************************/
1564
1565 /**
1566  * Task run during shutdown.
1567  *
1568  * @param cls unused
1569  * @param tc unused
1570  */
1571 static void
1572 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1573 {
1574     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1575                 "shutting down\n");
1576     if (core_handle != NULL) {
1577         GNUNET_CORE_disconnect (core_handle);
1578         core_handle = NULL;
1579     }
1580     if (dht_handle != NULL) {
1581         GNUNET_DHT_disconnect (dht_handle);
1582         dht_handle = NULL;
1583     }
1584     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1585                 "shut down\n");
1586 }
1587
1588 /**
1589  * Process mesh requests.
1590  *
1591  * @param cls closure
1592  * @param server the initialized server
1593  * @param c configuration to use
1594  */
1595 static void
1596 run (void *cls,
1597      struct GNUNET_SERVER_Handle *server,
1598      const struct GNUNET_CONFIGURATION_Handle *c)
1599 {
1600     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1601                 "starting to run\n");
1602     GNUNET_SERVER_add_handlers (server, plugin_handlers);
1603     GNUNET_SERVER_disconnect_notify (server, &handle_client_disconnect, NULL);
1604     core_handle = GNUNET_CORE_connect (c,               /* Main configuration */
1605                             1,                                  /* queue size */
1606                             NULL,         /* Closure passed to MESH functions */
1607                             &core_init,      /* Call core_init once connected */
1608                             &core_connect,                 /* Handle connects */
1609                             &core_disconnect,  /* remove peers on disconnects */
1610                             NULL,       /* Do we care about "status" updates? */
1611                             NULL, /* Don't notify about all incoming messages */
1612                             GNUNET_NO,     /* For header only in notification */
1613                             NULL, /* Don't notify about all outbound messages */
1614                             GNUNET_NO,    /* For header-only out notification */
1615                             core_handlers);        /* Register these handlers */
1616     if (core_handle == NULL) {
1617         GNUNET_break(0);
1618     }
1619     dht_handle = GNUNET_DHT_connect(c, 64);
1620     if (dht_handle == NULL) {
1621         GNUNET_break(0);
1622     }
1623     next_tid = 0;
1624
1625     tunnels = GNUNET_CONTAINER_multihashmap_create(32);
1626     peers = GNUNET_CONTAINER_multihashmap_create(32);
1627     clients = NULL;
1628     clients_tail = NULL;
1629
1630     /* Path keepalive */
1631     GNUNET_SCHEDULER_add_delayed(REFRESH_PATH_TIME,
1632                                  &path_refresh,
1633                                  NULL);
1634
1635     /* Scheduled the task to clean up when shutdown is called */
1636     GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
1637                                   &shutdown_task, NULL);
1638
1639     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1640                 "end if run()\n");
1641 }
1642
1643 /**
1644  * The main function for the mesh service.
1645  *
1646  * @param argc number of arguments from the command line
1647  * @param argv command line arguments
1648  * @return 0 ok, 1 on error
1649  */
1650 int
1651 main (int argc, char *const *argv)
1652 {
1653     int ret;
1654
1655     ret = (GNUNET_OK ==
1656            GNUNET_SERVICE_run (argc,
1657                                argv,
1658                                "mesh",
1659                                GNUNET_SERVICE_OPTION_NONE,
1660                                &run, NULL)) ? 0 : 1;
1661     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1662                 "end of main()\n");
1663     return ret;
1664 }