- Change hash to speed up 16/32 bit lookups
[oweals/gnunet.git] / src / mesh / gnunet-service-mesh-new.c
1 /*
2      This file is part of GNUnet.
3      (C) 2001-2013 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 ping message
41  * - relay corking down to core
42  * - set ttl relative to tree depth
43  * - Add data ACK count in path ACK
44  * - Make common GNUNET_MESH_Data header for unicast, to_orig, multicast
45  * TODO END
46  */
47
48 #include "platform.h"
49 #include "mesh2.h"
50 #include "mesh2_protocol.h"
51 #include "mesh_tunnel_tree.h"
52 #include "block_mesh.h"
53 #include "gnunet_dht_service.h"
54 #include "gnunet_statistics_service.h"
55
56 #define MESH_BLOOM_SIZE         128
57
58 #define MESH_DEBUG_DHT          GNUNET_NO
59 #define MESH_DEBUG_CONNECTION   GNUNET_NO
60 #define MESH_DEBUG_TIMING       __LINUX__ && GNUNET_NO
61
62 #define MESH_MAX_POLL_TIME      GNUNET_TIME_relative_multiply (\
63                                   GNUNET_TIME_UNIT_MINUTES,\
64                                   10)
65
66 #if MESH_DEBUG_CONNECTION
67 #define DEBUG_CONN(...) GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, __VA_ARGS__)
68 #else
69 #define DEBUG_CONN(...)
70 #endif
71
72 #if MESH_DEBUG_DHT
73 #define DEBUG_DHT(...) GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, __VA_ARGS__)
74 #else
75 #define DEBUG_DHT(...)
76 #endif
77
78 #if MESH_DEBUG_TIMING
79 #include <time.h>
80 double __sum;
81 uint64_t __count;
82 struct timespec __mesh_start;
83 struct timespec __mesh_end;
84 #define INTERVAL_START clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &(__mesh_start))
85 #define INTERVAL_END \
86 do {\
87   clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &(__mesh_end));\
88   double __diff = __mesh_end.tv_nsec - __mesh_start.tv_nsec;\
89   if (__diff < 0) __diff += 1000000000;\
90   __sum += __diff;\
91   __count++;\
92 } while (0)
93 #define INTERVAL_SHOW \
94 if (0 < __count)\
95   GNUNET_log (GNUNET_ERROR_TYPE_INFO, "AVG process time: %f ns\n", __sum/__count)
96 #else
97 #define INTERVAL_START
98 #define INTERVAL_END
99 #define INTERVAL_SHOW
100 #endif
101
102 /******************************************************************************/
103 /************************      DATA STRUCTURES     ****************************/
104 /******************************************************************************/
105
106 /** FWD declaration */
107 struct MeshPeerInfo;
108 struct MeshClient;
109
110
111 /**
112  * Struct containing info about a queued transmission to this peer
113  */
114 struct MeshPeerQueue
115 {
116     /**
117       * DLL next
118       */
119   struct MeshPeerQueue *next;
120
121     /**
122       * DLL previous
123       */
124   struct MeshPeerQueue *prev;
125
126     /**
127      * Peer this transmission is directed to.
128      */
129   struct MeshPeerInfo *peer;
130
131     /**
132      * Tunnel this message belongs to.
133      */
134   struct MeshTunnel *tunnel;
135
136     /**
137      * Pointer to info stucture used as cls.
138      */
139   void *cls;
140
141     /**
142      * Type of message
143      */
144   uint16_t type;
145
146     /**
147      * Size of the message
148      */
149   size_t size;
150 };
151
152
153 /**
154  * Struct containing all info possibly needed to build a package when called
155  * back by core.
156  */
157 struct MeshTransmissionDescriptor
158 {
159     /** ID of the tunnel this packet travels in */
160   struct MESH_TunnelID *origin;
161
162     /** Who was this message being sent to */
163   struct MeshPeerInfo *peer;
164
165     /** Ultimate destination of the packet */
166   GNUNET_PEER_Id destination;
167
168   /** Tunnel it belongs to. */
169   struct MeshTunnel *t;
170   
171   /** Size of the data. */
172   size_t data_len;
173   
174   /** Data itself */
175   void *data;
176 };
177
178
179 /**
180  * Struct containing all information regarding a given peer
181  */
182 struct MeshPeerInfo
183 {
184     /**
185      * ID of the peer
186      */
187   GNUNET_PEER_Id id;
188
189     /**
190      * Last time we heard from this peer
191      */
192   struct GNUNET_TIME_Absolute last_contact;
193
194     /**
195      * Number of attempts to reconnect so far
196      */
197   int n_reconnect_attempts;
198
199     /**
200      * Paths to reach the peer, ordered by ascending hop count
201      */
202   struct MeshPeerPath *path_head;
203
204     /**
205      * Paths to reach the peer, ordered by ascending hop count
206      */
207   struct MeshPeerPath *path_tail;
208
209     /**
210      * Handle to stop the DHT search for a path to this peer
211      */
212   struct GNUNET_DHT_GetHandle *dhtget;
213
214     /**
215      * Array of tunnels this peer is the target of.
216      * Most probably a small amount, therefore not a hashmap.
217      * When the path to the peer changes, notify these tunnels to let them
218      * re-adjust their path trees.
219      */
220   struct MeshTunnel **tunnels;
221
222     /**
223      * Number of tunnels this peers participates in
224      */
225   unsigned int ntunnels;
226
227    /**
228     * Transmission queue to core DLL head
229     */
230   struct MeshPeerQueue *queue_head;
231
232    /**
233     * Transmission queue to core DLL tail
234     */
235    struct MeshPeerQueue *queue_tail;
236
237    /**
238     * How many messages are in the queue to this peer.
239     */
240    unsigned int queue_n;
241
242    /**
243     * Handle to for queued transmissions
244     */
245   struct GNUNET_CORE_TransmitHandle *core_transmit;
246 };
247
248
249 /**
250  * Struct to encapsulate all the Flow Control information to a peer in the
251  * context of a tunnel: Same peer in different tunnels will have independent
252  * flow control structures, allowing to choke/free tunnels according to its
253  * own criteria.
254  */
255 struct MeshFlowControl
256 {
257   /**
258    * ID of the last packet sent towards the peer.
259    */
260   uint32_t last_pid_sent;
261
262   /**
263    * ID of the last packet received from the peer.
264    */
265   uint32_t last_pid_recv;
266
267   /**
268    * Last ACK sent to the peer (peer can't send more than this PID).
269    */
270   uint32_t last_ack_sent;
271
272   /**
273    * Last ACK sent towards the origin (for traffic towards leaf node).
274    */
275   uint32_t last_ack_recv;
276
277   /**
278    * How many messages are in the queue towards this peer.
279    */
280   uint32_t queue_n;
281
282   /**
283    * Task to poll the peer in case of a lost ACK causes stall.
284    */
285   GNUNET_SCHEDULER_TaskIdentifier poll_task;
286
287   /**
288    * How frequently to poll for ACKs.
289    */
290   struct GNUNET_TIME_Relative poll_time;
291
292   /**
293    * On which tunnel to poll.
294    * Using an explicit poll_ctx would not help memory wise,
295    * since the allocated context would have to be stored in the
296    * fc struct in order to free it upon cancelling poll_task.
297    */
298   struct MeshTunnel *t;
299 };
300
301
302 /**
303  * Globally unique tunnel identification (owner + number)
304  * DO NOT USE OVER THE NETWORK
305  */
306 struct MESH_TunnelID
307 {
308     /**
309      * Node that owns the tunnel
310      */
311   GNUNET_PEER_Id oid;
312
313     /**
314      * Tunnel number to differentiate all the tunnels owned by the node oid
315      * ( tid < GNUNET_MESH_LOCAL_TUNNEL_ID_CLI )
316      */
317   MESH_TunnelNumber tid;
318 };
319
320
321 /**
322  * Struct containing all information regarding a tunnel
323  * For an intermediate node the improtant info used will be:
324  * - id        Tunnel unique identification
325  * - paths[0]  To know where to send it next
326  * - metainfo: ready, speeds, accounting
327  */
328 struct MeshTunnel
329 {
330     /**
331      * Tunnel ID
332      */
333   struct MESH_TunnelID id;
334
335     /**
336      * Local tunnel number ( >= GNUNET_MESH_LOCAL_TUNNEL_ID_CLI or 0 )
337      */
338   MESH_TunnelNumber local_tid;
339
340     /**
341      * Local tunnel number for local destination clients (incoming number)
342      * ( >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV or 0). All clients share the same
343      * number.
344      */
345   MESH_TunnelNumber local_tid_dest;
346
347     /**
348      * Is the tunnel bufferless (minimum latency)?
349      */
350   int nobuffer;
351
352     /**
353      * Force sending ACK? Flag to allow duplicate ACK on POLL.
354      */
355   int force_ack;
356
357     /**
358      * How many messages do we accept in the forward queue.
359      */
360   unsigned int queue_max;
361
362     /**
363      * Last time the tunnel was used
364      */
365   struct GNUNET_TIME_Absolute timestamp;
366
367     /**
368      * Destination of the tunnel.
369      */
370   GNUNET_PEER_Id dest;
371
372     /**
373      * Next hop in the tunnel.
374      */
375   GNUNET_PEER_Id next_hop;
376
377     /**
378      * Previous hop in the tunnel.
379      */
380   GNUNET_PEER_Id prev_hop;
381
382     /**
383      * Flow control information about @c next_hop.
384      */
385   struct MeshFlowControl next_fc;
386
387   /**
388    * Flow control information about @c prev_hop.
389    */
390   struct MeshFlowControl prev_fc;
391
392     /**
393      * Client owner of the tunnel, if any
394      */
395   struct MeshClient *owner;
396
397     /**
398      * Task to keep the used paths alive at the owner,
399      * time tunnel out on all the other peers.
400      */
401   GNUNET_SCHEDULER_TaskIdentifier maintenance_task;
402
403     /**
404      * Clients that have been informed about and want to stay in the tunnel.
405      */
406   struct MeshClient **clients;
407
408     /**
409      * Flow control info for each client.
410      */
411   struct MeshTunnelClientInfo *clients_fc;
412
413     /**
414      * Number of elements in clients/clients_fc
415      */
416   unsigned int nclients;
417
418     /**
419      * Clients that have been informed but requested to leave the tunnel.
420      */
421   struct MeshClient **ignore;
422
423     /**
424      * Number of elements in clients
425      */
426   unsigned int nignore;
427
428     /**
429      * Path being used for the tunnel.
430      */
431   struct MeshPeerPath *path;
432
433     /**
434      * Flag to signal the destruction of the tunnel.
435      * If this is set GNUNET_YES the tunnel will be destroyed
436      * when the queue is empty.
437      */
438   int destroy;
439
440     /**
441      * Total messages pending for this tunnels, payload or not.
442      */
443   unsigned int pending_messages;
444
445     /**
446      * If the tunnel is empty, destoy it.
447      */
448   GNUNET_SCHEDULER_TaskIdentifier delayed_destroy;
449 };
450
451
452 /**
453  * Info about a leaf client of a tunnel, needed to perform flow control.
454  */
455 struct MeshTunnelClientInfo
456 {
457   /**
458    * PID of the last packet sent to the client (FWD).
459    */
460   uint32_t fwd_pid;
461
462   /**
463    * PID of the last packet received from the client (BCK).
464    */
465   uint32_t bck_pid;
466
467   /**
468    * Maximum PID allowed (FWD ACK received).
469    */
470   uint32_t fwd_ack;
471   
472   /**
473    * Last ACK sent to that child (BCK ACK).
474    */
475   uint32_t bck_ack;
476 };
477
478
479 /**
480  * Struct containing information about a client of the service
481  */
482 struct MeshClient
483 {
484     /**
485      * Linked list next
486      */
487   struct MeshClient *next;
488
489     /**
490      * Linked list prev
491      */
492   struct MeshClient *prev;
493
494     /**
495      * Tunnels that belong to this client, indexed by local id
496      */
497   struct GNUNET_CONTAINER_MultiHashMap *own_tunnels;
498
499    /**
500      * Tunnels this client has accepted, indexed by incoming local id
501      */
502   struct GNUNET_CONTAINER_MultiHashMap *incoming_tunnels;
503
504    /**
505      * Tunnels this client has rejected, indexed by incoming local id
506      */
507   struct GNUNET_CONTAINER_MultiHashMap *ignore_tunnels;
508     /**
509      * Handle to communicate with the client
510      */
511   struct GNUNET_SERVER_Client *handle;
512
513     /**
514      * Messages that this client has declared interest in.
515      * Indexed by a GMC_hash32 (type), contains *Client.
516      */
517   struct GNUNET_CONTAINER_MultiHashMap *types;
518
519     /**
520      * Whether the client is active or shutting down (don't send confirmations
521      * to a client that is shutting down.
522      */
523   int shutting_down;
524
525     /**
526      * ID of the client, mainly for debug messages
527      */
528   unsigned int id;
529
530 };
531
532
533 /******************************************************************************/
534 /************************      DEBUG FUNCTIONS     ****************************/
535 /******************************************************************************/
536
537 #if MESH_DEBUG
538 /**
539  * GNUNET_SCHEDULER_Task for printing a message after some operation is done
540  * @param cls string to print
541  * @param success  GNUNET_OK if the PUT was transmitted,
542  *                GNUNET_NO on timeout,
543  *                GNUNET_SYSERR on disconnect from service
544  *                after the PUT message was transmitted
545  *                (so we don't know if it was received or not)
546  */
547
548 #if 0
549 static void
550 mesh_debug (void *cls, int success)
551 {
552   char *s = cls;
553
554   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "%s (%d)\n", s, success);
555 }
556 #endif
557
558 unsigned int debug_fwd_ack;
559 unsigned int debug_bck_ack;
560
561 #endif
562
563 /******************************************************************************/
564 /***********************      GLOBAL VARIABLES     ****************************/
565 /******************************************************************************/
566
567 /************************** Configuration parameters **************************/
568
569 /**
570  * How often to send tunnel keepalives. Tunnels timeout after 4 missed.
571  */
572 static struct GNUNET_TIME_Relative refresh_path_time;
573
574 /**
575  * How often to PUT own ID in the DHT.
576  */
577 static struct GNUNET_TIME_Relative id_announce_time;
578
579 /**
580  * Maximum time allowed to connect to a peer found by string.
581  */
582 static struct GNUNET_TIME_Relative connect_timeout;
583
584 /**
585  * Default TTL for payload packets.
586  */
587 static unsigned long long default_ttl;
588
589 /**
590  * DHT replication level, see DHT API: GNUNET_DHT_get_start, GNUNET_DHT_put.
591  */
592 static unsigned long long dht_replication_level;
593
594 /**
595  * How many tunnels are we willing to maintain.
596  * Local tunnels are always allowed, even if there are more tunnels than max.
597  */
598 static unsigned long long max_tunnels;
599
600 /**
601  * How many messages *in total* are we willing to queue, divided by number of 
602  * tunnels to get tunnel queue size.
603  */
604 static unsigned long long max_msgs_queue;
605
606 /**
607  * How many peers do we want to remember?
608  */
609 static unsigned long long max_peers;
610
611
612 /*************************** Static global variables **************************/
613
614 /**
615  * Hostkey generation context
616  */
617 static struct GNUNET_CRYPTO_EccKeyGenerationContext *keygen;
618
619 /**
620  * DLL with all the clients, head.
621  */
622 static struct MeshClient *clients_head;
623
624 /**
625  * DLL with all the clients, tail.
626  */
627 static struct MeshClient *clients_tail;
628
629 /**
630  * Tunnels known, indexed by MESH_TunnelID (MeshTunnel).
631  */
632 static struct GNUNET_CONTAINER_MultiHashMap *tunnels;
633
634 /**
635  * Number of tunnels known.
636  */
637 static unsigned long long n_tunnels;
638
639 /**
640  * Tunnels incoming, indexed by MESH_TunnelNumber
641  * (which is greater than GNUNET_MESH_LOCAL_TUNNEL_ID_SERV).
642  */
643 static struct GNUNET_CONTAINER_MultiHashMap *incoming_tunnels;
644
645 /**
646  * Peers known, indexed by PeerIdentity (MeshPeerInfo).
647  */
648 static struct GNUNET_CONTAINER_MultiHashMap *peers;
649
650 /*
651  * Handle to communicate with transport
652  */
653 // static struct GNUNET_TRANSPORT_Handle *transport_handle;
654
655 /**
656  * Handle to communicate with core.
657  */
658 static struct GNUNET_CORE_Handle *core_handle;
659
660 /**
661  * Handle to use DHT.
662  */
663 static struct GNUNET_DHT_Handle *dht_handle;
664
665 /**
666  * Handle to server.
667  */
668 static struct GNUNET_SERVER_Handle *server_handle;
669
670 /**
671  * Handle to the statistics service.
672  */
673 static struct GNUNET_STATISTICS_Handle *stats;
674
675 /**
676  * Notification context, to send messages to local clients.
677  */
678 static struct GNUNET_SERVER_NotificationContext *nc;
679
680 /**
681  * Local peer own ID (memory efficient handle).
682  */
683 static GNUNET_PEER_Id myid;
684
685 /**
686  * Local peer own ID (full value).
687  */
688 static struct GNUNET_PeerIdentity my_full_id;
689
690 /**
691  * Own private key.
692  */
693 static struct GNUNET_CRYPTO_EccPrivateKey *my_private_key;
694
695 /**
696  * Own public key.
697  */
698 static struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded my_public_key;
699
700 /**
701  * Tunnel ID for the next created tunnel (global tunnel number).
702  */
703 static MESH_TunnelNumber next_tid;
704
705 /**
706  * Tunnel ID for the next incoming tunnel (local tunnel number).
707  */
708 static MESH_TunnelNumber next_local_tid;
709
710 /**
711  * All message types clients of this peer are interested in.
712  */
713 static struct GNUNET_CONTAINER_MultiHashMap *types;
714
715 /**
716  * Task to periodically announce itself in the network.
717  */
718 GNUNET_SCHEDULER_TaskIdentifier announce_id_task;
719
720 /**
721  * Next ID to assign to a client.
722  */
723 unsigned int next_client_id;
724
725
726 /******************************************************************************/
727 /***********************         DECLARATIONS        **************************/
728 /******************************************************************************/
729
730 /**
731  * Function to process paths received for a new peer addition. The recorded
732  * paths form the initial tunnel, which can be optimized later.
733  * Called on each result obtained for the DHT search.
734  *
735  * @param cls closure
736  * @param exp when will this value expire
737  * @param key key of the result
738  * @param type type of the result
739  * @param size number of bytes in data
740  * @param data pointer to the result data
741  */
742 static void
743 dht_get_id_handler (void *cls, struct GNUNET_TIME_Absolute exp,
744                     const struct GNUNET_HashCode * key,
745                     const struct GNUNET_PeerIdentity *get_path,
746                     unsigned int get_path_length,
747                     const struct GNUNET_PeerIdentity *put_path,
748                     unsigned int put_path_length, enum GNUNET_BLOCK_Type type,
749                     size_t size, const void *data);
750
751
752 /**
753  * Retrieve the MeshPeerInfo stucture associated with the peer, create one
754  * and insert it in the appropiate structures if the peer is not known yet.
755  *
756  * @param peer Full identity of the peer.
757  *
758  * @return Existing or newly created peer info.
759  */
760 static struct MeshPeerInfo *
761 peer_get (const struct GNUNET_PeerIdentity *peer);
762
763
764 /**
765  * Retrieve the MeshPeerInfo stucture associated with the peer, create one
766  * and insert it in the appropiate structures if the peer is not known yet.
767  *
768  * @param peer Short identity of the peer.
769  *
770  * @return Existing or newly created peer info.
771  */
772 static struct MeshPeerInfo *
773 peer_get_short (const GNUNET_PEER_Id peer);
774
775
776 /**
777  * Build a PeerPath from the paths returned from the DHT, reversing the paths
778  * to obtain a local peer -> destination path and interning the peer ids.
779  *
780  * @return Newly allocated and created path
781  */
782 static struct MeshPeerPath *
783 path_build_from_dht (const struct GNUNET_PeerIdentity *get_path,
784                      unsigned int get_path_length,
785                      const struct GNUNET_PeerIdentity *put_path,
786                      unsigned int put_path_length);
787
788
789 /**
790  * Adds a path to the peer_infos of all the peers in the path
791  *
792  * @param p Path to process.
793  * @param confirmed Whether we know if the path works or not.
794  */
795 static void
796 path_add_to_peers (struct MeshPeerPath *p, int confirmed);
797
798
799
800 /**
801  * Search for a tunnel by global ID using full PeerIdentities.
802  *
803  * @param oid owner of the tunnel.
804  * @param tid global tunnel number.
805  *
806  * @return tunnel handler, NULL if doesn't exist.
807  */
808 static struct MeshTunnel *
809 tunnel_get (const struct GNUNET_PeerIdentity *oid, MESH_TunnelNumber tid);
810
811
812 /**
813  * Delete an active client from the tunnel.
814  *
815  * @param t Tunnel.
816  * @param c Client.
817  */
818 static void
819 tunnel_delete_active_client (struct MeshTunnel *t, const struct MeshClient *c);
820
821 /**
822  * Notify a tunnel that a connection has broken that affects at least
823  * some of its peers.
824  *
825  * @param t Tunnel affected.
826  * @param p1 Peer that got disconnected from p2.
827  * @param p2 Peer that got disconnected from p1.
828  *
829  * @return Short ID of the peer disconnected (either p1 or p2).
830  *         0 if the tunnel remained unaffected.
831  */
832 static GNUNET_PEER_Id
833 tunnel_notify_connection_broken (struct MeshTunnel *t, GNUNET_PEER_Id p1,
834                                  GNUNET_PEER_Id p2);
835
836
837 /**
838  * Get the current ack value for a tunnel, for data going from root to leaves,
839  * taking in account the tunnel mode and the status of all children and clients.
840  *
841  * @param t Tunnel.
842  *
843  * @return Maximum PID allowed.
844  */
845 static uint32_t
846 tunnel_get_fwd_ack (struct MeshTunnel *t);
847
848
849 /**
850  * Add a client to a tunnel, initializing all needed data structures.
851  * 
852  * @param t Tunnel to which add the client.
853  * @param c Client which to add to the tunnel.
854  */
855 static void
856 tunnel_add_client (struct MeshTunnel *t, struct MeshClient *c);
857
858
859 /**
860  * Use the given path for the tunnel.
861  * 
862  * @param t Tunnel to update.
863  * @param p Path to use.
864  */
865 static void
866 tunnel_use_path (struct MeshTunnel *t, struct MeshPeerPath *p);
867
868 /**
869  * @brief Queue and pass message to core when possible.
870  * 
871  * If type is payload (UNICAST, TO_ORIGIN, MULTICAST) checks for queue status
872  * and accounts for it. In case the queue is full, the message is dropped and
873  * a break issued.
874  * 
875  * Otherwise, message is treated as internal and allowed to go regardless of 
876  * queue status.
877  *
878  * @param cls Closure (@c type dependant). It will be used by queue_send to
879  *            build the message to be sent if not already prebuilt.
880  * @param type Type of the message, 0 for a raw message.
881  * @param size Size of the message.
882  * @param dst Neighbor to send message to.
883  * @param t Tunnel this message belongs to.
884  */
885 static void
886 queue_add (void *cls, uint16_t type, size_t size,
887            struct MeshPeerInfo *dst, struct MeshTunnel *t);
888
889
890 /**
891  * Free a transmission that was already queued with all resources
892  * associated to the request.
893  *
894  * @param queue Queue handler to cancel.
895  * @param clear_cls Is it necessary to free associated cls?
896  */
897 static void
898 queue_destroy (struct MeshPeerQueue *queue, int clear_cls);
899
900
901 /**
902  * @brief Get the next transmittable message from the queue.
903  *
904  * This will be the head, except in the case of being a data packet
905  * not allowed by the destination peer.
906  *
907  * @param peer Destination peer.
908  *
909  * @return The next viable MeshPeerQueue element to send to that peer.
910  *         NULL when there are no transmittable messages.
911  */
912 struct MeshPeerQueue *
913 queue_get_next (const struct MeshPeerInfo *peer);
914
915
916 /**
917  * Core callback to write a queued packet to core buffer
918  *
919  * @param cls Closure (peer info).
920  * @param size Number of bytes available in buf.
921  * @param buf Where the to write the message.
922  *
923  * @return number of bytes written to buf
924  */
925 static size_t
926 queue_send (void *cls, size_t size, void *buf);
927
928
929 /******************************************************************************/
930 /************************    PERIODIC FUNCTIONS    ****************************/
931 /******************************************************************************/
932
933 /**
934  * Periodically announce self id in the DHT
935  *
936  * @param cls closure
937  * @param tc task context
938  */
939 static void
940 announce_id (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
941 {
942   struct PBlock block;
943
944   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
945   {
946     announce_id_task = GNUNET_SCHEDULER_NO_TASK;
947     return;
948   }
949   /* TODO
950    * - Set data expiration in function of X
951    * - Adapt X to churn
952    */
953   DEBUG_DHT ("DHT_put for ID %s started.\n", GNUNET_i2s (&my_full_id));
954
955   block.id = my_full_id;
956   block.type = htonl (0);
957   GNUNET_DHT_put (dht_handle,   /* DHT handle */
958                   &my_full_id.hashPubKey,       /* Key to use */
959                   dht_replication_level,     /* Replication level */
960                   GNUNET_DHT_RO_RECORD_ROUTE | GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE,    /* DHT options */
961                   GNUNET_BLOCK_TYPE_MESH_PEER,       /* Block type */
962                   sizeof (block),  /* Size of the data */
963                   (const char *) &block, /* Data itself */
964                   GNUNET_TIME_UNIT_FOREVER_ABS,  /* Data expiration */
965                   GNUNET_TIME_UNIT_FOREVER_REL, /* Retry time */
966                   NULL,         /* Continuation */
967                   NULL);        /* Continuation closure */
968   announce_id_task =
969       GNUNET_SCHEDULER_add_delayed (id_announce_time, &announce_id, cls);
970 }
971
972
973 /******************************************************************************/
974 /******************      GENERAL HELPER FUNCTIONS      ************************/
975 /******************************************************************************/
976
977
978 /**
979  * Check if client has registered with the service and has not disconnected
980  *
981  * @param client the client to check
982  *
983  * @return non-NULL if client exists in the global DLL
984  */
985 static struct MeshClient *
986 client_get (struct GNUNET_SERVER_Client *client)
987 {
988   struct MeshClient *c;
989
990   c = clients_head;
991   while (NULL != c)
992   {
993     if (c->handle == client)
994       return c;
995     c = c->next;
996   }
997   return NULL;
998 }
999
1000
1001 /**
1002  * Checks if a given client has subscribed to certain message type
1003  *
1004  * @param message_type Type of message to check
1005  * @param c Client to check
1006  *
1007  * @return GNUNET_YES or GNUNET_NO, depending on subscription status
1008  * 
1009  *  A real hash function alone takes 8-10us out of the ~55us for the whole
1010  * process of retransmitting the message from one local client to another.
1011  * GMC_hash32 aim to imporve this speed.
1012  */
1013 static int
1014 client_is_subscribed (uint16_t message_type, struct MeshClient *c)
1015 {
1016   struct GNUNET_HashCode hc;
1017
1018   if (NULL == c->types)
1019     return GNUNET_NO;
1020
1021   GMC_hash32 ((uint32_t) message_type, &hc);
1022   return GNUNET_CONTAINER_multihashmap_contains (c->types, &hc);
1023 }
1024
1025
1026 /**
1027  * Check whether client wants traffic from a tunnel.
1028  *
1029  * @param c Client to check.
1030  * @param t Tunnel to be found.
1031  *
1032  * @return GNUNET_YES if client knows tunnel.
1033  * 
1034  * TODO look in client hashmap
1035  */
1036 static int
1037 client_wants_tunnel (struct MeshClient *c, struct MeshTunnel *t)
1038 {
1039   unsigned int i;
1040
1041   for (i = 0; i < t->nclients; i++)
1042     if (t->clients[i] == c)
1043       return GNUNET_YES;
1044   return GNUNET_NO;
1045 }
1046
1047
1048 /**
1049  * Check whether client has been informed about a tunnel.
1050  *
1051  * @param c Client to check.
1052  * @param t Tunnel to be found.
1053  *
1054  * @return GNUNET_YES if client knows tunnel.
1055  * 
1056  * TODO look in client hashmap
1057  */
1058 static int
1059 client_knows_tunnel (struct MeshClient *c, struct MeshTunnel *t)
1060 {
1061   unsigned int i;
1062
1063   for (i = 0; i < t->nignore; i++)
1064     if (t->ignore[i] == c)
1065       return GNUNET_YES;
1066   return client_wants_tunnel(c, t);
1067 }
1068
1069
1070 /**
1071  * Marks a client as uninterested in traffic from the tunnel, updating both
1072  * client and tunnel to reflect this.
1073  *
1074  * @param c Client that doesn't want traffic anymore.
1075  * @param t Tunnel which should be ignored.
1076  *
1077  * FIXME when to delete an incoming tunnel?
1078  */
1079 static void
1080 client_ignore_tunnel (struct MeshClient *c, struct MeshTunnel *t)
1081 {
1082   struct GNUNET_HashCode hash;
1083
1084   GNUNET_CRYPTO_hash (&t->local_tid_dest, sizeof (MESH_TunnelNumber), &hash);
1085   GNUNET_break (GNUNET_YES ==
1086                 GNUNET_CONTAINER_multihashmap_remove (c->incoming_tunnels,
1087                                                       &hash, t));
1088   GNUNET_break (GNUNET_YES ==
1089                 GNUNET_CONTAINER_multihashmap_put (c->ignore_tunnels, &hash, t,
1090                                                    GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST));
1091   tunnel_delete_active_client (t, c);
1092   GNUNET_array_append (t->ignore, t->nignore, c);
1093 }
1094
1095
1096 /**
1097  * Deletes a tunnel from a client (either owner or destination). To be used on
1098  * tunnel destroy, otherwise, use client_ignore_tunnel.
1099  *
1100  * @param c Client whose tunnel to delete.
1101  * @param t Tunnel which should be deleted.
1102  */
1103 static void
1104 client_delete_tunnel (struct MeshClient *c, struct MeshTunnel *t)
1105 {
1106   struct GNUNET_HashCode hash;
1107
1108   if (c == t->owner)
1109   {
1110     GNUNET_CRYPTO_hash(&t->local_tid, sizeof (MESH_TunnelNumber), &hash);
1111     GNUNET_assert (GNUNET_YES ==
1112                    GNUNET_CONTAINER_multihashmap_remove (c->own_tunnels,
1113                                                          &hash,
1114                                                          t));
1115   }
1116   else
1117   {
1118     GNUNET_CRYPTO_hash(&t->local_tid_dest, sizeof (MESH_TunnelNumber), &hash);
1119     // FIXME XOR?
1120     GNUNET_assert (GNUNET_YES ==
1121                    GNUNET_CONTAINER_multihashmap_remove (c->incoming_tunnels,
1122                                                          &hash,
1123                                                          t) ||
1124                    GNUNET_YES ==
1125                    GNUNET_CONTAINER_multihashmap_remove (c->ignore_tunnels,
1126                                                          &hash,
1127                                                          t));
1128   }
1129 }
1130
1131
1132 /**
1133  * Send the message to all clients that have subscribed to its type
1134  *
1135  * @param msg Pointer to the message itself
1136  * @param payload Pointer to the payload of the message.
1137  * @param t The tunnel to whose clients this message goes.
1138  * 
1139  * @return number of clients this message was sent to
1140  */
1141 static unsigned int
1142 send_subscribed_clients (const struct GNUNET_MessageHeader *msg,
1143                          const struct GNUNET_MessageHeader *payload,
1144                          struct MeshTunnel *t)
1145 {
1146   struct MeshClient *c;
1147   MESH_TunnelNumber *tid;
1148   unsigned int count;
1149   uint16_t type;
1150   char cbuf[htons (msg->size)];
1151
1152   type = ntohs (payload->type);
1153   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending to clients...\n");
1154   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "message of type %s\n",
1155               GNUNET_MESH_DEBUG_M2S (type));
1156
1157   memcpy (cbuf, msg, sizeof (cbuf));
1158   switch (htons (msg->type))
1159   {
1160     struct GNUNET_MESH_Unicast *uc;
1161     struct GNUNET_MESH_ToOrigin *to;
1162
1163     case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
1164       uc = (struct GNUNET_MESH_Unicast *) cbuf;
1165       tid = &uc->tid;
1166       break;
1167     case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
1168       to = (struct GNUNET_MESH_ToOrigin *) cbuf;
1169       tid = &to->tid;
1170       break;
1171     default:
1172       GNUNET_break (0);
1173       return 0;
1174   }
1175
1176   for (count = 0, c = clients_head; c != NULL; c = c->next)
1177   {
1178     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   client %u\n", c->id);
1179     if (client_is_subscribed (type, c))
1180     {
1181       if (htons (msg->type) == GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN)
1182       {
1183         if (c != t->owner)
1184           continue;
1185         *tid = htonl (t->local_tid);
1186       }
1187       else
1188       {
1189         if (GNUNET_NO == client_knows_tunnel (c, t))
1190         {
1191           /* This client doesn't know the tunnel */
1192           struct GNUNET_MESH_TunnelNotification tmsg;
1193           struct GNUNET_HashCode hash;
1194
1195           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "     sending tunnel create\n");
1196           tmsg.header.size = htons (sizeof (tmsg));
1197           tmsg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_CREATE);
1198           GNUNET_PEER_resolve (t->id.oid, &tmsg.peer);
1199           tmsg.tunnel_id = htonl (t->local_tid_dest);
1200           tmsg.opt = 0;
1201           if (GNUNET_YES == t->nobuffer)
1202             tmsg.opt |= MESH_TUNNEL_OPT_NOBUFFER;
1203           GNUNET_SERVER_notification_context_unicast (nc, c->handle,
1204                                                       &tmsg.header, GNUNET_NO);
1205           tunnel_add_client (t, c);
1206           GNUNET_CRYPTO_hash (&t->local_tid_dest, sizeof (MESH_TunnelNumber),
1207                               &hash);
1208           GNUNET_break (GNUNET_OK == GNUNET_CONTAINER_multihashmap_put (
1209                                        c->incoming_tunnels, &hash, t,
1210                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST));
1211         }
1212         *tid = htonl (t->local_tid_dest);
1213       }
1214
1215       /* Check if the client wants to get traffic from the tunnel */
1216       if (GNUNET_NO == client_wants_tunnel(c, t))
1217         continue;
1218       count++;
1219       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "     sending\n");
1220       GNUNET_SERVER_notification_context_unicast (nc, c->handle,
1221                                                   (struct GNUNET_MessageHeader
1222                                                    *) cbuf, GNUNET_NO);
1223     }
1224   }
1225
1226   return count;
1227 }
1228
1229
1230 /**
1231  * Notify all clients (not depending on registration status) that the incoming
1232  * tunnel is no longer valid.
1233  *
1234  * @param t Tunnel that was destroyed.
1235  */
1236 static void
1237 send_clients_tunnel_destroy (struct MeshTunnel *t)
1238 {
1239   struct GNUNET_MESH_TunnelMessage msg;
1240
1241   msg.header.size = htons (sizeof (msg));
1242   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_DESTROY);
1243   msg.tunnel_id = htonl (t->local_tid_dest);
1244   GNUNET_SERVER_notification_context_broadcast (nc, &msg.header, GNUNET_NO);
1245 }
1246
1247
1248 /**
1249  * Notify clients of tunnel disconnections, if needed.
1250  * In case the origin disconnects, the destination clients get a tunnel destroy
1251  * notification. If the last destination disconnects (only one remaining client
1252  * in tunnel), the origin gets a (local ID) peer disconnected.
1253  * Note that the function must be called BEFORE removing the client from
1254  * the tunnel.
1255  *
1256  * @param t Tunnel that was destroyed.
1257  * @param c Client that disconnected.
1258  */
1259 static void
1260 send_client_tunnel_disconnect (struct MeshTunnel *t, struct MeshClient *c)
1261 {
1262   unsigned int i;
1263
1264   if (c == t->owner)
1265   {
1266     struct GNUNET_MESH_TunnelMessage msg;
1267
1268     msg.header.size = htons (sizeof (msg));
1269     msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_DESTROY);
1270     msg.tunnel_id = htonl (t->local_tid_dest);
1271     for (i = 0; i < t->nclients; i++)
1272       GNUNET_SERVER_notification_context_unicast (nc, t->clients[i]->handle,
1273                                                   &msg.header, GNUNET_NO);
1274   }
1275   // FIXME when to disconnect an incoming tunnel?
1276 }
1277
1278
1279 /**
1280  * Iterator over all the peers to remove the oldest not-used entry.
1281  *
1282  * @param cls Closure (unsued).
1283  * @param key ID of the peer.
1284  * @param value Peer_Info of the peer.
1285  *
1286  * FIXME implement
1287  */
1288 static int
1289 peer_info_timeout (void *cls,
1290                    const struct GNUNET_HashCode *key,
1291                    void *value)
1292 {
1293   return GNUNET_YES;
1294 }
1295
1296 /**
1297  * Retrieve the MeshPeerInfo stucture associated with the peer, create one
1298  * and insert it in the appropiate structures if the peer is not known yet.
1299  *
1300  * @param peer Full identity of the peer.
1301  *
1302  * @return Existing or newly created peer info.
1303  */
1304 static struct MeshPeerInfo *
1305 peer_get (const struct GNUNET_PeerIdentity *peer)
1306 {
1307   struct MeshPeerInfo *peer_info;
1308
1309   peer_info = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
1310   if (NULL == peer_info)
1311   {
1312     peer_info =
1313         (struct MeshPeerInfo *) GNUNET_malloc (sizeof (struct MeshPeerInfo));
1314     if (GNUNET_CONTAINER_multihashmap_size (peers) > max_peers)
1315     {
1316       GNUNET_CONTAINER_multihashmap_iterate (peers,
1317                                              &peer_info_timeout,
1318                                              NULL);
1319     }
1320     GNUNET_CONTAINER_multihashmap_put (peers, &peer->hashPubKey, peer_info,
1321                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
1322     peer_info->id = GNUNET_PEER_intern (peer);
1323   }
1324   peer_info->last_contact = GNUNET_TIME_absolute_get();
1325
1326   return peer_info;
1327 }
1328
1329
1330 /**
1331  * Retrieve the MeshPeerInfo stucture associated with the peer, create one
1332  * and insert it in the appropiate structures if the peer is not known yet.
1333  *
1334  * @param peer Short identity of the peer.
1335  *
1336  * @return Existing or newly created peer info.
1337  */
1338 static struct MeshPeerInfo *
1339 peer_get_short (const GNUNET_PEER_Id peer)
1340 {
1341   struct GNUNET_PeerIdentity id;
1342
1343   GNUNET_PEER_resolve (peer, &id);
1344   return peer_get (&id);
1345 }
1346
1347
1348 /**
1349  * Choose the best path towards a peer considering the tunnel properties.
1350  * 
1351  * @param peer The destination peer.
1352  * @param t The tunnel the path is for.
1353  *
1354  * @return Best current known path towards the peer, if any.
1355  */
1356 static struct MeshPeerPath *
1357 peer_get_best_path (const struct MeshPeerInfo *peer, const struct MeshTunnel *t)
1358 {
1359   struct MeshPeerPath *best_p;
1360   struct MeshPeerPath *p;
1361   unsigned int best_cost;
1362   unsigned int cost;
1363
1364   best_p = p = peer->path_head;
1365   best_cost = cost = p->length;
1366   while (NULL != p)
1367   {
1368     if ((cost = p->length) < best_cost)
1369     {
1370       best_cost = cost;
1371       best_p = p;
1372     }
1373         p = p->next;
1374   }
1375   return best_p;
1376 }
1377
1378
1379 /**
1380  * Remove the tunnel from the list of tunnels to which a peer is target.
1381  *
1382  * @param peer PeerInfo of the peer.
1383  * @param t Tunnel to remove.
1384  */
1385 static void
1386 peer_remove_tunnel (struct MeshPeerInfo *peer, struct MeshTunnel *t)
1387 {
1388   unsigned int i;
1389
1390   for (i = 0; i < peer->ntunnels; i++)
1391   {
1392     if (0 ==
1393         memcmp (&peer->tunnels[i]->id, &t->id, sizeof (struct MESH_TunnelID)))
1394     {
1395       peer->ntunnels--;
1396       peer->tunnels[i] = peer->tunnels[peer->ntunnels];
1397       peer->tunnels = 
1398         GNUNET_realloc (peer->tunnels, 
1399                         peer->ntunnels * sizeof(struct MeshTunnel *));
1400       return;
1401     }
1402   }
1403 }
1404
1405
1406 /**
1407   * Core callback to write a pre-constructed data packet to core buffer
1408   *
1409   * @param cls Closure (MeshTransmissionDescriptor with data in "data" member).
1410   * @param size Number of bytes available in buf.
1411   * @param buf Where the to write the message.
1412   *
1413   * @return number of bytes written to buf
1414   */
1415 static size_t
1416 send_core_data_raw (void *cls, size_t size, void *buf)
1417 {
1418   struct MeshTransmissionDescriptor *info = cls;
1419   struct GNUNET_MessageHeader *msg;
1420   size_t total_size;
1421
1422   GNUNET_assert (NULL != info);
1423   msg = (struct GNUNET_MessageHeader *) info->data;
1424   total_size = ntohs (msg->size);
1425
1426   if (total_size > size)
1427   {
1428     GNUNET_break (0);
1429     return 0;
1430   }
1431   memcpy (buf, msg, total_size);
1432   GNUNET_free (info->data);
1433   GNUNET_free (info);
1434   return total_size;
1435 }
1436
1437
1438 /**
1439  * Sends an already built message to a peer, properly registrating
1440  * all used resources.
1441  *
1442  * @param message Message to send. Function makes a copy of it.
1443  * @param peer Short ID of the neighbor whom to send the message.
1444  * @param t Tunnel on which this message is transmitted.
1445  */
1446 static void
1447 send_prebuilt_message (const struct GNUNET_MessageHeader *message,
1448                        GNUNET_PEER_Id peer,
1449                        struct MeshTunnel *t)
1450 {
1451   struct MeshTransmissionDescriptor *info;
1452   struct GNUNET_PeerIdentity id;
1453   struct MeshPeerInfo *neighbor;
1454   struct MeshPeerPath *p;
1455   size_t size;
1456   uint16_t type;
1457
1458 //   GNUNET_TRANSPORT_try_connect(); FIXME use?
1459
1460   if (0 == peer)
1461     return;
1462
1463   size = ntohs (message->size);
1464   info = GNUNET_malloc (sizeof (struct MeshTransmissionDescriptor));
1465   info->data = GNUNET_malloc (size);
1466   memcpy (info->data, message, size);
1467   type = ntohs(message->type);
1468   switch (type)
1469   {
1470     struct GNUNET_MESH_Unicast *m;
1471     struct GNUNET_MESH_ToOrigin *to;
1472
1473     case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
1474       m = (struct GNUNET_MESH_Unicast *) info->data;
1475       m->ttl = htonl (ntohl (m->ttl) - 1);
1476       break;
1477     case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
1478       to = (struct GNUNET_MESH_ToOrigin *) info->data;
1479       t->prev_fc.last_pid_sent++; /* FIXME per hop? */
1480       to->pid = htonl (t->prev_fc.last_pid_sent);
1481   }
1482   info->data_len = size;
1483   GNUNET_PEER_resolve (peer, &id);
1484   neighbor = peer_get (&id);
1485   for (p = neighbor->path_head; NULL != p; p = p->next)
1486   {
1487     if (2 >= p->length)
1488     {
1489       break;
1490     }
1491   }
1492   if (NULL == p)
1493   {
1494 #if MESH_DEBUG
1495     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1496                 "  %s IS NOT DIRECTLY CONNECTED\n",
1497                 GNUNET_i2s(&id));
1498     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1499                 "  PATHS TO %s:\n",
1500                 GNUNET_i2s(&id));
1501     for (p = neighbor->path_head; NULL != p; p = p->next)
1502     {
1503       struct GNUNET_PeerIdentity debug_id;
1504       unsigned int i;
1505
1506       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1507                   "    path with %u hops through:\n",
1508                   p->length);
1509       for (i = 0; i < p->length; i++)
1510       {
1511         GNUNET_PEER_resolve(p->peers[i], &debug_id);
1512         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1513                     "      hop %u: %s\n",
1514                     i, GNUNET_i2s(&debug_id));
1515       }
1516     }
1517 #endif
1518     GNUNET_break (0); // FIXME sometimes fails (testing disconnect?)
1519     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1520                     " no direct connection to %s\n",
1521                     GNUNET_i2s (&id));
1522     GNUNET_free (info->data);
1523     GNUNET_free (info);
1524     return;
1525   }
1526   info->peer = neighbor;
1527   if (GNUNET_MESSAGE_TYPE_MESH_PATH_ACK == type)
1528     type = 0;
1529   queue_add (info,
1530              type,
1531              size,
1532              neighbor,
1533              t);
1534 }
1535
1536
1537 /**
1538  * Sends a CREATE PATH message for a path to a peer, properly registrating
1539  * all used resources.
1540  *
1541  * @param peer PeerInfo of the final peer for whom this path is being created.
1542  * @param p Path itself.
1543  * @param t Tunnel for which the path is created.
1544  */
1545 static void
1546 send_create_path (struct MeshPeerInfo *peer, struct MeshPeerPath *p,
1547                   struct MeshTunnel *t)
1548 {
1549   struct MeshPeerInfo *neighbor;
1550
1551   if (NULL == p)
1552   {
1553     GNUNET_break (0);
1554     return;
1555   }
1556
1557   neighbor = peer_get_short (t->next_hop);
1558   queue_add (t,
1559              GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE,
1560              sizeof (struct GNUNET_MESH_ManipulatePath) +
1561                 (p->length * sizeof (struct GNUNET_PeerIdentity)),
1562              neighbor,
1563              t);
1564 }
1565
1566
1567 /**
1568  * Sends a PATH ACK message in reponse to a received PATH_CREATE directed to us.
1569  *
1570  * @param t Tunnel which to confirm.
1571  */
1572 static void
1573 send_path_ack (struct MeshTunnel *t) 
1574 {
1575   struct MeshTransmissionDescriptor *info;
1576   struct GNUNET_PeerIdentity id;
1577
1578   GNUNET_PEER_resolve (t->prev_hop, &id);
1579   info = GNUNET_malloc (sizeof (struct MeshTransmissionDescriptor));
1580   info->origin = &t->id;
1581   info->peer = GNUNET_CONTAINER_multihashmap_get (peers, &id.hashPubKey);
1582   GNUNET_assert (NULL != info->peer);
1583
1584   queue_add (info,
1585              GNUNET_MESSAGE_TYPE_MESH_PATH_ACK,
1586              sizeof (struct GNUNET_MESH_PathACK),
1587              info->peer,
1588              t);
1589 }
1590
1591
1592 /**
1593  * Try to establish a new connection to this peer in the fiven tunnel.
1594  * If the peer doesn't have any path to it yet, try to get one.
1595  * If the peer already has some path, send a CREATE PATH towards it.
1596  *
1597  * @param peer PeerInfo of the peer.
1598  * @param t Tunnel for which to create the path, if possible.
1599  */
1600 static void
1601 peer_connect (struct MeshPeerInfo *peer, struct MeshTunnel *t)
1602 {
1603   struct MeshPeerPath *p;
1604
1605   if (NULL != peer->path_head)
1606   {
1607     p = peer_get_best_path (peer, t);
1608     tunnel_use_path (t, p);
1609     send_create_path (peer, p, t);
1610   }
1611   else if (NULL == peer->dhtget)
1612   {
1613     struct GNUNET_PeerIdentity id;
1614
1615     GNUNET_PEER_resolve (peer->id, &id);
1616     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1617                 "  Starting DHT GET for peer %s\n", GNUNET_i2s (&id));
1618     peer->dhtget = GNUNET_DHT_get_start (dht_handle,    /* handle */
1619                                          GNUNET_BLOCK_TYPE_MESH_PEER, /* type */
1620                                          &id.hashPubKey,     /* key to search */
1621                                          dht_replication_level, /* replication level */
1622                                          GNUNET_DHT_RO_RECORD_ROUTE |
1623                                          GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE,
1624                                          NULL,       /* xquery */
1625                                          0,     /* xquery bits */
1626                                          &dht_get_id_handler, peer);
1627   }
1628   /* Otherwise, there is no path but the DHT get is already started. */
1629 }
1630
1631
1632 /**
1633  * Destroy the peer_info and free any allocated resources linked to it
1634  *
1635  * @param pi The peer_info to destroy.
1636  *
1637  * @return GNUNET_OK on success
1638  */
1639 static int
1640 peer_info_destroy (struct MeshPeerInfo *pi)
1641 {
1642   struct GNUNET_PeerIdentity id;
1643   struct MeshPeerPath *p;
1644   struct MeshPeerPath *nextp;
1645
1646   GNUNET_PEER_resolve (pi->id, &id);
1647   GNUNET_PEER_change_rc (pi->id, -1);
1648
1649   if (GNUNET_YES !=
1650       GNUNET_CONTAINER_multihashmap_remove (peers, &id.hashPubKey, pi))
1651   {
1652     GNUNET_break (0);
1653     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1654                 "removing peer %s, not in hashmap\n", GNUNET_i2s (&id));
1655   }
1656   if (NULL != pi->dhtget)
1657   {
1658     GNUNET_DHT_get_stop (pi->dhtget);
1659   }
1660   p = pi->path_head;
1661   while (NULL != p)
1662   {
1663     nextp = p->next;
1664     GNUNET_CONTAINER_DLL_remove (pi->path_head, pi->path_tail, p);
1665     path_destroy (p);
1666     p = nextp;
1667   }
1668   GNUNET_free (pi);
1669   return GNUNET_OK;
1670 }
1671
1672
1673 /**
1674  * Remove all paths that rely on a direct connection between p1 and p2
1675  * from the peer itself and notify all tunnels about it.
1676  *
1677  * @param peer PeerInfo of affected peer.
1678  * @param p1 GNUNET_PEER_Id of one peer.
1679  * @param p2 GNUNET_PEER_Id of another peer that was connected to the first and
1680  *           no longer is.
1681  *
1682  * TODO: optimize (see below)
1683  */
1684 static void
1685 peer_remove_path (struct MeshPeerInfo *peer, GNUNET_PEER_Id p1,
1686                        GNUNET_PEER_Id p2)
1687 {
1688   struct MeshPeerPath *p;
1689   struct MeshPeerPath *next;
1690   struct MeshPeerInfo *peer_d;
1691   GNUNET_PEER_Id d;
1692   unsigned int destroyed;
1693   unsigned int i;
1694
1695   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "peer_info_remove_path\n");
1696   destroyed = 0;
1697   for (p = peer->path_head; NULL != p; p = next)
1698   {
1699     next = p->next;
1700     for (i = 0; i < (p->length - 1); i++)
1701     {
1702       if ((p->peers[i] == p1 && p->peers[i + 1] == p2) ||
1703           (p->peers[i] == p2 && p->peers[i + 1] == p1))
1704       {
1705         GNUNET_CONTAINER_DLL_remove (peer->path_head, peer->path_tail, p);
1706         path_destroy (p);
1707         destroyed++;
1708         break;
1709       }
1710     }
1711   }
1712   if (0 == destroyed)
1713     return;
1714
1715   for (i = 0; i < peer->ntunnels; i++)
1716   {
1717     d = tunnel_notify_connection_broken (peer->tunnels[i], p1, p2);
1718     if (0 == d)
1719       continue;
1720
1721     peer_d = peer_get_short (d);
1722     next = peer_get_best_path (peer_d, peer->tunnels[i]);
1723     tunnel_use_path (peer->tunnels[i], next);
1724     peer_connect (peer_d, peer->tunnels[i]);
1725   }
1726   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "peer_info_remove_path END\n");
1727 }
1728
1729
1730 /**
1731  * Add the path to the peer and update the path used to reach it in case this
1732  * is the shortest.
1733  *
1734  * @param peer_info Destination peer to add the path to.
1735  * @param path New path to add. Last peer must be the peer in arg 1.
1736  *             Path will be either used of freed if already known.
1737  * @param trusted Do we trust that this path is real?
1738  */
1739 void
1740 peer_info_add_path (struct MeshPeerInfo *peer_info, struct MeshPeerPath *path,
1741                     int trusted)
1742 {
1743   struct MeshPeerPath *aux;
1744   unsigned int l;
1745   unsigned int l2;
1746
1747   if ((NULL == peer_info) || (NULL == path))
1748   {
1749     GNUNET_break (0);
1750     path_destroy (path);
1751     return;
1752   }
1753   if (path->peers[path->length - 1] != peer_info->id)
1754   {
1755     GNUNET_break (0);
1756     path_destroy (path);
1757     return;
1758   }
1759   if (path->length <= 2 && GNUNET_NO == trusted)
1760   {
1761     /* Only allow CORE to tell us about direct paths */
1762     path_destroy (path);
1763     return;
1764   }
1765   GNUNET_assert (peer_info->id == path->peers[path->length - 1]);
1766   for (l = 1; l < path->length; l++)
1767   {
1768     if (path->peers[l] == myid)
1769     {
1770       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shortening path by %u\n", l);
1771       for (l2 = 0; l2 < path->length - l; l2++)
1772       {
1773         path->peers[l2] = path->peers[l + l2];
1774       }
1775       path->length -= l;
1776       l = 1;
1777       path->peers =
1778           GNUNET_realloc (path->peers, path->length * sizeof (GNUNET_PEER_Id));
1779     }
1780   }
1781 #if MESH_DEBUG
1782   {
1783     struct GNUNET_PeerIdentity id;
1784
1785     GNUNET_PEER_resolve (peer_info->id, &id);
1786     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "adding path [%u] to peer %s\n",
1787                 path->length, GNUNET_i2s (&id));
1788   }
1789 #endif
1790   l = path_get_length (path);
1791   if (0 == l)
1792   {
1793     GNUNET_free (path);
1794     return;
1795   }
1796
1797   GNUNET_assert (peer_info->id == path->peers[path->length - 1]);
1798   for (aux = peer_info->path_head; aux != NULL; aux = aux->next)
1799   {
1800     l2 = path_get_length (aux);
1801     if (l2 > l)
1802     {
1803       GNUNET_CONTAINER_DLL_insert_before (peer_info->path_head,
1804                                           peer_info->path_tail, aux, path);
1805       return;
1806     }
1807     else
1808     {
1809       if (l2 == l && memcmp (path->peers, aux->peers, l) == 0)
1810       {
1811         path_destroy (path);
1812         return;
1813       }
1814     }
1815   }
1816   GNUNET_CONTAINER_DLL_insert_tail (peer_info->path_head, peer_info->path_tail,
1817                                     path);
1818   return;
1819 }
1820
1821
1822 /**
1823  * Add the path to the origin peer and update the path used to reach it in case
1824  * this is the shortest.
1825  * The path is given in peer_info -> destination, therefore we turn the path
1826  * upside down first.
1827  *
1828  * @param peer_info Peer to add the path to, being the origin of the path.
1829  * @param path New path to add after being inversed.
1830  * @param trusted Do we trust that this path is real?
1831  */
1832 static void
1833 peer_info_add_path_to_origin (struct MeshPeerInfo *peer_info,
1834                               struct MeshPeerPath *path, int trusted)
1835 {
1836   path_invert (path);
1837   peer_info_add_path (peer_info, path, trusted);
1838 }
1839
1840
1841 /**
1842  * Function called if the connection to the peer has been stalled for a while,
1843  * possibly due to a missed ACK. Poll the peer about its ACK status.
1844  *
1845  * @param cls Closure (poll ctx).
1846  * @param tc TaskContext.
1847  */
1848 static void
1849 tunnel_poll (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1850 {
1851   struct MeshFlowControl *fc = cls;
1852   struct GNUNET_MESH_Poll msg;
1853   struct MeshTunnel *t = fc->t;
1854   GNUNET_PEER_Id peer;
1855
1856   fc->poll_task = GNUNET_SCHEDULER_NO_TASK;
1857   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1858   {
1859     return;
1860   }
1861
1862   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_POLL);
1863   msg.header.size = htons (sizeof (msg));
1864   msg.tid = htonl (t->id.tid);
1865   GNUNET_PEER_resolve (t->id.oid, &msg.oid);
1866   msg.last_ack = htonl (fc->last_ack_recv);
1867
1868   if (fc == &t->prev_fc)
1869   {
1870     peer = t->prev_hop;
1871   }
1872   else
1873   {
1874     peer = t->next_hop;
1875   }
1876   send_prebuilt_message (&msg.header, peer, t);
1877   fc->poll_time = GNUNET_TIME_STD_BACKOFF (fc->poll_time);
1878   fc->poll_task = GNUNET_SCHEDULER_add_delayed (fc->poll_time,
1879                                                 &tunnel_poll, fc);
1880 }
1881
1882
1883 /**
1884  * Build a PeerPath from the paths returned from the DHT, reversing the paths
1885  * to obtain a local peer -> destination path and interning the peer ids.
1886  *
1887  * @return Newly allocated and created path
1888  */
1889 static struct MeshPeerPath *
1890 path_build_from_dht (const struct GNUNET_PeerIdentity *get_path,
1891                      unsigned int get_path_length,
1892                      const struct GNUNET_PeerIdentity *put_path,
1893                      unsigned int put_path_length)
1894 {
1895   struct MeshPeerPath *p;
1896   GNUNET_PEER_Id id;
1897   int i;
1898
1899   p = path_new (1);
1900   p->peers[0] = myid;
1901   GNUNET_PEER_change_rc (myid, 1);
1902   i = get_path_length;
1903   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   GET has %d hops.\n", i);
1904   for (i--; i >= 0; i--)
1905   {
1906     id = GNUNET_PEER_intern (&get_path[i]);
1907     if (p->length > 0 && id == p->peers[p->length - 1])
1908     {
1909       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   Optimizing 1 hop out.\n");
1910       GNUNET_PEER_change_rc (id, -1);
1911     }
1912     else
1913     {
1914       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   Adding from GET: %s.\n",
1915                   GNUNET_i2s (&get_path[i]));
1916       p->length++;
1917       p->peers = GNUNET_realloc (p->peers, sizeof (GNUNET_PEER_Id) * p->length);
1918       p->peers[p->length - 1] = id;
1919     }
1920   }
1921   i = put_path_length;
1922   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   PUT has %d hops.\n", i);
1923   for (i--; i >= 0; i--)
1924   {
1925     id = GNUNET_PEER_intern (&put_path[i]);
1926     if (id == myid)
1927     {
1928       /* PUT path went through us, so discard the path up until now and start
1929        * from here to get a much shorter (and loop-free) path.
1930        */
1931       path_destroy (p);
1932       p = path_new (0);
1933     }
1934     if (p->length > 0 && id == p->peers[p->length - 1])
1935     {
1936       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   Optimizing 1 hop out.\n");
1937       GNUNET_PEER_change_rc (id, -1);
1938     }
1939     else
1940     {
1941       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   Adding from PUT: %s.\n",
1942                   GNUNET_i2s (&put_path[i]));
1943       p->length++;
1944       p->peers = GNUNET_realloc (p->peers, sizeof (GNUNET_PEER_Id) * p->length);
1945       p->peers[p->length - 1] = id;
1946     }
1947   }
1948 #if MESH_DEBUG
1949   if (get_path_length > 0)
1950     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   (first of GET: %s)\n",
1951                 GNUNET_i2s (&get_path[0]));
1952   if (put_path_length > 0)
1953     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   (first of PUT: %s)\n",
1954                 GNUNET_i2s (&put_path[0]));
1955   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   In total: %d hops\n",
1956               p->length);
1957   for (i = 0; i < p->length; i++)
1958   {
1959     struct GNUNET_PeerIdentity peer_id;
1960
1961     GNUNET_PEER_resolve (p->peers[i], &peer_id);
1962     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "       %u: %s\n", p->peers[i],
1963                 GNUNET_i2s (&peer_id));
1964   }
1965 #endif
1966   return p;
1967 }
1968
1969
1970 /**
1971  * Adds a path to the peer_infos of all the peers in the path
1972  *
1973  * @param p Path to process.
1974  * @param confirmed Whether we know if the path works or not.
1975  */
1976 static void
1977 path_add_to_peers (struct MeshPeerPath *p, int confirmed)
1978 {
1979   unsigned int i;
1980
1981   /* TODO: invert and add */
1982   for (i = 0; i < p->length && p->peers[i] != myid; i++) /* skip'em */ ;
1983   for (i++; i < p->length; i++)
1984   {
1985     struct MeshPeerInfo *aux;
1986     struct MeshPeerPath *copy;
1987
1988     aux = peer_get_short (p->peers[i]);
1989     copy = path_duplicate (p);
1990     copy->length = i + 1;
1991     peer_info_add_path (aux, copy, GNUNET_NO);
1992   }
1993 }
1994
1995
1996 /**
1997  * Send keepalive packets for a peer
1998  *
1999  * @param cls Closure (tunnel for which to send the keepalive).
2000  * @param tc Notification context.
2001  */
2002 static void
2003 path_refresh (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
2004
2005
2006 /**
2007  * Search for a tunnel among the incoming tunnels
2008  *
2009  * @param tid the local id of the tunnel
2010  *
2011  * @return tunnel handler, NULL if doesn't exist
2012  */
2013 static struct MeshTunnel *
2014 tunnel_get_incoming (MESH_TunnelNumber tid)
2015 {
2016   struct GNUNET_HashCode hash;
2017
2018   GNUNET_assert (tid >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV);
2019   GNUNET_CRYPTO_hash (&tid, sizeof (MESH_TunnelNumber), &hash);
2020   return GNUNET_CONTAINER_multihashmap_get (incoming_tunnels, &hash);
2021 }
2022
2023
2024 /**
2025  * Search for a tunnel among the tunnels for a client
2026  *
2027  * @param c the client whose tunnels to search in
2028  * @param tid the local id of the tunnel
2029  *
2030  * @return tunnel handler, NULL if doesn't exist
2031  */
2032 static struct MeshTunnel *
2033 tunnel_get_by_local_id (struct MeshClient *c, MESH_TunnelNumber tid)
2034 {
2035   if (tid >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
2036   {
2037     return tunnel_get_incoming (tid);
2038   }
2039   else
2040   {
2041     struct GNUNET_HashCode hash;
2042
2043     GNUNET_CRYPTO_hash (&tid, sizeof (MESH_TunnelNumber), &hash);
2044     return GNUNET_CONTAINER_multihashmap_get (c->own_tunnels, &hash);
2045   }
2046 }
2047
2048
2049 /**
2050  * Search for a tunnel by global ID using PEER_ID
2051  *
2052  * @param pi owner of the tunnel
2053  * @param tid global tunnel number
2054  *
2055  * @return tunnel handler, NULL if doesn't exist
2056  */
2057 static struct MeshTunnel *
2058 tunnel_get_by_pi (GNUNET_PEER_Id pi, MESH_TunnelNumber tid)
2059 {
2060   struct MESH_TunnelID id;
2061   struct GNUNET_HashCode hash;
2062
2063   id.oid = pi;
2064   id.tid = tid;
2065
2066   GNUNET_CRYPTO_hash (&id, sizeof (struct MESH_TunnelID), &hash);
2067   return GNUNET_CONTAINER_multihashmap_get (tunnels, &hash);
2068 }
2069
2070
2071 /**
2072  * Search for a tunnel by global ID using full PeerIdentities
2073  *
2074  * @param oid owner of the tunnel
2075  * @param tid global tunnel number
2076  *
2077  * @return tunnel handler, NULL if doesn't exist
2078  */
2079 static struct MeshTunnel *
2080 tunnel_get (const struct GNUNET_PeerIdentity *oid, MESH_TunnelNumber tid)
2081 {
2082   return tunnel_get_by_pi (GNUNET_PEER_search (oid), tid);
2083 }
2084
2085
2086 /**
2087  * Delete an active client from the tunnel.
2088  * 
2089  * @param t Tunnel.
2090  * @param c Client.
2091  */
2092 static void
2093 tunnel_delete_active_client (struct MeshTunnel *t, const struct MeshClient *c)
2094 {
2095   unsigned int i;
2096
2097   for (i = 0; i < t->nclients; i++)
2098   {
2099     if (t->clients[i] == c)
2100     {
2101       t->clients[i] = t->clients[t->nclients - 1];
2102       t->clients_fc[i] = t->clients_fc[t->nclients - 1];
2103       GNUNET_array_grow (t->clients, t->nclients, t->nclients - 1);
2104       t->nclients++;
2105       GNUNET_array_grow (t->clients_fc, t->nclients, t->nclients - 1);
2106       break;
2107     }
2108   }
2109 }
2110
2111
2112 /**
2113  * Delete an ignored client from the tunnel.
2114  * 
2115  * @param t Tunnel.
2116  * @param c Client.
2117  */
2118 static void
2119 tunnel_delete_ignored_client (struct MeshTunnel *t, const struct MeshClient *c)
2120 {
2121   unsigned int i;
2122
2123   for (i = 0; i < t->nignore; i++)
2124   {
2125     if (t->ignore[i] == c)
2126     {
2127       t->ignore[i] = t->ignore[t->nignore - 1];
2128       GNUNET_array_grow (t->ignore, t->nignore, t->nignore - 1);
2129       break;
2130     }
2131   }
2132 }
2133
2134
2135 /**
2136  * Delete a client from the tunnel. It should be only done on
2137  * client disconnection, otherwise use client_ignore_tunnel.
2138  * 
2139  * @param t Tunnel.
2140  * @param c Client.
2141  */
2142 static void
2143 tunnel_delete_client (struct MeshTunnel *t, const struct MeshClient *c)
2144 {
2145   tunnel_delete_ignored_client (t, c);
2146   tunnel_delete_active_client (t, c);
2147 }
2148
2149 /* FIXME check initial values */
2150 static void
2151 tunnel_add_client (struct MeshTunnel *t, struct MeshClient *c)
2152 {
2153   struct MeshTunnelClientInfo clinfo;
2154
2155   GNUNET_array_append (t->clients, t->nclients, c);
2156   clinfo.fwd_ack = t->prev_fc.last_pid_recv + 1;
2157   clinfo.fwd_pid = t->prev_fc.last_pid_recv;
2158   clinfo.bck_ack = t->nobuffer ? 1 : INITIAL_WINDOW_SIZE - 1;
2159   clinfo.bck_pid = (uint32_t) -1; /* Expected next: 0 */
2160   t->nclients--; /* Double append */
2161   GNUNET_array_append (t->clients_fc, t->nclients, clinfo);
2162 }
2163
2164
2165 static void
2166 tunnel_use_path (struct MeshTunnel *t, struct MeshPeerPath *p)
2167 {
2168   unsigned int i;
2169
2170   for (i = 0; i < p->length; i++)
2171   {
2172     if (p->peers[i] == myid)
2173       break;
2174   }
2175   if (i > p->length - 1)
2176   {
2177     GNUNET_break (0);
2178     return;
2179   }
2180
2181   if (i < p->length - 1)
2182     t->next_hop = p->peers[i + 1];
2183   else
2184     t->next_hop = 0;
2185   if (0 < i)
2186     t->prev_hop = p->peers[i - 1];
2187   else
2188     t->prev_hop = 0;
2189
2190   if (NULL != t->path)
2191     path_destroy (t->path);
2192   t->path = path_duplicate (p);
2193   if (GNUNET_SCHEDULER_NO_TASK == t->maintenance_task)
2194     t->maintenance_task =
2195         GNUNET_SCHEDULER_add_delayed (refresh_path_time, &path_refresh, t);
2196 }
2197
2198
2199 /**
2200  * Notifies a tunnel that a connection has broken that affects at least
2201  * some of its peers. Sends a notification towards the root of the tree.
2202  * In case the peer is the owner of the tree, notifies the client that owns
2203  * the tunnel and tries to reconnect.
2204  *
2205  * @param t Tunnel affected.
2206  * @param p1 Peer that got disconnected from p2.
2207  * @param p2 Peer that got disconnected from p1.
2208  *
2209  * @return Short ID of the peer disconnected (either p1 or p2).
2210  *         0 if the tunnel remained unaffected.
2211  */
2212 static GNUNET_PEER_Id
2213 tunnel_notify_connection_broken (struct MeshTunnel *t, GNUNET_PEER_Id p1,
2214                                  GNUNET_PEER_Id p2)
2215 {
2216 //   if (myid != p1 && myid != p2) FIXME
2217 //   {
2218 //     return;
2219 //   }
2220 // 
2221 //   if (tree_get_predecessor (t->tree) != 0)
2222 //   {
2223 //     /* We are the peer still connected, notify owner of the disconnection. */
2224 //     struct GNUNET_MESH_PathBroken msg;
2225 //     struct GNUNET_PeerIdentity neighbor;
2226 // 
2227 //     msg.header.size = htons (sizeof (msg));
2228 //     msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_BROKEN);
2229 //     GNUNET_PEER_resolve (t->id.oid, &msg.oid);
2230 //     msg.tid = htonl (t->id.tid);
2231 //     msg.peer1 = my_full_id;
2232 //     GNUNET_PEER_resolve (pid, &msg.peer2);
2233 //     GNUNET_PEER_resolve (tree_get_predecessor (t->tree), &neighbor);
2234 //     send_prebuilt_message (&msg.header, &neighbor, t);
2235 //   }
2236   return 0;
2237 }
2238
2239
2240 /**
2241  * Get the Flow Control info of a client.
2242  * 
2243  * @param t Tunnel on which to look.
2244  * @param c Client whose ACK to get.
2245  * 
2246  * @return ACK value.
2247  */
2248 static struct MeshTunnelClientInfo *
2249 tunnel_get_client_fc (struct MeshTunnel *t,
2250                       struct MeshClient *c)
2251 {
2252   unsigned int i;
2253
2254   for (i = 0; i < t->nclients; i++)
2255   {
2256     if (t->clients[i] != c)
2257       continue;
2258     return &t->clients_fc[i];
2259   }
2260   GNUNET_assert (0);
2261   return NULL; // avoid compiler / coverity complaints
2262 }
2263
2264
2265 /**
2266  * Set the FWD ACK value of a client in a particular tunnel.
2267  * 
2268  * @param t Tunnel affected.
2269  * @param c Client whose ACK to set.
2270  * @param ack ACK value.
2271  */
2272 static void
2273 tunnel_set_client_fwd_ack (struct MeshTunnel *t,
2274                            struct MeshClient *c, 
2275                            uint32_t ack)
2276 {
2277   unsigned int i;
2278
2279   for (i = 0; i < t->nclients; i++)
2280   {
2281     if (t->clients[i] != c)
2282       continue;
2283     t->clients_fc[i].fwd_ack = ack;
2284     return;
2285   }
2286   GNUNET_break (0);
2287 }
2288
2289
2290 /**
2291  * Get the highest ACK value of all clients in a particular tunnel,
2292  * according to the buffering/speed settings.
2293  * 
2294  * @param t Tunnel on which to look.
2295  * 
2296  * @return Corresponding ACK value (max uint32_t).
2297  *         If no clients are suscribed, -1LL.
2298  */
2299 static int64_t
2300 tunnel_get_clients_fwd_ack (struct MeshTunnel *t)
2301 {
2302   unsigned int i;
2303   int64_t ack;
2304
2305   if (0 == t->nclients)
2306   {
2307     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2308                 "  tunnel has no clients, no FWD ACK\n");
2309     return -1LL;
2310   }
2311
2312   for (ack = -1LL, i = 0; i < t->nclients; i++)
2313   {
2314     if (-1LL == ack ||
2315         GNUNET_YES == GMC_is_pid_bigger (ack, t->clients_fc[i].fwd_ack))
2316     {
2317       ack = t->clients_fc[i].fwd_ack;
2318     }
2319   }
2320
2321   if (GNUNET_YES == t->nobuffer &&
2322       GMC_is_pid_bigger(ack, t->prev_fc.last_pid_recv))
2323     ack = (uint32_t) t->prev_fc.last_pid_recv + 1; // Might overflow, it's ok.
2324
2325   return (uint32_t) ack;
2326 }
2327
2328
2329 /** FIXME
2330  * Get the current fwd ack value for a tunnel, taking in account the tunnel
2331  * mode and the status of all children nodes.
2332  *
2333  * @param t Tunnel.
2334  *
2335  * @return Maximum PID allowed.
2336  */
2337 static uint32_t
2338 tunnel_get_fwd_ack (struct MeshTunnel *t)
2339 {
2340   uint32_t ack;
2341   uint32_t buffer_free;
2342   int64_t client_ack;
2343
2344   buffer_free = t->queue_max - t->next_fc.queue_n;
2345   client_ack = tunnel_get_clients_fwd_ack (t);
2346   if (GNUNET_YES == t->nobuffer)
2347   {
2348     ack = t->prev_fc.last_ack_sent;
2349   }
2350   else
2351   {
2352     ack = t->prev_fc.last_ack_sent + buffer_free; // Overflow? OK!
2353   }
2354   if (-1LL == client_ack)
2355   {
2356     client_ack = ack;
2357   }
2358   /* FIXME check */
2359   ack = GMC_max_pid ((uint32_t) client_ack, ack);
2360
2361   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2362               "c %u, bf %u, cl %lld, ACK: %u\n",
2363               t->prev_fc.last_ack_sent, buffer_free, client_ack, ack);
2364   return ack;
2365 }
2366
2367
2368 /**
2369  * Build a local ACK message and send it to a local client.
2370  * 
2371  * @param t Tunnel on which to send the ACK.
2372  * @param c Client to whom send the ACK.
2373  * @param ack Value of the ACK.
2374  */
2375 static void
2376 send_local_ack (struct MeshTunnel *t, struct MeshClient *c, uint32_t ack)
2377 {
2378   struct GNUNET_MESH_LocalAck msg;
2379
2380   msg.header.size = htons (sizeof (msg));
2381   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK);
2382   msg.tunnel_id = htonl (t->owner == c ? t->local_tid : t->local_tid_dest);
2383   msg.max_pid = htonl (ack); 
2384   GNUNET_SERVER_notification_context_unicast(nc,
2385                                               c->handle,
2386                                               &msg.header,
2387                                               GNUNET_NO);
2388 }
2389
2390 /**
2391  * Build an ACK message and queue it to send to the given peer.
2392  * 
2393  * @param t Tunnel on which to send the ACK.
2394  * @param peer Peer to whom send the ACK.
2395  * @param ack Value of the ACK.
2396  */
2397 static void
2398 send_ack (struct MeshTunnel *t, GNUNET_PEER_Id peer,  uint32_t ack)
2399 {
2400   struct GNUNET_MESH_ACK msg;
2401
2402   GNUNET_PEER_resolve (t->id.oid, &msg.oid);
2403   msg.header.size = htons (sizeof (msg));
2404   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_ACK);
2405   msg.pid = htonl (ack);
2406   msg.tid = htonl (t->id.tid);
2407
2408   send_prebuilt_message (&msg.header, peer, t);
2409 }
2410
2411
2412 /**
2413  * Notify a the owner of a tunnel about how many more
2414  * payload packages will we accept on a given tunnel.
2415  *
2416  * @param t Tunnel on which to send the ACK.
2417  */
2418 static void
2419 tunnel_send_client_fwd_ack (struct MeshTunnel *t)
2420 {
2421   uint32_t ack;
2422
2423   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2424               "Sending client FWD ACK on tunnel %X\n",
2425               t->local_tid);
2426
2427   ack = tunnel_get_fwd_ack (t);
2428
2429   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " ack %u\n", ack);
2430   if (t->prev_fc.last_ack_sent == ack)
2431   {
2432     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " same as last, not sending!\n");
2433     return;
2434   }
2435
2436   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " sending!\n");
2437   t->prev_fc.last_ack_sent = ack;
2438   send_local_ack (t, t->owner, ack);
2439 }
2440
2441
2442 /**
2443  * Send an ACK informing the predecessor about the available buffer space.
2444  * In case there is no predecessor, inform the owning client.
2445  * If buffering is off, send only on behalf of children or self if endpoint.
2446  * If buffering is on, send when sent to children and buffer space is free.
2447  * Note that although the name is fwd_ack, the FWD mean forward *traffic*,
2448  * the ACK itself goes "back" (towards root).
2449  * 
2450  * @param t Tunnel on which to send the ACK.
2451  * @param type Type of message that triggered the ACK transmission.
2452  */
2453 static void
2454 tunnel_send_fwd_ack (struct MeshTunnel *t, uint16_t type)
2455 {
2456   uint32_t ack;
2457
2458   if (NULL != t->owner)
2459   {
2460     tunnel_send_client_fwd_ack (t);
2461     return;
2462   }
2463   /* Is it after unicast retransmission? */
2464   switch (type)
2465   {
2466     case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
2467       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2468                   "ACK due to FWD DATA retransmission\n");
2469       if (GNUNET_YES == t->nobuffer)
2470       {
2471         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Not sending ACK, nobuffer\n");
2472         return;
2473       }
2474       break;
2475     case GNUNET_MESSAGE_TYPE_MESH_ACK:
2476     case GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK:
2477       break;
2478     case GNUNET_MESSAGE_TYPE_MESH_POLL:
2479       t->force_ack = GNUNET_YES;
2480       break;
2481     default:
2482       GNUNET_break (0);
2483   }
2484
2485   /* Check if we need to transmit the ACK */
2486   if (t->queue_max > t->next_fc.queue_n * 4 &&
2487       GMC_is_pid_bigger(t->prev_fc.last_ack_sent, t->prev_fc.last_pid_recv) &&
2488       GNUNET_NO == t->force_ack)
2489   {
2490     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Not sending ACK, buffer free\n");
2491     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2492                 "  t->qmax: %u, t->qn: %u\n",
2493                 t->queue_max, t->next_fc.queue_n);
2494     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2495                 "  t->pid: %u, t->ack: %u\n",
2496                 t->prev_fc.last_pid_recv, t->prev_fc.last_ack_sent);
2497     return;
2498   }
2499
2500   /* Ok, ACK might be necessary, what PID to ACK? */
2501   ack = tunnel_get_fwd_ack (t);
2502   if (ack == t->prev_fc.last_ack_sent && GNUNET_NO == t->force_ack)
2503   {
2504     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Not sending FWD ACK, not ready\n");
2505     return;
2506   }
2507
2508   t->prev_fc.last_ack_sent = ack;
2509   send_ack (t, t->prev_hop, ack);
2510   debug_fwd_ack++;
2511   t->force_ack = GNUNET_NO;
2512 }
2513
2514
2515 /**
2516  * Send a child node a BCK ACK to allow him to send more to_origin data.
2517  *
2518  * @param t Tunnel.
2519  * @param id Id of the child node.
2520  */
2521 static void
2522 tunnel_send_mesh_bck_ack (struct MeshTunnel *t,
2523                            GNUNET_PEER_Id peer)
2524 {
2525   uint32_t ack = 0; // FIXME
2526
2527   ack = t->next_fc.last_pid_recv + t->queue_max - t->prev_fc.queue_n;
2528
2529   if (t->next_fc.last_ack_sent == ack && GNUNET_NO == t->force_ack)
2530   {
2531     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2532                 "    Not sending ACK, not needed\n");
2533     return;
2534   }
2535   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2536               "    Sending BCK ACK %u (last sent: %u)\n",
2537               ack, t->next_fc.last_ack_sent);
2538   t->next_fc.last_ack_sent = ack;
2539
2540   send_ack (t, peer, ack);
2541 }
2542
2543
2544 /**
2545  * @brief Send BCK ACKs to clients to allow them more to_origin traffic
2546  * 
2547  * Iterates over all clients and sends BCK ACKs to the ones that need it.
2548  *
2549  * FIXME fc: what happens if we have 2 clients but q_size is 1?
2550  *           - implement a size 1 buffer in each client_fc AND children_fc
2551  *           to hold at least 1 message per "child".
2552  *             problem: violates no buffer policy
2553  *           - ack 0 and make "children" poll for transmission slots
2554  *             problem: big overhead, extra latency even in low traffic
2555  *                      settings
2556  * 
2557  * @param t Tunnel on which to send the BCK ACKs.
2558  */
2559 static void
2560 tunnel_send_clients_bck_ack (struct MeshTunnel *t)
2561 {
2562   unsigned int i;
2563   unsigned int tunnel_delta;
2564
2565   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Sending BCK ACK to clients\n");
2566
2567   tunnel_delta = t->queue_max - t->next_fc.queue_n;
2568   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   tunnel delta: %u\n", tunnel_delta);
2569
2570   /* Find client whom to allow to send to origin (with lowest buffer space) */
2571   for (i = 0; i < t->nclients; i++)
2572   {
2573     struct MeshTunnelClientInfo *clinfo;
2574     unsigned int delta;
2575
2576     clinfo = &t->clients_fc[i];
2577     delta = clinfo->bck_ack - clinfo->bck_pid;
2578     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "    client %u delta: %u\n",
2579          t->clients[i]->id, delta);
2580
2581     if ((GNUNET_NO == t->nobuffer && tunnel_delta > delta) ||
2582         (GNUNET_YES == t->nobuffer && 0 == delta))
2583     {
2584       uint32_t ack;
2585
2586       ack = clinfo->bck_pid;
2587       ack += t->nobuffer ? 1 : tunnel_delta;
2588       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2589                   "    sending ack to client %u: %u\n",
2590                   t->clients[i]->id, ack);
2591       send_local_ack (t, t->clients[i], ack);
2592       clinfo->bck_ack = ack;
2593     }
2594     else
2595     {
2596       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2597                   "    not sending ack to client %u (td %u, d %u)\n",
2598                   t->clients[i]->id, tunnel_delta, delta);
2599     }
2600   }
2601 }
2602
2603
2604 /**
2605  * Send an ACK informing the children nodes and destination clients about
2606  * the available buffer space.
2607  * If buffering is off, send only on behalf of root (can be self).
2608  * If buffering is on, send when sent to predecessor and buffer space is free.
2609  * Note that although the name is bck_ack, the BCK mean backwards *traffic*,
2610  * the ACK itself goes "forward" (towards children/clients).
2611  * 
2612  * @param t Tunnel on which to send the ACK.
2613  * @param type Type of message that triggered the ACK transmission.
2614  */
2615 static void
2616 tunnel_send_bck_ack (struct MeshTunnel *t, uint16_t type)
2617 {
2618   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2619               "Sending BCK ACK on tunnel %u [%u] due to %s\n",
2620               t->id.oid, t->id.tid, GNUNET_MESH_DEBUG_M2S(type));
2621   /* Is it after data to_origin retransmission? */
2622   switch (type)
2623   {
2624     case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
2625       if (GNUNET_YES == t->nobuffer)
2626       {
2627         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2628                     "    Not sending ACK, nobuffer\n");
2629         return;
2630       }
2631       break;
2632     case GNUNET_MESSAGE_TYPE_MESH_ACK:
2633     case GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK:
2634       break;
2635     case GNUNET_MESSAGE_TYPE_MESH_POLL:
2636       t->force_ack = GNUNET_YES;
2637       break;
2638     default:
2639       GNUNET_break (0);
2640   }
2641
2642   tunnel_send_clients_bck_ack (t);
2643     tunnel_send_mesh_bck_ack (t, t->next_hop);
2644   t->force_ack = GNUNET_NO;
2645 }
2646
2647
2648 /**
2649  * @brief Re-initiate traffic to this peer if necessary.
2650  *
2651  * Check if there is traffic queued towards this peer
2652  * and the core transmit handle is NULL (traffic was stalled).
2653  * If so, call core tmt rdy.
2654  *
2655  * @param peer_id Short ID of peer to which initiate traffic.
2656  */
2657 static void
2658 peer_unlock_queue(GNUNET_PEER_Id peer_id)
2659 {
2660   struct MeshPeerInfo *peer;
2661   struct GNUNET_PeerIdentity id;
2662   struct MeshPeerQueue *q;
2663   size_t size;
2664
2665   peer = peer_get_short (peer_id);
2666   if (NULL != peer->core_transmit)
2667     return;
2668
2669   q = queue_get_next (peer);
2670   if (NULL == q)
2671   {
2672     /* Might br multicast traffic already sent to this particular peer but
2673      * not to other children in this tunnel.
2674      * This way t->queue_n would be > 0 but the queue of this particular peer
2675      * would be empty.
2676      */
2677     return;
2678   }
2679   size = q->size;
2680   GNUNET_PEER_resolve (peer->id, &id);
2681   peer->core_transmit =
2682         GNUNET_CORE_notify_transmit_ready(core_handle,
2683                                           0,
2684                                           0,
2685                                           GNUNET_TIME_UNIT_FOREVER_REL,
2686                                           &id,
2687                                           size,
2688                                           &queue_send,
2689                                           peer);
2690         return;
2691 }
2692
2693
2694 /**
2695  * Send a message to all peers in this tunnel that the tunnel is no longer
2696  * valid.
2697  *
2698  * @param t The tunnel whose peers to notify.
2699  */
2700 static void
2701 tunnel_send_destroy (struct MeshTunnel *t)
2702 {
2703   struct GNUNET_MESH_TunnelDestroy msg;
2704   struct GNUNET_PeerIdentity id;
2705
2706   msg.header.size = htons (sizeof (msg));
2707   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_TUNNEL_DESTROY);
2708   GNUNET_PEER_resolve (t->id.oid, &msg.oid);
2709   msg.tid = htonl (t->id.tid);
2710   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2711               "  sending tunnel destroy for tunnel: %s [%X]\n",
2712               GNUNET_i2s (&msg.oid), t->id.tid);
2713
2714   if (0 != t->next_hop)
2715   {
2716     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  child: %u\n", t->next_hop);
2717     GNUNET_PEER_resolve (t->next_hop, &id);
2718     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2719                 "  sending forward to %s\n",
2720                 GNUNET_i2s (&id));
2721     send_prebuilt_message (&msg.header, t->next_hop, t);
2722   }
2723   if (0 != t->prev_hop)
2724   {
2725     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  parent: %u\n", t->prev_hop);
2726     GNUNET_PEER_resolve (t->prev_hop, &id);
2727     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2728                 "  sending back to %s\n",
2729                 GNUNET_i2s (&id));
2730     send_prebuilt_message (&msg.header, t->prev_hop, t);
2731   }
2732 }
2733
2734
2735 /**
2736  * Cancel all transmissions towards a neighbor that belongs to a certain tunnel.
2737  *
2738  * @param t Tunnel which to cancel.
2739  * @param neighbor Short ID of the neighbor to whom cancel the transmissions.
2740  */
2741 static void
2742 peer_cancel_queues (GNUNET_PEER_Id neighbor, struct MeshTunnel *t)
2743 {
2744   struct MeshPeerInfo *peer_info;
2745   struct MeshPeerQueue *pq;
2746   struct MeshPeerQueue *next;
2747
2748   peer_info = peer_get_short (neighbor);
2749   for (pq = peer_info->queue_head; NULL != pq; pq = next)
2750   {
2751     next = pq->next;
2752     if (pq->tunnel == t)
2753     {
2754       if (GNUNET_MESSAGE_TYPE_MESH_UNICAST == pq->type ||
2755           GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN == pq->type)
2756       {
2757         // Should have been removed on destroy children
2758         GNUNET_break (0);
2759       }
2760       queue_destroy (pq, GNUNET_YES);
2761     }
2762   }
2763   if (NULL == peer_info->queue_head && NULL != peer_info->core_transmit)
2764   {
2765     GNUNET_CORE_notify_transmit_ready_cancel(peer_info->core_transmit);
2766     peer_info->core_transmit = NULL;
2767   }
2768 }
2769
2770
2771 /**
2772  * Destroy the tunnel and free any allocated resources linked to it.
2773  *
2774  * @param t the tunnel to destroy
2775  *
2776  * @return GNUNET_OK on success
2777  */
2778 static int
2779 tunnel_destroy (struct MeshTunnel *t)
2780 {
2781   struct MeshClient *c;
2782   struct GNUNET_HashCode hash;
2783   unsigned int i;
2784   int r;
2785
2786   if (NULL == t)
2787     return GNUNET_OK;
2788
2789   r = GNUNET_OK;
2790   c = t->owner;
2791 #if MESH_DEBUG
2792   {
2793     struct GNUNET_PeerIdentity id;
2794
2795     GNUNET_PEER_resolve (t->id.oid, &id);
2796     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "destroying tunnel %s [%x]\n",
2797                 GNUNET_i2s (&id), t->id.tid);
2798     if (NULL != c)
2799       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
2800   }
2801 #endif
2802
2803   GNUNET_CRYPTO_hash (&t->id, sizeof (struct MESH_TunnelID), &hash);
2804   if (GNUNET_YES != GNUNET_CONTAINER_multihashmap_remove (tunnels, &hash, t))
2805   {
2806     GNUNET_break (0);
2807     r = GNUNET_SYSERR;
2808   }
2809
2810   if (NULL != c)
2811   {
2812     GNUNET_CRYPTO_hash (&t->local_tid, sizeof (MESH_TunnelNumber), &hash);
2813     if (GNUNET_YES !=
2814         GNUNET_CONTAINER_multihashmap_remove (c->own_tunnels, &hash, t))
2815     {
2816       GNUNET_break (0);
2817       r = GNUNET_SYSERR;
2818     }
2819   }
2820
2821   GNUNET_CRYPTO_hash (&t->local_tid_dest, sizeof (MESH_TunnelNumber), &hash);
2822   for (i = 0; i < t->nclients; i++)
2823   {
2824     c = t->clients[i];
2825     if (GNUNET_YES !=
2826           GNUNET_CONTAINER_multihashmap_remove (c->incoming_tunnels, &hash, t))
2827     {
2828       GNUNET_break (0);
2829       r = GNUNET_SYSERR;
2830     }
2831   }
2832   for (i = 0; i < t->nignore; i++)
2833   {
2834     c = t->ignore[i];
2835     if (GNUNET_YES !=
2836           GNUNET_CONTAINER_multihashmap_remove (c->ignore_tunnels, &hash, t))
2837     {
2838       GNUNET_break (0);
2839       r = GNUNET_SYSERR;
2840     }
2841   }
2842
2843   (void) GNUNET_CONTAINER_multihashmap_remove (incoming_tunnels, &hash, t);
2844   GNUNET_free_non_null (t->clients);
2845   GNUNET_free_non_null (t->ignore);
2846   GNUNET_free_non_null (t->clients_fc);
2847
2848   peer_cancel_queues (t->next_hop, t);
2849   peer_cancel_queues (t->prev_hop, t);
2850
2851   if (GNUNET_SCHEDULER_NO_TASK != t->maintenance_task)
2852     GNUNET_SCHEDULER_cancel (t->maintenance_task);
2853
2854   n_tunnels--;
2855   GNUNET_STATISTICS_update (stats, "# tunnels", -1, GNUNET_NO);
2856   GNUNET_free (t);
2857   return r;
2858 }
2859
2860 #define TUNNEL_DESTROY_EMPTY_TIME GNUNET_TIME_UNIT_MILLISECONDS
2861
2862 /**
2863  * Tunnel is empty: destroy it.
2864  * 
2865  * @param cls Closure (Tunnel).
2866  * @param tc TaskContext. 
2867  */
2868 static void
2869 tunnel_destroy_empty_delayed (void *cls,
2870                               const struct GNUNET_SCHEDULER_TaskContext *tc)
2871 {
2872   struct MeshTunnel *t = cls;
2873
2874   t->delayed_destroy = GNUNET_SCHEDULER_NO_TASK;
2875   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
2876     return;
2877
2878   if (0 != t->nclients)
2879     return;
2880
2881   #if MESH_DEBUG
2882   {
2883     struct GNUNET_PeerIdentity id;
2884
2885     GNUNET_PEER_resolve (t->id.oid, &id);
2886     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2887                 "executing destruction of empty tunnel %s [%X]\n",
2888                 GNUNET_i2s (&id), t->id.tid);
2889   }
2890   #endif
2891
2892   tunnel_send_destroy (t);
2893   if (0 == t->pending_messages)
2894     tunnel_destroy (t);
2895   else
2896     t->destroy = GNUNET_YES;
2897 }
2898
2899
2900 /**
2901  * Schedule tunnel destruction if is empty and no new traffic comes in a time.
2902  * 
2903  * @param t Tunnel to destroy if empty.
2904  */
2905 static void
2906 tunnel_destroy_empty (struct MeshTunnel *t)
2907 {
2908   if (GNUNET_SCHEDULER_NO_TASK != t->delayed_destroy || 
2909       0 != t->nclients)
2910   {
2911     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "%u %u\n",
2912                 t->delayed_destroy, t->nclients);
2913     return;
2914   }
2915
2916   #if MESH_DEBUG
2917   {
2918     struct GNUNET_PeerIdentity id;
2919
2920     GNUNET_PEER_resolve (t->id.oid, &id);
2921     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2922                 "scheduling destruction of empty tunnel %s [%X]\n",
2923                 GNUNET_i2s (&id), t->id.tid);
2924   }
2925   #endif
2926
2927   t->delayed_destroy =
2928       GNUNET_SCHEDULER_add_delayed (TUNNEL_DESTROY_EMPTY_TIME,
2929                                     &tunnel_destroy_empty_delayed,
2930                                     t);
2931 }
2932
2933
2934 /**
2935  * Create a new tunnel
2936  * 
2937  * @param owner Who is the owner of the tunnel (short ID).
2938  * @param tid Tunnel Number of the tunnel.
2939  * @param client Clients that owns the tunnel, NULL for foreign tunnels.
2940  * @param local Tunnel Number for the tunnel, for the client point of view.
2941  * 
2942  * @return A new initialized tunnel. NULL on error.
2943  */
2944 static struct MeshTunnel *
2945 tunnel_new (GNUNET_PEER_Id owner,
2946             MESH_TunnelNumber tid,
2947             struct MeshClient *client,
2948             MESH_TunnelNumber local)
2949 {
2950   struct MeshTunnel *t;
2951   struct GNUNET_HashCode hash;
2952
2953   if (n_tunnels >= max_tunnels && NULL == client)
2954     return NULL;
2955
2956   t = GNUNET_malloc (sizeof (struct MeshTunnel));
2957   t->id.oid = owner;
2958   t->id.tid = tid;
2959   t->queue_max = (max_msgs_queue / max_tunnels) + 1;
2960   t->owner = client;
2961   t->next_fc.last_pid_sent = (uint32_t) -1; /* Next (expected) = 0 */
2962   t->next_fc.last_pid_recv = (uint32_t) -1;
2963   t->prev_fc.last_pid_sent = (uint32_t) -1;
2964   t->prev_fc.last_pid_recv = (uint32_t) -1;
2965   t->next_fc.last_ack_sent = INITIAL_WINDOW_SIZE - 1;
2966   t->next_fc.last_ack_recv = INITIAL_WINDOW_SIZE - 1;
2967   t->prev_fc.last_ack_sent = INITIAL_WINDOW_SIZE - 1;
2968   t->prev_fc.last_ack_recv = INITIAL_WINDOW_SIZE - 1;
2969   t->local_tid = local;
2970   n_tunnels++;
2971   GNUNET_STATISTICS_update (stats, "# tunnels", 1, GNUNET_NO);
2972
2973   GNUNET_CRYPTO_hash (&t->id, sizeof (struct MESH_TunnelID), &hash);
2974   if (GNUNET_OK !=
2975       GNUNET_CONTAINER_multihashmap_put (tunnels, &hash, t,
2976                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
2977   {
2978     GNUNET_break (0);
2979     tunnel_destroy (t);
2980     if (NULL != client)
2981     {
2982       GNUNET_break (0);
2983       GNUNET_SERVER_receive_done (client->handle, GNUNET_SYSERR);
2984     }
2985     return NULL;
2986   }
2987
2988   if (NULL != client)
2989   {
2990     GNUNET_CRYPTO_hash (&t->local_tid, sizeof (MESH_TunnelNumber), &hash);
2991     if (GNUNET_OK !=
2992         GNUNET_CONTAINER_multihashmap_put (client->own_tunnels, &hash, t,
2993                                           GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
2994     {
2995       tunnel_destroy (t);
2996       GNUNET_break (0);
2997       GNUNET_SERVER_receive_done (client->handle, GNUNET_SYSERR);
2998       return NULL;
2999     }
3000   }
3001
3002   return t;
3003 }
3004
3005
3006
3007 /**
3008  * tunnel_destroy_iterator: iterator for deleting each tunnel that belongs to a
3009  * client when the client disconnects. If the client is not the owner, the
3010  * owner will get notified if no more clients are in the tunnel and the client
3011  * get removed from the tunnel's list.
3012  *
3013  * @param cls closure (client that is disconnecting)
3014  * @param key the hash of the local tunnel id (used to access the hashmap)
3015  * @param value the value stored at the key (tunnel to destroy)
3016  *
3017  * @return GNUNET_OK, keep iterating.
3018  */
3019 static int
3020 tunnel_destroy_iterator (void *cls,
3021                          const struct GNUNET_HashCode * key,
3022                          void *value)
3023 {
3024   struct MeshTunnel *t = value;
3025   struct MeshClient *c = cls;
3026
3027   send_client_tunnel_disconnect (t, c);
3028   if (c != t->owner)
3029   {
3030     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Client %u is destination.\n", c->id);
3031     tunnel_delete_client (t, c);
3032     client_delete_tunnel (c, t);
3033     tunnel_destroy_empty (t);
3034     return GNUNET_OK;
3035   }
3036   tunnel_send_destroy (t);
3037   t->owner = NULL;
3038   t->destroy = GNUNET_YES;
3039
3040   return GNUNET_OK;
3041 }
3042
3043
3044 /**
3045  * Timeout function, destroys tunnel if called
3046  *
3047  * @param cls Closure (tunnel to destroy).
3048  * @param tc TaskContext
3049  */
3050 static void
3051 tunnel_timeout (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3052 {
3053   struct MeshTunnel *t = cls;
3054   struct GNUNET_PeerIdentity id;
3055
3056   t->maintenance_task = GNUNET_SCHEDULER_NO_TASK;
3057   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
3058     return;
3059   GNUNET_PEER_resolve(t->id.oid, &id);
3060   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3061               "Tunnel %s [%X] timed out. Destroying.\n",
3062               GNUNET_i2s(&id), t->id.tid);
3063   send_clients_tunnel_destroy (t);
3064   tunnel_destroy (t);
3065 }
3066
3067 /**
3068  * Resets the tunnel timeout. Starts it if no timeout was running.
3069  *
3070  * @param t Tunnel whose timeout to reset.
3071  *
3072  * TODO use heap to improve efficiency of scheduler.
3073  */
3074 static void
3075 tunnel_reset_timeout (struct MeshTunnel *t)
3076 {
3077   if (NULL != t->owner || 0 != t->local_tid || 0 == t->prev_hop)
3078     return;
3079   if (GNUNET_SCHEDULER_NO_TASK != t->maintenance_task)
3080     GNUNET_SCHEDULER_cancel (t->maintenance_task);
3081   t->maintenance_task =
3082       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply
3083                                     (refresh_path_time, 4), &tunnel_timeout, t);
3084 }
3085
3086
3087 /******************************************************************************/
3088 /****************      MESH NETWORK HANDLER HELPERS     ***********************/
3089 /******************************************************************************/
3090
3091 /**
3092  * Function to send a create path packet to a peer.
3093  *
3094  * @param cls closure
3095  * @param size number of bytes available in buf
3096  * @param buf where the callee should write the message
3097  * @return number of bytes written to buf
3098  */
3099 static size_t
3100 send_core_path_create (void *cls, size_t size, void *buf)
3101 {
3102   struct MeshTunnel *t = cls;
3103   struct GNUNET_MESH_ManipulatePath *msg;
3104   struct GNUNET_PeerIdentity *peer_ptr;
3105   struct MeshPeerPath *p = t->path;
3106   size_t size_needed;
3107   uint32_t opt;
3108   int i;
3109
3110   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "CREATE PATH sending...\n");
3111   size_needed =
3112       sizeof (struct GNUNET_MESH_ManipulatePath) +
3113       p->length * sizeof (struct GNUNET_PeerIdentity);
3114
3115   if (size < size_needed || NULL == buf)
3116   {
3117     GNUNET_break (0);
3118     return 0;
3119   }
3120   msg = (struct GNUNET_MESH_ManipulatePath *) buf;
3121   msg->header.size = htons (size_needed);
3122   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE);
3123   msg->tid = ntohl (t->id.tid);
3124
3125   opt = 0;
3126   if (GNUNET_YES == t->nobuffer)
3127     opt |= MESH_TUNNEL_OPT_NOBUFFER;
3128   msg->opt = htonl(opt);
3129   msg->reserved = 0;
3130
3131   peer_ptr = (struct GNUNET_PeerIdentity *) &msg[1];
3132   for (i = 0; i < p->length; i++)
3133   {
3134     GNUNET_PEER_resolve (p->peers[i], peer_ptr++);
3135   }
3136
3137   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3138               "CREATE PATH (%u bytes long) sent!\n", size_needed);
3139   return size_needed;
3140 }
3141
3142
3143 /**
3144  * Creates a path ack message in buf and frees all unused resources.
3145  *
3146  * @param cls closure (MeshTransmissionDescriptor)
3147  * @param size number of bytes available in buf
3148  * @param buf where the callee should write the message
3149  * @return number of bytes written to buf
3150  */
3151 static size_t
3152 send_core_path_ack (void *cls, size_t size, void *buf)
3153 {
3154   struct MeshTransmissionDescriptor *info = cls;
3155   struct GNUNET_MESH_PathACK *msg = buf;
3156
3157   GNUNET_assert (NULL != info);
3158   if (sizeof (struct GNUNET_MESH_PathACK) > size)
3159   {
3160     GNUNET_break (0);
3161     return 0;
3162   }
3163   msg->header.size = htons (sizeof (struct GNUNET_MESH_PathACK));
3164   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_ACK);
3165   GNUNET_PEER_resolve (info->origin->oid, &msg->oid);
3166   msg->tid = htonl (info->origin->tid);
3167   msg->peer_id = my_full_id;
3168
3169   GNUNET_free (info);
3170   /* TODO add signature */
3171
3172   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "PATH ACK sent!\n");
3173   return sizeof (struct GNUNET_MESH_PathACK);
3174 }
3175
3176
3177 /**
3178  * Free a transmission that was already queued with all resources
3179  * associated to the request.
3180  *
3181  * @param queue Queue handler to cancel.
3182  * @param clear_cls Is it necessary to free associated cls?
3183  */
3184 static void
3185 queue_destroy (struct MeshPeerQueue *queue, int clear_cls)
3186 {
3187   struct MeshTransmissionDescriptor *dd;
3188 //   unsigned int max;
3189
3190   if (GNUNET_YES == clear_cls)
3191   {
3192     switch (queue->type)
3193     {
3194       case GNUNET_MESSAGE_TYPE_MESH_TUNNEL_DESTROY:
3195         GNUNET_log (GNUNET_ERROR_TYPE_INFO, "   cancelling TUNNEL_DESTROY\n");
3196         GNUNET_break (GNUNET_YES == queue->tunnel->destroy);
3197         /* fall through */
3198       case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
3199       case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
3200       case GNUNET_MESSAGE_TYPE_MESH_ACK:
3201       case GNUNET_MESSAGE_TYPE_MESH_POLL:
3202       case GNUNET_MESSAGE_TYPE_MESH_PATH_KEEPALIVE:
3203         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3204                     "   prebuilt message\n");
3205         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3206                     "   type %s\n",
3207                     GNUNET_MESH_DEBUG_M2S(queue->type));
3208         dd = queue->cls;
3209         GNUNET_free (dd->data);
3210         break;
3211       case GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE:
3212         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   type create path\n");
3213         break;
3214       default:
3215         GNUNET_break (0);
3216         GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3217                     "   type %s unknown!\n",
3218                     GNUNET_MESH_DEBUG_M2S(queue->type));
3219     }
3220     GNUNET_free_non_null (queue->cls);
3221   }
3222   GNUNET_CONTAINER_DLL_remove (queue->peer->queue_head,
3223                                queue->peer->queue_tail,
3224                                queue);
3225
3226   /* Delete from child_fc in the appropiate tunnel */
3227 //   max = queue->tunnel->fwd_queue_max;
3228 //   GNUNET_PEER_resolve (queue->peer->id, &id);
3229 //   if (NULL != cinfo)
3230 //   { FIXME
3231 //     for (i = 0; i < cinfo->send_buffer_n; i++)
3232 //     {
3233 //       i2 = (cinfo->send_buffer_start + i) % max;
3234 //       if (cinfo->send_buffer[i2] == queue)
3235 //       {
3236 //         /* Found corresponding entry in the send_buffer. Move all others back. */
3237 //         unsigned int j;
3238 // 
3239 // 
3240 //         for (j = i, j2 = 0, j3 = 0; j < cinfo->send_buffer_n - 1; j++)
3241 //         {
3242 //           j2 = (cinfo->send_buffer_start + j) % max;
3243 //           j3 = (cinfo->send_buffer_start + j + 1) % max;
3244 //           cinfo->send_buffer[j2] = cinfo->send_buffer[j3];
3245 //         }
3246 // 
3247 //         cinfo->send_buffer[j3] = NULL;
3248 //         cinfo->send_buffer_n--;
3249 //       }
3250 //     }
3251 //   }
3252
3253   GNUNET_free (queue);
3254 }
3255
3256
3257 /**
3258  * @brief Get the next transmittable message from the queue.
3259  *
3260  * This will be the head, except in the case of being a data packet
3261  * not allowed by the destination peer.
3262  *
3263  * @param peer Destination peer.
3264  *
3265  * @return The next viable MeshPeerQueue element to send to that peer.
3266  *         NULL when there are no transmittable messages.
3267  */
3268 struct MeshPeerQueue *
3269 queue_get_next (const struct MeshPeerInfo *peer)
3270 {
3271   struct MeshPeerQueue *q;
3272  
3273   struct MeshTransmissionDescriptor *info;
3274 //   struct GNUNET_MESH_Unicast *ucast;
3275 //   struct GNUNET_MESH_ToOrigin *to_orig;
3276   struct GNUNET_PeerIdentity id;
3277 //   uint32_t pid;
3278 //   uint32_t ack; FIXME
3279
3280   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   selecting message\n");
3281   for (q = peer->queue_head; NULL != q; q = q->next)
3282   {
3283 //     t = q->tunnel;
3284     info = q->cls;
3285     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3286                 "*********     %s\n",
3287                 GNUNET_MESH_DEBUG_M2S(q->type));
3288     switch (q->type)
3289     {
3290       case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
3291 //         ucast = (struct GNUNET_MESH_Unicast *) info->mesh_data->data;
3292 //         pid = ntohl (ucast->pid);
3293         GNUNET_PEER_resolve (info->peer->id, &id);
3294 //         ack = cinfo->fwd_ack;
3295         break;
3296       case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
3297 //         to_orig = (struct GNUNET_MESH_ToOrigin *) info->mesh_data->data;
3298 //         pid = ntohl (to_orig->pid);
3299 //         ack = t->bck_ack;
3300         break;
3301       default:
3302         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3303                     "*********   OK!\n");
3304         return q;
3305     }
3306 //     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3307 //                 "*********     ACK: %u, PID: %u\n",
3308 //                 ack, pid);
3309 //     if (GNUNET_NO == GMC_is_pid_bigger(pid, ack))
3310 //     {
3311 //       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3312 //                   "*********   OK!\n");
3313 //       return q;
3314 //     }
3315 //     else
3316 //     {
3317 //       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3318 //                   "*********     NEXT!\n");
3319 //     }
3320   }
3321   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3322                 "*********   nothing found\n");
3323   return NULL;
3324 }
3325
3326
3327 static size_t
3328 queue_send (void *cls, size_t size, void *buf)
3329 {
3330     struct MeshPeerInfo *peer = cls;
3331     struct GNUNET_MessageHeader *msg;
3332     struct MeshPeerQueue *queue;
3333     struct MeshTunnel *t;
3334     struct GNUNET_PeerIdentity dst_id;
3335     struct MeshFlowControl *fc;
3336     size_t data_size;
3337
3338     peer->core_transmit = NULL;
3339
3340     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "********* Queue send\n");
3341     queue = queue_get_next (peer);
3342
3343     /* Queue has no internal mesh traffic nor sendable payload */
3344     if (NULL == queue)
3345     {
3346       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   not ready, return\n");
3347       if (NULL == peer->queue_head)
3348         GNUNET_break (0); /* Core tmt_rdy should've been canceled */
3349       return 0;
3350     }
3351     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   not empty\n");
3352
3353     GNUNET_PEER_resolve (peer->id, &dst_id);
3354     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3355                 "*********   towards %s\n",
3356                 GNUNET_i2s(&dst_id));
3357     /* Check if buffer size is enough for the message */
3358     if (queue->size > size)
3359     {
3360         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3361                     "*********   not enough room, reissue\n");
3362         peer->core_transmit =
3363             GNUNET_CORE_notify_transmit_ready (core_handle,
3364                                                0,
3365                                                0,
3366                                                GNUNET_TIME_UNIT_FOREVER_REL,
3367                                                &dst_id,
3368                                                queue->size,
3369                                                &queue_send,
3370                                                peer);
3371         return 0;
3372     }
3373     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   size ok\n");
3374
3375     t = queue->tunnel;
3376     GNUNET_assert (0 < t->pending_messages);
3377     t->pending_messages--;
3378     if (GNUNET_MESSAGE_TYPE_MESH_UNICAST == queue->type)
3379     {
3380       t->next_fc.queue_n--;
3381       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3382                   "*********   unicast: t->q (%u/%u)\n",
3383                   t->next_fc.queue_n, t->queue_max);
3384     }
3385     else if (GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN == queue->type)
3386     {
3387       t->prev_fc.queue_n--;
3388       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3389                   "*********   to orig: t->q (%u/%u)\n",
3390                   t->prev_fc.queue_n, t->queue_max);
3391     }
3392
3393     /* Fill buf */
3394     switch (queue->type)
3395     {
3396       case 0:
3397       case GNUNET_MESSAGE_TYPE_MESH_ACK:
3398       case GNUNET_MESSAGE_TYPE_MESH_POLL:
3399       case GNUNET_MESSAGE_TYPE_MESH_PATH_BROKEN:
3400       case GNUNET_MESSAGE_TYPE_MESH_PATH_DESTROY:
3401       case GNUNET_MESSAGE_TYPE_MESH_TUNNEL_DESTROY:
3402       case GNUNET_MESSAGE_TYPE_MESH_PATH_KEEPALIVE:
3403         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3404                     "*********   raw: %s\n",
3405                     GNUNET_MESH_DEBUG_M2S (queue->type));
3406         /* Fall through */
3407       case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
3408       case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
3409         data_size = send_core_data_raw (queue->cls, size, buf);
3410         msg = (struct GNUNET_MessageHeader *) buf;
3411         switch (ntohs (msg->type)) // Type of preconstructed message
3412         {
3413           case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
3414             tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_UNICAST);
3415             break;
3416           case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
3417             tunnel_send_bck_ack (t, GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN);
3418             break;
3419           default:
3420               break;
3421         }
3422         break;
3423       case GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE:
3424         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   path create\n");
3425         data_size = send_core_path_create (queue->cls, size, buf);
3426         break;
3427       case GNUNET_MESSAGE_TYPE_MESH_PATH_ACK:
3428         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   path ack\n");
3429         data_size = send_core_path_ack (queue->cls, size, buf);
3430         break;
3431       default:
3432         GNUNET_break (0);
3433         GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3434                     "*********   type unknown: %u\n",
3435                     queue->type);
3436         data_size = 0;
3437     }
3438     switch (queue->type)
3439     {
3440       case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
3441       case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
3442 //         if (cinfo->send_buffer[cinfo->send_buffer_start] != queue)
3443 //         { FIXME
3444 //           GNUNET_break (0);
3445 //           GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3446 //                       "at pos %u (%p) != %p\n",
3447 //                       cinfo->send_buffer_start,
3448 //                       cinfo->send_buffer[cinfo->send_buffer_start],
3449 //                       queue);
3450 //         }
3451 //         if (cinfo->send_buffer_n > 0)
3452 //         {
3453 //           cinfo->send_buffer[cinfo->send_buffer_start] = NULL;
3454 //           cinfo->send_buffer_n--;
3455 //           cinfo->send_buffer_start++;
3456 //           cinfo->send_buffer_start %= t->fwd_queue_max;
3457 //         }
3458 //         else
3459 //         {
3460 //           GNUNET_break (0);
3461 //         }
3462         break;
3463       default:
3464         break;
3465     }
3466
3467     /* Free queue, but cls was freed by send_core_* */
3468     queue_destroy (queue, GNUNET_NO);
3469
3470     if (GNUNET_YES == t->destroy && 0 == t->pending_messages)
3471     {
3472       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********  destroying tunnel!\n");
3473       tunnel_destroy (t);
3474     }
3475
3476     /* If more data in queue, send next */
3477     queue = queue_get_next (peer);
3478     if (NULL != queue)
3479     {
3480         struct GNUNET_PeerIdentity id;
3481
3482         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   more data!\n");
3483         GNUNET_PEER_resolve (peer->id, &id);
3484         peer->core_transmit =
3485             GNUNET_CORE_notify_transmit_ready(core_handle,
3486                                               0,
3487                                               0,
3488                                               GNUNET_TIME_UNIT_FOREVER_REL,
3489                                               &id,
3490                                               queue->size,
3491                                               &queue_send,
3492                                               peer);
3493     }
3494     else
3495     {
3496       if (NULL != peer->queue_head)
3497       {
3498         GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3499                     "*********   %s stalled\n",
3500                     GNUNET_i2s(&my_full_id));
3501         if (peer->id == t->next_hop)
3502           fc = &t->next_fc;
3503         else
3504           fc = &t->prev_fc;
3505         if (GNUNET_SCHEDULER_NO_TASK == fc->poll_task)
3506         {
3507           fc->t = t;
3508           fc->poll_task = GNUNET_SCHEDULER_add_delayed (fc->poll_time,
3509                                                         &tunnel_poll, fc);
3510         }
3511       }
3512     }
3513     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   return %d\n", data_size);
3514     return data_size;
3515 }
3516
3517
3518 /**
3519  * @brief Queue and pass message to core when possible.
3520  * 
3521  * If type is payload (UNICAST, TO_ORIGIN) checks for queue status and
3522  * accounts for it. In case the queue is full, the message is dropped and
3523  * a break issued.
3524  * 
3525  * Otherwise, message is treated as internal and allowed to go regardless of 
3526  * queue status.
3527  *
3528  * @param cls Closure (@c type dependant). It will be used by queue_send to
3529  *            build the message to be sent if not already prebuilt.
3530  * @param type Type of the message, 0 for a raw message.
3531  * @param size Size of the message.
3532  * @param dst Neighbor to send message to.
3533  * @param t Tunnel this message belongs to.
3534  */
3535 static void
3536 queue_add (void *cls, uint16_t type, size_t size,
3537            struct MeshPeerInfo *dst, struct MeshTunnel *t)
3538 {
3539   struct MeshPeerQueue *queue;
3540   struct GNUNET_PeerIdentity id;
3541   unsigned int *n;
3542
3543   n = NULL;
3544   if (GNUNET_MESSAGE_TYPE_MESH_UNICAST == type)
3545   {
3546     n = &t->next_fc.queue_n;
3547   }
3548   else if (GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN == type)
3549   {
3550     n = &t->prev_fc.queue_n;
3551   }
3552   if (NULL != n)
3553   {
3554     if (*n >= t->queue_max)
3555     {
3556       GNUNET_break(0);
3557       GNUNET_STATISTICS_update(stats,
3558                                "# messages dropped (buffer full)",
3559                                1, GNUNET_NO);
3560       return; // Drop message
3561     }
3562     (*n)++;
3563   }
3564   queue = GNUNET_malloc (sizeof (struct MeshPeerQueue));
3565   queue->cls = cls;
3566   queue->type = type;
3567   queue->size = size;
3568   queue->peer = dst;
3569   queue->tunnel = t;
3570   GNUNET_CONTAINER_DLL_insert_tail (dst->queue_head, dst->queue_tail, queue);
3571   if (NULL == dst->core_transmit)
3572   {
3573     GNUNET_PEER_resolve (dst->id, &id);
3574     dst->core_transmit =
3575         GNUNET_CORE_notify_transmit_ready (core_handle,
3576                                            0,
3577                                            0,
3578                                            GNUNET_TIME_UNIT_FOREVER_REL,
3579                                            &id,
3580                                            size,
3581                                            &queue_send,
3582                                            dst);
3583   }
3584   t->pending_messages++;
3585 }
3586
3587
3588 /******************************************************************************/
3589 /********************      MESH NETWORK HANDLERS     **************************/
3590 /******************************************************************************/
3591
3592
3593 /**
3594  * Core handler for path creation
3595  *
3596  * @param cls closure
3597  * @param message message
3598  * @param peer peer identity this notification is about
3599  *
3600  * @return GNUNET_OK to keep the connection open,
3601  *         GNUNET_SYSERR to close it (signal serious error)
3602  */
3603 static int
3604 handle_mesh_path_create (void *cls, const struct GNUNET_PeerIdentity *peer,
3605                          const struct GNUNET_MessageHeader *message)
3606 {
3607   unsigned int own_pos;
3608   uint16_t size;
3609   uint16_t i;
3610   MESH_TunnelNumber tid;
3611   struct GNUNET_MESH_ManipulatePath *msg;
3612   struct GNUNET_PeerIdentity *pi;
3613   struct GNUNET_HashCode hash;
3614   struct MeshPeerPath *path;
3615   struct MeshPeerInfo *dest_peer_info;
3616   struct MeshPeerInfo *orig_peer_info;
3617   struct MeshTunnel *t;
3618
3619   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3620               "Received a path create msg [%s]\n",
3621               GNUNET_i2s (&my_full_id));
3622   size = ntohs (message->size);
3623   if (size < sizeof (struct GNUNET_MESH_ManipulatePath))
3624   {
3625     GNUNET_break_op (0);
3626     return GNUNET_OK;
3627   }
3628
3629   size -= sizeof (struct GNUNET_MESH_ManipulatePath);
3630   if (size % sizeof (struct GNUNET_PeerIdentity))
3631   {
3632     GNUNET_break_op (0);
3633     return GNUNET_OK;
3634   }
3635   size /= sizeof (struct GNUNET_PeerIdentity);
3636   if (size < 2)
3637   {
3638     GNUNET_break_op (0);
3639     return GNUNET_OK;
3640   }
3641   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "    path has %u hops.\n", size);
3642   msg = (struct GNUNET_MESH_ManipulatePath *) message;
3643
3644   tid = ntohl (msg->tid);
3645   pi = (struct GNUNET_PeerIdentity *) &msg[1];
3646   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3647               "    path is for tunnel %s [%X].\n", GNUNET_i2s (pi), tid);
3648   t = tunnel_get (pi, tid);
3649   if (NULL == t) // FIXME only for INCOMING tunnels?
3650   {
3651     uint32_t opt;
3652
3653     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Creating tunnel\n");
3654     t = tunnel_new (GNUNET_PEER_intern (pi), tid, NULL, 0);
3655     if (NULL == t)
3656     {
3657       // FIXME notify failure
3658       return GNUNET_OK;
3659     }
3660     opt = ntohl (msg->opt);
3661     if (0 != (opt & MESH_TUNNEL_OPT_NOBUFFER))
3662     {
3663       t->nobuffer = GNUNET_YES;
3664       t->prev_fc.last_ack_sent = t->prev_fc.last_pid_recv + 1;
3665     }
3666     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  nobuffer:%d\n", t->nobuffer);
3667
3668     if (GNUNET_YES == t->nobuffer)
3669     {
3670       t->queue_max = 1;
3671     }
3672
3673     // FIXME only assign a local tid if a local client is interested (on demand)
3674     while (NULL != tunnel_get_incoming (next_local_tid))
3675       next_local_tid = (next_local_tid + 1) | GNUNET_MESH_LOCAL_TUNNEL_ID_SERV;
3676     t->local_tid_dest = next_local_tid++;
3677     next_local_tid = next_local_tid | GNUNET_MESH_LOCAL_TUNNEL_ID_SERV;
3678     // FIXME end
3679
3680     tunnel_reset_timeout (t);
3681     GNUNET_CRYPTO_hash (&t->local_tid_dest, sizeof (MESH_TunnelNumber), &hash);
3682     if (GNUNET_OK !=
3683         GNUNET_CONTAINER_multihashmap_put (incoming_tunnels, &hash, t,
3684                                            GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
3685     {
3686       tunnel_destroy (t);
3687       GNUNET_break (0);
3688       return GNUNET_OK;
3689     }
3690   }
3691   dest_peer_info =
3692       GNUNET_CONTAINER_multihashmap_get (peers, &pi[size - 1].hashPubKey);
3693   if (NULL == dest_peer_info)
3694   {
3695     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3696                 "  Creating PeerInfo for destination.\n");
3697     dest_peer_info = GNUNET_malloc (sizeof (struct MeshPeerInfo));
3698     dest_peer_info->id = GNUNET_PEER_intern (&pi[size - 1]);
3699     GNUNET_CONTAINER_multihashmap_put (peers, &pi[size - 1].hashPubKey,
3700                                        dest_peer_info,
3701                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
3702   }
3703   orig_peer_info = GNUNET_CONTAINER_multihashmap_get (peers, &pi->hashPubKey);
3704   if (NULL == orig_peer_info)
3705   {
3706     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3707                 "  Creating PeerInfo for origin.\n");
3708     orig_peer_info = GNUNET_malloc (sizeof (struct MeshPeerInfo));
3709     orig_peer_info->id = GNUNET_PEER_intern (pi);
3710     GNUNET_CONTAINER_multihashmap_put (peers, &pi->hashPubKey, orig_peer_info,
3711                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
3712   }
3713   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Creating path...\n");
3714   path = path_new (size);
3715   own_pos = 0;
3716   for (i = 0; i < size; i++)
3717   {
3718     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  ... adding %s\n",
3719                 GNUNET_i2s (&pi[i]));
3720     path->peers[i] = GNUNET_PEER_intern (&pi[i]);
3721     if (path->peers[i] == myid)
3722       own_pos = i;
3723   }
3724   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Own position: %u\n", own_pos);
3725   if (own_pos == 0)
3726   {
3727     /* cannot be self, must be 'not found' */
3728     /* create path: self not found in path through self */
3729     GNUNET_break_op (0);
3730     path_destroy (path);
3731     tunnel_destroy (t);
3732     return GNUNET_OK;
3733   }
3734   path_add_to_peers (path, GNUNET_NO);
3735   t->prev_hop = path->peers[own_pos - 1];
3736   GNUNET_PEER_change_rc (t->prev_hop, 1);
3737   if (own_pos == size - 1)
3738   {
3739     /* It is for us! Send ack. */
3740     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  It's for us!\n");
3741     peer_info_add_path_to_origin (orig_peer_info, path, GNUNET_NO);
3742     t->dest = myid;
3743     send_path_ack (t);
3744   }
3745   else
3746   {
3747     struct MeshPeerPath *path2;
3748
3749     t->next_hop = path->peers[own_pos + 1];
3750     GNUNET_PEER_change_rc(t->next_hop, 1);
3751
3752     /* It's for somebody else! Retransmit. */
3753     path2 = path_duplicate (path);
3754     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Retransmitting.\n");
3755     peer_info_add_path (dest_peer_info, path2, GNUNET_NO);
3756     path2 = path_duplicate (path);
3757     peer_info_add_path_to_origin (orig_peer_info, path2, GNUNET_NO);
3758     send_create_path (dest_peer_info, path, t);
3759   }
3760   return GNUNET_OK;
3761 }
3762
3763
3764 /**
3765  * Core handler for path destruction
3766  *
3767  * @param cls closure
3768  * @param message message
3769  * @param peer peer identity this notification is about
3770  *
3771  * @return GNUNET_OK to keep the connection open,
3772  *         GNUNET_SYSERR to close it (signal serious error)
3773  */
3774 static int
3775 handle_mesh_path_destroy (void *cls, const struct GNUNET_PeerIdentity *peer,
3776                           const struct GNUNET_MessageHeader *message)
3777 {
3778   struct GNUNET_MESH_ManipulatePath *msg;
3779   struct GNUNET_PeerIdentity *pi;
3780   struct MeshPeerPath *path;
3781   struct MeshTunnel *t;
3782   unsigned int own_pos;
3783   unsigned int i;
3784   size_t size;
3785
3786   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3787               "Received a PATH DESTROY msg from %s\n", GNUNET_i2s (peer));
3788   size = ntohs (message->size);
3789   if (size < sizeof (struct GNUNET_MESH_ManipulatePath))
3790   {
3791     GNUNET_break_op (0);
3792     return GNUNET_OK;
3793   }
3794
3795   size -= sizeof (struct GNUNET_MESH_ManipulatePath);
3796   if (size % sizeof (struct GNUNET_PeerIdentity))
3797   {
3798     GNUNET_break_op (0);
3799     return GNUNET_OK;
3800   }
3801   size /= sizeof (struct GNUNET_PeerIdentity);
3802   if (size < 2)
3803   {
3804     GNUNET_break_op (0);
3805     return GNUNET_OK;
3806   }
3807   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "    path has %u hops.\n", size);
3808
3809   msg = (struct GNUNET_MESH_ManipulatePath *) message;
3810   pi = (struct GNUNET_PeerIdentity *) &msg[1];
3811   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3812               "    path is for tunnel %s [%X].\n", GNUNET_i2s (pi),
3813               msg->tid);
3814   t = tunnel_get (pi, ntohl (msg->tid));
3815   if (NULL == t)
3816   {
3817     /* TODO notify back: we don't know this tunnel */
3818     GNUNET_break_op (0);
3819     return GNUNET_OK;
3820   }
3821   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Creating path...\n");
3822   path = path_new (size);
3823   own_pos = 0;
3824   for (i = 0; i < size; i++)
3825   {
3826     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  ... adding %s\n",
3827                 GNUNET_i2s (&pi[i]));
3828     path->peers[i] = GNUNET_PEER_intern (&pi[i]);
3829     if (path->peers[i] == myid)
3830       own_pos = i;
3831   }
3832   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Own position: %u\n", own_pos);
3833   if (own_pos < path->length - 1)
3834     send_prebuilt_message (message, path->peers[own_pos + 1], t);
3835   else
3836     send_client_tunnel_disconnect(t, NULL);
3837
3838 //   tunnel_delete_peer (t, path->peers[path->length - 1]); FIXME
3839   path_destroy (path);
3840   return GNUNET_OK;
3841 }
3842
3843
3844 /**
3845  * Core handler for notifications of broken paths
3846  *
3847  * @param cls closure
3848  * @param message message
3849  * @param peer peer identity this notification is about
3850  *
3851  * @return GNUNET_OK to keep the connection open,
3852  *         GNUNET_SYSERR to close it (signal serious error)
3853  */
3854 static int
3855 handle_mesh_path_broken (void *cls, const struct GNUNET_PeerIdentity *peer,
3856                          const struct GNUNET_MessageHeader *message)
3857 {
3858   struct GNUNET_MESH_PathBroken *msg;
3859   struct MeshTunnel *t;
3860
3861   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3862               "Received a PATH BROKEN msg from %s\n", GNUNET_i2s (peer));
3863   msg = (struct GNUNET_MESH_PathBroken *) message;
3864   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  regarding %s\n",
3865               GNUNET_i2s (&msg->peer1));
3866   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  regarding %s\n",
3867               GNUNET_i2s (&msg->peer2));
3868   t = tunnel_get (&msg->oid, ntohl (msg->tid));
3869   if (NULL == t)
3870   {
3871     GNUNET_break_op (0);
3872     return GNUNET_OK;
3873   }
3874   tunnel_notify_connection_broken (t, GNUNET_PEER_search (&msg->peer1),
3875                                    GNUNET_PEER_search (&msg->peer2));
3876   return GNUNET_OK;
3877
3878 }
3879
3880
3881 /**
3882  * Core handler for tunnel destruction
3883  *
3884  * @param cls closure
3885  * @param message message
3886  * @param peer peer identity this notification is about
3887  *
3888  * @return GNUNET_OK to keep the connection open,
3889  *         GNUNET_SYSERR to close it (signal serious error)
3890  */
3891 static int
3892 handle_mesh_tunnel_destroy (void *cls, const struct GNUNET_PeerIdentity *peer,
3893                             const struct GNUNET_MessageHeader *message)
3894 {
3895   struct GNUNET_MESH_TunnelDestroy *msg;
3896   struct MeshTunnel *t;
3897   GNUNET_PEER_Id pid;
3898
3899   msg = (struct GNUNET_MESH_TunnelDestroy *) message;
3900   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3901               "Got a TUNNEL DESTROY packet from %s\n",
3902               GNUNET_i2s (peer));
3903   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3904               "  for tunnel %s [%u]\n",
3905               GNUNET_i2s (&msg->oid), ntohl (msg->tid));
3906   t = tunnel_get (&msg->oid, ntohl (msg->tid));
3907   /* Check signature */
3908   if (NULL == t)
3909   {
3910     /* Probably already got the message from another path,
3911      * destroyed the tunnel and retransmitted to children.
3912      * Safe to ignore.
3913      */
3914     GNUNET_STATISTICS_update (stats, "# control on unknown tunnel",
3915                               1, GNUNET_NO);
3916     return GNUNET_OK;
3917   }
3918   pid = GNUNET_PEER_search (peer);
3919   if (pid != t->prev_hop && 0 < t->nclients)
3920   {
3921     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3922                 "still in use by %u clients\n",
3923                 t->nclients);
3924     return GNUNET_OK;
3925   }
3926   if (t->local_tid_dest >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
3927   {
3928     /* Tunnel was incoming, notify clients */
3929     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "INCOMING TUNNEL %X %X\n",
3930                 t->local_tid, t->local_tid_dest);
3931     send_clients_tunnel_destroy (t);
3932   }
3933   tunnel_send_destroy (t);
3934   t->destroy = GNUNET_YES;
3935   // TODO: add timeout to destroy the tunnel anyway
3936   return GNUNET_OK;
3937 }
3938
3939
3940 /**
3941  * Core handler for mesh network traffic going from the origin to a peer
3942  *
3943  * @param cls closure
3944  * @param peer peer identity this notification is about
3945  * @param message message
3946  * @return GNUNET_OK to keep the connection open,
3947  *         GNUNET_SYSERR to close it (signal serious error)
3948  */
3949 static int
3950 handle_mesh_data_unicast (void *cls, const struct GNUNET_PeerIdentity *peer,
3951                           const struct GNUNET_MessageHeader *message)
3952 {
3953   struct GNUNET_MESH_Unicast *msg;
3954   struct MeshTunnel *t;
3955   uint32_t pid;
3956   uint32_t ttl;
3957   size_t size;
3958
3959   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a unicast packet from %s\n",
3960               GNUNET_i2s (peer));
3961   /* Check size */
3962   size = ntohs (message->size);
3963   if (size <
3964       sizeof (struct GNUNET_MESH_Unicast) +
3965       sizeof (struct GNUNET_MessageHeader))
3966   {
3967     GNUNET_break (0);
3968     return GNUNET_OK;
3969   }
3970   msg = (struct GNUNET_MESH_Unicast *) message;
3971   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " of type %s\n",
3972               GNUNET_MESH_DEBUG_M2S (ntohs (msg[1].header.type)));
3973   /* Check tunnel */
3974   t = tunnel_get (&msg->oid, ntohl (msg->tid));
3975   if (NULL == t)
3976   {
3977     /* TODO notify back: we don't know this tunnel */
3978     GNUNET_STATISTICS_update (stats, "# data on unknown tunnel", 1, GNUNET_NO);
3979     GNUNET_break_op (0);
3980     return GNUNET_OK;
3981   }
3982   pid = ntohl (msg->pid);
3983   if (t->prev_fc.last_pid_recv == pid)
3984   {
3985     GNUNET_STATISTICS_update (stats, "# duplicate PID drops", 1, GNUNET_NO);
3986     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3987                 " Already seen pid %u, DROPPING!\n", pid);
3988     return GNUNET_OK;
3989   }
3990   else
3991   {
3992     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3993                 " pid %u not seen yet, forwarding\n", pid);
3994   }
3995
3996   t->prev_fc.last_pid_recv = pid;
3997
3998   if (GMC_is_pid_bigger (pid, t->prev_fc.last_ack_sent))
3999   {
4000     GNUNET_STATISTICS_update (stats, "# unsolicited unicast", 1, GNUNET_NO);
4001     GNUNET_break_op (0);
4002     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4003                 "Received PID %u, ACK %u\n",
4004                 pid, t->prev_fc.last_ack_sent);
4005     return GNUNET_OK;
4006   }
4007
4008   tunnel_reset_timeout (t);
4009   if (t->dest == myid)
4010   {
4011     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4012                 "  it's for us! sending to clients...\n");
4013     GNUNET_STATISTICS_update (stats, "# unicast received", 1, GNUNET_NO);
4014     send_subscribed_clients (message, &msg[1].header, t);
4015     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_UNICAST);
4016     return GNUNET_OK;
4017   }
4018   ttl = ntohl (msg->ttl);
4019   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   ttl: %u\n", ttl);
4020   if (ttl == 0)
4021   {
4022     GNUNET_STATISTICS_update (stats, "# TTL drops", 1, GNUNET_NO);
4023     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, " TTL is 0, DROPPING!\n");
4024     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_ACK);
4025     return GNUNET_OK;
4026   }
4027   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4028               "  not for us, retransmitting...\n");
4029
4030   if (GNUNET_YES == t->nobuffer &&
4031       GNUNET_YES == GMC_is_pid_bigger (pid, t->next_fc.last_ack_recv))
4032   {
4033     GNUNET_STATISTICS_update (stats, "# unsolicited unicast", 1, GNUNET_NO);
4034     GNUNET_log (GNUNET_ERROR_TYPE_INFO, "  %u > %u\n",
4035                 pid, t->next_fc.last_ack_recv);
4036     GNUNET_break_op (0);
4037     return GNUNET_OK;
4038   }
4039   send_prebuilt_message (message, t->next_hop, t);
4040   GNUNET_STATISTICS_update (stats, "# unicast forwarded", 1, GNUNET_NO);
4041   return GNUNET_OK;
4042 }
4043
4044
4045 /**
4046  * Core handler for mesh network traffic toward the owner of a tunnel
4047  *
4048  * @param cls closure
4049  * @param message message
4050  * @param peer peer identity this notification is about
4051  *
4052  * @return GNUNET_OK to keep the connection open,
4053  *         GNUNET_SYSERR to close it (signal serious error)
4054  */
4055 static int
4056 handle_mesh_data_to_orig (void *cls, const struct GNUNET_PeerIdentity *peer,
4057                           const struct GNUNET_MessageHeader *message)
4058 {
4059   struct GNUNET_MESH_ToOrigin *msg;
4060   struct MeshPeerInfo *peer_info;
4061   struct MeshTunnel *t;
4062   size_t size;
4063   uint32_t pid;
4064
4065   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a ToOrigin packet from %s\n",
4066               GNUNET_i2s (peer));
4067   size = ntohs (message->size);
4068   if (size < sizeof (struct GNUNET_MESH_ToOrigin) +     /* Payload must be */
4069       sizeof (struct GNUNET_MessageHeader))     /* at least a header */
4070   {
4071     GNUNET_break_op (0);
4072     return GNUNET_OK;
4073   }
4074   msg = (struct GNUNET_MESH_ToOrigin *) message;
4075   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " of type %s\n",
4076               GNUNET_MESH_DEBUG_M2S (ntohs (msg[1].header.type)));
4077   t = tunnel_get (&msg->oid, ntohl (msg->tid));
4078   pid = ntohl (msg->pid);
4079
4080   if (NULL == t)
4081   {
4082     /* TODO notify that we dont know this tunnel (whom)? */
4083     GNUNET_STATISTICS_update (stats, "# data on unknown tunnel", 1, GNUNET_NO);
4084     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4085                 "Received to_origin with PID %u on unknown tunnel %s [%u]\n",
4086                 pid, GNUNET_i2s (&msg->oid), ntohl (msg->tid));
4087     return GNUNET_OK;
4088   }
4089
4090
4091   if (t->next_fc.last_pid_recv == pid)
4092   {
4093     /* already seen this packet, drop */
4094     GNUNET_STATISTICS_update (stats, "# duplicate PID drops BCK", 1, GNUNET_NO);
4095     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4096                 " Already seen pid %u, DROPPING!\n", pid);
4097     tunnel_send_bck_ack (t, GNUNET_MESSAGE_TYPE_MESH_ACK);
4098     return GNUNET_OK;
4099   }
4100
4101   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4102               " pid %u not seen yet, forwarding\n", pid);
4103   t->next_fc.last_pid_recv = pid;
4104
4105   if (NULL != t->owner)
4106   {
4107     char cbuf[size];
4108     struct GNUNET_MESH_ToOrigin *copy;
4109
4110     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4111                 "  it's for us! sending to clients...\n");
4112     /* TODO signature verification */
4113     memcpy (cbuf, message, size);
4114     copy = (struct GNUNET_MESH_ToOrigin *) cbuf;
4115     copy->tid = htonl (t->local_tid);
4116     GNUNET_STATISTICS_update (stats, "# to origin received", 1, GNUNET_NO);
4117     GNUNET_SERVER_notification_context_unicast (nc, t->owner->handle,
4118                                                 &copy->header, GNUNET_NO);
4119     tunnel_send_bck_ack (t, GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN);
4120     return GNUNET_OK;
4121   }
4122   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4123               "  not for us, retransmitting...\n");
4124
4125   peer_info = peer_get (&msg->oid);
4126   if (NULL == peer_info)
4127   {
4128     /* unknown origin of tunnel */
4129     GNUNET_break (0);
4130     return GNUNET_OK;
4131   }
4132   if (0 == t->prev_hop) /* No owner AND no prev hop */
4133   {
4134     if (GNUNET_YES == t->destroy)
4135     {
4136       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4137                   "to orig received on a dying tunnel %s [%X]\n",
4138                   GNUNET_i2s (&msg->oid), ntohl(msg->tid));
4139       return GNUNET_OK;
4140     }
4141     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, 
4142                 "unknown to origin at %s\n",
4143                 GNUNET_i2s (&my_full_id));
4144     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, 
4145                 "from peer %s\n",
4146                 GNUNET_i2s (peer));
4147     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, 
4148                 "for tunnel %s [%X]\n",
4149                 GNUNET_i2s (&msg->oid), ntohl(msg->tid));
4150     return GNUNET_OK;
4151   }
4152   send_prebuilt_message (message, t->prev_hop, t);
4153   GNUNET_STATISTICS_update (stats, "# to origin forwarded", 1, GNUNET_NO);
4154
4155   return GNUNET_OK;
4156 }
4157
4158
4159 /**
4160  * Core handler for mesh network traffic point-to-point acks.
4161  *
4162  * @param cls closure
4163  * @param message message
4164  * @param peer peer identity this notification is about
4165  *
4166  * @return GNUNET_OK to keep the connection open,
4167  *         GNUNET_SYSERR to close it (signal serious error)
4168  */
4169 static int
4170 handle_mesh_ack (void *cls, const struct GNUNET_PeerIdentity *peer,
4171                  const struct GNUNET_MessageHeader *message)
4172 {
4173   struct GNUNET_MESH_ACK *msg;
4174   struct MeshTunnel *t;
4175   uint32_t ack;
4176
4177   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got an ACK packet from %s!\n",
4178               GNUNET_i2s (peer));
4179   msg = (struct GNUNET_MESH_ACK *) message;
4180
4181   t = tunnel_get (&msg->oid, ntohl (msg->tid));
4182
4183   if (NULL == t)
4184   {
4185     /* TODO notify that we dont know this tunnel (whom)? */
4186     GNUNET_STATISTICS_update (stats, "# ack on unknown tunnel", 1, GNUNET_NO);
4187     return GNUNET_OK;
4188   }
4189   ack = ntohl (msg->pid);
4190   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  ACK %u\n", ack);
4191
4192   /* Is this a forward or backward ACK? */
4193   if (t->prev_hop != GNUNET_PEER_search (peer))
4194   {
4195     debug_bck_ack++;
4196     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  FWD ACK\n");
4197     if (GNUNET_SCHEDULER_NO_TASK != t->next_fc.poll_task &&
4198         GMC_is_pid_bigger (ack, t->next_fc.last_ack_recv))
4199     {
4200       GNUNET_SCHEDULER_cancel (t->next_fc.poll_task);
4201       t->next_fc.poll_task = GNUNET_SCHEDULER_NO_TASK;
4202       t->next_fc.poll_time = GNUNET_TIME_UNIT_SECONDS;
4203     }
4204     t->next_fc.last_ack_recv = ack;
4205     peer_unlock_queue (t->next_hop);
4206     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_ACK);
4207   }
4208   else
4209   {
4210     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  BCK ACK\n");
4211     if (GNUNET_SCHEDULER_NO_TASK != t->prev_fc.poll_task &&
4212         GMC_is_pid_bigger (ack, t->prev_fc.last_ack_recv))
4213     {
4214       GNUNET_SCHEDULER_cancel (t->prev_fc.poll_task);
4215       t->prev_fc.poll_task = GNUNET_SCHEDULER_NO_TASK;
4216       t->prev_fc.poll_time = GNUNET_TIME_UNIT_SECONDS;
4217     }
4218     t->prev_fc.last_ack_recv = ack;
4219     peer_unlock_queue (t->prev_hop);
4220     tunnel_send_bck_ack (t, GNUNET_MESSAGE_TYPE_MESH_ACK);
4221   }
4222   return GNUNET_OK;
4223 }
4224
4225
4226 /**
4227  * Core handler for mesh network traffic point-to-point ack polls.
4228  *
4229  * @param cls closure
4230  * @param message message
4231  * @param peer peer identity this notification is about
4232  *
4233  * @return GNUNET_OK to keep the connection open,
4234  *         GNUNET_SYSERR to close it (signal serious error)
4235  */
4236 static int
4237 handle_mesh_poll (void *cls, const struct GNUNET_PeerIdentity *peer,
4238                   const struct GNUNET_MessageHeader *message)
4239 {
4240   struct GNUNET_MESH_Poll *msg;
4241   struct MeshTunnel *t;
4242
4243   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got an POLL packet from %s!\n",
4244               GNUNET_i2s (peer));
4245
4246   msg = (struct GNUNET_MESH_Poll *) message;
4247
4248   t = tunnel_get (&msg->oid, ntohl (msg->tid));
4249
4250   if (NULL == t)
4251   {
4252     /* TODO notify that we dont know this tunnel (whom)? */
4253     GNUNET_STATISTICS_update (stats, "# poll on unknown tunnel", 1, GNUNET_NO);
4254     GNUNET_break_op (0);
4255     return GNUNET_OK;
4256   }
4257
4258   /* Is this a forward or backward ACK? */
4259   if (t->prev_hop != GNUNET_PEER_search(peer))
4260   {
4261     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  from FWD\n");
4262     /* FIXME cinfo->bck_ack = cinfo->fwd_pid; // mark as ready to send */
4263     tunnel_send_bck_ack (t, GNUNET_MESSAGE_TYPE_MESH_POLL);
4264   }
4265   else
4266   {
4267     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  from BCK\n");
4268     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_POLL);
4269   }
4270
4271   return GNUNET_OK;
4272 }
4273
4274 /**
4275  * Core handler for path ACKs
4276  *
4277  * @param cls closure
4278  * @param message message
4279  * @param peer peer identity this notification is about
4280  *
4281  * @return GNUNET_OK to keep the connection open,
4282  *         GNUNET_SYSERR to close it (signal serious error)
4283  */
4284 static int
4285 handle_mesh_path_ack (void *cls, const struct GNUNET_PeerIdentity *peer,
4286                       const struct GNUNET_MessageHeader *message)
4287 {
4288   struct GNUNET_MESH_PathACK *msg;
4289   struct MeshPeerInfo *peer_info;
4290   struct MeshPeerPath *p;
4291   struct MeshTunnel *t;
4292
4293   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received a path ACK msg [%s]\n",
4294               GNUNET_i2s (&my_full_id));
4295   msg = (struct GNUNET_MESH_PathACK *) message;
4296   t = tunnel_get (&msg->oid, ntohl(msg->tid));
4297   if (NULL == t)
4298   {
4299     /* TODO notify that we don't know the tunnel */
4300     GNUNET_STATISTICS_update (stats, "# control on unknown tunnel", 1, GNUNET_NO);
4301     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  don't know the tunnel %s [%X]!\n",
4302                 GNUNET_i2s (&msg->oid), ntohl(msg->tid));
4303     return GNUNET_OK;
4304   }
4305   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %s [%X]\n",
4306               GNUNET_i2s (&msg->oid), ntohl(msg->tid));
4307
4308   peer_info = peer_get (&msg->peer_id);
4309   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by peer %s\n",
4310               GNUNET_i2s (&msg->peer_id));
4311   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  via peer %s\n",
4312               GNUNET_i2s (peer));
4313
4314   /* Add path to peers? */
4315   p = t->path;
4316   if (NULL != p)
4317   {
4318     path_add_to_peers (p, GNUNET_YES);
4319   }
4320   else
4321   {
4322     GNUNET_break (0);
4323   }
4324
4325   /* Message for us? */
4326   if (0 == memcmp (&msg->oid, &my_full_id, sizeof (struct GNUNET_PeerIdentity)))
4327   {
4328     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  It's for us!\n");
4329     if (NULL == t->owner)
4330     {
4331       GNUNET_break_op (0);
4332       return GNUNET_OK;
4333     }
4334     if (NULL != peer_info->dhtget)
4335     {
4336       GNUNET_DHT_get_stop (peer_info->dhtget);
4337       peer_info->dhtget = NULL;
4338     }
4339     return GNUNET_OK;
4340   }
4341
4342   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4343               "  not for us, retransmitting...\n");
4344   peer_info = peer_get (&msg->oid);
4345   send_prebuilt_message (message, t->prev_hop, t);
4346   return GNUNET_OK;
4347 }
4348
4349
4350 /**
4351  * Core handler for mesh keepalives.
4352  *
4353  * @param cls closure
4354  * @param message message
4355  * @param peer peer identity this notification is about
4356  * @return GNUNET_OK to keep the connection open,
4357  *         GNUNET_SYSERR to close it (signal serious error)
4358  *
4359  * TODO: Check who we got this from, to validate route.
4360  */
4361 static int
4362 handle_mesh_keepalive (void *cls, const struct GNUNET_PeerIdentity *peer,
4363                        const struct GNUNET_MessageHeader *message)
4364 {
4365   struct GNUNET_MESH_TunnelKeepAlive *msg;
4366   struct MeshTunnel *t;
4367
4368   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a keepalive packet from %s\n",
4369               GNUNET_i2s (peer));
4370
4371   msg = (struct GNUNET_MESH_TunnelKeepAlive *) message;
4372   t = tunnel_get (&msg->oid, ntohl (msg->tid));
4373
4374   if (NULL == t)
4375   {
4376     /* TODO notify that we dont know that tunnel */
4377     GNUNET_STATISTICS_update (stats, "# keepalive on unknown tunnel", 1,
4378                               GNUNET_NO);
4379     return GNUNET_OK;
4380   }
4381
4382   tunnel_reset_timeout (t);
4383
4384   GNUNET_STATISTICS_update (stats, "# keepalives forwarded", 1, GNUNET_NO);
4385   send_prebuilt_message (message, t->next_hop, t);
4386   return GNUNET_OK;
4387   }
4388
4389
4390
4391 /**
4392  * Functions to handle messages from core
4393  */
4394 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
4395   {&handle_mesh_path_create, GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE, 0},
4396   {&handle_mesh_path_destroy, GNUNET_MESSAGE_TYPE_MESH_PATH_DESTROY, 0},
4397   {&handle_mesh_path_broken, GNUNET_MESSAGE_TYPE_MESH_PATH_BROKEN,
4398    sizeof (struct GNUNET_MESH_PathBroken)},
4399   {&handle_mesh_tunnel_destroy, GNUNET_MESSAGE_TYPE_MESH_TUNNEL_DESTROY,
4400    sizeof (struct GNUNET_MESH_TunnelDestroy)},
4401   {&handle_mesh_data_unicast, GNUNET_MESSAGE_TYPE_MESH_UNICAST, 0},
4402   {&handle_mesh_keepalive, GNUNET_MESSAGE_TYPE_MESH_PATH_KEEPALIVE,
4403     sizeof (struct GNUNET_MESH_TunnelKeepAlive)},
4404   {&handle_mesh_data_to_orig, GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN, 0},
4405   {&handle_mesh_ack, GNUNET_MESSAGE_TYPE_MESH_ACK,
4406     sizeof (struct GNUNET_MESH_ACK)},
4407   {&handle_mesh_poll, GNUNET_MESSAGE_TYPE_MESH_POLL,
4408     sizeof (struct GNUNET_MESH_Poll)},
4409   {&handle_mesh_path_ack, GNUNET_MESSAGE_TYPE_MESH_PATH_ACK,
4410    sizeof (struct GNUNET_MESH_PathACK)},
4411   {NULL, 0, 0}
4412 };
4413
4414
4415
4416 /******************************************************************************/
4417 /****************       MESH LOCAL HANDLER HELPERS      ***********************/
4418 /******************************************************************************/
4419
4420
4421 #if LATER
4422 /**
4423  * notify_client_connection_failure: notify a client that the connection to the
4424  * requested remote peer is not possible (for instance, no route found)
4425  * Function called when the socket is ready to queue more data. "buf" will be
4426  * NULL and "size" zero if the socket was closed for writing in the meantime.
4427  *
4428  * @param cls closure
4429  * @param size number of bytes available in buf
4430  * @param buf where the callee should write the message
4431  * @return number of bytes written to buf
4432  */
4433 static size_t
4434 notify_client_connection_failure (void *cls, size_t size, void *buf)
4435 {
4436   int size_needed;
4437   struct MeshPeerInfo *peer_info;
4438   struct GNUNET_MESH_PeerControl *msg;
4439   struct GNUNET_PeerIdentity id;
4440
4441   if (0 == size && NULL == buf)
4442   {
4443     // TODO retry? cancel?
4444     return 0;
4445   }
4446
4447   size_needed = sizeof (struct GNUNET_MESH_PeerControl);
4448   peer_info = (struct MeshPeerInfo *) cls;
4449   msg = (struct GNUNET_MESH_PeerControl *) buf;
4450   msg->header.size = htons (sizeof (struct GNUNET_MESH_PeerControl));
4451   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_DISCONNECTED);
4452 //     msg->tunnel_id = htonl(peer_info->t->tid);
4453   GNUNET_PEER_resolve (peer_info->id, &id);
4454   memcpy (&msg->peer, &id, sizeof (struct GNUNET_PeerIdentity));
4455
4456   return size_needed;
4457 }
4458 #endif
4459
4460
4461 /**
4462  * Send keepalive packets for a tunnel.
4463  *
4464  * @param cls Closure (tunnel for which to send the keepalive).
4465  * @param tc Notification context.
4466  */
4467 static void
4468 path_refresh (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
4469 {
4470   struct MeshTunnel *t = cls;
4471   struct GNUNET_MESH_TunnelKeepAlive *msg;
4472   size_t size = sizeof (struct GNUNET_MESH_TunnelKeepAlive);
4473   char cbuf[size];
4474
4475   t->maintenance_task = GNUNET_SCHEDULER_NO_TASK;
4476   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) ||
4477       NULL == t->owner || 0 == t->local_tid || 0 != t->prev_hop)
4478   {
4479     return;
4480   }
4481
4482   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4483               "sending keepalive for tunnel %d\n", t->id.tid);
4484
4485   msg = (struct GNUNET_MESH_TunnelKeepAlive *) cbuf;
4486   msg->header.size = htons (size);
4487   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_KEEPALIVE);
4488   msg->oid = my_full_id;
4489   msg->tid = htonl (t->id.tid);
4490   send_prebuilt_message (&msg->header, t->next_hop, t);
4491
4492   t->maintenance_task =
4493       GNUNET_SCHEDULER_add_delayed (refresh_path_time, &path_refresh, t);
4494 }
4495
4496
4497 /**
4498  * Function to process paths received for a new peer addition. The recorded
4499  * paths form the initial tunnel, which can be optimized later.
4500  * Called on each result obtained for the DHT search.
4501  *
4502  * @param cls closure
4503  * @param exp when will this value expire
4504  * @param key key of the result
4505  * @param get_path path of the get request
4506  * @param get_path_length lenght of get_path
4507  * @param put_path path of the put request
4508  * @param put_path_length length of the put_path
4509  * @param type type of the result
4510  * @param size number of bytes in data
4511  * @param data pointer to the result data
4512  *
4513  * TODO: re-issue the request after certain time? cancel after X results?
4514  */
4515 static void
4516 dht_get_id_handler (void *cls, struct GNUNET_TIME_Absolute exp,
4517                     const struct GNUNET_HashCode * key,
4518                     const struct GNUNET_PeerIdentity *get_path,
4519                     unsigned int get_path_length,
4520                     const struct GNUNET_PeerIdentity *put_path,
4521                     unsigned int put_path_length, enum GNUNET_BLOCK_Type type,
4522                     size_t size, const void *data)
4523 {
4524   struct MeshPeerInfo *peer = cls;
4525   struct MeshPeerPath *p;
4526   struct GNUNET_PeerIdentity pi;
4527   int i;
4528
4529   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got results from DHT!\n");
4530   GNUNET_PEER_resolve (peer->id, &pi);
4531   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  for %s\n", GNUNET_i2s (&pi));
4532
4533   p = path_build_from_dht (get_path, get_path_length,
4534                            put_path, put_path_length);
4535   path_add_to_peers (p, GNUNET_NO);
4536   path_destroy (p);
4537   for (i = 0; i < peer->ntunnels; i++)
4538   {
4539     peer_connect (peer, peer->tunnels[i]); // FIXME add if
4540   }
4541
4542   return;
4543 }
4544
4545
4546 /******************************************************************************/
4547 /*********************       MESH LOCAL HANDLES      **************************/
4548 /******************************************************************************/
4549
4550
4551 /**
4552  * Handler for client disconnection
4553  *
4554  * @param cls closure
4555  * @param client identification of the client; NULL
4556  *        for the last call when the server is destroyed
4557  */
4558 static void
4559 handle_local_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
4560 {
4561   struct MeshClient *c;
4562   struct MeshClient *next;
4563
4564   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "client disconnected\n");
4565   if (client == NULL)
4566   {
4567     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   (SERVER DOWN)\n");
4568     return;
4569   }
4570
4571   c = clients_head;
4572   while (NULL != c)
4573   {
4574     if (c->handle != client)
4575     {
4576       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   ... searching\n");
4577       c = c->next;
4578       continue;
4579     }
4580     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "matching client found (%u)\n",
4581                 c->id);
4582     GNUNET_SERVER_client_drop (c->handle);
4583     c->shutting_down = GNUNET_YES;
4584     GNUNET_CONTAINER_multihashmap_iterate (c->own_tunnels,
4585                                            &tunnel_destroy_iterator, c);
4586     GNUNET_CONTAINER_multihashmap_iterate (c->incoming_tunnels,
4587                                            &tunnel_destroy_iterator, c);
4588     GNUNET_CONTAINER_multihashmap_iterate (c->ignore_tunnels,
4589                                            &tunnel_destroy_iterator, c);
4590     GNUNET_CONTAINER_multihashmap_destroy (c->own_tunnels);
4591     GNUNET_CONTAINER_multihashmap_destroy (c->incoming_tunnels);
4592     GNUNET_CONTAINER_multihashmap_destroy (c->ignore_tunnels);
4593
4594     if (NULL != c->types)
4595       GNUNET_CONTAINER_multihashmap_destroy (c->types);
4596     next = c->next;
4597     GNUNET_CONTAINER_DLL_remove (clients_head, clients_tail, c);
4598     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  CLIENT FREE at %p\n", c);
4599     GNUNET_free (c);
4600     GNUNET_STATISTICS_update (stats, "# clients", -1, GNUNET_NO);
4601     c = next;
4602   }
4603   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "done!\n");
4604   return;
4605 }
4606
4607
4608 /**
4609  * Handler for new clients
4610  *
4611  * @param cls closure
4612  * @param client identification of the client
4613  * @param message the actual message, which includes messages the client wants
4614  */
4615 static void
4616 handle_local_new_client (void *cls, struct GNUNET_SERVER_Client *client,
4617                          const struct GNUNET_MessageHeader *message)
4618 {
4619   struct GNUNET_MESH_ClientConnect *cc_msg;
4620   struct MeshClient *c;
4621   unsigned int size;
4622   uint16_t ntypes;
4623   uint16_t *t;
4624   uint16_t i;
4625
4626   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new client connected\n");
4627
4628   /* Check data sanity */
4629   size = ntohs (message->size) - sizeof (struct GNUNET_MESH_ClientConnect);
4630   cc_msg = (struct GNUNET_MESH_ClientConnect *) message;
4631   ntypes = ntohs (cc_msg->types);
4632   if (size != ntypes * sizeof (uint16_t))
4633   {
4634     GNUNET_break (0);
4635     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4636     return;
4637   }
4638
4639   /* Create new client structure */
4640   c = GNUNET_malloc (sizeof (struct MeshClient));
4641   c->id = next_client_id++; // overflow not important: just for debug
4642   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  CLIENT NEW %u\n", c->id);
4643   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  client has %u types\n", ntypes);
4644   c->handle = client;
4645   GNUNET_SERVER_client_keep (client);
4646   if (ntypes > 0)
4647   {
4648     uint16_t u16;
4649     struct GNUNET_HashCode hc;
4650
4651     t = (uint16_t *) &cc_msg[1];
4652     c->types = GNUNET_CONTAINER_multihashmap_create (ntypes, GNUNET_NO);
4653     for (i = 0; i < ntypes; i++)
4654     {
4655       u16 = ntohs (t[i]);
4656       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "    msg type: %u\n", u16);
4657       GMC_hash32 ((uint32_t) u16, &hc);
4658
4659       /* store in clients hashmap */
4660       GNUNET_CONTAINER_multihashmap_put (c->types, &hc, c,
4661                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
4662       /* store in global hashmap */
4663       GNUNET_CONTAINER_multihashmap_put (types, &hc, c,
4664                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
4665     }
4666   }
4667
4668   GNUNET_CONTAINER_DLL_insert (clients_head, clients_tail, c);
4669   c->own_tunnels = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
4670   c->incoming_tunnels = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
4671   c->ignore_tunnels = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
4672   GNUNET_SERVER_notification_context_add (nc, client);
4673   GNUNET_STATISTICS_update (stats, "# clients", 1, GNUNET_NO);
4674
4675   GNUNET_SERVER_receive_done (client, GNUNET_OK);
4676   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new client processed\n");
4677 }
4678
4679
4680 /**
4681  * Handler for requests of new tunnels
4682  *
4683  * @param cls Closure.
4684  * @param client Identification of the client.
4685  * @param message The actual message.
4686  */
4687 static void
4688 handle_local_tunnel_create (void *cls, struct GNUNET_SERVER_Client *client,
4689                             const struct GNUNET_MessageHeader *message)
4690 {
4691   struct GNUNET_MESH_TunnelMessage *t_msg;
4692   struct MeshPeerInfo *peer_info;
4693   struct MeshTunnel *t;
4694   struct MeshClient *c;
4695   MESH_TunnelNumber tid;
4696
4697   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new tunnel requested\n");
4698
4699   /* Sanity check for client registration */
4700   if (NULL == (c = client_get (client)))
4701   {
4702     GNUNET_break (0);
4703     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4704     return;
4705   }
4706   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
4707
4708   /* Message sanity check */
4709   if (sizeof (struct GNUNET_MESH_TunnelMessage) != ntohs (message->size))
4710   {
4711     GNUNET_break (0);
4712     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4713     return;
4714   }
4715
4716   t_msg = (struct GNUNET_MESH_TunnelMessage *) message;
4717   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  towards %s\n",
4718               GNUNET_i2s (&t_msg->peer));
4719   /* Sanity check for tunnel numbering */
4720   tid = ntohl (t_msg->tunnel_id);
4721   if (0 == (tid & GNUNET_MESH_LOCAL_TUNNEL_ID_CLI))
4722   {
4723     GNUNET_break (0);
4724     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4725     return;
4726   }
4727   /* Sanity check for duplicate tunnel IDs */
4728   if (NULL != tunnel_get_by_local_id (c, tid))
4729   {
4730     GNUNET_break (0);
4731     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4732     return;
4733   }
4734
4735   while (NULL != tunnel_get_by_pi (myid, next_tid))
4736     next_tid = (next_tid + 1) & ~GNUNET_MESH_LOCAL_TUNNEL_ID_CLI;
4737   t = tunnel_new (myid, next_tid, c, tid);
4738   next_tid = (next_tid + 1) & ~GNUNET_MESH_LOCAL_TUNNEL_ID_CLI;
4739   if (NULL == t)
4740   {
4741     GNUNET_break (0);
4742     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4743     return;
4744   }
4745   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "CREATED TUNNEL %s [%x] (%x)\n",
4746               GNUNET_i2s (&my_full_id), t->id.tid, t->local_tid);
4747
4748   peer_info = peer_get (&t_msg->peer);
4749   GNUNET_array_append (peer_info->tunnels, peer_info->ntunnels, t);
4750   peer_connect (peer_info, t);
4751   GNUNET_SERVER_receive_done (client, GNUNET_OK);
4752   return;
4753 }
4754
4755
4756 /**
4757  * Handler for requests of deleting tunnels
4758  *
4759  * @param cls closure
4760  * @param client identification of the client
4761  * @param message the actual message
4762  */
4763 static void
4764 handle_local_tunnel_destroy (void *cls, struct GNUNET_SERVER_Client *client,
4765                              const struct GNUNET_MessageHeader *message)
4766 {
4767   struct GNUNET_MESH_TunnelMessage *tunnel_msg;
4768   struct MeshClient *c;
4769   struct MeshTunnel *t;
4770   MESH_TunnelNumber tid;
4771
4772   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4773               "Got a DESTROY TUNNEL from client!\n");
4774
4775   /* Sanity check for client registration */
4776   if (NULL == (c = client_get (client)))
4777   {
4778     GNUNET_break (0);
4779     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4780     return;
4781   }
4782   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
4783
4784   /* Message sanity check */
4785   if (sizeof (struct GNUNET_MESH_TunnelMessage) != ntohs (message->size))
4786   {
4787     GNUNET_break (0);
4788     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4789     return;
4790   }
4791
4792   tunnel_msg = (struct GNUNET_MESH_TunnelMessage *) message;
4793
4794   /* Retrieve tunnel */
4795   tid = ntohl (tunnel_msg->tunnel_id);
4796   t = tunnel_get_by_local_id(c, tid);
4797   if (NULL == t)
4798   {
4799     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "  tunnel %X not found\n", tid);
4800     GNUNET_break (0);
4801     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4802     return;
4803   }
4804   if (c != t->owner || tid >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
4805   {
4806     client_ignore_tunnel (c, t);
4807     tunnel_destroy_empty (t);
4808     GNUNET_SERVER_receive_done (client, GNUNET_OK);
4809     return;
4810   }
4811   send_client_tunnel_disconnect (t, c);
4812   client_delete_tunnel (c, t);
4813
4814   /* Don't try to ACK the client about the tunnel_destroy multicast packet */
4815   t->owner = NULL;
4816   tunnel_send_destroy (t);
4817   peer_remove_tunnel (peer_get_short(t->dest), t);
4818   t->destroy = GNUNET_YES;
4819   /* The tunnel will be destroyed when the last message is transmitted. */
4820   GNUNET_SERVER_receive_done (client, GNUNET_OK);
4821   return;
4822 }
4823
4824
4825 /**
4826  * Handler for requests of seeting tunnel's buffering policy.
4827  *
4828  * @param cls Closure (unused).
4829  * @param client Identification of the client.
4830  * @param message The actual message.
4831  */
4832 static void
4833 handle_local_tunnel_buffer (void *cls, struct GNUNET_SERVER_Client *client,
4834                             const struct GNUNET_MessageHeader *message)
4835 {
4836   struct GNUNET_MESH_TunnelMessage *tunnel_msg;
4837   struct MeshClient *c;
4838   struct MeshTunnel *t;
4839   MESH_TunnelNumber tid;
4840
4841   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4842               "Got a BUFFER request from client!\n");
4843
4844   /* Sanity check for client registration */
4845   if (NULL == (c = client_get (client)))
4846   {
4847     GNUNET_break (0);
4848     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4849     return;
4850   }
4851   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
4852
4853   tunnel_msg = (struct GNUNET_MESH_TunnelMessage *) message;
4854
4855   /* Retrieve tunnel */
4856   tid = ntohl (tunnel_msg->tunnel_id);
4857   t = tunnel_get_by_local_id(c, tid);
4858   if (NULL == t)
4859   {
4860     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "  tunnel %X not found\n", tid);
4861     GNUNET_break (0);
4862     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4863     return;
4864   }
4865
4866   switch (ntohs(message->type))
4867   {
4868       case GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_BUFFER:
4869           t->nobuffer = GNUNET_NO;
4870           break;
4871       case GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_NOBUFFER:
4872           t->nobuffer = GNUNET_YES;
4873           break;
4874       default:
4875           GNUNET_break (0);
4876   }
4877
4878   GNUNET_SERVER_receive_done (client, GNUNET_OK);
4879 }
4880
4881
4882 /**
4883  * Handler for client traffic directed to one peer
4884  *
4885  * @param cls closure
4886  * @param client identification of the client
4887  * @param message the actual message
4888  */
4889 static void
4890 handle_local_unicast (void *cls, struct GNUNET_SERVER_Client *client,
4891                       const struct GNUNET_MessageHeader *message)
4892 {
4893   struct MeshClient *c;
4894   struct MeshTunnel *t;
4895   struct GNUNET_MESH_Unicast *data_msg;
4896   MESH_TunnelNumber tid;
4897   size_t size;
4898
4899   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4900               "Got a unicast request from a client!\n");
4901
4902   /* Sanity check for client registration */
4903   if (NULL == (c = client_get (client)))
4904   {
4905     GNUNET_break (0);
4906     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4907     return;
4908   }
4909   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
4910
4911   data_msg = (struct GNUNET_MESH_Unicast *) message;
4912
4913   /* Sanity check for message size */
4914   size = ntohs (message->size);
4915   if (sizeof (struct GNUNET_MESH_Unicast) +
4916       sizeof (struct GNUNET_MessageHeader) > size)
4917   {
4918     GNUNET_break (0);
4919     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4920     return;
4921   }
4922
4923   /* Tunnel exists? */
4924   tid = ntohl (data_msg->tid);
4925   t = tunnel_get_by_local_id (c, tid);
4926   if (NULL == t)
4927   {
4928     GNUNET_break (0);
4929     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4930     return;
4931   }
4932
4933   /*  Is it a local tunnel? Then, does client own the tunnel? */
4934   if (t->owner->handle != client)
4935   {
4936     GNUNET_break (0);
4937     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4938     return;
4939   }
4940
4941   /* PID should be as expected: client<->service communication */
4942   if (ntohl (data_msg->pid) != t->prev_fc.last_pid_recv + 1)
4943   {
4944     GNUNET_break (0);
4945     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4946               "Unicast PID, expected %u, got %u\n",
4947               t->prev_fc.last_pid_recv + 1, ntohl (data_msg->pid));
4948     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4949     return;
4950   }
4951
4952   /* Ok, everything is correct, send the message
4953    * (pretend we got it from a mesh peer)
4954    */
4955   {
4956     /* Work around const limitation */
4957     char buf[ntohs (message->size)] GNUNET_ALIGN;
4958     struct GNUNET_MESH_Unicast *copy;
4959
4960     copy = (struct GNUNET_MESH_Unicast *) buf;
4961     memcpy (buf, data_msg, size);
4962     copy->oid = my_full_id;
4963     copy->tid = htonl (t->id.tid);
4964     copy->ttl = htonl (default_ttl);
4965     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4966                 "  calling generic handler...\n");
4967     handle_mesh_data_unicast (NULL, &my_full_id, &copy->header);
4968   }
4969   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "receive done OK\n");
4970   GNUNET_SERVER_receive_done (client, GNUNET_OK);
4971
4972   return;
4973 }
4974
4975
4976 /**
4977  * Handler for client traffic directed to the origin
4978  *
4979  * @param cls closure
4980  * @param client identification of the client
4981  * @param message the actual message
4982  */
4983 static void
4984 handle_local_to_origin (void *cls, struct GNUNET_SERVER_Client *client,
4985                         const struct GNUNET_MessageHeader *message)
4986 {
4987   struct GNUNET_MESH_ToOrigin *data_msg;
4988   struct MeshTunnelClientInfo *clinfo;
4989   struct MeshClient *c;
4990   struct MeshTunnel *t;
4991   MESH_TunnelNumber tid;
4992   size_t size;
4993
4994   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4995               "Got a ToOrigin request from a client!\n");
4996   /* Sanity check for client registration */
4997   if (NULL == (c = client_get (client)))
4998   {
4999     GNUNET_break (0);
5000     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5001     return;
5002   }
5003   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
5004
5005   data_msg = (struct GNUNET_MESH_ToOrigin *) message;
5006
5007   /* Sanity check for message size */
5008   size = ntohs (message->size);
5009   if (sizeof (struct GNUNET_MESH_ToOrigin) +
5010       sizeof (struct GNUNET_MessageHeader) > size)
5011   {
5012     GNUNET_break (0);
5013     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5014     return;
5015   }
5016
5017   /* Tunnel exists? */
5018   tid = ntohl (data_msg->tid);
5019   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %X\n", tid);
5020   if (tid < GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
5021   {
5022     GNUNET_break (0);
5023     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5024     return;
5025   }
5026   t = tunnel_get_by_local_id (c, tid);
5027   if (NULL == t)
5028   {
5029     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Tunnel %X unknown.\n", tid);
5030     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "  for client %u.\n", c->id);
5031     GNUNET_break (0);
5032     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5033     return;
5034   }
5035
5036   /*  It should be sent by someone who has this as incoming tunnel. */
5037   if (GNUNET_NO == client_knows_tunnel (c, t))
5038   {
5039     GNUNET_break (0);
5040     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5041     return;
5042   }
5043
5044   /* PID should be as expected */
5045   clinfo = tunnel_get_client_fc (t, c);
5046   if (ntohl (data_msg->pid) != clinfo->bck_pid + 1)
5047   {
5048     GNUNET_break (0);
5049     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
5050                 "To Origin PID, expected %u, got %u\n",
5051                 clinfo->bck_pid + 1,
5052                 ntohl (data_msg->pid));
5053     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5054     return;
5055   }
5056   clinfo->bck_pid++;
5057
5058   /* Ok, everything is correct, send the message
5059    * (pretend we got it from a mesh peer)
5060    */
5061   {
5062     char buf[ntohs (message->size)] GNUNET_ALIGN;
5063     struct GNUNET_MESH_ToOrigin *copy;
5064
5065     /* Work around 'const' limitation */
5066     copy = (struct GNUNET_MESH_ToOrigin *) buf;
5067     memcpy (buf, data_msg, size);
5068     GNUNET_PEER_resolve (t->id.oid, &copy->oid);
5069     copy->tid = htonl (t->id.tid);
5070     copy->ttl = htonl (default_ttl);
5071     copy->pid = htonl (t->prev_fc.last_pid_sent + 1);
5072
5073     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5074                 "  calling generic handler...\n");
5075     handle_mesh_data_to_orig (NULL, &my_full_id, &copy->header);
5076   }
5077   GNUNET_SERVER_receive_done (client, GNUNET_OK);
5078
5079   return;
5080 }
5081
5082
5083 /**
5084  * Handler for client's ACKs for payload traffic.
5085  *
5086  * @param cls Closure (unused).
5087  * @param client Identification of the client.
5088  * @param message The actual message.
5089  */
5090 static void
5091 handle_local_ack (void *cls, struct GNUNET_SERVER_Client *client,
5092                   const struct GNUNET_MessageHeader *message)
5093 {
5094   struct GNUNET_MESH_LocalAck *msg;
5095   struct MeshTunnel *t;
5096   struct MeshClient *c;
5097   MESH_TunnelNumber tid;
5098   uint32_t ack;
5099
5100   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a local ACK\n");
5101   /* Sanity check for client registration */
5102   if (NULL == (c = client_get (client)))
5103   {
5104     GNUNET_break (0);
5105     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5106     return;
5107   }
5108   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
5109
5110   msg = (struct GNUNET_MESH_LocalAck *) message;
5111
5112   /* Tunnel exists? */
5113   tid = ntohl (msg->tunnel_id);
5114   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %X\n", tid);
5115   t = tunnel_get_by_local_id (c, tid);
5116   if (NULL == t)
5117   {
5118     GNUNET_break (0);
5119     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Tunnel %X unknown.\n", tid);
5120     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "  for client %u.\n", c->id);
5121     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5122     return;
5123   }
5124
5125   ack = ntohl (msg->max_pid);
5126   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  ack %u\n", ack);
5127
5128   /* Does client own tunnel? I.E: Is this an ACK for BCK traffic? */
5129   if (NULL != t->owner && t->owner->handle == client)
5130   {
5131     /* The client owns the tunnel, ACK is for data to_origin, send BCK ACK. */
5132     t->next_fc.last_ack_sent = ack;
5133     tunnel_send_bck_ack(t, GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK);
5134   }
5135   else
5136   {
5137     /* The client doesn't own the tunnel, this ACK is for FWD traffic. */
5138     tunnel_set_client_fwd_ack (t, c, ack);
5139     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK);
5140   }
5141
5142   GNUNET_SERVER_receive_done (client, GNUNET_OK);
5143
5144   return;
5145 }
5146
5147
5148
5149 /**
5150  * Iterator over all tunnels to send a monitoring client info about each tunnel.
5151  *
5152  * @param cls Closure (client handle).
5153  * @param key Key (hashed tunnel ID, unused).
5154  * @param value Tunnel info.
5155  *
5156  * @return GNUNET_YES, to keep iterating.
5157  */
5158 static int
5159 monitor_all_tunnels_iterator (void *cls,
5160                               const struct GNUNET_HashCode * key,
5161                               void *value)
5162 {
5163   struct GNUNET_SERVER_Client *client = cls;
5164   struct MeshTunnel *t = value;
5165   struct GNUNET_MESH_LocalMonitor *msg;
5166
5167   msg = GNUNET_malloc (sizeof(struct GNUNET_MESH_LocalMonitor));
5168   GNUNET_PEER_resolve(t->id.oid, &msg->owner);
5169   msg->tunnel_id = htonl (t->id.tid);
5170   msg->header.size = htons (sizeof (struct GNUNET_MESH_LocalMonitor));
5171   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_INFO_TUNNELS);
5172   GNUNET_PEER_resolve (t->dest, &msg->destination);
5173
5174   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
5175               "*  sending info about tunnel %s [%u]\n",
5176               GNUNET_i2s (&msg->owner), t->id.tid);
5177
5178   GNUNET_SERVER_notification_context_unicast (nc, client,
5179                                               &msg->header, GNUNET_NO);
5180   return GNUNET_YES;
5181 }
5182
5183
5184 /**
5185  * Handler for client's MONITOR request.
5186  *
5187  * @param cls Closure (unused).
5188  * @param client Identification of the client.
5189  * @param message The actual message.
5190  */
5191 static void
5192 handle_local_get_tunnels (void *cls, struct GNUNET_SERVER_Client *client,
5193                           const struct GNUNET_MessageHeader *message)
5194 {
5195   struct MeshClient *c;
5196
5197   /* Sanity check for client registration */
5198   if (NULL == (c = client_get (client)))
5199   {
5200     GNUNET_break (0);
5201     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5202     return;
5203   }
5204
5205   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
5206               "Received get tunnels request from client %u\n",
5207               c->id);
5208   GNUNET_CONTAINER_multihashmap_iterate (tunnels,
5209                                          monitor_all_tunnels_iterator,
5210                                          client);
5211   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
5212               "Get tunnels request from client %u completed\n",
5213               c->id);
5214   GNUNET_SERVER_receive_done (client, GNUNET_OK);
5215 }
5216
5217
5218 /**
5219  * Handler for client's MONITOR_TUNNEL request.
5220  *
5221  * @param cls Closure (unused).
5222  * @param client Identification of the client.
5223  * @param message The actual message.
5224  */
5225 static void
5226 handle_local_show_tunnel (void *cls, struct GNUNET_SERVER_Client *client,
5227                           const struct GNUNET_MessageHeader *message)
5228 {
5229   const struct GNUNET_MESH_LocalMonitor *msg;
5230   struct GNUNET_MESH_LocalMonitor *resp;
5231   struct MeshClient *c;
5232   struct MeshTunnel *t;
5233
5234   /* Sanity check for client registration */
5235   if (NULL == (c = client_get (client)))
5236   {
5237     GNUNET_break (0);
5238     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5239     return;
5240   }
5241
5242   msg = (struct GNUNET_MESH_LocalMonitor *) message;
5243   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
5244               "Received tunnel info request from client %u for tunnel %s[%X]\n",
5245               c->id,
5246               &msg->owner,
5247               ntohl (msg->tunnel_id));
5248   t = tunnel_get (&msg->owner, ntohl (msg->tunnel_id));
5249   if (NULL == t)
5250   {
5251     /* We don't know the tunnel FIXME */
5252     struct GNUNET_MESH_LocalMonitor warn;
5253
5254     warn = *msg;
5255     GNUNET_SERVER_notification_context_unicast (nc, client,
5256                                                 &warn.header,
5257                                                 GNUNET_NO);
5258     GNUNET_SERVER_receive_done (client, GNUNET_OK);
5259     return;
5260   }
5261
5262   /* Initialize context */
5263   resp = GNUNET_malloc (sizeof (struct GNUNET_MESH_LocalMonitor));
5264   *resp = *msg;
5265   GNUNET_PEER_resolve (t->dest, &resp->destination);
5266   resp->header.size = htons (sizeof (struct GNUNET_MESH_LocalMonitor));
5267   GNUNET_SERVER_notification_context_unicast (nc, c->handle,
5268                                               &resp->header, GNUNET_NO);
5269   GNUNET_free (resp);
5270
5271   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
5272               "Monitor tunnel request from client %u completed\n",
5273               c->id);
5274   GNUNET_SERVER_receive_done (client, GNUNET_OK);
5275 }
5276
5277
5278 /**
5279  * Functions to handle messages from clients
5280  */
5281 static struct GNUNET_SERVER_MessageHandler client_handlers[] = {
5282   {&handle_local_new_client, NULL,
5283    GNUNET_MESSAGE_TYPE_MESH_LOCAL_CONNECT, 0},
5284   {&handle_local_tunnel_create, NULL,
5285    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_CREATE,
5286    sizeof (struct GNUNET_MESH_TunnelMessage)},
5287   {&handle_local_tunnel_destroy, NULL,
5288    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_DESTROY,
5289    sizeof (struct GNUNET_MESH_TunnelMessage)},
5290   {&handle_local_tunnel_buffer, NULL,
5291    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_BUFFER,
5292    sizeof (struct GNUNET_MESH_TunnelMessage)},
5293   {&handle_local_tunnel_buffer, NULL,
5294    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_NOBUFFER,
5295    sizeof (struct GNUNET_MESH_TunnelMessage)},
5296   {&handle_local_unicast, NULL,
5297    GNUNET_MESSAGE_TYPE_MESH_UNICAST, 0},
5298   {&handle_local_to_origin, NULL,
5299    GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN, 0},
5300   {&handle_local_ack, NULL,
5301    GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK,
5302    sizeof (struct GNUNET_MESH_LocalAck)},
5303   {&handle_local_get_tunnels, NULL,
5304    GNUNET_MESSAGE_TYPE_MESH_LOCAL_INFO_TUNNELS,
5305    sizeof (struct GNUNET_MessageHeader)},
5306   {&handle_local_show_tunnel, NULL,
5307    GNUNET_MESSAGE_TYPE_MESH_LOCAL_INFO_TUNNEL,
5308      sizeof (struct GNUNET_MESH_LocalMonitor)},
5309   {NULL, NULL, 0, 0}
5310 };
5311
5312
5313 /**
5314  * To be called on core init/fail.
5315  *
5316  * @param cls service closure
5317  * @param server handle to the server for this service
5318  * @param identity the public identity of this peer
5319  */
5320 static void
5321 core_init (void *cls, struct GNUNET_CORE_Handle *server,
5322            const struct GNUNET_PeerIdentity *identity)
5323 {
5324   static int i = 0;
5325   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Core init\n");
5326   core_handle = server;
5327   if (0 != memcmp (identity, &my_full_id, sizeof (my_full_id)) ||
5328       NULL == server)
5329   {
5330     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _("Wrong CORE service\n"));
5331     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
5332                 " core id %s\n",
5333                 GNUNET_i2s (identity));
5334     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
5335                 " my id %s\n",
5336                 GNUNET_i2s (&my_full_id));
5337     GNUNET_SCHEDULER_shutdown (); // Try gracefully
5338     if (10 < i++)
5339       GNUNET_abort(); // Try harder
5340   }
5341   return;
5342 }
5343
5344
5345 /**
5346  * Method called whenever a given peer connects.
5347  *
5348  * @param cls closure
5349  * @param peer peer identity this notification is about
5350  */
5351 static void
5352 core_connect (void *cls, const struct GNUNET_PeerIdentity *peer)
5353 {
5354   struct MeshPeerInfo *peer_info;
5355   struct MeshPeerPath *path;
5356
5357   DEBUG_CONN ("Peer connected\n");
5358   DEBUG_CONN ("     %s\n", GNUNET_i2s (&my_full_id));
5359   peer_info = peer_get (peer);
5360   if (myid == peer_info->id)
5361   {
5362     DEBUG_CONN ("     (self)\n");
5363     return;
5364   }
5365   else
5366   {
5367     DEBUG_CONN ("     %s\n", GNUNET_i2s (peer));
5368   }
5369   path = path_new (2);
5370   path->peers[0] = myid;
5371   path->peers[1] = peer_info->id;
5372   GNUNET_PEER_change_rc (myid, 1);
5373   GNUNET_PEER_change_rc (peer_info->id, 1);
5374   peer_info_add_path (peer_info, path, GNUNET_YES);
5375   GNUNET_STATISTICS_update (stats, "# peers", 1, GNUNET_NO);
5376   return;
5377 }
5378
5379
5380 /**
5381  * Method called whenever a peer disconnects.
5382  *
5383  * @param cls closure
5384  * @param peer peer identity this notification is about
5385  */
5386 static void
5387 core_disconnect (void *cls, const struct GNUNET_PeerIdentity *peer)
5388 {
5389   struct MeshPeerInfo *pi;
5390   struct MeshPeerQueue *q;
5391   struct MeshPeerQueue *n;
5392
5393   DEBUG_CONN ("Peer disconnected\n");
5394   pi = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
5395   if (NULL == pi)
5396   {
5397     GNUNET_break (0);
5398     return;
5399   }
5400   q = pi->queue_head;
5401   while (NULL != q)
5402   {
5403       n = q->next;
5404       /* TODO try to reroute this traffic instead */
5405       queue_destroy(q, GNUNET_YES);
5406       q = n;
5407   }
5408   if (NULL != pi->core_transmit)
5409   {
5410     GNUNET_CORE_notify_transmit_ready_cancel(pi->core_transmit);
5411     pi->core_transmit = NULL;
5412   }
5413     peer_remove_path (pi, pi->id, myid);
5414   if (myid == pi->id)
5415   {
5416     DEBUG_CONN ("     (self)\n");
5417   }
5418   GNUNET_STATISTICS_update (stats, "# peers", -1, GNUNET_NO);
5419   return;
5420 }
5421
5422
5423 /******************************************************************************/
5424 /************************      MAIN FUNCTIONS      ****************************/
5425 /******************************************************************************/
5426
5427 /**
5428  * Iterator over tunnel hash map entries to destroy the tunnel during shutdown.
5429  *
5430  * @param cls closure
5431  * @param key current key code
5432  * @param value value in the hash map
5433  * @return GNUNET_YES if we should continue to iterate,
5434  *         GNUNET_NO if not.
5435  */
5436 static int
5437 shutdown_tunnel (void *cls, const struct GNUNET_HashCode * key, void *value)
5438 {
5439   struct MeshTunnel *t = value;
5440
5441   tunnel_destroy (t);
5442   return GNUNET_YES;
5443 }
5444
5445 /**
5446  * Iterator over peer hash map entries to destroy the tunnel during shutdown.
5447  *
5448  * @param cls closure
5449  * @param key current key code
5450  * @param value value in the hash map
5451  * @return GNUNET_YES if we should continue to iterate,
5452  *         GNUNET_NO if not.
5453  */
5454 static int
5455 shutdown_peer (void *cls, const struct GNUNET_HashCode * key, void *value)
5456 {
5457   struct MeshPeerInfo *p = value;
5458   struct MeshPeerQueue *q;
5459   struct MeshPeerQueue *n;
5460
5461   q = p->queue_head;
5462   while (NULL != q)
5463   {
5464       n = q->next;
5465       if (q->peer == p)
5466       {
5467         queue_destroy(q, GNUNET_YES);
5468       }
5469       q = n;
5470   }
5471   peer_info_destroy (p);
5472   return GNUNET_YES;
5473 }
5474
5475
5476 /**
5477  * Task run during shutdown.
5478  *
5479  * @param cls unused
5480  * @param tc unused
5481  */
5482 static void
5483 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
5484 {
5485   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shutting down\n");
5486
5487   if (core_handle != NULL)
5488   {
5489     GNUNET_CORE_disconnect (core_handle);
5490     core_handle = NULL;
5491   }
5492   if (NULL != keygen)
5493   {
5494     GNUNET_CRYPTO_ecc_key_create_stop (keygen);
5495     keygen = NULL;
5496   }
5497   GNUNET_CONTAINER_multihashmap_iterate (tunnels, &shutdown_tunnel, NULL);
5498   GNUNET_CONTAINER_multihashmap_iterate (peers, &shutdown_peer, NULL);
5499   if (dht_handle != NULL)
5500   {
5501     GNUNET_DHT_disconnect (dht_handle);
5502     dht_handle = NULL;
5503   }
5504   if (nc != NULL)
5505   {
5506     GNUNET_SERVER_notification_context_destroy (nc);
5507     nc = NULL;
5508   }
5509   if (GNUNET_SCHEDULER_NO_TASK != announce_id_task)
5510   {
5511     GNUNET_SCHEDULER_cancel (announce_id_task);
5512     announce_id_task = GNUNET_SCHEDULER_NO_TASK;
5513   }
5514   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shut down\n");
5515 }
5516
5517
5518 /**
5519  * Callback for hostkey read/generation.
5520  *
5521  * @param cls Closure (Configuration handle).
5522  * @param pk The ECC private key.
5523  * @param emsg Error message, if any.
5524  */
5525 static void
5526 key_generation_cb (void *cls,
5527                    struct GNUNET_CRYPTO_EccPrivateKey *pk,
5528                    const char *emsg)
5529 {
5530   const struct GNUNET_CONFIGURATION_Handle *c = cls;
5531   struct MeshPeerInfo *peer;
5532   struct MeshPeerPath *p;
5533
5534   keygen = NULL;  
5535   if (NULL == pk)
5536   {
5537     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
5538                 _("Mesh service could not access hostkey: %s. Exiting.\n"),
5539                 emsg);
5540     GNUNET_SCHEDULER_shutdown ();
5541     return;
5542   }
5543   my_private_key = pk;
5544   GNUNET_CRYPTO_ecc_key_get_public (my_private_key, &my_public_key);
5545   GNUNET_CRYPTO_hash (&my_public_key, sizeof (my_public_key),
5546                       &my_full_id.hashPubKey);
5547   myid = GNUNET_PEER_intern (&my_full_id);
5548   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
5549               "Mesh for peer [%s] starting\n",
5550               GNUNET_i2s(&my_full_id));
5551
5552   core_handle = GNUNET_CORE_connect (c, /* Main configuration */
5553                                      NULL,      /* Closure passed to MESH functions */
5554                                      &core_init,        /* Call core_init once connected */
5555                                      &core_connect,     /* Handle connects */
5556                                      &core_disconnect,  /* remove peers on disconnects */
5557                                      NULL,      /* Don't notify about all incoming messages */
5558                                      GNUNET_NO, /* For header only in notification */
5559                                      NULL,      /* Don't notify about all outbound messages */
5560                                      GNUNET_NO, /* For header-only out notification */
5561                                      core_handlers);    /* Register these handlers */
5562   
5563   if (core_handle == NULL)
5564   {
5565     GNUNET_break (0);
5566     GNUNET_SCHEDULER_shutdown ();
5567     return;
5568   }
5569
5570   next_tid = 0;
5571   next_local_tid = GNUNET_MESH_LOCAL_TUNNEL_ID_SERV;
5572
5573
5574   GNUNET_SERVER_add_handlers (server_handle, client_handlers);
5575   nc = GNUNET_SERVER_notification_context_create (server_handle, 1);
5576   GNUNET_SERVER_disconnect_notify (server_handle,
5577                                    &handle_local_client_disconnect, NULL);
5578
5579
5580   clients_head = NULL;
5581   clients_tail = NULL;
5582   next_client_id = 0;
5583
5584   announce_id_task = GNUNET_SCHEDULER_add_now (&announce_id, cls);
5585
5586   /* Create a peer_info for the local peer */
5587   peer = peer_get (&my_full_id);
5588   p = path_new (1);
5589   p->peers[0] = myid;
5590   GNUNET_PEER_change_rc (myid, 1);
5591   peer_info_add_path (peer, p, GNUNET_YES);
5592   GNUNET_SERVER_resume (server_handle);
5593   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Mesh service running\n");
5594 }
5595
5596
5597 /**
5598  * Process mesh requests.
5599  *
5600  * @param cls closure
5601  * @param server the initialized server
5602  * @param c configuration to use
5603  */
5604 static void
5605 run (void *cls, struct GNUNET_SERVER_Handle *server,
5606      const struct GNUNET_CONFIGURATION_Handle *c)
5607 {
5608   char *keyfile;
5609
5610   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "starting to run\n");
5611   server_handle = server;
5612
5613   if (GNUNET_OK !=
5614       GNUNET_CONFIGURATION_get_value_filename (c, "PEER", "PRIVATE_KEY",
5615                                                &keyfile))
5616   {
5617     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
5618                 _
5619                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
5620                 "mesh", "peer/privatekey");
5621     GNUNET_SCHEDULER_shutdown ();
5622     return;
5623   }
5624
5625   if (GNUNET_OK !=
5626       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "REFRESH_PATH_TIME",
5627                                            &refresh_path_time))
5628   {
5629     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
5630                 _
5631                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
5632                 "mesh", "refresh path time");
5633     GNUNET_SCHEDULER_shutdown ();
5634     return;
5635   }
5636
5637   if (GNUNET_OK !=
5638       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "ID_ANNOUNCE_TIME",
5639                                            &id_announce_time))
5640   {
5641     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
5642                 _
5643                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
5644                 "mesh", "id announce time");
5645     GNUNET_SCHEDULER_shutdown ();
5646     return;
5647   }
5648
5649   if (GNUNET_OK !=
5650       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "CONNECT_TIMEOUT",
5651                                            &connect_timeout))
5652   {
5653     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
5654                 _
5655                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
5656                 "mesh", "connect timeout");
5657     GNUNET_SCHEDULER_shutdown ();
5658     return;
5659   }
5660
5661   if (GNUNET_OK !=
5662       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_MSGS_QUEUE",
5663                                              &max_msgs_queue))
5664   {
5665     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
5666                 _
5667                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
5668                 "mesh", "max msgs queue");
5669     GNUNET_SCHEDULER_shutdown ();
5670     return;
5671   }
5672
5673   if (GNUNET_OK !=
5674       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_TUNNELS",
5675                                              &max_tunnels))
5676   {
5677     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
5678                 _
5679                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
5680                 "mesh", "max tunnels");
5681     GNUNET_SCHEDULER_shutdown ();
5682     return;
5683   }
5684
5685   if (GNUNET_OK !=
5686       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DEFAULT_TTL",
5687                                              &default_ttl))
5688   {
5689     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
5690                 _
5691                 ("%s service is lacking key configuration settings (%s). Using default (%u).\n"),
5692                 "mesh", "default ttl", 64);
5693     default_ttl = 64;
5694   }
5695
5696   if (GNUNET_OK !=
5697       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_PEERS",
5698                                              &max_peers))
5699   {
5700     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
5701                 _("%s service is lacking key configuration settings (%s). Using default (%u).\n"),
5702                 "mesh", "max peers", 1000);
5703     max_peers = 1000;
5704   }
5705
5706   if (GNUNET_OK !=
5707       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DHT_REPLICATION_LEVEL",
5708                                              &dht_replication_level))
5709   {
5710     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
5711                 _
5712                 ("%s service is lacking key configuration settings (%s). Using default (%u).\n"),
5713                 "mesh", "dht replication level", 3);
5714     dht_replication_level = 3;
5715   }
5716
5717   tunnels = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
5718   incoming_tunnels = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
5719   peers = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
5720   types = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
5721
5722   dht_handle = GNUNET_DHT_connect (c, 64);
5723   if (NULL == dht_handle)
5724   {
5725     GNUNET_break (0);
5726   }
5727   stats = GNUNET_STATISTICS_create ("mesh", c);
5728
5729   GNUNET_SERVER_suspend (server_handle);
5730   /* Scheduled the task to clean up when shutdown is called */
5731   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
5732                                 NULL);
5733   keygen = GNUNET_CRYPTO_ecc_key_create_start (keyfile,
5734                                                &key_generation_cb,
5735                                                (void *) c);
5736   GNUNET_free (keyfile);
5737 }
5738
5739
5740 /**
5741  * The main function for the mesh service.
5742  *
5743  * @param argc number of arguments from the command line
5744  * @param argv command line arguments
5745  * @return 0 ok, 1 on error
5746  */
5747 int
5748 main (int argc, char *const *argv)
5749 {
5750   int ret;
5751   int r;
5752
5753   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "main()\n");
5754   r = GNUNET_SERVICE_run (argc, argv, "mesh", GNUNET_SERVICE_OPTION_NONE, &run,
5755                           NULL);
5756   ret = (GNUNET_OK == r) ? 0 : 1;
5757   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "main() END\n");
5758
5759   INTERVAL_SHOW;
5760
5761   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
5762               "Mesh for peer [%s] FWD ACKs %u, BCK ACKs %u\n",
5763               GNUNET_i2s(&my_full_id), debug_fwd_ack, debug_bck_ack);
5764
5765   return ret;
5766 }