Added notification of client that peers disconnected from tunnel
[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(&root->children[i], peer);
1127     if (NULL != n)
1128       return n;
1129   }
1130   return NULL;
1131 }
1132
1133
1134 /**
1135  * Recusively mark peer and children as disconnected, notify client
1136  * 
1137  * @param parent Node to be clean, potentially with children
1138  */
1139 static void
1140 tunnel_mark_peers_disconnected (struct MeshTunnelPathNode *parent)
1141 {
1142   struct GNUNET_MESH_PeerControl msg;
1143   unsigned int i;
1144
1145   parent->status = MESH_PEER_RECONNECTING;
1146   for (i = 0; i < parent->nchildren; i++)
1147   {
1148     tunnel_mark_peers_disconnected (&parent->children[i]);
1149   }
1150   if (NULL == parent->t->client)
1151     return;
1152   msg.header.size = htons(sizeof(msg));
1153   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_DEL);
1154   msg.tunnel_id = htonl(parent->t->local_tid);
1155   GNUNET_PEER_resolve(parent->peer->id, &msg.peer);
1156   GNUNET_SERVER_notification_context_unicast (nc, parent->t->client->handle,
1157                                               &msg.header, GNUNET_NO);
1158 }
1159
1160 /**
1161  * Delete the current path to the peer, including all now unused relays.
1162  *
1163  * @param t Tunnel where to add the new path.
1164  * @param p Path to be integrated.
1165  *
1166  * @return pointer to the pathless node, NULL on error
1167  * 
1168  * TODO: notify peers of deletion
1169  */
1170 static struct MeshTunnelPathNode *
1171 tunnel_del_path(struct MeshTunnel *t, struct MeshPeerInfo *peer)
1172 {
1173   struct MeshTunnelPathNode *parent;
1174   struct MeshTunnelPathNode *node;
1175   struct MeshTunnelPathNode *n;
1176
1177   node = n = tunnel_find_peer(t->paths->me, peer);
1178   if (NULL == n)
1179     return NULL;
1180   parent = n->parent;
1181   n->parent = NULL;
1182   while (NULL != parent &&
1183     MESH_PEER_RELAY == parent->status &&
1184     1 == parent->nchildren)
1185   {
1186     n = parent;
1187     GNUNET_free(parent->children);
1188     parent = parent->parent;
1189   }
1190   if (NULL == parent)
1191     return node;
1192   *n = parent->children[parent->nchildren - 1];
1193   parent->nchildren--;
1194   parent->children = GNUNET_realloc (parent->children, parent->nchildren);
1195
1196   tunnel_mark_peers_disconnected(node);
1197
1198   return node;
1199 }
1200
1201
1202 /**
1203  * Integrate a stand alone path into the tunnel tree.
1204  *
1205  * @param t Tunnel where to add the new path.
1206  * @param p Path to be integrated.
1207  *
1208  * @return GNUNET_OK in case of success.
1209  *         GNUNET_SYSERR in case of error.
1210  * 
1211  * TODO: optimize
1212  * - go backwards on path looking for each peer in the present tree
1213  */
1214 static int
1215 tunnel_add_path(struct MeshTunnel *t, struct MeshPeerPath *p)
1216 {
1217   struct MeshTunnelPathNode *parent;
1218   struct MeshTunnelPathNode *oldnode;
1219   struct MeshTunnelPathNode *n;
1220   struct GNUNET_PeerIdentity id;
1221   struct GNUNET_PeerIdentity hop;
1222   int me;
1223   unsigned int i;
1224   unsigned int j;
1225
1226   n = t->paths->root;
1227   if (n->peer->id != p->peers[0])
1228   {
1229     GNUNET_break (0);
1230     return GNUNET_SYSERR;
1231   }
1232   /* Ignore return value, if not found it's ok. */
1233   GNUNET_PEER_resolve(p->peers[p->length - 1], &id);
1234   oldnode = tunnel_del_path(t, peer_info_get(&id));
1235   /* Look for the first node that is not already present in the tree
1236    * 
1237    * Assuming that the tree is somewhat balanced, O(log n * log N).
1238    * - Length of the path is expected to be log N (size of whole network).
1239    * - Each level of the tree is expected to have log n children (size of tree).
1240    */
1241   for (i = 1, me = -1; i < p->length; i++)
1242   {
1243     parent = n;
1244     if (p->peers[i] == myid)
1245       me = i;
1246     for (j = 0; j < n->nchildren; j++)
1247     {
1248       if (n->children[j].peer->id == p->peers[i])
1249       {
1250         n = &n->children[j];
1251         break;
1252       }
1253     }
1254     /*  If we couldn't find a child equal to path[i], we have reached the end
1255      * of the common path. */
1256     if (parent == n)
1257       break;
1258   }
1259   if (-1 == me)
1260   {
1261     /* New path deviates from tree before reaching us. What happened? */
1262     GNUNET_break (0);
1263     return GNUNET_SYSERR;
1264   }
1265   /* Add the rest of the path as a branch from parent. */
1266   while (i < p->length)
1267   {
1268     parent->nchildren++;
1269     parent->children = GNUNET_realloc(parent->children, parent->nchildren);
1270     n = &parent->children[parent->nchildren - 1];
1271     if (i == p->length - 1)
1272     {
1273       if (NULL != oldnode)
1274       {
1275         /* Assignation and free can be misleading, using explicit mempcy */
1276         memcpy (n, oldnode, sizeof(struct MeshTunnelPathNode));
1277         GNUNET_free (oldnode);
1278       }
1279     }
1280     else
1281     {
1282       n->t = t;
1283       n->status = MESH_PEER_RELAY;
1284       GNUNET_PEER_resolve(p->peers[i], &id);
1285       n->peer = peer_info_get(&id);
1286     }
1287     n->parent = parent;
1288     i++;
1289     parent = n;
1290   }
1291
1292   /* Add info about first hop into hashmap. */
1293   if (me < p->length - 1)
1294   {
1295     GNUNET_PEER_resolve(p->peers[p->length - 1], &id);
1296     GNUNET_PEER_resolve(p->peers[me + 1], &hop);
1297     GNUNET_CONTAINER_multihashmap_put(
1298       t->paths->first_hops,
1299       &id.hashPubKey,
1300       peer_info_get(&hop),
1301       GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
1302   }
1303   return GNUNET_OK;
1304 }
1305
1306
1307 /**
1308  * Add a peer to a tunnel, accomodating paths accordingly and initializing all
1309  * needed rescources.
1310  *
1311  * @param t Tunnel we want to add a new peer to
1312  * @param peer PeerInfo of the peer being added
1313  *
1314  */
1315 static void
1316 tunnel_add_peer(struct MeshTunnel *t, struct MeshPeerInfo *peer)
1317 {
1318   struct MeshPeerPath *p;
1319   struct MeshPeerPath *best_p;
1320   unsigned int best_cost;
1321   unsigned int cost;
1322
1323   GNUNET_array_append(peer->tunnels, peer->ntunnels, t);
1324   if (NULL == (p = peer->path_head))
1325     return;
1326
1327   best_p = p;
1328   best_cost = UINT_MAX;
1329   while (NULL != p)
1330   {
1331     if ((cost = path_get_cost(t, p)) < best_cost)
1332     {
1333       best_cost = cost;
1334       best_p = p;
1335     }
1336     p = p->next;
1337   }
1338   tunnel_add_path(t, best_p);
1339   if (GNUNET_SCHEDULER_NO_TASK == t->path_refresh_task)
1340     t->path_refresh_task = GNUNET_SCHEDULER_add_delayed (REFRESH_PATH_TIME,
1341                                                          &path_refresh, t);
1342 }
1343
1344
1345 /**
1346  * Notify a tunnel that a connection has broken that affects at least
1347  * some of its peers.
1348  *
1349  * @param t Tunnel affected
1350  * @param peer Peer that (at least) has been affected by the disconnection
1351  * @param p1 Peer that got disconnected from p2
1352  * @param p2 Peer that got disconnected from p1
1353  */
1354 static void
1355 tunnel_notify_connection_broken(struct MeshTunnel *t,
1356                                 struct MeshPeerInfo *peer,
1357                                 GNUNET_PEER_Id p1,
1358                                 GNUNET_PEER_Id p2)
1359 {
1360 }
1361
1362
1363 /**
1364  * Destroy the tunnel and free any allocated resources linked to it
1365  * 
1366  * @param t the tunnel to destroy
1367  * 
1368  * @return GNUNET_OK on success
1369  */
1370 static int
1371 tunnel_destroy (struct MeshTunnel *t)
1372 {
1373   struct MeshClient *c;
1374   struct MeshQueue *q;
1375   struct MeshQueue *qn;
1376   GNUNET_HashCode hash;
1377   int r;
1378
1379   if (NULL == t)
1380     return GNUNET_OK;
1381
1382   c = t->client;
1383
1384   GNUNET_CRYPTO_hash (&t->id, sizeof (struct MESH_TunnelID), &hash);
1385   if (GNUNET_YES != GNUNET_CONTAINER_multihashmap_remove (tunnels, &hash, t))
1386   {
1387     r = GNUNET_SYSERR;
1388   }
1389
1390   GNUNET_CRYPTO_hash (&t->local_tid, sizeof (MESH_TunnelNumber), &hash);
1391   if (GNUNET_YES != GNUNET_CONTAINER_multihashmap_remove (c->tunnels, &hash, t))
1392   {
1393     r = GNUNET_SYSERR;
1394   }
1395   GNUNET_CONTAINER_multihashmap_destroy (t->peers);
1396   q = t->queue_head;
1397   while (NULL != q)
1398   {
1399     if (NULL != q->data)
1400       GNUNET_free (q->data);
1401     qn = q->next;
1402     GNUNET_free (q);
1403     q = qn;
1404     /* TODO cancel core transmit ready in case it was active */
1405   }
1406   GNUNET_free (t);
1407   return r;
1408 }
1409
1410
1411 /******************************************************************************/
1412 /****************      MESH NETWORK HANDLER HELPERS     ***********************/
1413 /******************************************************************************/
1414
1415
1416 /**
1417  * Function called to notify a client about the socket
1418  * being ready to queue more data.  "buf" will be
1419  * NULL and "size" zero if the socket was closed for
1420  * writing in the meantime.
1421  *
1422  * @param cls closure
1423  * @param size number of bytes available in buf
1424  * @param buf where the callee should write the message
1425  * @return number of bytes written to buf
1426  */
1427 static size_t
1428 send_core_create_path (void *cls, size_t size, void *buf)
1429 {
1430   struct MeshPathInfo *info = cls;
1431   struct GNUNET_MESH_ManipulatePath *msg;
1432   struct GNUNET_PeerIdentity *peer_ptr;
1433   struct GNUNET_PeerIdentity id;
1434   struct MeshPeerInfo *peer = info->peer;
1435   struct MeshTunnel *t = info->t;
1436   struct MeshPeerPath *p = info->path;
1437   size_t size_needed;
1438   int i;
1439
1440   size_needed =
1441       sizeof (struct GNUNET_MESH_ManipulatePath) +
1442       p->length * sizeof (struct GNUNET_PeerIdentity);
1443
1444   if (size < size_needed || NULL == buf)
1445   {
1446     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: Retransmitting create path\n");
1447     GNUNET_PEER_resolve (path_get_first_hop (t, peer)->id, &id);
1448     GNUNET_CORE_notify_transmit_ready (core_handle, 0, 0,
1449                                        GNUNET_TIME_UNIT_FOREVER_REL, &id,
1450                                        size_needed, &send_core_create_path,
1451                                        info);
1452     return 0;
1453   }
1454
1455   msg = (struct GNUNET_MESH_ManipulatePath *) buf;
1456   msg->header.size = htons (size_needed);
1457   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE);
1458   msg->tid = ntohl(t->id.tid);
1459
1460   peer_ptr = (struct GNUNET_PeerIdentity *) &msg[1];
1461   for (i = 0; i < p->length; i++)
1462   {
1463     GNUNET_PEER_resolve (p->peers[i], peer_ptr++);
1464   }
1465
1466   path_destroy(p);
1467   GNUNET_free (info);
1468
1469   return size_needed;
1470 }
1471
1472
1473 #if LATER
1474 /**
1475  * Function called to notify a client about the socket
1476  * being ready to queue more data.  "buf" will be
1477  * NULL and "size" zero if the socket was closed for
1478  * writing in the meantime.
1479  *
1480  * @param cls closure (MeshDataDescriptor with all info to build packet)
1481  * @param size number of bytes available in buf
1482  * @param buf where the callee should write the message
1483  * @return number of bytes written to buf
1484  */
1485 static size_t
1486 send_core_data_to_origin (void *cls, size_t size, void *buf)
1487 {
1488   struct MeshDataDescriptor *info = cls;
1489   struct GNUNET_MESH_ToOrigin *msg = buf;
1490   size_t total_size;
1491
1492   GNUNET_assert (NULL != info);
1493   total_size = sizeof (struct GNUNET_MESH_ToOrigin) + info->size;
1494   GNUNET_assert (total_size < 65536);   /* UNIT16_MAX */
1495
1496   if (total_size > size)
1497   {
1498     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1499                 "not enough buffer to send data to origin\n");
1500     return 0;
1501   }
1502   msg->header.size = htons (total_size);
1503   msg->header.type = htons (GNUNET_MESSAGE_TYPE_DATA_MESSAGE_TO_ORIGIN);
1504   GNUNET_PEER_resolve (info->origin->oid, &msg->oid);
1505   msg->tid = htonl (info->origin->tid);
1506   if (0 != info->size)
1507   {
1508     memcpy (&msg[1], &info[1], info->size);
1509   }
1510   if (NULL != info->client)
1511   {
1512     GNUNET_SERVER_receive_done (info->client, GNUNET_OK);
1513   }
1514   GNUNET_free (info);
1515   return total_size;
1516 }
1517 #endif
1518
1519 /**
1520  * Function called to notify a client about the socket
1521  * being ready to queue more data.  "buf" will be
1522  * NULL and "size" zero if the socket was closed for
1523  * writing in the meantime.
1524  *
1525  * @param cls closure (data itself)
1526  * @param size number of bytes available in buf
1527  * @param buf where the callee should write the message
1528  * @return number of bytes written to buf
1529  */
1530 static size_t
1531 send_core_data_unicast (void *cls, size_t size, void *buf)
1532 {
1533   struct MeshDataDescriptor *info = cls;
1534   struct GNUNET_MESH_Unicast *msg = buf;
1535   size_t total_size;
1536
1537   GNUNET_assert (NULL != info);
1538   total_size = sizeof (struct GNUNET_MESH_Unicast) + info->size;
1539   GNUNET_assert (total_size < 65536);   /* UNIT16_MAX */
1540
1541   if (total_size > size)
1542   {
1543     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1544                 "not enough buffer to send data to peer\n");
1545     return 0;
1546   }
1547   msg->header.size = htons (total_size);
1548   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_UNICAST);
1549   GNUNET_PEER_resolve (info->origin->oid, &msg->oid);
1550   GNUNET_PEER_resolve (info->destination, &msg->destination);
1551   msg->tid = htonl (info->origin->tid);
1552   if (0 != info->size)
1553   {
1554     memcpy (&msg[1], &info[1], info->size);
1555   }
1556   if (NULL != info->client)
1557   {
1558     GNUNET_SERVER_receive_done (info->client, GNUNET_OK);
1559   }
1560   GNUNET_free (info);
1561   return total_size;
1562 }
1563
1564
1565 /**
1566  * Function called to notify a client about the socket
1567  * being ready to queue more data.  "buf" will be
1568  * NULL and "size" zero if the socket was closed for
1569  * writing in the meantime.
1570  *
1571  * @param cls closure (data itself)
1572  * @param size number of bytes available in buf
1573  * @param buf where the callee should write the message
1574  * @return number of bytes written to buf
1575  */
1576 static size_t
1577 send_core_data_multicast (void *cls, size_t size, void *buf)
1578 {
1579   struct MeshDataDescriptor *info = cls;
1580   struct GNUNET_MESH_Multicast *msg = buf;
1581   size_t total_size;
1582
1583   GNUNET_assert (NULL != info);
1584   total_size = info->size + sizeof (struct GNUNET_MESH_Multicast);
1585   GNUNET_assert (total_size < GNUNET_SERVER_MAX_MESSAGE_SIZE);
1586
1587   if (info->peer)
1588   {
1589     info->peer->core_transmit[info->handler_n] = NULL;
1590   }
1591   if (total_size > size)
1592   {
1593     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1594                 "not enough buffer to send data futher\n");
1595     return 0;
1596   }
1597   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_MULTICAST);
1598   msg->header.size = htons (total_size);
1599   GNUNET_PEER_resolve (info->origin->oid, &msg->oid);
1600   msg->tid = htonl (info->origin->tid);
1601   memcpy (&msg[1], &info[1], total_size);
1602   if (0 == --info->copies)
1603   {
1604     if (NULL != info->client)
1605     {
1606       GNUNET_SERVER_receive_done (info->client, GNUNET_OK);
1607     }
1608     GNUNET_free (info);
1609   }
1610   return total_size;
1611 }
1612
1613
1614 /**
1615  * Function called to notify a client about the socket
1616  * being ready to queue more data.  "buf" will be
1617  * NULL and "size" zero if the socket was closed for
1618  * writing in the meantime.
1619  *
1620  * @param cls closure (MeshDataDescriptor)
1621  * @param size number of bytes available in buf
1622  * @param buf where the callee should write the message
1623  * @return number of bytes written to buf
1624  */
1625 static size_t
1626 send_core_path_ack (void *cls, size_t size, void *buf)
1627 {
1628   struct MeshDataDescriptor *info = cls;
1629   struct GNUNET_MESH_PathACK *msg = buf;
1630
1631   GNUNET_assert (NULL != info);
1632   if (info->peer)
1633   {
1634     info->peer->core_transmit[info->handler_n] = NULL;
1635   }
1636   if (sizeof (struct GNUNET_MESH_PathACK) > size)
1637   {
1638     GNUNET_break (0);
1639     return 0;
1640   }
1641   msg->header.size = htons (sizeof (struct GNUNET_MESH_PathACK));
1642   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_ACK);
1643   GNUNET_PEER_resolve (info->origin->oid, &msg->oid);
1644   msg->tid = htonl (info->origin->tid);
1645   msg->peer_id = my_full_id;
1646   GNUNET_free(info);
1647   /* TODO add signature */
1648
1649   return sizeof (struct GNUNET_MESH_PathACK);
1650 }
1651
1652
1653 /**
1654  * Function called to notify a client about the socket
1655  * being ready to queue more data.  "buf" will be
1656  * NULL and "size" zero if the socket was closed for
1657  * writing in the meantime.
1658  *
1659  * @param cls closure (data itself)
1660  * @param size number of bytes available in buf
1661  * @param buf where the callee should write the message
1662  * @return number of bytes written to buf
1663  */
1664 static size_t
1665 send_core_data_raw (void *cls, size_t size, void *buf)
1666 {
1667   struct GNUNET_MessageHeader *msg = cls;
1668   size_t total_size;
1669
1670   GNUNET_assert (NULL != msg);
1671   total_size = ntohs (msg->size);
1672
1673   if (total_size > size)
1674   {
1675     GNUNET_break (0);
1676     return 0;
1677   }
1678   memcpy (buf, msg, total_size);
1679   GNUNET_free (cls);
1680   return total_size;
1681 }
1682
1683
1684 #if LATER
1685 /**
1686  * Send another peer a notification to destroy a tunnel
1687  * @param cls The tunnel to destroy
1688  * @param size Size in the buffer
1689  * @param buf Memory where to put the data to transmit
1690  * @return Size of data put in buffer
1691  */
1692 static size_t
1693 send_p2p_tunnel_destroy (void *cls, size_t size, void *buf)
1694 {
1695   struct MeshTunnel *t = cls;
1696   struct MeshClient *c;
1697   struct GNUNET_MESH_TunnelMessage *msg;
1698
1699   c = t->client;
1700   msg = buf;
1701   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_DESTROY);
1702    /*FIXME*/ msg->header.size =
1703       htons (sizeof (struct GNUNET_MESH_TunnelMessage));
1704   msg->tunnel_id = htonl (t->id.tid);
1705
1706   tunnel_destroy (c, t);
1707   return sizeof (struct GNUNET_MESH_TunnelMessage);
1708 }
1709 #endif
1710
1711
1712 /**
1713  * Send the message to all clients that have subscribed to its type
1714  *
1715  * @param msg Pointer to the message itself
1716  * @return number of clients this message was sent to
1717  */
1718 static unsigned int
1719 send_subscribed_clients (struct GNUNET_MessageHeader *msg)
1720 {
1721   struct MeshClient *c;
1722   unsigned int count;
1723   uint16_t type;
1724
1725   type = ntohs (msg->type);
1726   for (count = 0, c = clients; c != NULL; c = c->next)
1727   {
1728     if (client_is_subscribed (type, c))
1729     {
1730       count++;
1731       GNUNET_SERVER_notification_context_unicast (nc, c->handle, msg,
1732                                                   GNUNET_YES);
1733     }
1734   }
1735   return count;
1736 }
1737
1738
1739 /**
1740  * Iterator over hash map peer entries collect all neighbors who to resend the
1741  * data to.
1742  *
1743  * @param cls closure (**GNUNET_PEER_Id to store hops to send packet)
1744  * @param key current key code (peer id hash)
1745  * @param value value in the hash map (peer_info)
1746  * @return GNUNET_YES if we should continue to iterate, GNUNET_NO if not.
1747  */
1748 static int
1749 iterate_collect_neighbors (void *cls, const GNUNET_HashCode * key, void *value)
1750 {
1751   struct MeshPeerInfo *peer_info = value;
1752   struct MeshPathInfo *neighbors = cls;
1753   unsigned int i;
1754
1755   if (peer_info->id == myid)
1756   {
1757     return GNUNET_YES;
1758   }
1759   peer_info = path_get_first_hop (neighbors->t, peer_info);
1760   for (i = 0; i < neighbors->path->length; i++)
1761   {
1762     if (neighbors->path->peers[i] == peer_info->id)
1763       return GNUNET_YES;
1764   }
1765   GNUNET_array_append(neighbors->path->peers,
1766                       neighbors->path->length,
1767                       peer_info->id);
1768
1769   return GNUNET_YES;
1770 }
1771
1772
1773 /******************************************************************************/
1774 /********************      MESH NETWORK HANDLERS     **************************/
1775 /******************************************************************************/
1776
1777
1778 /**
1779  * Core handler for path creation
1780  * struct GNUNET_CORE_MessageHandler
1781  *
1782  * @param cls closure
1783  * @param message message
1784  * @param peer peer identity this notification is about
1785  * @param atsi performance data
1786  * @return GNUNET_OK to keep the connection open,
1787  *         GNUNET_SYSERR to close it (signal serious error)
1788  *
1789  */
1790 static int
1791 handle_mesh_path_create (void *cls, const struct GNUNET_PeerIdentity *peer,
1792                          const struct GNUNET_MessageHeader *message,
1793                          const struct GNUNET_TRANSPORT_ATS_Information *atsi)
1794 {
1795   unsigned int own_pos;
1796   uint16_t size;
1797   uint16_t i;
1798   MESH_TunnelNumber tid;
1799   struct GNUNET_MESH_ManipulatePath *msg;
1800   struct GNUNET_PeerIdentity *pi;
1801   struct GNUNET_PeerIdentity id;
1802   GNUNET_HashCode hash;
1803   struct MeshPeerPath *path;
1804   struct MeshPeerInfo *dest_peer_info;
1805   struct MeshPeerInfo *orig_peer_info;
1806   struct MeshTunnel *t;
1807
1808   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1809               "MESH: Received a MESH path create msg\n");
1810   size = ntohs (message->size);
1811   if (size < sizeof (struct GNUNET_MESH_ManipulatePath))
1812   {
1813     GNUNET_break_op (0);
1814     return GNUNET_OK;
1815   }
1816
1817   size -= sizeof (struct GNUNET_MESH_ManipulatePath);
1818   if (size % sizeof (struct GNUNET_PeerIdentity))
1819   {
1820     GNUNET_break_op (0);
1821     return GNUNET_OK;
1822   }
1823   size /= sizeof (struct GNUNET_PeerIdentity);
1824   if (size < 2)
1825   {
1826     GNUNET_break_op (0);
1827     return GNUNET_OK;
1828   }
1829   msg = (struct GNUNET_MESH_ManipulatePath *) message;
1830
1831   tid = ntohl (msg->tid);
1832   pi = (struct GNUNET_PeerIdentity *) &msg[1];
1833   t = tunnel_get (pi, tid);
1834
1835   if (NULL == t)
1836   {
1837     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: Creating tunnel\n");
1838     t = GNUNET_malloc (sizeof (struct MeshTunnel));
1839     t->id.oid = GNUNET_PEER_intern (pi);
1840     t->id.tid = tid;
1841     t->peers = GNUNET_CONTAINER_multihashmap_create (32);
1842
1843     GNUNET_CRYPTO_hash (&t->id, sizeof (struct MESH_TunnelID), &hash);
1844     if (GNUNET_OK !=
1845         GNUNET_CONTAINER_multihashmap_put (
1846           tunnels, &hash, t,
1847           GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
1848     {
1849       GNUNET_break (0);
1850       return GNUNET_OK;
1851     }
1852
1853   }
1854   dest_peer_info =
1855       GNUNET_CONTAINER_multihashmap_get (peers, &pi[size - 1].hashPubKey);
1856   if (NULL == dest_peer_info)
1857   {
1858     dest_peer_info = GNUNET_malloc (sizeof (struct MeshPeerInfo));
1859     dest_peer_info->id = GNUNET_PEER_intern (&pi[size - 1]);
1860     GNUNET_CONTAINER_multihashmap_put (
1861       peers,
1862       &pi[size - 1].hashPubKey,
1863       dest_peer_info,
1864       GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
1865   }
1866   orig_peer_info = GNUNET_CONTAINER_multihashmap_get (peers, &pi->hashPubKey);
1867   if (NULL == orig_peer_info)
1868   {
1869     orig_peer_info = GNUNET_malloc (sizeof (struct MeshPeerInfo));
1870     orig_peer_info->id = GNUNET_PEER_intern (pi);
1871     GNUNET_CONTAINER_multihashmap_put (
1872       peers,
1873       &pi->hashPubKey,
1874       orig_peer_info,
1875       GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
1876   }
1877
1878   path = GNUNET_malloc (sizeof (struct MeshPeerPath));
1879   path->length = size;
1880   path->peers = GNUNET_malloc (size * sizeof (GNUNET_PEER_Id));
1881   own_pos = 0;
1882   for (i = 0; i < size; i++)
1883   {
1884     path->peers[i] = GNUNET_PEER_intern (&pi[i]);
1885     if (path->peers[i] == myid)
1886       own_pos = i;
1887   }
1888   if (own_pos == 0)
1889   {                             /* cannot be self, must be 'not found' */
1890     /* create path: self not found in path through self */
1891     GNUNET_break_op (0);
1892     path_destroy (path);
1893     /* FIXME error. destroy tunnel? leave for timeout? */
1894     return 0;
1895   }
1896   if (own_pos == size - 1)
1897   {
1898     /* It is for us! Send ack. */
1899     struct MeshDataDescriptor *info;
1900     unsigned int j;
1901
1902     path_add_to_origin (orig_peer_info, path);  /* inverts path!  */
1903     info = GNUNET_malloc (sizeof (struct MeshDataDescriptor));
1904     info->origin = &t->id;
1905     info->peer = GNUNET_CONTAINER_multihashmap_get (peers, &id.hashPubKey);
1906     GNUNET_assert (info->peer);
1907     for (j = 0; info->peer->core_transmit[j]; j++)
1908     {
1909       if (j == 9)
1910       {
1911         GNUNET_break (0);
1912         return GNUNET_OK;
1913       }
1914     }
1915     info->handler_n = j;
1916     info->peer->core_transmit[j] =
1917         GNUNET_CORE_notify_transmit_ready (core_handle, 0, 100,
1918                                            GNUNET_TIME_UNIT_FOREVER_REL, peer,
1919                                            sizeof (struct GNUNET_MessageHeader),
1920                                            &send_core_path_ack, info);
1921   }
1922   else
1923   {
1924     /* It's for somebody else! Retransmit. */
1925     struct MeshPathInfo *path_info;
1926
1927     path_info = GNUNET_malloc (sizeof(struct MeshPathInfo));
1928     path_info->t = t;
1929     path_info->path = path;
1930     path_info->peer = dest_peer_info;
1931
1932     path_add_to_peer (dest_peer_info, path);
1933     GNUNET_PEER_resolve (path->peers[own_pos + 1], &id);
1934     GNUNET_CORE_notify_transmit_ready (core_handle, 0, 0,
1935                                        GNUNET_TIME_UNIT_FOREVER_REL, &id,
1936                                        sizeof (struct GNUNET_MessageHeader),
1937                                        &send_core_create_path,
1938                                        path_info);
1939   }
1940   return GNUNET_OK;
1941 }
1942
1943
1944 /**
1945  * Core handler for mesh network traffic going from the origin to a peer
1946  *
1947  * @param cls closure
1948  * @param peer peer identity this notification is about
1949  * @param message message
1950  * @param atsi performance data
1951  * @return GNUNET_OK to keep the connection open,
1952  *         GNUNET_SYSERR to close it (signal serious error)
1953  */
1954 static int
1955 handle_mesh_data_unicast (void *cls, const struct GNUNET_PeerIdentity *peer,
1956                           const struct GNUNET_MessageHeader *message,
1957                           const struct GNUNET_TRANSPORT_ATS_Information *atsi)
1958 {
1959   struct GNUNET_MESH_Unicast *msg;
1960   struct GNUNET_PeerIdentity id;
1961   struct MeshTunnel *t;
1962   struct MeshPeerInfo *pi;
1963   size_t size;
1964
1965   size = ntohs (message->size);
1966   if (size <
1967       sizeof (struct GNUNET_MESH_Unicast) +
1968       sizeof (struct GNUNET_MessageHeader))
1969   {
1970     GNUNET_break (0);
1971     return GNUNET_OK;
1972   }
1973   msg = (struct GNUNET_MESH_Unicast *) message;
1974   t = tunnel_get (&msg->oid, ntohl (msg->tid));
1975   if (NULL == t)
1976   {
1977     /* TODO notify back: we don't know this tunnel */
1978     return GNUNET_OK;
1979   }
1980   pi = GNUNET_CONTAINER_multihashmap_get (t->peers,
1981                                           &msg->destination.hashPubKey);
1982   if (NULL == pi)
1983   {
1984     /* TODO maybe feedback, log to statistics */
1985     return GNUNET_OK;
1986   }
1987   if (pi->id == myid)
1988   {
1989     send_subscribed_clients ((struct GNUNET_MessageHeader *) &msg[1]);
1990     return GNUNET_OK;
1991   }
1992   GNUNET_PEER_resolve (path_get_first_hop (t, pi)->id, &id);
1993   msg = GNUNET_malloc (size);
1994   memcpy (msg, message, size);
1995   GNUNET_CORE_notify_transmit_ready (core_handle, 0, 0,
1996                                      GNUNET_TIME_UNIT_FOREVER_REL, &id, size,
1997                                      &send_core_data_raw, msg);
1998   return GNUNET_OK;
1999 }
2000
2001
2002 /**
2003  * Core handler for mesh network traffic going from the origin to all peers
2004  *
2005  * @param cls closure
2006  * @param message message
2007  * @param peer peer identity this notification is about
2008  * @param atsi performance data
2009  * @return GNUNET_OK to keep the connection open,
2010  *         GNUNET_SYSERR to close it (signal serious error)
2011  */
2012 static int
2013 handle_mesh_data_multicast (void *cls, const struct GNUNET_PeerIdentity *peer,
2014                             const struct GNUNET_MessageHeader *message,
2015                             const struct GNUNET_TRANSPORT_ATS_Information *atsi)
2016 {
2017   struct GNUNET_MESH_Multicast *msg;
2018   struct GNUNET_PeerIdentity id;
2019   struct MeshDataDescriptor *info;
2020   struct MeshPathInfo neighbors;
2021   struct MeshTunnel *t;
2022   size_t size;
2023   uint16_t i;
2024   uint16_t j;
2025
2026
2027   size = ntohs (message->size);
2028   if (size <
2029       sizeof (struct GNUNET_MESH_Multicast) +
2030       sizeof (struct GNUNET_MessageHeader))
2031   {
2032     GNUNET_break_op (0);
2033     return GNUNET_OK;
2034   }
2035   msg = (struct GNUNET_MESH_Multicast *) message;
2036   t = tunnel_get (&msg->oid, ntohl (msg->tid));
2037
2038   if (NULL == t)
2039   {
2040     /* TODO notify that we dont know that tunnel */
2041     return GNUNET_OK;
2042   }
2043
2044   /* Transmit to locally interested clients */
2045   if (GNUNET_CONTAINER_multihashmap_contains (t->peers, &my_full_id.hashPubKey))
2046   {
2047     send_subscribed_clients ((struct GNUNET_MessageHeader *) &msg[1]);
2048   }
2049
2050   /* Retransmit to other peers.
2051    * Using path here as just a collection of peers, not a path per se.
2052    */
2053   neighbors.t = t;
2054   neighbors.path = GNUNET_malloc (sizeof(struct MeshPeerPath));
2055   GNUNET_CONTAINER_multihashmap_iterate (t->peers, &iterate_collect_neighbors,
2056                                          &neighbors);
2057   if (0 == neighbors.path->length)
2058   {
2059     GNUNET_free(neighbors.path);
2060     return GNUNET_OK;
2061   }
2062   size -= sizeof (struct GNUNET_MESH_Multicast);
2063   info = GNUNET_malloc (sizeof (struct MeshDataDescriptor) + size);
2064   info->origin = &t->id;
2065   info->copies = neighbors.path->length;
2066   for (i = 0; i < info->copies; i++)
2067   {
2068     GNUNET_PEER_resolve (neighbors.path->peers[i], &id);
2069     info->peer = GNUNET_CONTAINER_multihashmap_get (peers, &id.hashPubKey);
2070     GNUNET_assert (NULL != info->peer);
2071     for (j = 0; 0 != info->peer->core_transmit[j]; j++)
2072     {
2073       if (j == (CORE_QUEUE_SIZE - 1))
2074       {
2075         GNUNET_break (0);
2076         return GNUNET_OK;
2077       }
2078     }
2079     info->handler_n = j;
2080     info->peer->infos[j] = info;
2081     info->peer->core_transmit[j] =
2082         GNUNET_CORE_notify_transmit_ready (core_handle, 0, 0,
2083                                            GNUNET_TIME_UNIT_FOREVER_REL, &id,
2084                                            ntohs (msg->header.size),
2085                                            &send_core_data_multicast, info);
2086   }
2087   GNUNET_free(neighbors.path->peers);
2088   GNUNET_free(neighbors.path);
2089   return GNUNET_OK;
2090 }
2091
2092
2093 /**
2094  * Core handler for mesh network traffic
2095  *
2096  * @param cls closure
2097  * @param message message
2098  * @param peer peer identity this notification is about
2099  * @param atsi performance data
2100  * @return GNUNET_OK to keep the connection open,
2101  *         GNUNET_SYSERR to close it (signal serious error)
2102  *
2103  * FIXME path
2104  */
2105 static int
2106 handle_mesh_data_to_orig (void *cls, const struct GNUNET_PeerIdentity *peer,
2107                           const struct GNUNET_MessageHeader *message,
2108                           const struct GNUNET_TRANSPORT_ATS_Information *atsi)
2109 {  
2110   struct GNUNET_MESH_ToOrigin *msg;
2111   struct GNUNET_PeerIdentity id;
2112   struct MeshTunnel *t;
2113   struct MeshPeerInfo *peer_info;
2114   size_t size;
2115
2116   size = ntohs (message->size);
2117   if (size <
2118       sizeof (struct GNUNET_MESH_ToOrigin) +
2119       sizeof (struct GNUNET_MessageHeader))
2120   {
2121     GNUNET_break_op (0);
2122     return GNUNET_OK;
2123   }
2124   msg = (struct GNUNET_MESH_ToOrigin *) message;
2125   t = tunnel_get (&msg->oid, ntohl (msg->tid));
2126
2127   if (NULL == t)
2128   {
2129     /* TODO notify that we dont know this tunnel (whom)? */
2130     return GNUNET_OK;
2131   }
2132
2133   if (t->id.oid == myid)
2134   {
2135     if (NULL == t->client)
2136     {
2137       /* got data packet for ownerless tunnel */
2138       GNUNET_break_op (0);
2139       return GNUNET_OK;
2140     }
2141     GNUNET_SERVER_notification_context_unicast (nc, t->client->handle, message,
2142                                                 GNUNET_YES);
2143     return GNUNET_OK;
2144   }
2145   peer_info = peer_info_get (&msg->oid);
2146   if (NULL == peer_info)
2147   {
2148     /* unknown origin of tunnel */
2149     GNUNET_break (0);
2150     return GNUNET_OK;
2151   }
2152   GNUNET_PEER_resolve (path_get_first_hop (t, peer_info)->id, &id);
2153   msg = GNUNET_malloc (size);
2154   memcpy (msg, message, size);
2155   GNUNET_CORE_notify_transmit_ready (core_handle, 0, 0,
2156                                      GNUNET_TIME_UNIT_FOREVER_REL, &id, size,
2157                                      &send_core_data_raw, msg);
2158
2159   return GNUNET_OK;
2160 }
2161
2162
2163 /**
2164  * Core handler for path ACKs
2165  *
2166  * @param cls closure
2167  * @param message message
2168  * @param peer peer identity this notification is about
2169  * @param atsi performance data
2170  *
2171  * @return GNUNET_OK to keep the connection open,
2172  *         GNUNET_SYSERR to close it (signal serious error)
2173  *
2174  * FIXME path change state
2175  */
2176 static int
2177 handle_mesh_path_ack (void *cls, const struct GNUNET_PeerIdentity *peer,
2178                       const struct GNUNET_MessageHeader *message,
2179                       const struct GNUNET_TRANSPORT_ATS_Information *atsi)
2180 {
2181   struct GNUNET_MESH_PathACK *msg;
2182   struct GNUNET_PeerIdentity id;
2183   struct MeshTunnel *t;
2184   struct MeshPeerInfo *peer_info;
2185
2186   msg = (struct GNUNET_MESH_PathACK *) message;
2187   t = tunnel_get (&msg->oid, msg->tid);
2188   if (NULL == t)
2189   {
2190     /* TODO notify that we don't know the tunnel */
2191     return GNUNET_OK;
2192   }
2193
2194   /* Message for us? */
2195   if (0 == memcmp (&msg->oid, &my_full_id, sizeof (struct GNUNET_PeerIdentity)))
2196   {
2197     struct GNUNET_MESH_PeerControl pc;
2198
2199     if (NULL == t->client)
2200     {
2201       GNUNET_break (0);
2202       return GNUNET_OK;
2203     }
2204     peer_info = peer_info_get (&msg->peer_id);
2205     if (NULL == peer_info)
2206     {
2207       GNUNET_break_op (0);
2208       return GNUNET_OK;
2209     }
2210     /* FIXME change state of peer */
2211     pc.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD);
2212     pc.header.size = htons (sizeof (struct GNUNET_MESH_PeerControl));
2213     pc.tunnel_id = htonl (t->local_tid);
2214     GNUNET_PEER_resolve (peer_info->id, &pc.peer);
2215     GNUNET_SERVER_notification_context_unicast (nc, t->client->handle,
2216                                                 &pc.header, GNUNET_NO);
2217     return GNUNET_OK;
2218   }
2219
2220   peer_info = peer_info_get (&msg->oid);
2221   if (NULL == peer_info)
2222   {
2223     /* If we know the tunnel, we should DEFINITELY know the peer */
2224     GNUNET_break (0);
2225     return GNUNET_OK;
2226   }
2227   GNUNET_PEER_resolve (path_get_first_hop (t, peer_info)->id, &id);
2228   msg = GNUNET_malloc (sizeof (struct GNUNET_MESH_PathACK));
2229   memcpy (msg, message, sizeof (struct GNUNET_MESH_PathACK));
2230   GNUNET_CORE_notify_transmit_ready (core_handle, 0, 0,
2231                                      GNUNET_TIME_UNIT_FOREVER_REL, &id,
2232                                      sizeof (struct GNUNET_MESH_PathACK),
2233                                      &send_core_data_raw, msg);
2234   return GNUNET_OK;
2235 }
2236
2237
2238 /**
2239  * Functions to handle messages from core
2240  */
2241 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
2242   {&handle_mesh_path_create, GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE, 0},
2243   {&handle_mesh_data_unicast, GNUNET_MESSAGE_TYPE_MESH_UNICAST, 0},
2244   {&handle_mesh_data_multicast, GNUNET_MESSAGE_TYPE_MESH_MULTICAST, 0},
2245   {&handle_mesh_data_to_orig, GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN, 0},
2246   {&handle_mesh_path_ack, GNUNET_MESSAGE_TYPE_MESH_PATH_ACK,
2247    sizeof (struct GNUNET_MESH_PathACK)},
2248   {NULL, 0, 0}
2249 };
2250
2251
2252
2253 /******************************************************************************/
2254 /****************       MESH LOCAL HANDLER HELPERS      ***********************/
2255 /******************************************************************************/
2256
2257 /**
2258  * delete_tunnel_entry: iterator for deleting each tunnel that belongs to a
2259  * client when the client disconnects.
2260  * @param cls closure (client that is disconnecting)
2261  * @param key the hash of the local tunnel id (used to access the hashmap)
2262  * @param value the value stored at the key (tunnel to destroy)
2263  * @return GNUNET_OK on success
2264  */
2265 static int
2266 delete_tunnel_entry (void *cls, const GNUNET_HashCode * key, void *value)
2267 {
2268   int r;
2269
2270   r = tunnel_destroy ((struct MeshTunnel *) value);
2271   return r;
2272 }
2273
2274
2275 /**
2276  * deregister_app: iterator for removing each application registered by a client
2277  * @param cls closure
2278  * @param key the hash of the application id (used to access the hashmap)
2279  * @param value the value stored at the key (client)
2280  * @return GNUNET_OK on success
2281  */
2282 static int
2283 deregister_app (void *cls, const GNUNET_HashCode * key, void *value)
2284 {
2285   GNUNET_CONTAINER_multihashmap_remove (applications, key, value);
2286   return GNUNET_OK;
2287 }
2288
2289 #if LATER
2290 /**
2291  * notify_client_connection_failure: notify a client that the connection to the
2292  * requested remote peer is not possible (for instance, no route found)
2293  * Function called when the socket is ready to queue more data. "buf" will be
2294  * NULL and "size" zero if the socket was closed for writing in the meantime.
2295  *
2296  * @param cls closure
2297  * @param size number of bytes available in buf
2298  * @param buf where the callee should write the message
2299  * @return number of bytes written to buf
2300  */
2301 static size_t
2302 notify_client_connection_failure (void *cls, size_t size, void *buf)
2303 {
2304   int size_needed;
2305   struct MeshPeerInfo *peer_info;
2306   struct GNUNET_MESH_PeerControl *msg;
2307   struct GNUNET_PeerIdentity id;
2308
2309   if (0 == size && NULL == buf)
2310   {
2311     // TODO retry? cancel?
2312     return 0;
2313   }
2314
2315   size_needed = sizeof (struct GNUNET_MESH_PeerControl);
2316   peer_info = (struct MeshPeerInfo *) cls;
2317   msg = (struct GNUNET_MESH_PeerControl *) buf;
2318   msg->header.size = htons (sizeof (struct GNUNET_MESH_PeerControl));
2319   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_DISCONNECTED);
2320 //     msg->tunnel_id = htonl(peer_info->t->tid);
2321   GNUNET_PEER_resolve (peer_info->id, &id);
2322   memcpy (&msg->peer, &id, sizeof (struct GNUNET_PeerIdentity));
2323
2324   return size_needed;
2325 }
2326 #endif
2327
2328
2329 /**
2330  * Function to process paths received for a new peer addition. The recorded
2331  * paths form the initial tunnel, which can be optimized later.
2332  * Called on each result obtained for the DHT search.
2333  *
2334  * @param cls closure
2335  * @param exp when will this value expire
2336  * @param key key of the result
2337  * @param get_path NULL-terminated array of pointers
2338  *                 to the peers on reverse GET path (or NULL if not recorded)
2339  * @param put_path NULL-terminated array of pointers
2340  *                 to the peers on the PUT path (or NULL if not recorded)
2341  * @param type type of the result
2342  * @param size number of bytes in data
2343  * @param data pointer to the result data
2344  *
2345  * FIXME path
2346  */
2347 static void
2348 dht_get_id_handler (void *cls, struct GNUNET_TIME_Absolute exp,
2349                     const GNUNET_HashCode * key,
2350                     const struct GNUNET_PeerIdentity *const *get_path,
2351                     const struct GNUNET_PeerIdentity *const *put_path,
2352                     enum GNUNET_BLOCK_Type type, size_t size, const void *data)
2353 {
2354   struct MeshPathInfo *path_info = cls;
2355   struct MeshPeerPath *p;
2356   struct GNUNET_PeerIdentity pi;
2357   int i;
2358
2359   if (NULL == get_path || NULL == put_path)
2360   {
2361     if (NULL == path_info->peer->path_head)
2362     {
2363       // Find ourselves some alternate initial path to the destination: retry
2364       GNUNET_DHT_get_stop (path_info->peer->dhtget);
2365       GNUNET_PEER_resolve (path_info->peer->id, &pi);
2366       path_info->peer->dhtget = GNUNET_DHT_get_start (
2367         dht_handle,       /* handle */
2368         GNUNET_TIME_UNIT_FOREVER_REL, /* timeout */
2369         GNUNET_BLOCK_TYPE_TEST,     /* type */
2370         &pi.hashPubKey,   /*key to search */
2371         4,        /* replication level */
2372         GNUNET_DHT_RO_RECORD_ROUTE, NULL, /* bloom filter */
2373         0,        /* mutator */
2374         NULL,     /* xquery */
2375         0,        /* xquery bits */
2376         dht_get_id_handler,
2377         (void *) path_info);
2378       return;
2379     }
2380   }
2381
2382   p = path_build_from_dht(get_path, put_path);
2383   path_add_to_peer (path_info->peer, p);
2384   for (i = 0; i < path_info->peer->ntunnels; i++)
2385   {
2386     tunnel_add_peer(path_info->peer->tunnels[i], path_info->peer);
2387   }
2388   GNUNET_free(path_info);
2389
2390   return;
2391 }
2392
2393
2394 /**
2395  * Function to process paths received for a new peer addition. The recorded
2396  * paths form the initial tunnel, which can be optimized later.
2397  * Called on each result obtained for the DHT search.
2398  *
2399  * @param cls closure
2400  * @param exp when will this value expire
2401  * @param key key of the result
2402  * @param get_path NULL-terminated array of pointers
2403  *                 to the peers on reverse GET path (or NULL if not recorded)
2404  * @param put_path NULL-terminated array of pointers
2405  *                 to the peers on the PUT path (or NULL if not recorded)
2406  * @param type type of the result
2407  * @param size number of bytes in data
2408  * @param data pointer to the result data
2409  */
2410 static void
2411 dht_get_type_handler (void *cls, struct GNUNET_TIME_Absolute exp,
2412                       const GNUNET_HashCode * key,
2413                       const struct GNUNET_PeerIdentity *const *get_path,
2414                       const struct GNUNET_PeerIdentity *const *put_path,
2415                       enum GNUNET_BLOCK_Type type, size_t size,
2416                       const void *data)
2417 {
2418   const struct GNUNET_PeerIdentity *pi = data;
2419   struct GNUNET_PeerIdentity id;
2420   struct MeshTunnel *t = cls;
2421   struct MeshPeerInfo *peer_info;
2422   struct MeshPeerPath *p;
2423   int i;
2424
2425   if (size != sizeof (struct GNUNET_PeerIdentity))
2426   {
2427     GNUNET_break_op (0);
2428     return;
2429   }
2430   GNUNET_assert (NULL != t->client);
2431   GNUNET_DHT_get_stop (t->client->dht_get_type);
2432   t->client->dht_get_type = NULL;
2433   peer_info = peer_info_get (pi);
2434   GNUNET_CONTAINER_multihashmap_put (t->peers, &pi->hashPubKey, peer_info,
2435                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
2436
2437   if ((NULL == get_path || NULL == put_path) &&
2438     NULL == peer_info->path_head &&
2439     NULL == peer_info->dhtget)
2440   {
2441     /* we don't have a route to the peer, let's try a direct lookup */
2442     peer_info->dhtget = GNUNET_DHT_get_start (
2443       dht_handle,     /* handle */
2444       GNUNET_TIME_UNIT_FOREVER_REL, /* timeout */
2445       GNUNET_BLOCK_TYPE_TEST, /* block type */
2446       &pi->hashPubKey, /* key to look up */
2447       10U,     /* replication level */
2448       GNUNET_DHT_RO_RECORD_ROUTE, /* option to dht: record route */
2449       NULL,   /* bloom filter */
2450       0,      /* mutator */
2451       NULL,   /* xquery */
2452       0,      /* xquery bits */
2453       dht_get_id_handler,       /* callback */
2454       peer_info);       /* closure */
2455   }
2456
2457   p = path_build_from_dht(get_path, put_path);
2458   path_add_to_peer (peer_info, p);
2459 #if MESH_DEBUG
2460   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2461              "MESH: new route for tunnel 0x%x found, has %u hops\n",
2462              t->local_tid,
2463              p->length);
2464   for (i = 0; i < p->length; i++)
2465   {
2466     GNUNET_PEER_resolve(p->peers[0], &id);
2467     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2468               "MESH:\t%d\t%s\n",
2469                i,
2470               GNUNET_h2s_full(&id.hashPubKey));
2471   }
2472 #endif
2473
2474   GNUNET_PEER_resolve (p->peers[1], &id);
2475   GNUNET_CORE_notify_transmit_ready (
2476     core_handle,       /* handle */
2477     0,                 /* cork */
2478     0,                 /* priority*/
2479     GNUNET_TIME_UNIT_FOREVER_REL,       /* timeout */
2480     &id,       /* target */
2481     sizeof (struct GNUNET_MESH_ManipulatePath) +
2482     (p->length * sizeof (struct GNUNET_PeerIdentity)),          /*size */
2483     &send_core_create_path,    /* callback */
2484     peer_info);        /* cls */
2485 }
2486
2487 /******************************************************************************/
2488 /*********************       MESH LOCAL HANDLES      **************************/
2489 /******************************************************************************/
2490
2491
2492 /**
2493  * Handler for client disconnection
2494  *
2495  * @param cls closure
2496  * @param client identification of the client; NULL
2497  *        for the last call when the server is destroyed
2498  */
2499 static void
2500 handle_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
2501 {
2502   struct MeshClient *c;
2503   struct MeshClient *next;
2504
2505   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: client disconnected\n");
2506   c = clients;
2507   while (NULL != c)
2508   {
2509     if (c->handle != client)
2510     {
2511       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:    ... searching\n");
2512       c = c->next;
2513       continue;
2514     }
2515     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: matching client found\n");
2516     if (NULL != c->tunnels)
2517     {
2518       GNUNET_CONTAINER_multihashmap_iterate (c->tunnels, &delete_tunnel_entry,
2519                                              c);
2520       GNUNET_CONTAINER_multihashmap_destroy (c->tunnels);
2521     }
2522
2523     /* deregister clients applications */
2524     if (NULL != c->apps)
2525     {
2526       GNUNET_CONTAINER_multihashmap_iterate (c->apps, &deregister_app, NULL);
2527       GNUNET_CONTAINER_multihashmap_destroy (c->apps);
2528     }
2529     if (0 == GNUNET_CONTAINER_multihashmap_size (applications) &&
2530         GNUNET_SCHEDULER_NO_TASK != announce_applications_task)
2531     {
2532       GNUNET_SCHEDULER_cancel (announce_applications_task);
2533       announce_applications_task = GNUNET_SCHEDULER_NO_TASK;
2534     }
2535     if (NULL != c->types)
2536       GNUNET_CONTAINER_multihashmap_destroy (c->types);
2537     if (NULL != c->dht_get_type)
2538       GNUNET_DHT_get_stop (c->dht_get_type);
2539     GNUNET_CONTAINER_DLL_remove (clients, clients_tail, c);
2540     next = c->next;
2541     GNUNET_free (c);
2542     c = next;
2543   }
2544
2545   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:    done!\n");
2546   return;
2547 }
2548
2549
2550 /**
2551  * Handler for new clients
2552  *
2553  * @param cls closure
2554  * @param client identification of the client
2555  * @param message the actual message, which includes messages the client wants
2556  */
2557 static void
2558 handle_local_new_client (void *cls, struct GNUNET_SERVER_Client *client,
2559                          const struct GNUNET_MessageHeader *message)
2560 {
2561   struct GNUNET_MESH_ClientConnect *cc_msg;
2562   struct MeshClient *c;
2563   GNUNET_MESH_ApplicationType *a;
2564   unsigned int size;
2565   uint16_t ntypes;
2566   uint16_t *t;
2567   uint16_t napps;
2568   uint16_t i;
2569
2570   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: new client connected\n");
2571   /* Check data sanity */
2572   size = ntohs (message->size) - sizeof (struct GNUNET_MESH_ClientConnect);
2573   cc_msg = (struct GNUNET_MESH_ClientConnect *) message;
2574   ntypes = ntohs (cc_msg->types);
2575   napps = ntohs (cc_msg->applications);
2576   if (size !=
2577       ntypes * sizeof (uint16_t) + napps * sizeof (GNUNET_MESH_ApplicationType))
2578   {
2579     GNUNET_break (0);
2580     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2581     return;
2582   }
2583
2584   /* Create new client structure */
2585   c = GNUNET_malloc (sizeof (struct MeshClient));
2586   c->handle = client;
2587   a = (GNUNET_MESH_ApplicationType *) &cc_msg[1];
2588   if (napps > 0)
2589   {
2590     GNUNET_MESH_ApplicationType at;
2591     GNUNET_HashCode hc;
2592
2593     c->apps = GNUNET_CONTAINER_multihashmap_create (napps);
2594     for (i = 0; i < napps; i++)
2595     {
2596       at = ntohl (a[i]);
2597       GNUNET_CRYPTO_hash (&at, sizeof (at), &hc);
2598       /* store in clients hashmap */
2599       GNUNET_CONTAINER_multihashmap_put (c->apps, &hc, c,
2600                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2601       /* store in global hashmap, for announcements */
2602       GNUNET_CONTAINER_multihashmap_put (applications, &hc, c,
2603                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2604     }
2605     if (GNUNET_SCHEDULER_NO_TASK == announce_applications_task)
2606       announce_applications_task =
2607           GNUNET_SCHEDULER_add_now (&announce_applications, NULL);
2608
2609   }
2610   if (ntypes > 0)
2611   {
2612     uint16_t u16;
2613     GNUNET_HashCode hc;
2614
2615     t = (uint16_t *) & a[napps];
2616     c->types = GNUNET_CONTAINER_multihashmap_create (ntypes);
2617     for (i = 0; i < ntypes; i++)
2618     {
2619       u16 = ntohs (t[i]);
2620       GNUNET_CRYPTO_hash (&u16, sizeof (u16), &hc);
2621
2622       /* store in clients hashmap */
2623       GNUNET_CONTAINER_multihashmap_put (c->types, &hc, c,
2624                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2625       /* store in global hashmap */
2626       GNUNET_CONTAINER_multihashmap_put (types, &hc, c,
2627                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2628     }
2629   }
2630   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2631               "MESH:  client has %u+%u subscriptions\n", napps, ntypes);
2632
2633   GNUNET_CONTAINER_DLL_insert (clients, clients_tail, c);
2634   c->tunnels = GNUNET_CONTAINER_multihashmap_create (32);
2635   GNUNET_SERVER_notification_context_add (nc, client);
2636
2637   GNUNET_SERVER_receive_done (client, GNUNET_OK);
2638
2639 }
2640
2641
2642 /**
2643  * Handler for requests of new tunnels
2644  *
2645  * @param cls closure
2646  * @param client identification of the client
2647  * @param message the actual message
2648  */
2649 static void
2650 handle_local_tunnel_create (void *cls, struct GNUNET_SERVER_Client *client,
2651                             const struct GNUNET_MessageHeader *message)
2652 {
2653   struct GNUNET_MESH_TunnelMessage *t_msg;
2654   struct MeshTunnel *t;
2655   struct MeshClient *c;
2656   GNUNET_HashCode hash;
2657
2658   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: new tunnel requested\n");
2659
2660   /* Sanity check for client registration */
2661   if (NULL == (c = client_get (client)))
2662   {
2663     GNUNET_break (0);
2664     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2665     return;
2666   }
2667
2668   /* Message sanity check */
2669   if (sizeof (struct GNUNET_MESH_TunnelMessage) != ntohs (message->size))
2670   {
2671     GNUNET_break (0);
2672     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2673     return;
2674   }
2675
2676   t_msg = (struct GNUNET_MESH_TunnelMessage *) message;
2677   /* Sanity check for tunnel numbering */
2678   if (0 == (ntohl (t_msg->tunnel_id) & GNUNET_MESH_LOCAL_TUNNEL_ID_CLI))
2679   {
2680     GNUNET_break (0);
2681     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2682     return;
2683   }
2684   /* Sanity check for duplicate tunnel IDs */
2685   if (NULL != tunnel_get_by_local_id (c, ntohl (t_msg->tunnel_id)))
2686   {
2687     GNUNET_break (0);
2688     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2689     return;
2690   }
2691
2692   t = GNUNET_malloc (sizeof (struct MeshTunnel));
2693   while (NULL != tunnel_get_by_pi (myid, next_tid))
2694     next_tid = (next_tid + 1) & ~GNUNET_MESH_LOCAL_TUNNEL_ID_CLI;
2695   t->id.tid = next_tid++;
2696   t->id.oid = myid;
2697   t->local_tid = ntohl (t_msg->tunnel_id);
2698   t->client = c;
2699   t->peers = GNUNET_CONTAINER_multihashmap_create (32);
2700
2701   GNUNET_CRYPTO_hash (&t->local_tid, sizeof (MESH_TunnelNumber), &hash);
2702   if (GNUNET_OK !=
2703       GNUNET_CONTAINER_multihashmap_put (c->tunnels, &hash, t,
2704                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
2705   {
2706     GNUNET_break (0);
2707     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2708     return;
2709   }
2710
2711   GNUNET_CRYPTO_hash (&t->id, sizeof (struct MESH_TunnelID), &hash);
2712   if (GNUNET_OK !=
2713       GNUNET_CONTAINER_multihashmap_put (tunnels, &hash, t,
2714                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
2715   {
2716     GNUNET_break (0);
2717     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2718     return;
2719   }
2720
2721   GNUNET_SERVER_receive_done (client, GNUNET_OK);
2722   return;
2723 }
2724
2725
2726 /**
2727  * Handler for requests of deleting tunnels
2728  *
2729  * @param cls closure
2730  * @param client identification of the client
2731  * @param message the actual message
2732  */
2733 static void
2734 handle_local_tunnel_destroy (void *cls, struct GNUNET_SERVER_Client *client,
2735                              const struct GNUNET_MessageHeader *message)
2736 {
2737   struct GNUNET_MESH_TunnelMessage *tunnel_msg;
2738   struct MeshClient *c;
2739   struct MeshTunnel *t;
2740   MESH_TunnelNumber tid;
2741   GNUNET_HashCode hash;
2742
2743   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: destroying tunnel\n");
2744
2745   /* Sanity check for client registration */
2746   if (NULL == (c = client_get (client)))
2747   {
2748     GNUNET_break (0);
2749     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2750     return;
2751   }
2752   /* Message sanity check */
2753   if (sizeof (struct GNUNET_MESH_TunnelMessage) != ntohs (message->size))
2754   {
2755     GNUNET_break (0);
2756     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2757     return;
2758   }
2759
2760   tunnel_msg = (struct GNUNET_MESH_TunnelMessage *) message;
2761
2762   /* Retrieve tunnel */
2763   tid = ntohl (tunnel_msg->tunnel_id);
2764
2765   /* Remove from local id hashmap */
2766   GNUNET_CRYPTO_hash (&tid, sizeof (MESH_TunnelNumber), &hash);
2767   t = GNUNET_CONTAINER_multihashmap_get (c->tunnels, &hash);
2768   GNUNET_CONTAINER_multihashmap_remove (c->tunnels, &hash, t);
2769
2770   /* Remove from global id hashmap */
2771   GNUNET_CRYPTO_hash (&t->id, sizeof (struct MESH_TunnelID), &hash);
2772   GNUNET_CONTAINER_multihashmap_remove (tunnels, &hash, t);
2773
2774 //     notify_tunnel_destroy(t);
2775   GNUNET_SERVER_receive_done (client, GNUNET_OK);
2776   return;
2777 }
2778
2779
2780 /**
2781  * Handler for connection requests to new peers
2782  *
2783  * @param cls closure
2784  * @param client identification of the client
2785  * @param message the actual message (PeerControl)
2786  *
2787  * FIXME path
2788  */
2789 static void
2790 handle_local_connect_add (void *cls, struct GNUNET_SERVER_Client *client,
2791                           const struct GNUNET_MessageHeader *message)
2792 {
2793   struct GNUNET_MESH_PeerControl *peer_msg;
2794   struct MeshClient *c;
2795   struct MeshTunnel *t;
2796   MESH_TunnelNumber tid;
2797   struct MeshPeerInfo *peer_info;
2798
2799
2800   /* Sanity check for client registration */
2801   if (NULL == (c = client_get (client)))
2802   {
2803     GNUNET_break (0);
2804     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2805     return;
2806   }
2807
2808   peer_msg = (struct GNUNET_MESH_PeerControl *) message;
2809   /* Sanity check for message size */
2810   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (peer_msg->header.size))
2811   {
2812     GNUNET_break (0);
2813     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2814     return;
2815   }
2816
2817   /* Tunnel exists? */
2818   tid = ntohl (peer_msg->tunnel_id);
2819   t = tunnel_get_by_local_id (c, tid);
2820   if (NULL == t)
2821   {
2822     GNUNET_break (0);
2823     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2824     return;
2825   }
2826
2827   /* Does client own tunnel? */
2828   if (t->client->handle != client)
2829   {
2830     GNUNET_break (0);
2831     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2832     return;
2833   }
2834
2835   t->peers_total++;
2836   peer_info = peer_info_get (&peer_msg->peer);
2837
2838   /* Start DHT search if needed FIXME: if not already connected */
2839   if (NULL == peer_info->dhtget)
2840   {
2841     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 */
2842                                               GNUNET_DHT_RO_RECORD_ROUTE, NULL, /* bloom filter */
2843                                               0,        /* mutator */
2844                                               NULL,     /* xquery */
2845                                               0,        /* xquery bits */
2846                                               dht_get_id_handler,
2847                                               (void *) peer_info);
2848   }
2849
2850   GNUNET_SERVER_receive_done (client, GNUNET_OK);
2851   return;
2852 }
2853
2854
2855 /**
2856  * Handler for disconnection requests of peers in a tunnel
2857  *
2858  * @param cls closure
2859  * @param client identification of the client
2860  * @param message the actual message (PeerControl)
2861  */
2862 static void
2863 handle_local_connect_del (void *cls, struct GNUNET_SERVER_Client *client,
2864                           const struct GNUNET_MessageHeader *message)
2865 {
2866   struct GNUNET_MESH_PeerControl *peer_msg;
2867   struct MeshClient *c;
2868   struct MeshTunnel *t;
2869   MESH_TunnelNumber tid;
2870
2871   /* Sanity check for client registration */
2872   if (NULL == (c = client_get (client)))
2873   {
2874     GNUNET_break (0);
2875     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2876     return;
2877   }
2878   peer_msg = (struct GNUNET_MESH_PeerControl *) message;
2879   /* Sanity check for message size */
2880   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (peer_msg->header.size))
2881   {
2882     GNUNET_break (0);
2883     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2884     return;
2885   }
2886
2887   /* Tunnel exists? */
2888   tid = ntohl (peer_msg->tunnel_id);
2889   t = tunnel_get_by_local_id (c, tid);
2890   if (NULL == t)
2891   {
2892     GNUNET_break (0);
2893     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2894     return;
2895   }
2896
2897   /* Does client own tunnel? */
2898   if (t->client->handle != client)
2899   {
2900     GNUNET_break (0);
2901     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2902     return;
2903   }
2904
2905   /* Ok, delete peer from tunnel */
2906   GNUNET_CONTAINER_multihashmap_remove_all (t->peers,
2907                                             &peer_msg->peer.hashPubKey);
2908
2909   GNUNET_SERVER_receive_done (client, GNUNET_OK);
2910   return;
2911 }
2912
2913
2914 /**
2915  * Handler for connection requests to new peers by type
2916  *
2917  * @param cls closure
2918  * @param client identification of the client
2919  * @param message the actual message (ConnectPeerByType)
2920  */
2921 static void
2922 handle_local_connect_by_type (void *cls, struct GNUNET_SERVER_Client *client,
2923                               const struct GNUNET_MessageHeader *message)
2924 {
2925   struct GNUNET_MESH_ConnectPeerByType *connect_msg;
2926   struct MeshClient *c;
2927   struct MeshTunnel *t;
2928   GNUNET_HashCode hash;
2929   GNUNET_MESH_ApplicationType type;
2930   MESH_TunnelNumber tid;
2931
2932   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: got connect by type request\n");
2933   /* Sanity check for client registration */
2934   if (NULL == (c = client_get (client)))
2935   {
2936     GNUNET_break (0);
2937     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2938     return;
2939   }
2940
2941   connect_msg = (struct GNUNET_MESH_ConnectPeerByType *) message;
2942   /* Sanity check for message size */
2943   if (sizeof (struct GNUNET_MESH_ConnectPeerByType) !=
2944       ntohs (connect_msg->header.size))
2945   {
2946     GNUNET_break (0);
2947     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2948     return;
2949   }
2950
2951   /* Tunnel exists? */
2952   tid = ntohl (connect_msg->tunnel_id);
2953   t = tunnel_get_by_local_id (c, tid);
2954   if (NULL == t)
2955   {
2956     GNUNET_break (0);
2957     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2958     return;
2959   }
2960
2961   /* Does client own tunnel? */
2962   if (t->client->handle != client)
2963   {
2964     GNUNET_break (0);
2965     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2966     return;
2967   }
2968
2969   /* Do WE have the service? */
2970   type = ntohl (connect_msg->type);
2971   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:  type requested: %u\n", type);
2972   GNUNET_CRYPTO_hash (&type, sizeof (GNUNET_MESH_ApplicationType), &hash);
2973   if (GNUNET_CONTAINER_multihashmap_contains (applications, &hash) ==
2974       GNUNET_YES)
2975   {
2976     /* Yes! Fast forward, add ourselves to the tunnel and send the
2977      * good news to the client
2978      */
2979     struct GNUNET_MESH_PeerControl pc;
2980
2981     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:  available locally\n");
2982     pc.peer = my_full_id;
2983     GNUNET_CONTAINER_multihashmap_put (t->peers, &pc.peer.hashPubKey,
2984                                        peer_info_get (&pc.peer),
2985                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
2986     pc.header.size = htons (sizeof (struct GNUNET_MESH_PeerControl));
2987     pc.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD);
2988     pc.tunnel_id = htonl (t->local_tid);
2989     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:  notifying client\n");
2990     GNUNET_SERVER_notification_context_unicast (nc,     /* context */
2991                                                 client, /* dest */
2992                                                 &pc.header,     /* msg */
2993                                                 GNUNET_NO);     /* can drop? */
2994     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:  Done\n");
2995     GNUNET_SERVER_receive_done (client, GNUNET_OK);
2996     return;
2997   }
2998   /* Ok, lets find a peer offering the service */
2999   if (c->dht_get_type)
3000   {
3001     GNUNET_DHT_get_stop (c->dht_get_type);
3002   }
3003   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:  looking in DHT for %s\n",
3004               GNUNET_h2s_full (&hash));
3005   c->dht_get_type =
3006       GNUNET_DHT_get_start (dht_handle, GNUNET_TIME_UNIT_FOREVER_REL,
3007                             GNUNET_BLOCK_TYPE_TEST, &hash, 10U,
3008                             GNUNET_DHT_RO_RECORD_ROUTE, NULL, 0, NULL, 0,
3009                             &dht_get_type_handler, t);
3010
3011   GNUNET_SERVER_receive_done (client, GNUNET_OK);
3012   return;
3013 }
3014
3015
3016 /**
3017  * Handler for client traffic directed to one peer
3018  *
3019  * @param cls closure
3020  * @param client identification of the client
3021  * @param message the actual message
3022  */
3023 static void
3024 handle_local_unicast (void *cls, struct GNUNET_SERVER_Client *client,
3025                       const struct GNUNET_MessageHeader *message)
3026 {
3027   struct MeshClient *c;
3028   struct MeshTunnel *t;
3029   struct MeshPeerInfo *pi;
3030   struct GNUNET_MESH_Unicast *data_msg;
3031   struct GNUNET_PeerIdentity next_hop;
3032   struct MeshDataDescriptor *info;
3033   MESH_TunnelNumber tid;
3034   size_t data_size;
3035
3036   /* Sanity check for client registration */
3037   if (NULL == (c = client_get (client)))
3038   {
3039     GNUNET_break (0);
3040     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3041     return;
3042   }
3043   data_msg = (struct GNUNET_MESH_Unicast *) message;
3044   /* Sanity check for message size */
3045   if (sizeof (struct GNUNET_MESH_Unicast) +
3046       sizeof (struct GNUNET_MessageHeader) > ntohs (data_msg->header.size))
3047   {
3048     GNUNET_break (0);
3049     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3050     return;
3051   }
3052
3053   /* Tunnel exists? */
3054   tid = ntohl (data_msg->tid);
3055   t = tunnel_get_by_local_id (c, tid);
3056   if (NULL == t)
3057   {
3058     GNUNET_break (0);
3059     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3060     return;
3061   }
3062
3063   /*  Is it a local tunnel? Then, does client own the tunnel? */
3064   if (t->client->handle != NULL && t->client->handle != client)
3065   {
3066     GNUNET_break (0);
3067     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3068     return;
3069   }
3070
3071   pi = GNUNET_CONTAINER_multihashmap_get (t->peers,
3072                                           &data_msg->destination.hashPubKey);
3073   /* Is the selected peer in the tunnel? */
3074   if (NULL == pi)
3075   {
3076     GNUNET_break (0);
3077     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3078     return;
3079   }
3080   if (pi->id == myid)
3081   {
3082     struct GNUNET_MESH_Unicast copy;
3083
3084     /* Work around const limitation */
3085     memcpy (&copy, data_msg, sizeof (struct GNUNET_MESH_Unicast));
3086     copy.oid = my_full_id;
3087     copy.tid = htonl (t->id.tid);
3088     handle_mesh_data_unicast (NULL, &my_full_id, &copy.header, NULL);
3089     return;
3090   }
3091   GNUNET_PEER_resolve (path_get_first_hop (t, pi)->id, &next_hop);
3092   data_size = ntohs (message->size) - sizeof (struct GNUNET_MESH_Unicast);
3093   info = GNUNET_malloc (sizeof (struct MeshDataDescriptor) + data_size);
3094   memcpy (&info[1], &data_msg[1], data_size);
3095   info->destination = pi->id;
3096   info->origin = &t->id;
3097   info->size = data_size;
3098   info->client = client;
3099   GNUNET_CORE_notify_transmit_ready (core_handle, 0, 0,
3100                                      GNUNET_TIME_UNIT_FOREVER_REL, &next_hop,
3101                                      /* FIXME re-check types */
3102                                      data_size +
3103                                      sizeof (struct GNUNET_MESH_Unicast),
3104                                      &send_core_data_unicast, info);
3105   return;
3106 }
3107
3108 /**
3109  * Handler for client traffic directed to all peers in a tunnel
3110  *
3111  * @param cls closure
3112  * @param client identification of the client
3113  * @param message the actual message
3114  */
3115 static void
3116 handle_local_multicast (void *cls, struct GNUNET_SERVER_Client *client,
3117                         const struct GNUNET_MessageHeader *message)
3118 {
3119   struct MeshClient *c;
3120   struct MeshTunnel *t;
3121   struct GNUNET_MESH_Multicast *data_msg;
3122   MESH_TunnelNumber tid;
3123
3124   /* Sanity check for client registration */
3125   if (NULL == (c = client_get (client)))
3126   {
3127     GNUNET_break (0);
3128     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3129     return;
3130   }
3131   data_msg = (struct GNUNET_MESH_Multicast *) message;
3132   /* Sanity check for message size */
3133   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (data_msg->header.size))
3134   {
3135     GNUNET_break (0);
3136     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3137     return;
3138   }
3139
3140   /* Tunnel exists? */
3141   tid = ntohl (data_msg->tid);
3142   t = tunnel_get_by_local_id (c, tid);
3143   if (NULL == t)
3144   {
3145     GNUNET_break (0);
3146     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3147     return;
3148   }
3149
3150   /* Does client own tunnel? */
3151   if (t->client->handle != client)
3152   {
3153     GNUNET_break (0);
3154     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3155     return;
3156   }
3157
3158   /*  TODO */
3159
3160   GNUNET_SERVER_receive_done (client, GNUNET_OK);
3161   return;
3162 }
3163
3164 /**
3165  * Functions to handle messages from clients
3166  */
3167 static struct GNUNET_SERVER_MessageHandler client_handlers[] = {
3168   {&handle_local_new_client, NULL, GNUNET_MESSAGE_TYPE_MESH_LOCAL_CONNECT, 0},
3169   {&handle_local_tunnel_create, NULL,
3170    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_CREATE,
3171    sizeof (struct GNUNET_MESH_TunnelMessage)},
3172   {&handle_local_tunnel_destroy, NULL,
3173    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_DESTROY,
3174    sizeof (struct GNUNET_MESH_TunnelMessage)},
3175   {&handle_local_connect_add, NULL,
3176    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD,
3177    sizeof (struct GNUNET_MESH_PeerControl)},
3178   {&handle_local_connect_del, NULL,
3179    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_DEL,
3180    sizeof (struct GNUNET_MESH_PeerControl)},
3181   {&handle_local_connect_by_type, NULL,
3182    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD_BY_TYPE,
3183    sizeof (struct GNUNET_MESH_ConnectPeerByType)},
3184   {&handle_local_unicast, NULL,
3185    GNUNET_MESSAGE_TYPE_MESH_UNICAST, 0},
3186   {&handle_local_unicast, NULL,
3187    GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN, 0},
3188   {&handle_local_multicast, NULL,
3189    GNUNET_MESSAGE_TYPE_MESH_MULTICAST, 0},
3190   {NULL, NULL, 0, 0}
3191 };
3192
3193
3194 /**
3195  * To be called on core init/fail.
3196  *
3197  * @param cls service closure
3198  * @param server handle to the server for this service
3199  * @param identity the public identity of this peer
3200  * @param publicKey the public key of this peer
3201  */
3202 static void
3203 core_init (void *cls, struct GNUNET_CORE_Handle *server,
3204            const struct GNUNET_PeerIdentity *identity,
3205            const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *publicKey)
3206 {
3207   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: Core init\n");
3208   core_handle = server;
3209   my_full_id = *identity;
3210   myid = GNUNET_PEER_intern (identity);
3211   announce_id_task = GNUNET_SCHEDULER_add_now (&announce_id, cls);
3212   return;
3213 }
3214
3215 /**
3216  * Method called whenever a given peer connects.
3217  *
3218  * @param cls closure
3219  * @param peer peer identity this notification is about
3220  * @param atsi performance data for the connection
3221  */
3222 static void
3223 core_connect (void *cls, const struct GNUNET_PeerIdentity *peer,
3224               const struct GNUNET_TRANSPORT_ATS_Information *atsi)
3225 {
3226 //     GNUNET_PEER_Id              pid;
3227   struct MeshPeerInfo *peer_info;
3228   struct MeshPeerPath *path;
3229
3230   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: Peer connected\n");
3231   peer_info = peer_info_get (peer);
3232   if (myid == peer_info->id)
3233   {
3234     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:      (self)\n");
3235   }
3236   path = GNUNET_malloc (sizeof (struct MeshPeerPath));
3237   path->length = 2;
3238   path->peers = GNUNET_malloc (sizeof (GNUNET_PEER_Id) * 2);
3239   path->peers[0] = myid;
3240   path->peers[1] = peer_info->id;
3241   path_add_to_peer (peer_info, path);
3242   return;
3243 }
3244
3245 /**
3246  * Method called whenever a peer disconnects.
3247  *
3248  * @param cls closure
3249  * @param peer peer identity this notification is about
3250  */
3251 static void
3252 core_disconnect (void *cls, const struct GNUNET_PeerIdentity *peer)
3253 {
3254   struct MeshPeerInfo *pi;
3255   unsigned int i;
3256
3257   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: Peer disconnected\n");
3258   pi = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
3259   if (!pi)
3260   {
3261     GNUNET_break (0);
3262     return;
3263   }
3264   for (i = 0; i < CORE_QUEUE_SIZE; i++)
3265   {
3266     if (pi->core_transmit[i])
3267     {
3268       GNUNET_CORE_notify_transmit_ready_cancel (pi->core_transmit[i]);
3269       /* TODO: notify that tranmission has failed */
3270       GNUNET_free (pi->infos[i]);
3271     }
3272   }
3273   path_remove_from_peer (pi, pi->id, myid);
3274   if (myid == pi->id)
3275   {
3276     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:      (self)\n");
3277   }
3278   return;
3279 }
3280
3281
3282 /******************************************************************************/
3283 /************************      MAIN FUNCTIONS      ****************************/
3284 /******************************************************************************/
3285
3286 /**
3287  * Task run during shutdown.
3288  *
3289  * @param cls unused
3290  * @param tc unused
3291  */
3292 static void
3293 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3294 {
3295   struct MeshClient *c;
3296
3297   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: shutting down\n");
3298   if (core_handle != NULL)
3299   {
3300     GNUNET_CORE_disconnect (core_handle);
3301     core_handle = NULL;
3302   }
3303   if (dht_handle != NULL)
3304   {
3305     for (c = clients; NULL != c; c = c->next)
3306       if (NULL != c->dht_get_type)
3307         GNUNET_DHT_get_stop (c->dht_get_type);
3308     GNUNET_DHT_disconnect (dht_handle);
3309     dht_handle = NULL;
3310   }
3311   if (nc != NULL)
3312   {
3313     GNUNET_SERVER_notification_context_destroy (nc);
3314     nc = NULL;
3315   }
3316   if (GNUNET_SCHEDULER_NO_TASK != announce_id_task)
3317   {
3318     GNUNET_SCHEDULER_cancel (announce_id_task);
3319     announce_id_task = GNUNET_SCHEDULER_NO_TASK;
3320   }
3321   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: shut down\n");
3322 }
3323
3324 /**
3325  * Process mesh requests.
3326  *
3327  * @param cls closure
3328  * @param server the initialized server
3329  * @param c configuration to use
3330  */
3331 static void
3332 run (void *cls, struct GNUNET_SERVER_Handle *server,
3333      const struct GNUNET_CONFIGURATION_Handle *c)
3334 {
3335   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: starting to run\n");
3336   GNUNET_SERVER_add_handlers (server, client_handlers);
3337   GNUNET_SERVER_disconnect_notify (server, &handle_client_disconnect, NULL);
3338   server_handle = server;
3339   core_handle = GNUNET_CORE_connect (c, /* Main configuration */
3340                                      CORE_QUEUE_SIZE,   /* queue size */
3341                                      NULL,      /* Closure passed to MESH functions */
3342                                      &core_init,        /* Call core_init once connected */
3343                                      &core_connect,     /* Handle connects */
3344                                      &core_disconnect,  /* remove peers on disconnects */
3345                                      NULL,      /* Do we care about "status" updates? */
3346                                      NULL,      /* Don't notify about all incoming messages */
3347                                      GNUNET_NO, /* For header only in notification */
3348                                      NULL,      /* Don't notify about all outbound messages */
3349                                      GNUNET_NO, /* For header-only out notification */
3350                                      core_handlers);    /* Register these handlers */
3351   if (core_handle == NULL)
3352   {
3353     GNUNET_break (0);
3354   }
3355   dht_handle = GNUNET_DHT_connect (c, 64);
3356   if (dht_handle == NULL)
3357   {
3358     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Error connecting to DHT.\
3359                    Running without DHT has a severe\
3360                    impact in MESH capabilities.\n\
3361                    Plase check your configuretion and enable DHT.\n");
3362     GNUNET_break (0);
3363   }
3364
3365   next_tid = 0;
3366
3367   tunnels = GNUNET_CONTAINER_multihashmap_create (32);
3368   peers = GNUNET_CONTAINER_multihashmap_create (32);
3369   applications = GNUNET_CONTAINER_multihashmap_create (32);
3370   types = GNUNET_CONTAINER_multihashmap_create (32);
3371   nc = GNUNET_SERVER_notification_context_create (server_handle,
3372                                                   LOCAL_QUEUE_SIZE);
3373   clients = NULL;
3374   clients_tail = NULL;
3375
3376   announce_applications_task = GNUNET_SCHEDULER_NO_TASK;
3377
3378   /* Scheduled the task to clean up when shutdown is called */
3379   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
3380                                 NULL);
3381
3382   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: end of run()\n");
3383 }
3384
3385 /**
3386  * The main function for the mesh service.
3387  *
3388  * @param argc number of arguments from the command line
3389  * @param argv command line arguments
3390  * @return 0 ok, 1 on error
3391  */
3392 int
3393 main (int argc, char *const *argv)
3394 {
3395   int ret;
3396
3397   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: main()\n");
3398   ret =
3399       (GNUNET_OK ==
3400        GNUNET_SERVICE_run (argc, argv, "mesh", GNUNET_SERVICE_OPTION_NONE, &run,
3401                            NULL)) ? 0 : 1;
3402   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: main() END\n");
3403   return ret;
3404 }