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