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