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