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