Fixed many bugs, test local 2 now passes, but with memory leaks
[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 *tree;
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 #if MESH_DEBUG
497     /**
498      * ID of the client, for debug messages
499      */
500   unsigned int id;
501 #endif
502
503 };
504
505 /******************************************************************************/
506 /***********************      GLOBAL VARIABLES     ****************************/
507 /******************************************************************************/
508
509 /**
510  * All the clients
511  */
512 static struct MeshClient *clients;
513 static struct MeshClient *clients_tail;
514
515 /**
516  * Tunnels known, indexed by MESH_TunnelID (MeshTunnel)
517  */
518 static struct GNUNET_CONTAINER_MultiHashMap *tunnels;
519
520 /**
521  * Peers known, indexed by PeerIdentity (MeshPeerInfo)
522  */
523 static struct GNUNET_CONTAINER_MultiHashMap *peers;
524
525 /**
526  * Handle to communicate with core
527  */
528 static struct GNUNET_CORE_Handle *core_handle;
529
530 /**
531  * Handle to use DHT
532  */
533 static struct GNUNET_DHT_Handle *dht_handle;
534
535 /**
536  * Handle to server
537  */
538 static struct GNUNET_SERVER_Handle *server_handle;
539
540 /**
541  * Notification context, to send messages to local clients
542  */
543 static struct GNUNET_SERVER_NotificationContext *nc;
544
545 /**
546  * Local peer own ID (memory efficient handle)
547  */
548 static GNUNET_PEER_Id myid;
549
550 /**
551  * Local peer own ID (full value)
552  */
553 static struct GNUNET_PeerIdentity my_full_id;
554
555 /**
556  * Own private key
557  */
558 static struct GNUNET_CRYPTO_RsaPrivateKey* my_private_key;
559
560 /**
561  * Own public key.
562  */
563 static struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded my_public_key;
564
565 /**
566  * Tunnel ID for the next created tunnel (global tunnel number)
567  */
568 static MESH_TunnelNumber next_tid;
569
570 /**
571  * All application types provided by this peer
572  */
573 static struct GNUNET_CONTAINER_MultiHashMap *applications;
574
575 /**
576  * All message types clients of this peer are interested in
577  */
578 static struct GNUNET_CONTAINER_MultiHashMap *types;
579
580 /**
581  * Task to periodically announce provided applications
582  */
583 GNUNET_SCHEDULER_TaskIdentifier announce_applications_task;
584
585 /**
586  * Task to periodically announce itself in the network
587  */
588 GNUNET_SCHEDULER_TaskIdentifier announce_id_task;
589
590 #if MESH_DEBUG
591 unsigned int next_client_id;
592 #endif
593
594
595 /******************************************************************************/
596 /************************    PERIODIC FUNCTIONS    ****************************/
597 /******************************************************************************/
598
599 /**
600  * Announce iterator over for each application provided by the peer
601  *
602  * @param cls closure
603  * @param key current key code
604  * @param value value in the hash map
605  * @return GNUNET_YES if we should continue to
606  *         iterate,
607  *         GNUNET_NO if not.
608  */
609 static int
610 announce_application (void *cls, const GNUNET_HashCode * key, void *value)
611 {
612   /* FIXME are hashes in multihash map equal on all aquitectures? */
613   GNUNET_DHT_put (dht_handle, key, 10U, GNUNET_DHT_RO_RECORD_ROUTE,
614                   GNUNET_BLOCK_TYPE_TEST, sizeof (struct GNUNET_PeerIdentity),
615                   (const char *) &my_full_id,
616 #if MESH_DEBUG
617                   GNUNET_TIME_UNIT_FOREVER_ABS, GNUNET_TIME_UNIT_FOREVER_REL,
618                   &mesh_debug, "DHT_put for app completed");
619 #else
620                   GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get (),
621                                             APP_ANNOUNCE_TIME),
622                   APP_ANNOUNCE_TIME, NULL, NULL);
623 #endif
624   return GNUNET_OK;
625 }
626
627
628 /**
629  * Periodically announce what applications are provided by local clients
630  *
631  * @param cls closure
632  * @param tc task context
633  */
634 static void
635 announce_applications (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
636 {
637   if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
638   {
639     announce_applications_task = GNUNET_SCHEDULER_NO_TASK;
640     return;
641   }
642   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: Starting PUT for apps\n");
643   GNUNET_CONTAINER_multihashmap_iterate (applications, &announce_application,
644                                          NULL);
645   announce_applications_task =
646       GNUNET_SCHEDULER_add_delayed (APP_ANNOUNCE_TIME, &announce_applications,
647                                     cls);
648   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: Finished PUT for apps\n");
649   return;
650 }
651
652
653 /**
654  * Periodically announce self id in the DHT
655  *
656  * @param cls closure
657  * @param tc task context
658  */
659 static void
660 announce_id (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
661 {
662   if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
663   {
664     announce_id_task = GNUNET_SCHEDULER_NO_TASK;
665     return;
666   }
667   /* TODO
668    * - Set data expiration in function of X
669    * - Adapt X to churn
670    */
671   GNUNET_DHT_put (dht_handle,   /* DHT handle */
672                   &my_full_id.hashPubKey,       /* Key to use */
673                   10U,          /* Replication level */
674                   GNUNET_DHT_RO_RECORD_ROUTE,   /* DHT options */
675                   GNUNET_BLOCK_TYPE_TEST,       /* Block type */
676                   0,            /* Size of the data */
677                   NULL,         /* Data itself */
678                   GNUNET_TIME_absolute_get_forever (),  /* Data expiration */
679                   GNUNET_TIME_UNIT_FOREVER_REL, /* Retry time */
680 #if MESH_DEBUG
681                   &mesh_debug, "DHT_put for id completed");
682 #else
683                   NULL,         /* Continuation */
684                   NULL);        /* Continuation closure */
685 #endif
686   announce_id_task =
687       GNUNET_SCHEDULER_add_delayed (ID_ANNOUNCE_TIME, &announce_id, cls);
688 }
689
690
691 /**
692  * Send keepalive packets for a peer
693  *
694  * @param cls unused
695  * @param tc unused
696  *
697  * FIXME path
698  */
699 static void
700 path_refresh (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
701 {
702   struct MeshTunnel *t = cls;
703
704 //   struct GNUNET_PeerIdentity id;
705
706   if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
707   {
708     return;
709   }
710   /* FIXME implement multicast keepalive. Just an empty multicast packet? */
711 //   GNUNET_PEER_resolve (path_get_first_hop (path->t, path->peer)->id, &id);
712 //   GNUNET_CORE_notify_transmit_ready (core_handle, 0, 0,
713 //                                      GNUNET_TIME_UNIT_FOREVER_REL, &id,
714 //                                      sizeof (struct GNUNET_MESH_ManipulatePath)
715 //                                      +
716 //                                      (path->path->length *
717 //                                       sizeof (struct GNUNET_PeerIdentity)),
718 //                                      &send_core_create_path,
719 //                                      t);
720   t->path_refresh_task =
721       GNUNET_SCHEDULER_add_delayed (REFRESH_PATH_TIME, &path_refresh, t);
722   return;
723 }
724
725
726 /******************************************************************************/
727 /******************      GENERAL HELPER FUNCTIONS      ************************/
728 /******************************************************************************/
729
730 /**
731  * Retrieve the MeshPeerInfo stucture associated with the peer, create one
732  * and insert it in the appropiate structures if the peer is not known yet.
733  *
734  * @param peer Identity of the peer
735  *
736  * @return Existing or newly created peer info
737  */
738 static struct MeshPeerInfo *
739 peer_info_get (const struct GNUNET_PeerIdentity *peer)
740 {
741   struct MeshPeerInfo *peer_info;
742
743   peer_info = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
744   if (NULL == peer_info)
745   {
746     peer_info =
747         (struct MeshPeerInfo *) GNUNET_malloc (sizeof (struct MeshPeerInfo));
748     GNUNET_CONTAINER_multihashmap_put (peers, &peer->hashPubKey, peer_info,
749                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
750     peer_info->id = GNUNET_PEER_intern (peer);
751   }
752
753   return peer_info;
754 }
755
756
757 #if LATER
758 /**
759  * Destroy the peer_info and free any allocated resources linked to it
760  * @param t tunnel the path belongs to
761  * @param pi the peer_info to destroy
762  * @return GNUNET_OK on success
763  */
764 static int
765 peer_info_destroy (struct MeshPeerInfo *pi)
766 {
767   GNUNET_HashCode hash;
768   struct GNUNET_PeerIdentity id;
769
770   GNUNET_PEER_resolve (pi->id, &id);
771   GNUNET_PEER_change_rc (pi->id, -1);
772   GNUNET_CRYPTO_hash (&id, sizeof (struct GNUNET_PeerIdentity), &hash);
773
774   GNUNET_CONTAINER_multihashmap_remove (peers, &hash, pi);
775   GNUNET_SCHEDULER_cancel (pi->path_refresh_task);
776   GNUNET_free (pi);
777   return GNUNET_OK;
778 }
779 #endif
780
781
782 /**
783  * Destroy the path and free any allocated resources linked to it
784  *
785  * @param p the path to destroy
786  *
787  * @return GNUNET_OK on success
788  */
789 static int
790 path_destroy (struct MeshPeerPath *p)
791 {
792   GNUNET_PEER_decrement_rcs (p->peers, p->length);
793   GNUNET_free (p->peers);
794   GNUNET_free (p);
795   return GNUNET_OK;
796 }
797
798
799 /**
800  * Invert the path
801  *
802  * @param p the path to invert
803  */
804 static void
805 path_invert (struct MeshPeerPath *path)
806 {
807   GNUNET_PEER_Id aux;
808   unsigned int i;
809
810   for (i = 0; i < path->length / 2; i++)
811   {
812     aux = path->peers[i];
813     path->peers[i] = path->peers[path->length - i - 1];
814     path->peers[path->length - i - 1] = aux;
815   }
816 }
817
818
819 /**
820  * Find the first peer whom to send a packet to go down this path
821  *
822  * @param t The tunnel to use
823  * @param peer The peerinfo of the peer we are trying to reach
824  *
825  * @return peerinfo of the peer who is the first hop in the tunnel
826  *         NULL on error
827  */
828 static struct MeshPeerInfo *
829 path_get_first_hop (struct MeshTunnel *t, struct MeshPeerInfo *peer)
830 {
831   struct GNUNET_PeerIdentity id;
832
833   GNUNET_PEER_resolve (peer->id, &id);
834   return GNUNET_CONTAINER_multihashmap_get (t->tree->first_hops,
835                                             &id.hashPubKey);
836 }
837
838
839 /**
840  * Get the length of a path
841  *
842  * @param path The path to measure, with the local peer at any point of it
843  *
844  * @return Number of hops to reach destination
845  *         UINT_MAX in case the peer is not in the path
846  */
847 static unsigned int
848 path_get_length (struct MeshPeerPath *path)
849 {
850   unsigned int i;
851
852   if (NULL == path)
853     return UINT_MAX;
854   for (i = 0; i < path->length; i++)
855   {
856     if (path->peers[i] == myid)
857     {
858       return path->length - i;
859     }
860   }
861   return UINT_MAX;
862 }
863
864
865 /**
866  * Get the cost of the path relative to the already built tunnel tree
867  *
868  * @param t The tunnel to which compare
869  * @param path The individual path to reach a peer
870  *
871  * @return Number of hops to reach destination, UINT_MAX in case the peer is not
872  * in the path
873  *
874  * TODO: remove dummy implementation, look into the tunnel tree
875  */
876 static unsigned int
877 path_get_cost (struct MeshTunnel *t, struct MeshPeerPath *path)
878 {
879   return path_get_length (path);
880 }
881
882
883 /**
884  * Add the path to the peer and update the path used to reach it in case this
885  * is the shortest.
886  *
887  * @param peer_info Destination peer to add the path to.
888  * @param path New path to add. Last peer must be the peer in arg 1.
889  *             Path will be either used of freed if already known.
890  *
891  * TODO: trim the part from origin to us? Add it as path to origin?
892  */
893 static void
894 path_add_to_peer (struct MeshPeerInfo *peer_info, struct MeshPeerPath *path)
895 {
896   struct MeshPeerPath *aux;
897   unsigned int l;
898   unsigned int l2;
899
900   if (NULL == peer_info || NULL == path)
901   {
902     GNUNET_break (0);
903     return;
904   }
905
906   l = path_get_length (path);
907
908   for (aux = peer_info->path_head; aux != NULL; aux = aux->next)
909   {
910     l2 = path_get_length (aux);
911     if (l2 > l)
912     {
913       GNUNET_CONTAINER_DLL_insert_before (peer_info->path_head,
914                                           peer_info->path_tail, aux, path);
915     }
916     else
917     {
918       if (l2 == l && memcmp(path->peers, aux->peers, l) == 0)
919       {
920         path_destroy(path);
921         return;
922       }
923     }
924   }
925   GNUNET_CONTAINER_DLL_insert_tail (peer_info->path_head, peer_info->path_tail,
926                                     path);
927   return;
928 }
929
930
931 /**
932  * Notify a tunnel that a connection has broken that affects at least
933  * some of its peers.
934  *
935  * @param t Tunnel affected
936  * @param peer Peer that (at least) has been affected by the disconnection
937  * @param p1 Peer that got disconnected from p2
938  * @param p2 Peer that got disconnected from p1
939  */
940 static void
941 tunnel_notify_connection_broken (struct MeshTunnel *t,
942                                  struct MeshPeerInfo *peer, GNUNET_PEER_Id p1,
943                                  GNUNET_PEER_Id p2);
944
945
946 /**
947  * Remove all paths that rely on a direct connection between p1 and p2
948  * from the peer itself and notify all tunnels about it.
949  *
950  * @param pi PeerInfo of affected peer
951  * @param p1 GNUNET_PEER_Id of one peer.
952  * @param p2 GNUNET_PEER_Id of another peer that was connected to the first and
953  *           no longer is.
954  */
955 static void
956 path_remove_from_peer (struct MeshPeerInfo *peer, GNUNET_PEER_Id p1,
957                        GNUNET_PEER_Id p2)
958 {
959   struct MeshPeerPath *p;
960   struct MeshPeerPath *aux;
961   unsigned int destroyed;
962   unsigned int i;
963
964   destroyed = 0;
965   p = peer->path_head;
966   while (NULL != p)
967   {
968     aux = p->next;
969     for (i = 0; i < (p->length - 1); i++)
970     {
971       if ((p->peers[i] == p1 && p->peers[i + 1] == p2) ||
972           (p->peers[i] == p2 && p->peers[i + 1] == p1))
973       {
974         path_destroy (p);
975         destroyed++;
976         break;
977       }
978     }
979     p = aux;
980   }
981   if (0 == destroyed)
982     return;
983
984   for (i = 0; i < peer->ntunnels; i++)
985   {
986     tunnel_notify_connection_broken (peer->tunnels[i], peer, p1, p2);
987   }
988 }
989
990
991 /**
992  * Add the path to the origin peer and update the path used to reach it in case
993  * this is the shortest.
994  * The path is given in peer_info -> destination, therefore we turn the path
995  * upside down first.
996  *
997  * @param peer_info Peer to add the path to, being the origin of the path.
998  * @param path New path to add after being inversed.
999  */
1000 static void
1001 path_add_to_origin (struct MeshPeerInfo *peer_info, struct MeshPeerPath *path)
1002 {
1003   path_invert(path);
1004   path_add_to_peer (peer_info, path);
1005 }
1006
1007
1008 /**
1009  * Build a PeerPath from the paths returned from the DHT, reversing the paths
1010  * to obtain a local peer -> destination path and interning the peer ids.
1011  *
1012  * @param get_path NULL-terminated array of pointers
1013  *                 to the peers on reverse GET path (or NULL if not recorded)
1014  * @param put_path NULL-terminated array of pointers
1015  *                 to the peers on the PUT path (or NULL if not recorded)
1016  *
1017  * @return Newly allocated and created path
1018  */
1019 static struct MeshPeerPath *
1020 path_build_from_dht (const struct GNUNET_PeerIdentity *const *get_path,
1021                      const struct GNUNET_PeerIdentity *const *put_path)
1022 {
1023   struct MeshPeerPath *p;
1024   GNUNET_PEER_Id id;
1025   int i;
1026
1027   p = GNUNET_malloc (sizeof (struct MeshPeerPath));
1028   for (i = 0; get_path[i] != NULL; i++) ;
1029   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "MESH:    GET has %d hops.\n", i);
1030   for (i--; i >= 0; i--)
1031   {
1032     id = GNUNET_PEER_intern (get_path[i]);
1033     if (p->length > 0 && id == p->peers[p->length - 1])
1034     {
1035       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "MESH:    Optimizing 1 hop out.\n");
1036       GNUNET_PEER_change_rc(id, -1);
1037     }
1038     else
1039     {
1040       p->peers =
1041         GNUNET_realloc (p->peers, sizeof (GNUNET_PEER_Id) * (p->length + 1));
1042       p->peers[p->length] = id;
1043       p->length++;
1044     }
1045   }
1046   for (i = 0; put_path[i] != NULL; i++) ;
1047   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "MESH:    PUT has %d hops.\n", i);
1048   for (i--; i >= 0; i--)
1049   {
1050     id = GNUNET_PEER_intern (put_path[i]);
1051     if (p->length > 0 && id == p->peers[p->length - 1])
1052     {
1053       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "MESH:    Optimizing 1 hop out.\n");
1054       GNUNET_PEER_change_rc(id, -1);
1055     }
1056     else
1057     {
1058       p->peers =
1059         GNUNET_realloc (p->peers, sizeof (GNUNET_PEER_Id) * (p->length + 1));
1060       p->peers[p->length] = id;
1061       p->length++;
1062     }
1063   }
1064 #if MESH_DEBUG
1065   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1066               "MESH:    (first of GET: %s)\n",
1067               GNUNET_h2s_full(&get_path[0]->hashPubKey));
1068   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1069               "MESH:    (first of PUT: %s)\n",
1070               GNUNET_h2s_full(&put_path[0]->hashPubKey));
1071   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1072               "MESH:    In total: %d hops\n",
1073               p->length);
1074 #endif
1075   return p;
1076 }
1077
1078
1079 /**
1080  * Check if client has registered with the service and has not disconnected
1081  *
1082  * @param client the client to check
1083  *
1084  * @return non-NULL if client exists in the global DLL
1085  */
1086 static struct MeshClient *
1087 client_get (struct GNUNET_SERVER_Client *client)
1088 {
1089   struct MeshClient *c;
1090
1091   c = clients;
1092   while (NULL != c)
1093   {
1094     if (c->handle == client)
1095       return c;
1096     c = c->next;
1097   }
1098   return NULL;
1099 }
1100
1101
1102 /**
1103  * Checks if a given client has subscribed to certain message type
1104  *
1105  * @param message_type Type of message to check
1106  * @param c Client to check
1107  *
1108  * @return GNUNET_YES or GNUNET_NO, depending on subscription status
1109  *
1110  * TODO inline?
1111  */
1112 static int
1113 client_is_subscribed (uint16_t message_type, struct MeshClient *c)
1114 {
1115   GNUNET_HashCode hc;
1116
1117   GNUNET_CRYPTO_hash (&message_type, sizeof (uint16_t), &hc);
1118   return GNUNET_CONTAINER_multihashmap_contains (c->types, &hc);
1119 }
1120
1121
1122 /**
1123  * Search for a tunnel among the tunnels for a client
1124  *
1125  * @param c the client whose tunnels to search in
1126  * @param tid the local id of the tunnel
1127  *
1128  * @return tunnel handler, NULL if doesn't exist
1129  */
1130 static struct MeshTunnel *
1131 tunnel_get_by_local_id (struct MeshClient *c, MESH_TunnelNumber tid)
1132 {
1133   GNUNET_HashCode hash;
1134
1135   GNUNET_CRYPTO_hash (&tid, sizeof (MESH_TunnelNumber), &hash);
1136   return GNUNET_CONTAINER_multihashmap_get (c->tunnels, &hash);
1137 }
1138
1139
1140 /**
1141  * Search for a tunnel by global ID using PEER_ID
1142  *
1143  * @param pi owner of the tunnel
1144  * @param tid global tunnel number
1145  *
1146  * @return tunnel handler, NULL if doesn't exist
1147  */
1148 static struct MeshTunnel *
1149 tunnel_get_by_pi (GNUNET_PEER_Id pi, MESH_TunnelNumber tid)
1150 {
1151   struct MESH_TunnelID id;
1152   GNUNET_HashCode hash;
1153
1154   id.oid = pi;
1155   id.tid = tid;
1156
1157   GNUNET_CRYPTO_hash (&id, sizeof (struct MESH_TunnelID), &hash);
1158   return GNUNET_CONTAINER_multihashmap_get (tunnels, &hash);
1159 }
1160
1161
1162
1163 /**
1164  * Search for a tunnel by global ID using full PeerIdentities
1165  *
1166  * @param oid owner of the tunnel
1167  * @param tid global tunnel number
1168  *
1169  * @return tunnel handler, NULL if doesn't exist
1170  */
1171 static struct MeshTunnel *
1172 tunnel_get (struct GNUNET_PeerIdentity *oid, MESH_TunnelNumber tid)
1173 {
1174   return tunnel_get_by_pi (GNUNET_PEER_search (oid), tid);
1175 }
1176
1177
1178 /**
1179  * Recursively find the given peer in the tree.
1180  *
1181  * @param t Tunnel where to look for the peer.
1182  * @param peer Peer to find
1183  *
1184  * @return Pointer to the node of the peer. NULL if not found.
1185  */
1186 static struct MeshTunnelPathNode *
1187 tunnel_find_peer (struct MeshTunnelPathNode *root, struct MeshPeerInfo *peer)
1188 {
1189   struct MeshTunnelPathNode *n;
1190   unsigned int i;
1191
1192   if (root->peer == peer)
1193     return root;
1194   for (i = 0; i < root->nchildren; i++)
1195   {
1196     n = tunnel_find_peer (&root->children[i], peer);
1197     if (NULL != n)
1198       return n;
1199   }
1200   return NULL;
1201 }
1202
1203
1204 /**
1205  * Recusively mark peer and children as disconnected, notify client
1206  *
1207  * @param parent Node to be clean, potentially with children
1208  */
1209 static void
1210 tunnel_mark_peers_disconnected (struct MeshTunnelPathNode *parent)
1211 {
1212   struct GNUNET_MESH_PeerControl msg;
1213   unsigned int i;
1214
1215   parent->status = MESH_PEER_RECONNECTING;
1216   for (i = 0; i < parent->nchildren; i++)
1217   {
1218     tunnel_mark_peers_disconnected (&parent->children[i]);
1219   }
1220   if (NULL == parent->t->client)
1221     return;
1222   msg.header.size = htons (sizeof (msg));
1223   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_DEL);
1224   msg.tunnel_id = htonl (parent->t->local_tid);
1225   GNUNET_PEER_resolve (parent->peer->id, &msg.peer);
1226   GNUNET_SERVER_notification_context_unicast (nc, parent->t->client->handle,
1227                                               &msg.header, GNUNET_NO);
1228 }
1229
1230 /**
1231  * Delete the current path to the peer, including all now unused relays.
1232  * The destination peer is NOT destroyed, it is returned in order to either set
1233  * a new path to it or destroy it explicitly, taking care of it's child nodes.
1234  *
1235  * @param t Tunnel where to delete the path from.
1236  * @param peer Destination peer whose path we want to remove.
1237  *
1238  * @return pointer to the pathless node, NULL on error
1239  *
1240  * TODO: notify peers of deletion
1241  */
1242 static struct MeshTunnelPathNode *
1243 tunnel_del_path (struct MeshTunnel *t, struct MeshPeerInfo *peer)
1244 {
1245   struct MeshTunnelPathNode *parent;
1246   struct MeshTunnelPathNode *node;
1247   struct MeshTunnelPathNode *n;
1248
1249   if (peer->id == t->tree->root->peer->id)
1250     return NULL;
1251   node = n = tunnel_find_peer (t->tree->me, peer);
1252   if (NULL == n)
1253     return NULL;
1254   parent = n->parent;
1255   n->parent = NULL;
1256   while (NULL != parent && MESH_PEER_RELAY == parent->status &&
1257          1 == parent->nchildren)
1258   {
1259     n = parent;
1260     GNUNET_free (parent->children);
1261     parent = parent->parent;
1262   }
1263   if (NULL == parent)
1264     return node;
1265   *n = parent->children[parent->nchildren - 1];
1266   parent->nchildren--;
1267   parent->children = GNUNET_realloc (parent->children, parent->nchildren);
1268
1269   tunnel_mark_peers_disconnected (node);
1270
1271   return node;
1272 }
1273
1274
1275 /**
1276  * Return a newly allocated individual path to reach a peer from the local peer,
1277  * according to the path tree of some tunnel.
1278  * 
1279  * @param t Tunnel from which to read the path tree
1280  * @param peer_info Destination peer to whom we want a path
1281  * 
1282  * @return A newly allocated individual path to reach the destination peer.
1283  *         Path must be destroyed afterwards.
1284  */
1285 static struct MeshPeerPath *
1286 tunnel_get_path_to_peer(struct MeshTunnel *t, struct MeshPeerInfo *peer_info)
1287 {
1288   struct MeshTunnelPathNode *n;
1289   struct MeshPeerPath *p;
1290
1291   n = tunnel_find_peer(t->tree->me, peer_info);
1292   p = GNUNET_malloc(sizeof(struct MeshPeerPath));
1293
1294   /* Building the path (inverted!) */
1295   while (n->peer->id != myid)
1296   {
1297     GNUNET_array_append(p->peers, p->length, n->peer->id);
1298     GNUNET_PEER_change_rc(n->peer->id, 1);
1299     n = n->parent;
1300     GNUNET_assert(NULL != n);
1301   }
1302   GNUNET_array_append(p->peers, p->length, myid);
1303   GNUNET_PEER_change_rc(myid, 1);
1304
1305   path_invert(p);
1306
1307   return p;
1308 }
1309
1310
1311 /**
1312  * Integrate a stand alone path into the tunnel tree.
1313  *
1314  * @param t Tunnel where to add the new path.
1315  * @param p Path to be integrated.
1316  *
1317  * @return GNUNET_OK in case of success.
1318  *         GNUNET_SYSERR in case of error.
1319  *
1320  * TODO: optimize
1321  * - go backwards on path looking for each peer in the present tree
1322  */
1323 static int
1324 tunnel_add_path (struct MeshTunnel *t, const struct MeshPeerPath *p)
1325 {
1326   struct MeshTunnelPathNode *parent;
1327   struct MeshTunnelPathNode *oldnode;
1328   struct MeshTunnelPathNode *n;
1329   struct GNUNET_PeerIdentity id;
1330   struct GNUNET_PeerIdentity hop;
1331   int me;
1332   unsigned int i;
1333   unsigned int j;
1334
1335   GNUNET_assert(0 != p->length);
1336   n = t->tree->root;
1337   if (n->peer->id != p->peers[0])
1338   {
1339     GNUNET_break (0);
1340     return GNUNET_SYSERR;
1341   }
1342   if (1 == p->length)
1343     return GNUNET_OK;
1344   GNUNET_PEER_resolve (p->peers[p->length - 1], &id);
1345   oldnode = tunnel_del_path (t, peer_info_get (&id));
1346   /* Look for the first node that is not already present in the tree
1347    *
1348    * Assuming that the tree is somewhat balanced, O(log n * log N).
1349    * - Length of the path is expected to be log N (size of whole network).
1350    * - Each level of the tree is expected to have log n children (size of tree).
1351    */
1352   for (i = 0, me = -1; i < p->length; i++)
1353   {
1354     parent = n;
1355     if (p->peers[i] == myid)
1356       me = i;
1357     for (j = 0; j < n->nchildren; j++)
1358     {
1359       if (n->children[j].peer->id == p->peers[i])
1360       {
1361         n = &n->children[j];
1362         break;
1363       }
1364     }
1365     /*  If we couldn't find a child equal to path[i], we have reached the end
1366      * of the common path. */
1367     if (parent == n)
1368       break;
1369   }
1370   if (-1 == me)
1371   {
1372     /* New path deviates from tree before reaching us. What happened? */
1373     GNUNET_break (0);
1374     return GNUNET_SYSERR;
1375   }
1376   /* Add the rest of the path as a branch from parent. */
1377   while (i < p->length)
1378   {
1379     parent->nchildren++;
1380     parent->children = GNUNET_realloc (parent->children,
1381                                        parent->nchildren *
1382                                        sizeof(struct MeshTunnelPathNode));
1383     n = &parent->children[parent->nchildren - 1];
1384     if (i == p->length - 1 && NULL != oldnode)
1385     {
1386       /* Assignation and free can be misleading, using explicit mempcy */
1387       memcpy (n, oldnode, sizeof (struct MeshTunnelPathNode));
1388       GNUNET_free (oldnode);
1389     }
1390     else
1391     {
1392       n->t = t;
1393       n->status = MESH_PEER_RELAY;
1394       GNUNET_PEER_resolve (p->peers[i], &id);
1395       n->peer = peer_info_get (&id);
1396     }
1397     n->parent = parent;
1398     i++;
1399     parent = n;
1400   }
1401
1402   /* Add info about first hop into hashmap. */
1403   if (me < p->length - 1)
1404   {
1405     GNUNET_PEER_resolve (p->peers[p->length - 1], &id);
1406     GNUNET_PEER_resolve (p->peers[me + 1], &hop);
1407     GNUNET_CONTAINER_multihashmap_put (t->tree->first_hops, &id.hashPubKey,
1408                                        peer_info_get (&hop),
1409                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
1410   }
1411   return GNUNET_OK;
1412 }
1413
1414
1415 /**
1416  * Add a peer to a tunnel, accomodating paths accordingly and initializing all
1417  * needed rescources.
1418  *
1419  * @param t Tunnel we want to add a new peer to
1420  * @param peer PeerInfo of the peer being added
1421  *
1422  */
1423 static void
1424 tunnel_add_peer (struct MeshTunnel *t, struct MeshPeerInfo *peer)
1425 {
1426   struct MeshPeerPath *p;
1427   struct MeshPeerPath *best_p;
1428   unsigned int best_cost;
1429   unsigned int cost;
1430
1431   GNUNET_array_append (peer->tunnels, peer->ntunnels, t);
1432   if (NULL == (p = peer->path_head))
1433     return;
1434
1435   best_p = p;
1436   best_cost = UINT_MAX;
1437   while (NULL != p)
1438   {
1439     if ((cost = path_get_cost (t, p)) < best_cost)
1440     {
1441       best_cost = cost;
1442       best_p = p;
1443     }
1444     p = p->next;
1445   }
1446   tunnel_add_path (t, best_p);
1447   if (GNUNET_SCHEDULER_NO_TASK == t->path_refresh_task)
1448     t->path_refresh_task =
1449         GNUNET_SCHEDULER_add_delayed (REFRESH_PATH_TIME, &path_refresh, t);
1450 }
1451
1452
1453 /**
1454  * Notify a tunnel that a connection has broken that affects at least
1455  * some of its peers.
1456  *
1457  * @param t Tunnel affected
1458  * @param peer Peer that (at least) has been affected by the disconnection
1459  * @param p1 Peer that got disconnected from p2
1460  * @param p2 Peer that got disconnected from p1
1461  * 
1462  * FIXME path
1463  */
1464 static void
1465 tunnel_notify_connection_broken (struct MeshTunnel *t,
1466                                  struct MeshPeerInfo *peer, GNUNET_PEER_Id p1,
1467                                  GNUNET_PEER_Id p2)
1468 {
1469 }
1470
1471
1472 /**
1473  * Recursively destory the path tree of a tunnel.
1474  * Note: it does not liberate memory for itself, parent must do it!
1475  *
1476  * @param n The node to destroy, along with children.
1477  *
1478  * @return GNUNET_OK on success
1479  */
1480 static void
1481 tunnel_destroy_tree_node (struct MeshTunnelPathNode *n)
1482 {
1483   unsigned int i;
1484
1485   for (i = 0; i < n->nchildren; i++)
1486   {
1487     tunnel_destroy_tree_node(&n->children[i]);
1488   }
1489   if (NULL != n->children)
1490     GNUNET_free (n->children);
1491 }
1492
1493
1494 /**
1495  * Destroy the tunnel and free any allocated resources linked to it
1496  *
1497  * @param t the tunnel to destroy
1498  *
1499  * @return GNUNET_OK on success
1500  */
1501 static int
1502 tunnel_destroy (struct MeshTunnel *t)
1503 {
1504   struct MeshClient *c;
1505   struct MeshQueue *q;
1506   struct MeshQueue *qn;
1507   GNUNET_HashCode hash;
1508   int r;
1509
1510   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: DESTROYING TUNNEL at %p\n", t);
1511   if (NULL == t)
1512     return GNUNET_OK;
1513
1514   c = t->client;
1515 #if MESH_DEBUG
1516   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   by client %u\n", c->id);
1517 #endif
1518
1519   GNUNET_CRYPTO_hash (&t->id, sizeof (struct MESH_TunnelID), &hash);
1520   if (GNUNET_YES != GNUNET_CONTAINER_multihashmap_remove (tunnels, &hash, t))
1521   {
1522     r = GNUNET_SYSERR;
1523   }
1524
1525   GNUNET_CRYPTO_hash (&t->local_tid, sizeof (MESH_TunnelNumber), &hash);
1526   if (GNUNET_YES != GNUNET_CONTAINER_multihashmap_remove (c->tunnels, &hash, t))
1527   {
1528     r = GNUNET_SYSERR;
1529   }
1530   GNUNET_CONTAINER_multihashmap_destroy (t->peers);
1531   q = t->queue_head;
1532   while (NULL != q)
1533   {
1534     if (NULL != q->data)
1535       GNUNET_free (q->data);
1536     qn = q->next;
1537     GNUNET_free (q);
1538     q = qn;
1539     /* TODO cancel core transmit ready in case it was active */
1540   }
1541
1542   GNUNET_CONTAINER_multihashmap_destroy(t->tree->first_hops);
1543   tunnel_destroy_tree_node(t->tree->root);
1544   GNUNET_free(t->tree->root);
1545   GNUNET_free (t->tree);
1546   GNUNET_free (t);
1547   return r;
1548 }
1549
1550
1551 /**
1552  * tunnel_destroy_iterator: iterator for deleting each tunnel that belongs to a
1553  * client when the client disconnects.
1554  * 
1555  * @param cls closure (client that is disconnecting)
1556  * @param key the hash of the local tunnel id (used to access the hashmap)
1557  * @param value the value stored at the key (tunnel to destroy)
1558  * 
1559  * @return GNUNET_OK on success
1560  */
1561 static int
1562 tunnel_destroy_iterator (void *cls, const GNUNET_HashCode * key, void *value)
1563 {
1564   int r;
1565
1566   r = tunnel_destroy ((struct MeshTunnel *) value);
1567   return r;
1568 }
1569
1570
1571 /******************************************************************************/
1572 /****************      MESH NETWORK HANDLER HELPERS     ***********************/
1573 /******************************************************************************/
1574
1575
1576 /**
1577  * Function called to notify a client about the socket
1578  * being ready to queue more data.  "buf" will be
1579  * NULL and "size" zero if the socket was closed for
1580  * writing in the meantime.
1581  *
1582  * @param cls closure
1583  * @param size number of bytes available in buf
1584  * @param buf where the callee should write the message
1585  * @return number of bytes written to buf
1586  */
1587 static size_t
1588 send_core_create_path (void *cls, size_t size, void *buf)
1589 {
1590   struct MeshPathInfo *info = cls;
1591   struct GNUNET_MESH_ManipulatePath *msg;
1592   struct GNUNET_PeerIdentity *peer_ptr;
1593   struct GNUNET_PeerIdentity id;
1594   struct MeshPeerInfo *peer = info->peer;
1595   struct MeshTunnel *t = info->t;
1596   struct MeshPeerPath *p = info->path;
1597   size_t size_needed;
1598   int i;
1599
1600   size_needed =
1601       sizeof (struct GNUNET_MESH_ManipulatePath) +
1602       p->length * sizeof (struct GNUNET_PeerIdentity);
1603
1604   if (size < size_needed || NULL == buf)
1605   {
1606     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: Retransmitting create path\n");
1607     GNUNET_PEER_resolve (path_get_first_hop (t, peer)->id, &id);
1608     GNUNET_CORE_notify_transmit_ready (core_handle, 0, 0,
1609                                        GNUNET_TIME_UNIT_FOREVER_REL, &id,
1610                                        size_needed, &send_core_create_path,
1611                                        info);
1612     return 0;
1613   }
1614
1615   msg = (struct GNUNET_MESH_ManipulatePath *) buf;
1616   msg->header.size = htons (size_needed);
1617   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE);
1618   msg->tid = ntohl (t->id.tid);
1619
1620   peer_ptr = (struct GNUNET_PeerIdentity *) &msg[1];
1621   for (i = 0; i < p->length; i++)
1622   {
1623     GNUNET_PEER_resolve (p->peers[i], peer_ptr++);
1624   }
1625
1626   path_destroy (p);
1627   GNUNET_free (info);
1628
1629   return size_needed;
1630 }
1631
1632
1633 #if LATER
1634 /**
1635  * Function called to notify a client about the socket
1636  * being ready to queue more data.  "buf" will be
1637  * NULL and "size" zero if the socket was closed for
1638  * writing in the meantime.
1639  *
1640  * @param cls closure (MeshDataDescriptor with all info to build packet)
1641  * @param size number of bytes available in buf
1642  * @param buf where the callee should write the message
1643  * @return number of bytes written to buf
1644  */
1645 static size_t
1646 send_core_data_to_origin (void *cls, size_t size, void *buf)
1647 {
1648   struct MeshDataDescriptor *info = cls;
1649   struct GNUNET_MESH_ToOrigin *msg = buf;
1650   size_t total_size;
1651
1652   GNUNET_assert (NULL != info);
1653   total_size = sizeof (struct GNUNET_MESH_ToOrigin) + info->size;
1654   GNUNET_assert (total_size < 65536);   /* UNIT16_MAX */
1655
1656   if (total_size > size)
1657   {
1658     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1659                 "not enough buffer to send data to origin\n");
1660     return 0;
1661   }
1662   msg->header.size = htons (total_size);
1663   msg->header.type = htons (GNUNET_MESSAGE_TYPE_DATA_MESSAGE_TO_ORIGIN);
1664   GNUNET_PEER_resolve (info->origin->oid, &msg->oid);
1665   msg->tid = htonl (info->origin->tid);
1666   if (0 != info->size)
1667   {
1668     memcpy (&msg[1], &info[1], info->size);
1669   }
1670   if (NULL != info->client)
1671   {
1672     GNUNET_SERVER_receive_done (info->client, GNUNET_OK);
1673   }
1674   GNUNET_free (info);
1675   return total_size;
1676 }
1677 #endif
1678
1679 /**
1680  * Function called to notify a client about the socket
1681  * being ready to queue more data.  "buf" will be
1682  * NULL and "size" zero if the socket was closed for
1683  * writing in the meantime.
1684  *
1685  * @param cls closure (data itself)
1686  * @param size number of bytes available in buf
1687  * @param buf where the callee should write the message
1688  * @return number of bytes written to buf
1689  */
1690 static size_t
1691 send_core_data_unicast (void *cls, size_t size, void *buf)
1692 {
1693   struct MeshDataDescriptor *info = cls;
1694   struct GNUNET_MESH_Unicast *msg = buf;
1695   size_t total_size;
1696
1697   GNUNET_assert (NULL != info);
1698   total_size = sizeof (struct GNUNET_MESH_Unicast) + info->size;
1699   GNUNET_assert (total_size < 65536);   /* UNIT16_MAX */
1700
1701   if (total_size > size)
1702   {
1703     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1704                 "not enough buffer to send data to peer\n");
1705     return 0;
1706   }
1707   msg->header.size = htons (total_size);
1708   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_UNICAST);
1709   GNUNET_PEER_resolve (info->origin->oid, &msg->oid);
1710   GNUNET_PEER_resolve (info->destination, &msg->destination);
1711   msg->tid = htonl (info->origin->tid);
1712   if (0 != info->size)
1713   {
1714     memcpy (&msg[1], &info[1], info->size);
1715   }
1716   if (NULL != info->client)
1717   {
1718     GNUNET_SERVER_receive_done (info->client, GNUNET_OK);
1719   }
1720   GNUNET_free (info);
1721   return total_size;
1722 }
1723
1724
1725 /**
1726  * Function called to notify a client about the socket
1727  * being ready to queue more data.  "buf" will be
1728  * NULL and "size" zero if the socket was closed for
1729  * writing in the meantime.
1730  *
1731  * @param cls closure (data itself)
1732  * @param size number of bytes available in buf
1733  * @param buf where the callee should write the message
1734  * @return number of bytes written to buf
1735  */
1736 static size_t
1737 send_core_data_multicast (void *cls, size_t size, void *buf)
1738 {
1739   struct MeshDataDescriptor *info = cls;
1740   struct GNUNET_MESH_Multicast *msg = buf;
1741   size_t total_size;
1742
1743   GNUNET_assert (NULL != info);
1744   total_size = info->size + sizeof (struct GNUNET_MESH_Multicast);
1745   GNUNET_assert (total_size < GNUNET_SERVER_MAX_MESSAGE_SIZE);
1746
1747   if (info->peer)
1748   {
1749     info->peer->core_transmit[info->handler_n] = NULL;
1750   }
1751   if (total_size > size)
1752   {
1753     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1754                 "not enough buffer to send data futher\n");
1755     return 0;
1756   }
1757   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_MULTICAST);
1758   msg->header.size = htons (total_size);
1759   GNUNET_PEER_resolve (info->origin->oid, &msg->oid);
1760   msg->tid = htonl (info->origin->tid);
1761   memcpy (&msg[1], &info[1], total_size);
1762   if (0 == --info->copies)
1763   {
1764     if (NULL != info->client)
1765     {
1766       GNUNET_SERVER_receive_done (info->client, GNUNET_OK);
1767     }
1768     GNUNET_free (info);
1769   }
1770   return total_size;
1771 }
1772
1773
1774 /**
1775  * Function called to notify a client about the socket
1776  * being ready to queue more data.  "buf" will be
1777  * NULL and "size" zero if the socket was closed for
1778  * writing in the meantime.
1779  *
1780  * @param cls closure (MeshDataDescriptor)
1781  * @param size number of bytes available in buf
1782  * @param buf where the callee should write the message
1783  * @return number of bytes written to buf
1784  */
1785 static size_t
1786 send_core_path_ack (void *cls, size_t size, void *buf)
1787 {
1788   struct MeshDataDescriptor *info = cls;
1789   struct GNUNET_MESH_PathACK *msg = buf;
1790
1791   GNUNET_assert (NULL != info);
1792   if (info->peer)
1793   {
1794     info->peer->core_transmit[info->handler_n] = NULL;
1795   }
1796   if (sizeof (struct GNUNET_MESH_PathACK) > size)
1797   {
1798     GNUNET_break (0);
1799     return 0;
1800   }
1801   msg->header.size = htons (sizeof (struct GNUNET_MESH_PathACK));
1802   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_ACK);
1803   GNUNET_PEER_resolve (info->origin->oid, &msg->oid);
1804   msg->tid = htonl (info->origin->tid);
1805   msg->peer_id = my_full_id;
1806   GNUNET_free (info);
1807   /* TODO add signature */
1808
1809   return sizeof (struct GNUNET_MESH_PathACK);
1810 }
1811
1812
1813 /**
1814  * Function called to notify a client about the socket
1815  * being ready to queue more data.  "buf" will be
1816  * NULL and "size" zero if the socket was closed for
1817  * writing in the meantime.
1818  *
1819  * @param cls closure (data itself)
1820  * @param size number of bytes available in buf
1821  * @param buf where the callee should write the message
1822  * @return number of bytes written to buf
1823  */
1824 static size_t
1825 send_core_data_raw (void *cls, size_t size, void *buf)
1826 {
1827   struct GNUNET_MessageHeader *msg = cls;
1828   size_t total_size;
1829
1830   GNUNET_assert (NULL != msg);
1831   total_size = ntohs (msg->size);
1832
1833   if (total_size > size)
1834   {
1835     GNUNET_break (0);
1836     return 0;
1837   }
1838   memcpy (buf, msg, total_size);
1839   GNUNET_free (cls);
1840   return total_size;
1841 }
1842
1843
1844 #if LATER
1845 /**
1846  * Send another peer a notification to destroy a tunnel
1847  * @param cls The tunnel to destroy
1848  * @param size Size in the buffer
1849  * @param buf Memory where to put the data to transmit
1850  * @return Size of data put in buffer
1851  */
1852 static size_t
1853 send_p2p_tunnel_destroy (void *cls, size_t size, void *buf)
1854 {
1855   struct MeshTunnel *t = cls;
1856   struct MeshClient *c;
1857   struct GNUNET_MESH_TunnelMessage *msg;
1858
1859   c = t->client;
1860   msg = buf;
1861   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_DESTROY);
1862    /*FIXME*/ msg->header.size =
1863       htons (sizeof (struct GNUNET_MESH_TunnelMessage));
1864   msg->tunnel_id = htonl (t->id.tid);
1865
1866   tunnel_destroy (c, t);
1867   return sizeof (struct GNUNET_MESH_TunnelMessage);
1868 }
1869 #endif
1870
1871
1872 /**
1873  * Send the message to all clients that have subscribed to its type
1874  *
1875  * @param msg Pointer to the message itself
1876  * @return number of clients this message was sent to
1877  */
1878 static unsigned int
1879 send_subscribed_clients (struct GNUNET_MessageHeader *msg)
1880 {
1881   struct MeshClient *c;
1882   unsigned int count;
1883   uint16_t type;
1884
1885   type = ntohs (msg->type);
1886   for (count = 0, c = clients; c != NULL; c = c->next)
1887   {
1888     if (client_is_subscribed (type, c))
1889     {
1890       count++;
1891       GNUNET_SERVER_notification_context_unicast (nc, c->handle, msg,
1892                                                   GNUNET_YES);
1893     }
1894   }
1895   return count;
1896 }
1897
1898
1899
1900 /**
1901  * Notify the client that owns the tunnel that a peer has connected to it
1902  * 
1903  * @param t Tunnel whose owner to notify
1904  * @param id Short id of the peer that has connected
1905  */
1906 static void
1907 send_client_peer_connected (const struct MeshTunnel *t, const GNUNET_PEER_Id id)
1908 {
1909   struct GNUNET_MESH_PeerControl pc;
1910
1911   pc.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD);
1912   pc.header.size = htons (sizeof (struct GNUNET_MESH_PeerControl));
1913   pc.tunnel_id = htonl (t->local_tid);
1914   GNUNET_PEER_resolve (id, &pc.peer);
1915   GNUNET_SERVER_notification_context_unicast (nc, t->client->handle,
1916                                               &pc.header, GNUNET_NO);
1917 }
1918
1919
1920 /**
1921  * Iterator over hash map peer entries collect all neighbors who to resend the
1922  * data to.
1923  *
1924  * @param cls closure (**GNUNET_PEER_Id to store hops to send packet)
1925  * @param key current key code (peer id hash)
1926  * @param value value in the hash map (peer_info)
1927  * @return GNUNET_YES if we should continue to iterate, GNUNET_NO if not.
1928  */
1929 static int
1930 iterate_collect_neighbors (void *cls, const GNUNET_HashCode * key, void *value)
1931 {
1932   struct MeshPeerInfo *peer_info = value;
1933   struct MeshPathInfo *neighbors = cls;
1934   unsigned int i;
1935
1936   if (peer_info->id == myid)
1937   {
1938     return GNUNET_YES;
1939   }
1940   peer_info = path_get_first_hop (neighbors->t, peer_info);
1941   for (i = 0; i < neighbors->path->length; i++)
1942   {
1943     if (neighbors->path->peers[i] == peer_info->id)
1944       return GNUNET_YES;
1945   }
1946   GNUNET_array_append (neighbors->path->peers, neighbors->path->length,
1947                        peer_info->id);
1948
1949   return GNUNET_YES;
1950 }
1951
1952
1953 /******************************************************************************/
1954 /********************      MESH NETWORK HANDLERS     **************************/
1955 /******************************************************************************/
1956
1957
1958 /**
1959  * Core handler for path creation
1960  * struct GNUNET_CORE_MessageHandler
1961  *
1962  * @param cls closure
1963  * @param message message
1964  * @param peer peer identity this notification is about
1965  * @param atsi performance data
1966  * @return GNUNET_OK to keep the connection open,
1967  *         GNUNET_SYSERR to close it (signal serious error)
1968  *
1969  */
1970 static int
1971 handle_mesh_path_create (void *cls, const struct GNUNET_PeerIdentity *peer,
1972                          const struct GNUNET_MessageHeader *message,
1973                          const struct GNUNET_TRANSPORT_ATS_Information *atsi)
1974 {
1975   unsigned int own_pos;
1976   uint16_t size;
1977   uint16_t i;
1978   MESH_TunnelNumber tid;
1979   struct GNUNET_MESH_ManipulatePath *msg;
1980   struct GNUNET_PeerIdentity *pi;
1981   struct GNUNET_PeerIdentity id;
1982   GNUNET_HashCode hash;
1983   struct MeshPeerPath *path;
1984   struct MeshPeerInfo *dest_peer_info;
1985   struct MeshPeerInfo *orig_peer_info;
1986   struct MeshTunnel *t;
1987
1988   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1989               "MESH: Received a MESH path create msg\n");
1990   size = ntohs (message->size);
1991   if (size < sizeof (struct GNUNET_MESH_ManipulatePath))
1992   {
1993     GNUNET_break_op (0);
1994     return GNUNET_OK;
1995   }
1996
1997   size -= sizeof (struct GNUNET_MESH_ManipulatePath);
1998   if (size % sizeof (struct GNUNET_PeerIdentity))
1999   {
2000     GNUNET_break_op (0);
2001     return GNUNET_OK;
2002   }
2003   size /= sizeof (struct GNUNET_PeerIdentity);
2004   if (size < 2)
2005   {
2006     GNUNET_break_op (0);
2007     return GNUNET_OK;
2008   }
2009   msg = (struct GNUNET_MESH_ManipulatePath *) message;
2010
2011   tid = ntohl (msg->tid);
2012   pi = (struct GNUNET_PeerIdentity *) &msg[1];
2013   t = tunnel_get (pi, tid);
2014
2015   if (NULL == t)
2016   {
2017     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: Creating tunnel\n");
2018     t = GNUNET_malloc (sizeof (struct MeshTunnel));
2019     t->id.oid = GNUNET_PEER_intern (pi);
2020     t->id.tid = tid;
2021     t->peers = GNUNET_CONTAINER_multihashmap_create (32);
2022
2023     GNUNET_CRYPTO_hash (&t->id, sizeof (struct MESH_TunnelID), &hash);
2024     if (GNUNET_OK !=
2025         GNUNET_CONTAINER_multihashmap_put (tunnels, &hash, t,
2026                                            GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
2027     {
2028       GNUNET_break (0);
2029       return GNUNET_OK;
2030     }
2031
2032   }
2033   dest_peer_info =
2034       GNUNET_CONTAINER_multihashmap_get (peers, &pi[size - 1].hashPubKey);
2035   if (NULL == dest_peer_info)
2036   {
2037     dest_peer_info = GNUNET_malloc (sizeof (struct MeshPeerInfo));
2038     dest_peer_info->id = GNUNET_PEER_intern (&pi[size - 1]);
2039     GNUNET_CONTAINER_multihashmap_put (peers, &pi[size - 1].hashPubKey,
2040                                        dest_peer_info,
2041                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
2042   }
2043   orig_peer_info = GNUNET_CONTAINER_multihashmap_get (peers, &pi->hashPubKey);
2044   if (NULL == orig_peer_info)
2045   {
2046     orig_peer_info = GNUNET_malloc (sizeof (struct MeshPeerInfo));
2047     orig_peer_info->id = GNUNET_PEER_intern (pi);
2048     GNUNET_CONTAINER_multihashmap_put (peers, &pi->hashPubKey, orig_peer_info,
2049                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
2050   }
2051
2052   path = GNUNET_malloc (sizeof (struct MeshPeerPath));
2053   path->length = size;
2054   path->peers = GNUNET_malloc (size * sizeof (GNUNET_PEER_Id));
2055   own_pos = 0;
2056   for (i = 0; i < size; i++)
2057   {
2058     path->peers[i] = GNUNET_PEER_intern (&pi[i]);
2059     if (path->peers[i] == myid)
2060       own_pos = i;
2061   }
2062   if (own_pos == 0)
2063   {                             /* cannot be self, must be 'not found' */
2064     /* create path: self not found in path through self */
2065     GNUNET_break_op (0);
2066     path_destroy (path);
2067     /* FIXME error. destroy tunnel? leave for timeout? */
2068     return 0;
2069   }
2070   if (own_pos == size - 1)
2071   {
2072     /* It is for us! Send ack. */
2073     struct MeshDataDescriptor *info;
2074     unsigned int j;
2075
2076     path_add_to_origin (orig_peer_info, path);  /* inverts path!  */
2077     info = GNUNET_malloc (sizeof (struct MeshDataDescriptor));
2078     info->origin = &t->id;
2079     info->peer = GNUNET_CONTAINER_multihashmap_get (peers, &id.hashPubKey);
2080     GNUNET_assert (info->peer);
2081     for (j = 0; info->peer->core_transmit[j]; j++)
2082     {
2083       if (j == 9)
2084       {
2085         GNUNET_break (0);
2086         return GNUNET_OK;
2087       }
2088     }
2089     info->handler_n = j;
2090     info->peer->core_transmit[j] =
2091         GNUNET_CORE_notify_transmit_ready (core_handle, 0, 100,
2092                                            GNUNET_TIME_UNIT_FOREVER_REL, peer,
2093                                            sizeof (struct GNUNET_MessageHeader),
2094                                            &send_core_path_ack, info);
2095   }
2096   else
2097   {
2098     /* It's for somebody else! Retransmit. */
2099     struct MeshPathInfo *path_info;
2100
2101     path_info = GNUNET_malloc (sizeof (struct MeshPathInfo));
2102     path_info->t = t;
2103     path_info->path = path;
2104     path_info->peer = dest_peer_info;
2105
2106     path_add_to_peer (dest_peer_info, path);
2107     GNUNET_PEER_resolve (path->peers[own_pos + 1], &id);
2108     GNUNET_CORE_notify_transmit_ready (core_handle, 0, 0,
2109                                        GNUNET_TIME_UNIT_FOREVER_REL, &id,
2110                                        sizeof (struct GNUNET_MessageHeader),
2111                                        &send_core_create_path, path_info);
2112   }
2113   return GNUNET_OK;
2114 }
2115
2116
2117 /**
2118  * Core handler for mesh network traffic going from the origin to a peer
2119  *
2120  * @param cls closure
2121  * @param peer peer identity this notification is about
2122  * @param message message
2123  * @param atsi performance data
2124  * @return GNUNET_OK to keep the connection open,
2125  *         GNUNET_SYSERR to close it (signal serious error)
2126  */
2127 static int
2128 handle_mesh_data_unicast (void *cls, const struct GNUNET_PeerIdentity *peer,
2129                           const struct GNUNET_MessageHeader *message,
2130                           const struct GNUNET_TRANSPORT_ATS_Information *atsi)
2131 {
2132   struct GNUNET_MESH_Unicast *msg;
2133   struct GNUNET_PeerIdentity id;
2134   struct MeshTunnel *t;
2135   struct MeshPeerInfo *pi;
2136   size_t size;
2137
2138   size = ntohs (message->size);
2139   if (size <
2140       sizeof (struct GNUNET_MESH_Unicast) +
2141       sizeof (struct GNUNET_MessageHeader))
2142   {
2143     GNUNET_break (0);
2144     return GNUNET_OK;
2145   }
2146   msg = (struct GNUNET_MESH_Unicast *) message;
2147   t = tunnel_get (&msg->oid, ntohl (msg->tid));
2148   if (NULL == t)
2149   {
2150     /* TODO notify back: we don't know this tunnel */
2151     return GNUNET_OK;
2152   }
2153   pi = GNUNET_CONTAINER_multihashmap_get (t->peers,
2154                                           &msg->destination.hashPubKey);
2155   if (NULL == pi)
2156   {
2157     /* TODO maybe feedback, log to statistics */
2158     return GNUNET_OK;
2159   }
2160   if (pi->id == myid)
2161   {
2162     send_subscribed_clients ((struct GNUNET_MessageHeader *) &msg[1]);
2163     return GNUNET_OK;
2164   }
2165   GNUNET_PEER_resolve (path_get_first_hop (t, pi)->id, &id);
2166   msg = GNUNET_malloc (size);
2167   memcpy (msg, message, size);
2168   GNUNET_CORE_notify_transmit_ready (core_handle, 0, 0,
2169                                      GNUNET_TIME_UNIT_FOREVER_REL, &id, size,
2170                                      &send_core_data_raw, msg);
2171   return GNUNET_OK;
2172 }
2173
2174
2175 /**
2176  * Core handler for mesh network traffic going from the origin to all peers
2177  *
2178  * @param cls closure
2179  * @param message message
2180  * @param peer peer identity this notification is about
2181  * @param atsi performance data
2182  * @return GNUNET_OK to keep the connection open,
2183  *         GNUNET_SYSERR to close it (signal serious error)
2184  */
2185 static int
2186 handle_mesh_data_multicast (void *cls, const struct GNUNET_PeerIdentity *peer,
2187                             const struct GNUNET_MessageHeader *message,
2188                             const struct GNUNET_TRANSPORT_ATS_Information *atsi)
2189 {
2190   struct GNUNET_MESH_Multicast *msg;
2191   struct GNUNET_PeerIdentity id;
2192   struct MeshDataDescriptor *info;
2193   struct MeshPathInfo neighbors;
2194   struct MeshTunnel *t;
2195   size_t size;
2196   uint16_t i;
2197   uint16_t j;
2198
2199
2200   size = ntohs (message->size);
2201   if (size <
2202       sizeof (struct GNUNET_MESH_Multicast) +
2203       sizeof (struct GNUNET_MessageHeader))
2204   {
2205     GNUNET_break_op (0);
2206     return GNUNET_OK;
2207   }
2208   msg = (struct GNUNET_MESH_Multicast *) message;
2209   t = tunnel_get (&msg->oid, ntohl (msg->tid));
2210
2211   if (NULL == t)
2212   {
2213     /* TODO notify that we dont know that tunnel */
2214     return GNUNET_OK;
2215   }
2216
2217   /* Transmit to locally interested clients */
2218   if (GNUNET_CONTAINER_multihashmap_contains (t->peers, &my_full_id.hashPubKey))
2219   {
2220     send_subscribed_clients ((struct GNUNET_MessageHeader *) &msg[1]);
2221   }
2222
2223   /* Retransmit to other peers.
2224    * Using path here as just a collection of peers, not a path per se.
2225    */
2226   neighbors.t = t;
2227   neighbors.path = GNUNET_malloc (sizeof (struct MeshPeerPath));
2228   GNUNET_CONTAINER_multihashmap_iterate (t->peers, &iterate_collect_neighbors,
2229                                          &neighbors);
2230   if (0 == neighbors.path->length)
2231   {
2232     GNUNET_free (neighbors.path);
2233     return GNUNET_OK;
2234   }
2235   size -= sizeof (struct GNUNET_MESH_Multicast);
2236   info = GNUNET_malloc (sizeof (struct MeshDataDescriptor) + size);
2237   info->origin = &t->id;
2238   info->copies = neighbors.path->length;
2239   for (i = 0; i < info->copies; i++)
2240   {
2241     GNUNET_PEER_resolve (neighbors.path->peers[i], &id);
2242     info->peer = GNUNET_CONTAINER_multihashmap_get (peers, &id.hashPubKey);
2243     GNUNET_assert (NULL != info->peer);
2244     for (j = 0; 0 != info->peer->core_transmit[j]; j++)
2245     {
2246       if (j == (CORE_QUEUE_SIZE - 1))
2247       {
2248         GNUNET_break (0);
2249         return GNUNET_OK;
2250       }
2251     }
2252     info->handler_n = j;
2253     info->peer->infos[j] = info;
2254     info->peer->core_transmit[j] =
2255         GNUNET_CORE_notify_transmit_ready (core_handle, 0, 0,
2256                                            GNUNET_TIME_UNIT_FOREVER_REL, &id,
2257                                            ntohs (msg->header.size),
2258                                            &send_core_data_multicast, info);
2259   }
2260   GNUNET_free (neighbors.path->peers);
2261   GNUNET_free (neighbors.path);
2262   return GNUNET_OK;
2263 }
2264
2265
2266 /**
2267  * Core handler for mesh network traffic
2268  *
2269  * @param cls closure
2270  * @param message message
2271  * @param peer peer identity this notification is about
2272  * @param atsi performance data
2273  *
2274  * @return GNUNET_OK to keep the connection open,
2275  *         GNUNET_SYSERR to close it (signal serious error)
2276  */
2277 static int
2278 handle_mesh_data_to_orig (void *cls, const struct GNUNET_PeerIdentity *peer,
2279                           const struct GNUNET_MessageHeader *message,
2280                           const struct GNUNET_TRANSPORT_ATS_Information *atsi)
2281 {
2282   struct GNUNET_MESH_ToOrigin *msg;
2283   struct GNUNET_PeerIdentity id;
2284   struct MeshPeerInfo *peer_info;
2285   struct MeshTunnel *t;
2286   size_t size;
2287
2288   size = ntohs (message->size);
2289   if (size < sizeof (struct GNUNET_MESH_ToOrigin) +     /* Payload must be */
2290       sizeof (struct GNUNET_MessageHeader))     /* at least a header */
2291   {
2292     GNUNET_break_op (0);
2293     return GNUNET_OK;
2294   }
2295   msg = (struct GNUNET_MESH_ToOrigin *) message;
2296   t = tunnel_get (&msg->oid, ntohl (msg->tid));
2297
2298   if (NULL == t)
2299   {
2300     /* TODO notify that we dont know this tunnel (whom)? */
2301     return GNUNET_OK;
2302   }
2303
2304   if (t->id.oid == myid)
2305   {
2306     if (NULL == t->client)
2307     {
2308       /* got data packet for ownerless tunnel */
2309       GNUNET_break_op (0);
2310       return GNUNET_OK;
2311     }
2312     /* TODO signature verification */
2313     GNUNET_SERVER_notification_context_unicast (nc, t->client->handle, message,
2314                                                 GNUNET_YES);
2315     return GNUNET_OK;
2316   }
2317   peer_info = peer_info_get (&msg->oid);
2318   if (NULL == peer_info)
2319   {
2320     /* unknown origin of tunnel */
2321     GNUNET_break (0);
2322     return GNUNET_OK;
2323   }
2324   GNUNET_PEER_resolve (t->tree->me->parent->peer->id, &id);
2325   msg = GNUNET_malloc (size);
2326   memcpy (msg, message, size);
2327   GNUNET_CORE_notify_transmit_ready (core_handle, 0, 0,
2328                                      GNUNET_TIME_UNIT_FOREVER_REL, &id, size,
2329                                      &send_core_data_raw, msg);
2330
2331   return GNUNET_OK;
2332 }
2333
2334
2335 /**
2336  * Core handler for path ACKs
2337  *
2338  * @param cls closure
2339  * @param message message
2340  * @param peer peer identity this notification is about
2341  * @param atsi performance data
2342  *
2343  * @return GNUNET_OK to keep the connection open,
2344  *         GNUNET_SYSERR to close it (signal serious error)
2345  *
2346  * FIXME path change state
2347  */
2348 static int
2349 handle_mesh_path_ack (void *cls, const struct GNUNET_PeerIdentity *peer,
2350                       const struct GNUNET_MessageHeader *message,
2351                       const struct GNUNET_TRANSPORT_ATS_Information *atsi)
2352 {
2353   struct GNUNET_MESH_PathACK *msg;
2354   struct GNUNET_PeerIdentity id;
2355   struct MeshTunnel *t;
2356   struct MeshPeerInfo *peer_info;
2357
2358   msg = (struct GNUNET_MESH_PathACK *) message;
2359   t = tunnel_get (&msg->oid, msg->tid);
2360   if (NULL == t)
2361   {
2362     /* TODO notify that we don't know the tunnel */
2363     return GNUNET_OK;
2364   }
2365
2366   /* Message for us? */
2367   if (0 == memcmp (&msg->oid, &my_full_id, sizeof (struct GNUNET_PeerIdentity)))
2368   {
2369
2370     if (NULL == t->client)
2371     {
2372       GNUNET_break (0);
2373       return GNUNET_OK;
2374     }
2375     peer_info = peer_info_get (&msg->peer_id);
2376     if (NULL == peer_info)
2377     {
2378       GNUNET_break_op (0);
2379       return GNUNET_OK;
2380     }
2381     /* FIXME change state of peer */
2382     send_client_peer_connected(t, peer_info->id);
2383     return GNUNET_OK;
2384   }
2385
2386   peer_info = peer_info_get (&msg->oid);
2387   if (NULL == peer_info)
2388   {
2389     /* If we know the tunnel, we should DEFINITELY know the peer */
2390     GNUNET_break (0);
2391     return GNUNET_OK;
2392   }
2393   GNUNET_PEER_resolve (path_get_first_hop (t, peer_info)->id, &id);
2394   msg = GNUNET_malloc (sizeof (struct GNUNET_MESH_PathACK));
2395   memcpy (msg, message, sizeof (struct GNUNET_MESH_PathACK));
2396   GNUNET_CORE_notify_transmit_ready (core_handle, 0, 0,
2397                                      GNUNET_TIME_UNIT_FOREVER_REL, &id,
2398                                      sizeof (struct GNUNET_MESH_PathACK),
2399                                      &send_core_data_raw, msg);
2400   return GNUNET_OK;
2401 }
2402
2403
2404 /**
2405  * Functions to handle messages from core
2406  */
2407 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
2408   {&handle_mesh_path_create, GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE, 0},
2409   {&handle_mesh_data_unicast, GNUNET_MESSAGE_TYPE_MESH_UNICAST, 0},
2410   {&handle_mesh_data_multicast, GNUNET_MESSAGE_TYPE_MESH_MULTICAST, 0},
2411   {&handle_mesh_data_to_orig, GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN, 0},
2412   {&handle_mesh_path_ack, GNUNET_MESSAGE_TYPE_MESH_PATH_ACK,
2413    sizeof (struct GNUNET_MESH_PathACK)},
2414   {NULL, 0, 0}
2415 };
2416
2417
2418
2419 /******************************************************************************/
2420 /****************       MESH LOCAL HANDLER HELPERS      ***********************/
2421 /******************************************************************************/
2422
2423 /**
2424  * deregister_app: iterator for removing each application registered by a client
2425  * 
2426  * @param cls closure
2427  * @param key the hash of the application id (used to access the hashmap)
2428  * @param value the value stored at the key (client)
2429  * 
2430  * @return GNUNET_OK on success
2431  */
2432 static int
2433 deregister_app (void *cls, const GNUNET_HashCode * key, void *value)
2434 {
2435   GNUNET_CONTAINER_multihashmap_remove (applications, key, value);
2436   return GNUNET_OK;
2437 }
2438
2439 #if LATER
2440 /**
2441  * notify_client_connection_failure: notify a client that the connection to the
2442  * requested remote peer is not possible (for instance, no route found)
2443  * Function called when the socket is ready to queue more data. "buf" will be
2444  * NULL and "size" zero if the socket was closed for writing in the meantime.
2445  *
2446  * @param cls closure
2447  * @param size number of bytes available in buf
2448  * @param buf where the callee should write the message
2449  * @return number of bytes written to buf
2450  */
2451 static size_t
2452 notify_client_connection_failure (void *cls, size_t size, void *buf)
2453 {
2454   int size_needed;
2455   struct MeshPeerInfo *peer_info;
2456   struct GNUNET_MESH_PeerControl *msg;
2457   struct GNUNET_PeerIdentity id;
2458
2459   if (0 == size && NULL == buf)
2460   {
2461     // TODO retry? cancel?
2462     return 0;
2463   }
2464
2465   size_needed = sizeof (struct GNUNET_MESH_PeerControl);
2466   peer_info = (struct MeshPeerInfo *) cls;
2467   msg = (struct GNUNET_MESH_PeerControl *) buf;
2468   msg->header.size = htons (sizeof (struct GNUNET_MESH_PeerControl));
2469   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_DISCONNECTED);
2470 //     msg->tunnel_id = htonl(peer_info->t->tid);
2471   GNUNET_PEER_resolve (peer_info->id, &id);
2472   memcpy (&msg->peer, &id, sizeof (struct GNUNET_PeerIdentity));
2473
2474   return size_needed;
2475 }
2476 #endif
2477
2478
2479 /**
2480  * Function to process paths received for a new peer addition. The recorded
2481  * paths form the initial tunnel, which can be optimized later.
2482  * Called on each result obtained for the DHT search.
2483  *
2484  * @param cls closure
2485  * @param exp when will this value expire
2486  * @param key key of the result
2487  * @param get_path NULL-terminated array of pointers
2488  *                 to the peers on reverse GET path (or NULL if not recorded)
2489  * @param put_path NULL-terminated array of pointers
2490  *                 to the peers on the PUT path (or NULL if not recorded)
2491  * @param type type of the result
2492  * @param size number of bytes in data
2493  * @param data pointer to the result data
2494  *
2495  * FIXME path
2496  */
2497 static void
2498 dht_get_id_handler (void *cls, struct GNUNET_TIME_Absolute exp,
2499                     const GNUNET_HashCode * key,
2500                     const struct GNUNET_PeerIdentity *const *get_path,
2501                     const struct GNUNET_PeerIdentity *const *put_path,
2502                     enum GNUNET_BLOCK_Type type, size_t size, const void *data)
2503 {
2504   struct MeshPathInfo *path_info = cls;
2505   struct MeshPeerPath *p;
2506   struct GNUNET_PeerIdentity pi;
2507   int i;
2508
2509   if (NULL == get_path || NULL == put_path)
2510   {
2511     if (NULL == path_info->peer->path_head)
2512     {
2513       // Find ourselves some alternate initial path to the destination: retry
2514       GNUNET_DHT_get_stop (path_info->peer->dhtget);
2515       GNUNET_PEER_resolve (path_info->peer->id, &pi);
2516       path_info->peer->dhtget = GNUNET_DHT_get_start (dht_handle,       /* handle */
2517                                                       GNUNET_TIME_UNIT_FOREVER_REL,     /* timeout */
2518                                                       GNUNET_BLOCK_TYPE_TEST,   /* type */
2519                                                       &pi.hashPubKey,   /*key to search */
2520                                                       4,        /* replication level */
2521                                                       GNUNET_DHT_RO_RECORD_ROUTE, NULL, /* bloom filter */
2522                                                       0,        /* mutator */
2523                                                       NULL,     /* xquery */
2524                                                       0,        /* xquery bits */
2525                                                       dht_get_id_handler,
2526                                                       (void *) path_info);
2527       return;
2528     }
2529   }
2530
2531   p = path_build_from_dht (get_path, put_path);
2532   path_add_to_peer (path_info->peer, p);
2533   for (i = 0; i < path_info->peer->ntunnels; i++)
2534   {
2535     tunnel_add_peer (path_info->peer->tunnels[i], path_info->peer);
2536   }
2537   GNUNET_free (path_info);
2538
2539   return;
2540 }
2541
2542
2543 /**
2544  * Function to process paths received for a new peer addition. The recorded
2545  * paths form the initial tunnel, which can be optimized later.
2546  * Called on each result obtained for the DHT search.
2547  *
2548  * @param cls closure
2549  * @param exp when will this value expire
2550  * @param key key of the result
2551  * @param get_path NULL-terminated array of pointers
2552  *                 to the peers on reverse GET path (or NULL if not recorded)
2553  * @param put_path NULL-terminated array of pointers
2554  *                 to the peers on the PUT path (or NULL if not recorded)
2555  * @param type type of the result
2556  * @param size number of bytes in data
2557  * @param data pointer to the result data
2558  */
2559 static void
2560 dht_get_type_handler (void *cls, struct GNUNET_TIME_Absolute exp,
2561                       const GNUNET_HashCode * key,
2562                       const struct GNUNET_PeerIdentity *const *get_path,
2563                       const struct GNUNET_PeerIdentity *const *put_path,
2564                       enum GNUNET_BLOCK_Type type, size_t size,
2565                       const void *data)
2566 {
2567   const struct GNUNET_PeerIdentity *pi = data;
2568   struct GNUNET_PeerIdentity id;
2569   struct MeshTunnel *t = cls;
2570   struct MeshPeerInfo *peer_info;
2571   struct MeshPathInfo *path_info;
2572   struct MeshPeerPath *p;
2573   int i;
2574
2575   if (size != sizeof (struct GNUNET_PeerIdentity))
2576   {
2577     GNUNET_break_op (0);
2578     return;
2579   }
2580   GNUNET_assert (NULL != t->client);
2581   GNUNET_DHT_get_stop (t->client->dht_get_type);
2582   t->client->dht_get_type = NULL;
2583   peer_info = peer_info_get (pi);
2584   GNUNET_CONTAINER_multihashmap_put (t->peers, &pi->hashPubKey, peer_info,
2585                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
2586
2587   if ((NULL == get_path || NULL == put_path) && NULL == peer_info->path_head &&
2588       NULL == peer_info->dhtget)
2589   {
2590     /* we don't have a route to the peer, let's try a direct lookup */
2591     peer_info->dhtget = GNUNET_DHT_get_start (dht_handle,
2592                                               /* handle */
2593                                               GNUNET_TIME_UNIT_FOREVER_REL,
2594                                               /* timeout */
2595                                               GNUNET_BLOCK_TYPE_TEST,
2596                                               /* block type */
2597                                               &pi->hashPubKey,
2598                                               /* key to look up */
2599                                               10U,
2600                                               /* replication level */
2601                                               GNUNET_DHT_RO_RECORD_ROUTE,
2602                                               /* option to dht: record route */
2603                                               NULL,     /* bloom filter */
2604                                               0,        /* mutator */
2605                                               NULL,     /* xquery */
2606                                               0,        /* xquery bits */
2607                                               dht_get_id_handler,
2608                                               /* callback */
2609                                               peer_info);       /* closure */
2610   }
2611
2612   p = path_build_from_dht (get_path, put_path);
2613   path_add_to_peer (peer_info, p);
2614   tunnel_add_peer(t, peer_info);
2615   p = tunnel_get_path_to_peer(t, peer_info);
2616 #if MESH_DEBUG
2617   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2618               "MESH: new route for tunnel 0x%x found, has %u hops\n",
2619               t->local_tid, p->length);
2620   for (i = 0; i < p->length; i++)
2621   {
2622     GNUNET_PEER_resolve (p->peers[0], &id);
2623     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:\t%d\t%s\n", i,
2624                 GNUNET_h2s_full (&id.hashPubKey));
2625   }
2626 #endif
2627
2628   if (p->length > 1)
2629   {
2630     path_info = GNUNET_malloc(sizeof(struct MeshPathInfo));
2631     path_info->t = t;
2632     path_info->peer = peer_info;
2633     path_info->path = p;
2634     GNUNET_PEER_resolve (p->peers[1], &id);
2635     GNUNET_CORE_notify_transmit_ready (core_handle,
2636                                      /* handle */
2637                                      0,
2638                                      /* cork */
2639                                      0,
2640                                      /* priority */
2641                                      GNUNET_TIME_UNIT_FOREVER_REL,
2642                                      /* timeout */
2643                                      &id,
2644                                      /* target */
2645                                      sizeof (struct GNUNET_MESH_ManipulatePath)
2646                                      +
2647                                      (p->length *
2648                                       sizeof (struct GNUNET_PeerIdentity)),
2649                                      /*size */
2650                                      &send_core_create_path,
2651                                      /* callback */
2652                                      path_info);        /* cls */
2653     return;
2654   }
2655   path_destroy(p);
2656   send_client_peer_connected(t, myid);
2657 }
2658
2659 /******************************************************************************/
2660 /*********************       MESH LOCAL HANDLES      **************************/
2661 /******************************************************************************/
2662
2663
2664 /**
2665  * Handler for client disconnection
2666  *
2667  * @param cls closure
2668  * @param client identification of the client; NULL
2669  *        for the last call when the server is destroyed
2670  */
2671 static void
2672 handle_local_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
2673 {
2674   struct MeshClient *c;
2675   struct MeshClient *next;
2676
2677   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: client disconnected\n");
2678   if (client == NULL)
2679      GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:    (SERVER DOWN)\n");
2680   c = clients;
2681   while (NULL != c)
2682   {
2683     if (c->handle != client && NULL != client)
2684     {
2685       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:    ... searching\n");
2686       c = c->next;
2687       continue;
2688     }
2689     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: matching client found\n");
2690     if (NULL != c->tunnels)
2691     {
2692       GNUNET_CONTAINER_multihashmap_iterate (c->tunnels,
2693                                              &tunnel_destroy_iterator,
2694                                              c);
2695       GNUNET_CONTAINER_multihashmap_destroy (c->tunnels);
2696     }
2697
2698     /* deregister clients applications */
2699     if (NULL != c->apps)
2700     {
2701       GNUNET_CONTAINER_multihashmap_iterate (c->apps, &deregister_app, NULL);
2702       GNUNET_CONTAINER_multihashmap_destroy (c->apps);
2703     }
2704     if (0 == GNUNET_CONTAINER_multihashmap_size (applications) &&
2705         GNUNET_SCHEDULER_NO_TASK != announce_applications_task)
2706     {
2707       GNUNET_SCHEDULER_cancel (announce_applications_task);
2708       announce_applications_task = GNUNET_SCHEDULER_NO_TASK;
2709     }
2710     if (NULL != c->types)
2711       GNUNET_CONTAINER_multihashmap_destroy (c->types);
2712     if (NULL != c->dht_get_type)
2713       GNUNET_DHT_get_stop (c->dht_get_type);
2714     GNUNET_CONTAINER_DLL_remove (clients, clients_tail, c);
2715     next = c->next;
2716     GNUNET_free (c);
2717     c = next;
2718   }
2719
2720   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:    done!\n");
2721   return;
2722 }
2723
2724
2725 /**
2726  * Handler for new clients
2727  *
2728  * @param cls closure
2729  * @param client identification of the client
2730  * @param message the actual message, which includes messages the client wants
2731  */
2732 static void
2733 handle_local_new_client (void *cls, struct GNUNET_SERVER_Client *client,
2734                          const struct GNUNET_MessageHeader *message)
2735 {
2736   struct GNUNET_MESH_ClientConnect *cc_msg;
2737   struct MeshClient *c;
2738   GNUNET_MESH_ApplicationType *a;
2739   unsigned int size;
2740   uint16_t ntypes;
2741   uint16_t *t;
2742   uint16_t napps;
2743   uint16_t i;
2744
2745   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: new client connected\n");
2746   /* Check data sanity */
2747   size = ntohs (message->size) - sizeof (struct GNUNET_MESH_ClientConnect);
2748   cc_msg = (struct GNUNET_MESH_ClientConnect *) message;
2749   ntypes = ntohs (cc_msg->types);
2750   napps = ntohs (cc_msg->applications);
2751   if (size !=
2752       ntypes * sizeof (uint16_t) + napps * sizeof (GNUNET_MESH_ApplicationType))
2753   {
2754     GNUNET_break (0);
2755     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2756     return;
2757   }
2758
2759   /* Create new client structure */
2760   c = GNUNET_malloc (sizeof (struct MeshClient));
2761 #if MESH_DEBUG
2762   c->id = next_client_id++;
2763 #endif
2764   c->handle = client;
2765   a = (GNUNET_MESH_ApplicationType *) &cc_msg[1];
2766   if (napps > 0)
2767   {
2768     GNUNET_MESH_ApplicationType at;
2769     GNUNET_HashCode hc;
2770
2771     c->apps = GNUNET_CONTAINER_multihashmap_create (napps);
2772     for (i = 0; i < napps; i++)
2773     {
2774       at = ntohl (a[i]);
2775       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   app type: %u\n", at);
2776       GNUNET_CRYPTO_hash (&at, sizeof (at), &hc);
2777       /* store in clients hashmap */
2778       GNUNET_CONTAINER_multihashmap_put (c->apps, &hc, c,
2779                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2780       /* store in global hashmap, for announcements */
2781       GNUNET_CONTAINER_multihashmap_put (applications, &hc, c,
2782                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2783     }
2784     if (GNUNET_SCHEDULER_NO_TASK == announce_applications_task)
2785       announce_applications_task =
2786           GNUNET_SCHEDULER_add_now (&announce_applications, NULL);
2787
2788   }
2789   if (ntypes > 0)
2790   {
2791     uint16_t u16;
2792     GNUNET_HashCode hc;
2793
2794     t = (uint16_t *) & a[napps];
2795     c->types = GNUNET_CONTAINER_multihashmap_create (ntypes);
2796     for (i = 0; i < ntypes; i++)
2797     {
2798       u16 = ntohs (t[i]);
2799       GNUNET_CRYPTO_hash (&u16, sizeof (u16), &hc);
2800
2801       /* store in clients hashmap */
2802       GNUNET_CONTAINER_multihashmap_put (c->types, &hc, c,
2803                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2804       /* store in global hashmap */
2805       GNUNET_CONTAINER_multihashmap_put (types, &hc, c,
2806                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2807     }
2808   }
2809   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2810               "MESH:  client has %u+%u subscriptions\n", napps, ntypes);
2811
2812   GNUNET_CONTAINER_DLL_insert (clients, clients_tail, c);
2813   c->tunnels = GNUNET_CONTAINER_multihashmap_create (32);
2814   GNUNET_SERVER_notification_context_add (nc, client);
2815
2816   GNUNET_SERVER_receive_done (client, GNUNET_OK);
2817 #if MESH_DEBUG
2818   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: new client processed\n");
2819 #endif
2820 }
2821
2822
2823 /**
2824  * Handler for requests of new tunnels
2825  *
2826  * @param cls closure
2827  * @param client identification of the client
2828  * @param message the actual message
2829  */
2830 static void
2831 handle_local_tunnel_create (void *cls, struct GNUNET_SERVER_Client *client,
2832                             const struct GNUNET_MessageHeader *message)
2833 {
2834   struct GNUNET_MESH_TunnelMessage *t_msg;
2835   struct MeshTunnel *t;
2836   struct MeshClient *c;
2837   GNUNET_HashCode hash;
2838
2839   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: new tunnel requested\n");
2840
2841   /* Sanity check for client registration */
2842   if (NULL == (c = client_get (client)))
2843   {
2844     GNUNET_break (0);
2845     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2846     return;
2847   }
2848 #if MESH_DEBUG
2849   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   by client %u\n", c->id);
2850 #endif
2851
2852   /* Message sanity check */
2853   if (sizeof (struct GNUNET_MESH_TunnelMessage) != ntohs (message->size))
2854   {
2855     GNUNET_break (0);
2856     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2857     return;
2858   }
2859
2860   t_msg = (struct GNUNET_MESH_TunnelMessage *) message;
2861   /* Sanity check for tunnel numbering */
2862   if (0 == (ntohl (t_msg->tunnel_id) & GNUNET_MESH_LOCAL_TUNNEL_ID_CLI))
2863   {
2864     GNUNET_break (0);
2865     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2866     return;
2867   }
2868   /* Sanity check for duplicate tunnel IDs */
2869   if (NULL != tunnel_get_by_local_id (c, ntohl (t_msg->tunnel_id)))
2870   {
2871     GNUNET_break (0);
2872     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2873     return;
2874   }
2875
2876   t = GNUNET_malloc (sizeof (struct MeshTunnel));
2877   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: CREATED TUNNEL at %p\n", t);
2878   while (NULL != tunnel_get_by_pi (myid, next_tid))
2879     next_tid = (next_tid + 1) & ~GNUNET_MESH_LOCAL_TUNNEL_ID_CLI;
2880   t->id.tid = next_tid++;
2881   t->id.oid = myid;
2882   t->local_tid = ntohl (t_msg->tunnel_id);
2883   t->client = c;
2884   t->peers = GNUNET_CONTAINER_multihashmap_create (32);
2885
2886   GNUNET_CRYPTO_hash (&t->local_tid, sizeof (MESH_TunnelNumber), &hash);
2887   if (GNUNET_OK !=
2888       GNUNET_CONTAINER_multihashmap_put (c->tunnels, &hash, t,
2889                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
2890   {
2891     GNUNET_break (0);
2892     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2893     return;
2894   }
2895
2896   GNUNET_CRYPTO_hash (&t->id, sizeof (struct MESH_TunnelID), &hash);
2897   if (GNUNET_OK !=
2898       GNUNET_CONTAINER_multihashmap_put (tunnels, &hash, t,
2899                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
2900   {
2901     GNUNET_break (0);
2902     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2903     return;
2904   }
2905   t->tree = GNUNET_malloc (sizeof(struct MeshTunnelPath));
2906   t->tree->first_hops = GNUNET_CONTAINER_multihashmap_create(32);
2907   t->tree->t = t;
2908   t->tree->root = GNUNET_malloc(sizeof(struct MeshTunnelPathNode));
2909   t->tree->root->status = MESH_PEER_READY;
2910   t->tree->root->t = t;
2911   t->tree->root->peer = peer_info_get(&my_full_id);
2912   t->tree->me = t->tree->root;
2913
2914   GNUNET_SERVER_receive_done (client, GNUNET_OK);
2915   return;
2916 }
2917
2918
2919 /**
2920  * Handler for requests of deleting tunnels
2921  *
2922  * @param cls closure
2923  * @param client identification of the client
2924  * @param message the actual message
2925  */
2926 static void
2927 handle_local_tunnel_destroy (void *cls, struct GNUNET_SERVER_Client *client,
2928                              const struct GNUNET_MessageHeader *message)
2929 {
2930   struct GNUNET_MESH_TunnelMessage *tunnel_msg;
2931   struct MeshClient *c;
2932   struct MeshTunnel *t;
2933   MESH_TunnelNumber tid;
2934   GNUNET_HashCode hash;
2935
2936   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: destroying tunnel\n");
2937
2938   /* Sanity check for client registration */
2939   if (NULL == (c = client_get (client)))
2940   {
2941     GNUNET_break (0);
2942     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2943     return;
2944   }
2945   /* Message sanity check */
2946   if (sizeof (struct GNUNET_MESH_TunnelMessage) != ntohs (message->size))
2947   {
2948     GNUNET_break (0);
2949     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2950     return;
2951   }
2952 #if MESH_DEBUG
2953   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   by client %u\n", c->id);
2954 #endif
2955   tunnel_msg = (struct GNUNET_MESH_TunnelMessage *) message;
2956
2957   /* Retrieve tunnel */
2958   tid = ntohl (tunnel_msg->tunnel_id);
2959
2960   /* Remove from local id hashmap */
2961   GNUNET_CRYPTO_hash (&tid, sizeof (MESH_TunnelNumber), &hash);
2962   t = GNUNET_CONTAINER_multihashmap_get (c->tunnels, &hash);
2963   GNUNET_CONTAINER_multihashmap_remove (c->tunnels, &hash, t);
2964
2965   /* Remove from global id hashmap */
2966   GNUNET_CRYPTO_hash (&t->id, sizeof (struct MESH_TunnelID), &hash);
2967   GNUNET_CONTAINER_multihashmap_remove (tunnels, &hash, t);
2968
2969 //     notify_tunnel_destroy(t); FIXME
2970   tunnel_destroy(t);
2971   GNUNET_SERVER_receive_done (client, GNUNET_OK);
2972   return;
2973 }
2974
2975
2976 /**
2977  * Handler for connection requests to new peers
2978  *
2979  * @param cls closure
2980  * @param client identification of the client
2981  * @param message the actual message (PeerControl)
2982  *
2983  * FIXME path
2984  */
2985 static void
2986 handle_local_connect_add (void *cls, struct GNUNET_SERVER_Client *client,
2987                           const struct GNUNET_MessageHeader *message)
2988 {
2989   struct GNUNET_MESH_PeerControl *peer_msg;
2990   struct MeshClient *c;
2991   struct MeshTunnel *t;
2992   MESH_TunnelNumber tid;
2993   struct MeshPeerInfo *peer_info;
2994
2995
2996   /* Sanity check for client registration */
2997   if (NULL == (c = client_get (client)))
2998   {
2999     GNUNET_break (0);
3000     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3001     return;
3002   }
3003
3004   peer_msg = (struct GNUNET_MESH_PeerControl *) message;
3005   /* Sanity check for message size */
3006   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (peer_msg->header.size))
3007   {
3008     GNUNET_break (0);
3009     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3010     return;
3011   }
3012
3013   /* Tunnel exists? */
3014   tid = ntohl (peer_msg->tunnel_id);
3015   t = tunnel_get_by_local_id (c, tid);
3016   if (NULL == t)
3017   {
3018     GNUNET_break (0);
3019     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3020     return;
3021   }
3022
3023   /* Does client own tunnel? */
3024   if (t->client->handle != client)
3025   {
3026     GNUNET_break (0);
3027     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3028     return;
3029   }
3030
3031   t->peers_total++;
3032   peer_info = peer_info_get (&peer_msg->peer);
3033
3034   /* Start DHT search if needed FIXME: if not already connected */
3035   if (NULL == peer_info->dhtget)
3036   {
3037     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 */
3038                                               GNUNET_DHT_RO_RECORD_ROUTE, NULL, /* bloom filter */
3039                                               0,        /* mutator */
3040                                               NULL,     /* xquery */
3041                                               0,        /* xquery bits */
3042                                               dht_get_id_handler,
3043                                               (void *) peer_info);
3044   }
3045
3046   GNUNET_SERVER_receive_done (client, GNUNET_OK);
3047   return;
3048 }
3049
3050
3051 /**
3052  * Handler for disconnection requests of peers in a tunnel
3053  *
3054  * @param cls closure
3055  * @param client identification of the client
3056  * @param message the actual message (PeerControl)
3057  */
3058 static void
3059 handle_local_connect_del (void *cls, struct GNUNET_SERVER_Client *client,
3060                           const struct GNUNET_MessageHeader *message)
3061 {
3062   struct GNUNET_MESH_PeerControl *peer_msg;
3063   struct MeshClient *c;
3064   struct MeshTunnel *t;
3065   MESH_TunnelNumber tid;
3066
3067   /* Sanity check for client registration */
3068   if (NULL == (c = client_get (client)))
3069   {
3070     GNUNET_break (0);
3071     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3072     return;
3073   }
3074   peer_msg = (struct GNUNET_MESH_PeerControl *) message;
3075   /* Sanity check for message size */
3076   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (peer_msg->header.size))
3077   {
3078     GNUNET_break (0);
3079     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3080     return;
3081   }
3082
3083   /* Tunnel exists? */
3084   tid = ntohl (peer_msg->tunnel_id);
3085   t = tunnel_get_by_local_id (c, tid);
3086   if (NULL == t)
3087   {
3088     GNUNET_break (0);
3089     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3090     return;
3091   }
3092
3093   /* Does client own tunnel? */
3094   if (t->client->handle != client)
3095   {
3096     GNUNET_break (0);
3097     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3098     return;
3099   }
3100
3101   /* Ok, delete peer from tunnel */
3102   GNUNET_CONTAINER_multihashmap_remove_all (t->peers,
3103                                             &peer_msg->peer.hashPubKey);
3104
3105   GNUNET_SERVER_receive_done (client, GNUNET_OK);
3106   return;
3107 }
3108
3109
3110 /**
3111  * Handler for connection requests to new peers by type
3112  *
3113  * @param cls closure
3114  * @param client identification of the client
3115  * @param message the actual message (ConnectPeerByType)
3116  */
3117 static void
3118 handle_local_connect_by_type (void *cls, struct GNUNET_SERVER_Client *client,
3119                               const struct GNUNET_MessageHeader *message)
3120 {
3121   struct GNUNET_MESH_ConnectPeerByType *connect_msg;
3122   struct MeshClient *c;
3123   struct MeshTunnel *t;
3124   GNUNET_HashCode hash;
3125   GNUNET_MESH_ApplicationType type;
3126   MESH_TunnelNumber tid;
3127
3128   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: got connect by type request\n");
3129   /* Sanity check for client registration */
3130   if (NULL == (c = client_get (client)))
3131   {
3132     GNUNET_break (0);
3133     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3134     return;
3135   }
3136
3137   connect_msg = (struct GNUNET_MESH_ConnectPeerByType *) message;
3138   /* Sanity check for message size */
3139   if (sizeof (struct GNUNET_MESH_ConnectPeerByType) !=
3140       ntohs (connect_msg->header.size))
3141   {
3142     GNUNET_break (0);
3143     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3144     return;
3145   }
3146
3147   /* Tunnel exists? */
3148   tid = ntohl (connect_msg->tunnel_id);
3149   t = tunnel_get_by_local_id (c, tid);
3150   if (NULL == t)
3151   {
3152     GNUNET_break (0);
3153     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3154     return;
3155   }
3156
3157   /* Does client own tunnel? */
3158   if (t->client->handle != client)
3159   {
3160     GNUNET_break (0);
3161     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3162     return;
3163   }
3164
3165   /* Do WE have the service? */
3166   type = ntohl (connect_msg->type);
3167   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:  type requested: %u\n", type);
3168   GNUNET_CRYPTO_hash (&type, sizeof (GNUNET_MESH_ApplicationType), &hash);
3169   if (GNUNET_CONTAINER_multihashmap_contains (applications, &hash) ==
3170       GNUNET_YES)
3171   {
3172     /* Yes! Fast forward, add ourselves to the tunnel and send the
3173      * good news to the client
3174      */
3175     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:  available locally\n");
3176     GNUNET_CONTAINER_multihashmap_put (t->peers, &my_full_id.hashPubKey,
3177                                        peer_info_get (&my_full_id),
3178                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
3179
3180     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:  notifying client\n");
3181     send_client_peer_connected(t, myid);
3182     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:  Done\n");
3183     GNUNET_SERVER_receive_done (client, GNUNET_OK);
3184     return;
3185   }
3186   /* Ok, lets find a peer offering the service */
3187   if (c->dht_get_type)
3188   {
3189     GNUNET_DHT_get_stop (c->dht_get_type);
3190   }
3191   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:  looking in DHT for %s\n",
3192               GNUNET_h2s_full (&hash));
3193   c->dht_get_type =
3194       GNUNET_DHT_get_start (dht_handle, GNUNET_TIME_UNIT_FOREVER_REL,
3195                             GNUNET_BLOCK_TYPE_TEST, &hash, 10U,
3196                             GNUNET_DHT_RO_RECORD_ROUTE, NULL, 0, NULL, 0,
3197                             &dht_get_type_handler, t);
3198
3199   GNUNET_SERVER_receive_done (client, GNUNET_OK);
3200   return;
3201 }
3202
3203
3204 /**
3205  * Handler for client traffic directed to one peer
3206  *
3207  * @param cls closure
3208  * @param client identification of the client
3209  * @param message the actual message
3210  */
3211 static void
3212 handle_local_unicast (void *cls, struct GNUNET_SERVER_Client *client,
3213                       const struct GNUNET_MessageHeader *message)
3214 {
3215   struct MeshClient *c;
3216   struct MeshTunnel *t;
3217   struct MeshPeerInfo *pi;
3218   struct GNUNET_MESH_Unicast *data_msg;
3219   struct GNUNET_PeerIdentity next_hop;
3220   struct MeshDataDescriptor *info;
3221   MESH_TunnelNumber tid;
3222   size_t data_size;
3223
3224   /* Sanity check for client registration */
3225   if (NULL == (c = client_get (client)))
3226   {
3227     GNUNET_break (0);
3228     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3229     return;
3230   }
3231   data_msg = (struct GNUNET_MESH_Unicast *) message;
3232   /* Sanity check for message size */
3233   if (sizeof (struct GNUNET_MESH_Unicast) +
3234       sizeof (struct GNUNET_MessageHeader) > ntohs (data_msg->header.size))
3235   {
3236     GNUNET_break (0);
3237     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3238     return;
3239   }
3240
3241   /* Tunnel exists? */
3242   tid = ntohl (data_msg->tid);
3243   t = tunnel_get_by_local_id (c, tid);
3244   if (NULL == t)
3245   {
3246     GNUNET_break (0);
3247     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3248     return;
3249   }
3250
3251   /*  Is it a local tunnel? Then, does client own the tunnel? */
3252   if (t->client->handle != NULL && t->client->handle != client)
3253   {
3254     GNUNET_break (0);
3255     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3256     return;
3257   }
3258
3259   pi = GNUNET_CONTAINER_multihashmap_get (t->peers,
3260                                           &data_msg->destination.hashPubKey);
3261   /* Is the selected peer in the tunnel? */
3262   if (NULL == pi)
3263   {
3264     GNUNET_break (0);
3265     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3266     return;
3267   }
3268   if (pi->id == myid)
3269   {
3270     struct GNUNET_MESH_Unicast copy;
3271
3272     /* Work around const limitation */
3273     memcpy (&copy, data_msg, sizeof (struct GNUNET_MESH_Unicast));
3274     copy.oid = my_full_id;
3275     copy.tid = htonl (t->id.tid);
3276     handle_mesh_data_unicast (NULL, &my_full_id, &copy.header, NULL);
3277     return;
3278   }
3279   GNUNET_PEER_resolve (path_get_first_hop (t, pi)->id, &next_hop);
3280   data_size = ntohs (message->size) - sizeof (struct GNUNET_MESH_Unicast);
3281   info = GNUNET_malloc (sizeof (struct MeshDataDescriptor) + data_size);
3282   memcpy (&info[1], &data_msg[1], data_size);
3283   info->destination = pi->id;
3284   info->origin = &t->id;
3285   info->size = data_size;
3286   info->client = client;
3287   GNUNET_CORE_notify_transmit_ready (core_handle, 0, 0,
3288                                      GNUNET_TIME_UNIT_FOREVER_REL, &next_hop,
3289                                      /* FIXME re-check types */
3290                                      data_size +
3291                                      sizeof (struct GNUNET_MESH_Unicast),
3292                                      &send_core_data_unicast, info);
3293   return;
3294 }
3295
3296 /**
3297  * Handler for client traffic directed to all peers in a tunnel
3298  *
3299  * @param cls closure
3300  * @param client identification of the client
3301  * @param message the actual message
3302  */
3303 static void
3304 handle_local_multicast (void *cls, struct GNUNET_SERVER_Client *client,
3305                         const struct GNUNET_MessageHeader *message)
3306 {
3307   struct MeshClient *c;
3308   struct MeshTunnel *t;
3309   struct GNUNET_MESH_Multicast *data_msg;
3310   MESH_TunnelNumber tid;
3311
3312   /* Sanity check for client registration */
3313   if (NULL == (c = client_get (client)))
3314   {
3315     GNUNET_break (0);
3316     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3317     return;
3318   }
3319   data_msg = (struct GNUNET_MESH_Multicast *) message;
3320   /* Sanity check for message size */
3321   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (data_msg->header.size))
3322   {
3323     GNUNET_break (0);
3324     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3325     return;
3326   }
3327
3328   /* Tunnel exists? */
3329   tid = ntohl (data_msg->tid);
3330   t = tunnel_get_by_local_id (c, tid);
3331   if (NULL == t)
3332   {
3333     GNUNET_break (0);
3334     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3335     return;
3336   }
3337
3338   /* Does client own tunnel? */
3339   if (t->client->handle != client)
3340   {
3341     GNUNET_break (0);
3342     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3343     return;
3344   }
3345
3346   /*  TODO */
3347
3348   GNUNET_SERVER_receive_done (client, GNUNET_OK);
3349   return;
3350 }
3351
3352 /**
3353  * Functions to handle messages from clients
3354  */
3355 static struct GNUNET_SERVER_MessageHandler client_handlers[] = {
3356   {&handle_local_new_client, NULL, GNUNET_MESSAGE_TYPE_MESH_LOCAL_CONNECT, 0},
3357   {&handle_local_tunnel_create, NULL,
3358    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_CREATE,
3359    sizeof (struct GNUNET_MESH_TunnelMessage)},
3360   {&handle_local_tunnel_destroy, NULL,
3361    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_DESTROY,
3362    sizeof (struct GNUNET_MESH_TunnelMessage)},
3363   {&handle_local_connect_add, NULL,
3364    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD,
3365    sizeof (struct GNUNET_MESH_PeerControl)},
3366   {&handle_local_connect_del, NULL,
3367    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_DEL,
3368    sizeof (struct GNUNET_MESH_PeerControl)},
3369   {&handle_local_connect_by_type, NULL,
3370    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD_BY_TYPE,
3371    sizeof (struct GNUNET_MESH_ConnectPeerByType)},
3372   {&handle_local_unicast, NULL,
3373    GNUNET_MESSAGE_TYPE_MESH_UNICAST, 0},
3374   {&handle_local_unicast, NULL,
3375    GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN, 0},
3376   {&handle_local_multicast, NULL,
3377    GNUNET_MESSAGE_TYPE_MESH_MULTICAST, 0},
3378   {NULL, NULL, 0, 0}
3379 };
3380
3381
3382 /**
3383  * To be called on core init/fail.
3384  *
3385  * @param cls service closure
3386  * @param server handle to the server for this service
3387  * @param identity the public identity of this peer
3388  * @param publicKey the public key of this peer
3389  */
3390 static void
3391 core_init (void *cls, struct GNUNET_CORE_Handle *server,
3392            const struct GNUNET_PeerIdentity *identity,
3393            const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *publicKey)
3394 {
3395   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: Core init\n");
3396   core_handle = server;
3397   if (0 != memcmp(identity, &my_full_id, sizeof(my_full_id)) || NULL == server)
3398   {
3399     GNUNET_log(GNUNET_ERROR_TYPE_ERROR, _("MESH: Wrong CORE service\n"));
3400     GNUNET_SCHEDULER_shutdown();   
3401   }
3402   return;
3403 }
3404
3405 /**
3406  * Method called whenever a given peer connects.
3407  *
3408  * @param cls closure
3409  * @param peer peer identity this notification is about
3410  * @param atsi performance data for the connection
3411  */
3412 static void
3413 core_connect (void *cls, const struct GNUNET_PeerIdentity *peer,
3414               const struct GNUNET_TRANSPORT_ATS_Information *atsi)
3415 {
3416 //     GNUNET_PEER_Id              pid;
3417   struct MeshPeerInfo *peer_info;
3418   struct MeshPeerPath *path;
3419
3420   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: Peer connected\n");
3421   peer_info = peer_info_get (peer);
3422   path = GNUNET_malloc (sizeof (struct MeshPeerPath));
3423   if (myid == peer_info->id)
3424   {
3425     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:      (self)\n");
3426     return;
3427   }
3428   path->length = 2;
3429   path->peers = GNUNET_malloc (sizeof (GNUNET_PEER_Id) * 2);
3430   path->peers[0] = myid;
3431   path->peers[1] = peer_info->id;
3432   path_add_to_peer (peer_info, path);
3433   return;
3434 }
3435
3436 /**
3437  * Method called whenever a peer disconnects.
3438  *
3439  * @param cls closure
3440  * @param peer peer identity this notification is about
3441  */
3442 static void
3443 core_disconnect (void *cls, const struct GNUNET_PeerIdentity *peer)
3444 {
3445   struct MeshPeerInfo *pi;
3446   unsigned int i;
3447
3448   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: Peer disconnected\n");
3449   pi = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
3450   if (!pi)
3451   {
3452     GNUNET_break (0);
3453     return;
3454   }
3455   for (i = 0; i < CORE_QUEUE_SIZE; i++)
3456   {
3457     if (pi->core_transmit[i])
3458     {
3459       GNUNET_CORE_notify_transmit_ready_cancel (pi->core_transmit[i]);
3460       /* TODO: notify that tranmission has failed */
3461       GNUNET_free (pi->infos[i]);
3462     }
3463   }
3464   path_remove_from_peer (pi, pi->id, myid);
3465   if (myid == pi->id)
3466   {
3467     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:      (self)\n");
3468   }
3469   return;
3470 }
3471
3472
3473 /******************************************************************************/
3474 /************************      MAIN FUNCTIONS      ****************************/
3475 /******************************************************************************/
3476
3477 /**
3478  * Task run during shutdown.
3479  *
3480  * @param cls unused
3481  * @param tc unused
3482  */
3483 static void
3484 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3485 {
3486   struct MeshClient *c;
3487
3488   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: shutting down\n");
3489   if (core_handle != NULL)
3490   {
3491     GNUNET_CORE_disconnect (core_handle);
3492     core_handle = NULL;
3493   }
3494   if (dht_handle != NULL)
3495   {
3496     for (c = clients; NULL != c; c = c->next)
3497       if (NULL != c->dht_get_type)
3498         GNUNET_DHT_get_stop (c->dht_get_type);
3499     GNUNET_DHT_disconnect (dht_handle);
3500     dht_handle = NULL;
3501   }
3502   if (nc != NULL)
3503   {
3504     GNUNET_SERVER_notification_context_destroy (nc);
3505     nc = NULL;
3506   }
3507   if (GNUNET_SCHEDULER_NO_TASK != announce_id_task)
3508   {
3509     GNUNET_SCHEDULER_cancel (announce_id_task);
3510     announce_id_task = GNUNET_SCHEDULER_NO_TASK;
3511   }
3512   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: shut down\n");
3513 }
3514
3515 /**
3516  * Process mesh requests.
3517  *
3518  * @param cls closure
3519  * @param server the initialized server
3520  * @param c configuration to use
3521  */
3522 static void
3523 run (void *cls, struct GNUNET_SERVER_Handle *server,
3524      const struct GNUNET_CONFIGURATION_Handle *c)
3525 {
3526   struct MeshPeerInfo *peer;
3527   struct MeshPeerPath *p;
3528   char *keyfile;
3529
3530   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: starting to run\n");
3531   server_handle = server;
3532   core_handle = GNUNET_CORE_connect (c, /* Main configuration */
3533                                      CORE_QUEUE_SIZE,   /* queue size */
3534                                      NULL,      /* Closure passed to MESH functions */
3535                                      &core_init,        /* Call core_init once connected */
3536                                      &core_connect,     /* Handle connects */
3537                                      &core_disconnect,  /* remove peers on disconnects */
3538                                      NULL,      /* Do we care about "status" updates? */
3539                                      NULL,      /* Don't notify about all incoming messages */
3540                                      GNUNET_NO, /* For header only in notification */
3541                                      NULL,      /* Don't notify about all outbound messages */
3542                                      GNUNET_NO, /* For header-only out notification */
3543                                      core_handlers);    /* Register these handlers */
3544   if (core_handle == NULL)
3545   {
3546     GNUNET_break (0);
3547     GNUNET_SCHEDULER_shutdown ();
3548     return;
3549   }
3550
3551   if (GNUNET_OK !=
3552        GNUNET_CONFIGURATION_get_value_filename (c, "GNUNETD", "HOSTKEY",
3553                                                 &keyfile))
3554   {
3555     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3556                 _
3557                 ("Mesh service is lacking key configuration settings.  Exiting.\n"));
3558     GNUNET_SCHEDULER_shutdown ();
3559     return;
3560   }
3561   my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
3562   GNUNET_free (keyfile);
3563   if (my_private_key == NULL)
3564   {
3565     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3566                 _("Mesh service could not access hostkey.  Exiting.\n"));
3567     GNUNET_SCHEDULER_shutdown ();
3568     return;
3569   }
3570   GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
3571   GNUNET_CRYPTO_hash (&my_public_key, sizeof (my_public_key),
3572                       &my_full_id.hashPubKey);
3573   myid = GNUNET_PEER_intern (&my_full_id);
3574
3575   dht_handle = GNUNET_DHT_connect (c, 64);
3576   if (dht_handle == NULL)
3577   {
3578     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Error connecting to DHT.\
3579                    Running without DHT has a severe\
3580                    impact in MESH capabilities.\n\
3581                    Plase check your configuretion and enable DHT.\n");
3582     GNUNET_break (0);
3583   }
3584
3585   next_tid = 0;
3586
3587   tunnels = GNUNET_CONTAINER_multihashmap_create (32);
3588   peers = GNUNET_CONTAINER_multihashmap_create (32);
3589   applications = GNUNET_CONTAINER_multihashmap_create (32);
3590   types = GNUNET_CONTAINER_multihashmap_create (32);
3591
3592   GNUNET_SERVER_add_handlers (server_handle, client_handlers);
3593   nc = GNUNET_SERVER_notification_context_create (server_handle,
3594                                                   LOCAL_QUEUE_SIZE);
3595   GNUNET_SERVER_disconnect_notify (server_handle,
3596                                    &handle_local_client_disconnect,
3597                                    NULL);
3598
3599
3600   clients = NULL;
3601   clients_tail = NULL;
3602 #if MESH_DEBUG
3603   next_client_id = 0;
3604 #endif
3605
3606   announce_applications_task = GNUNET_SCHEDULER_NO_TASK;
3607   announce_id_task = GNUNET_SCHEDULER_add_now (&announce_id, cls);
3608
3609   /* Create a peer_info for the local peer */
3610   peer = peer_info_get(&my_full_id);
3611   p = GNUNET_malloc (sizeof (struct MeshPeerPath));
3612   p->peers = GNUNET_malloc (sizeof (GNUNET_PEER_Id));
3613   p->length = 1;
3614   p->peers[0] = myid;
3615   path_add_to_peer(peer, p);
3616
3617   /* Scheduled the task to clean up when shutdown is called */
3618   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
3619                                 NULL);
3620
3621   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: end of run()\n");
3622 }
3623
3624 /**
3625  * The main function for the mesh service.
3626  *
3627  * @param argc number of arguments from the command line
3628  * @param argv command line arguments
3629  * @return 0 ok, 1 on error
3630  */
3631 int
3632 main (int argc, char *const *argv)
3633 {
3634   int ret;
3635
3636 #if MESH_DEBUG
3637   fprintf (stderr, "main ()\n");
3638 #endif
3639   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: main()\n");
3640   ret =
3641       (GNUNET_OK ==
3642        GNUNET_SERVICE_run (argc, argv, "mesh", GNUNET_SERVICE_OPTION_NONE, &run,
3643                            NULL)) ? 0 : 1;
3644   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: main() END\n");
3645 #if MESH_DEBUG
3646   fprintf (stderr, "main () END\n");
3647 #endif
3648   return ret;
3649 }