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