- cancel poll when receiving big enough ack
[oweals/gnunet.git] / src / mesh / gnunet-service-mesh-new.c
1 /*
2      This file is part of GNUnet.
3      (C) 2001-2012 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      */
516   struct GNUNET_CONTAINER_MultiHashMap *types;
517
518     /**
519      * Whether the client is active or shutting down (don't send confirmations
520      * to a client that is shutting down.
521      */
522   int shutting_down;
523
524     /**
525      * ID of the client, mainly for debug messages
526      */
527   unsigned int id;
528
529 };
530
531
532 /******************************************************************************/
533 /************************      DEBUG FUNCTIONS     ****************************/
534 /******************************************************************************/
535
536 #if MESH_DEBUG
537 /**
538  * GNUNET_SCHEDULER_Task for printing a message after some operation is done
539  * @param cls string to print
540  * @param success  GNUNET_OK if the PUT was transmitted,
541  *                GNUNET_NO on timeout,
542  *                GNUNET_SYSERR on disconnect from service
543  *                after the PUT message was transmitted
544  *                (so we don't know if it was received or not)
545  */
546
547 #if 0
548 static void
549 mesh_debug (void *cls, int success)
550 {
551   char *s = cls;
552
553   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "%s (%d)\n", s, success);
554 }
555 #endif
556
557 unsigned int debug_fwd_ack;
558 unsigned int debug_bck_ack;
559
560 #endif
561
562 /******************************************************************************/
563 /***********************      GLOBAL VARIABLES     ****************************/
564 /******************************************************************************/
565
566 /************************** Configuration parameters **************************/
567
568 /**
569  * How often to send tunnel keepalives. Tunnels timeout after 4 missed.
570  */
571 static struct GNUNET_TIME_Relative refresh_path_time;
572
573 /**
574  * How often to PUT own ID in the DHT.
575  */
576 static struct GNUNET_TIME_Relative id_announce_time;
577
578 /**
579  * Maximum time allowed to connect to a peer found by string.
580  */
581 static struct GNUNET_TIME_Relative connect_timeout;
582
583 /**
584  * Default TTL for payload packets.
585  */
586 static unsigned long long default_ttl;
587
588 /**
589  * DHT replication level, see DHT API: GNUNET_DHT_get_start, GNUNET_DHT_put.
590  */
591 static unsigned long long dht_replication_level;
592
593 /**
594  * How many tunnels are we willing to maintain.
595  * Local tunnels are always allowed, even if there are more tunnels than max.
596  */
597 static unsigned long long max_tunnels;
598
599 /**
600  * How many messages *in total* are we willing to queue, divided by number of 
601  * tunnels to get tunnel queue size.
602  */
603 static unsigned long long max_msgs_queue;
604
605 /**
606  * How many peers do we want to remember?
607  */
608 static unsigned long long max_peers;
609
610
611 /*************************** Static global variables **************************/
612
613 /**
614  * Hostkey generation context
615  */
616 static struct GNUNET_CRYPTO_EccKeyGenerationContext *keygen;
617
618 /**
619  * DLL with all the clients, head.
620  */
621 static struct MeshClient *clients_head;
622
623 /**
624  * DLL with all the clients, tail.
625  */
626 static struct MeshClient *clients_tail;
627
628 /**
629  * Tunnels known, indexed by MESH_TunnelID (MeshTunnel).
630  */
631 static struct GNUNET_CONTAINER_MultiHashMap *tunnels;
632
633 /**
634  * Number of tunnels known.
635  */
636 static unsigned long long n_tunnels;
637
638 /**
639  * Tunnels incoming, indexed by MESH_TunnelNumber
640  * (which is greater than GNUNET_MESH_LOCAL_TUNNEL_ID_SERV).
641  */
642 static struct GNUNET_CONTAINER_MultiHashMap *incoming_tunnels;
643
644 /**
645  * Peers known, indexed by PeerIdentity (MeshPeerInfo).
646  */
647 static struct GNUNET_CONTAINER_MultiHashMap *peers;
648
649 /*
650  * Handle to communicate with transport
651  */
652 // static struct GNUNET_TRANSPORT_Handle *transport_handle;
653
654 /**
655  * Handle to communicate with core.
656  */
657 static struct GNUNET_CORE_Handle *core_handle;
658
659 /**
660  * Handle to use DHT.
661  */
662 static struct GNUNET_DHT_Handle *dht_handle;
663
664 /**
665  * Handle to server.
666  */
667 static struct GNUNET_SERVER_Handle *server_handle;
668
669 /**
670  * Handle to the statistics service.
671  */
672 static struct GNUNET_STATISTICS_Handle *stats;
673
674 /**
675  * Notification context, to send messages to local clients.
676  */
677 static struct GNUNET_SERVER_NotificationContext *nc;
678
679 /**
680  * Local peer own ID (memory efficient handle).
681  */
682 static GNUNET_PEER_Id myid;
683
684 /**
685  * Local peer own ID (full value).
686  */
687 static struct GNUNET_PeerIdentity my_full_id;
688
689 /**
690  * Own private key.
691  */
692 static struct GNUNET_CRYPTO_EccPrivateKey *my_private_key;
693
694 /**
695  * Own public key.
696  */
697 static struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded my_public_key;
698
699 /**
700  * Tunnel ID for the next created tunnel (global tunnel number).
701  */
702 static MESH_TunnelNumber next_tid;
703
704 /**
705  * Tunnel ID for the next incoming tunnel (local tunnel number).
706  */
707 static MESH_TunnelNumber next_local_tid;
708
709 /**
710  * All message types clients of this peer are interested in.
711  */
712 static struct GNUNET_CONTAINER_MultiHashMap *types;
713
714 /**
715  * Task to periodically announce itself in the network.
716  */
717 GNUNET_SCHEDULER_TaskIdentifier announce_id_task;
718
719 /**
720  * Next ID to assign to a client.
721  */
722 unsigned int next_client_id;
723
724
725 /******************************************************************************/
726 /***********************         DECLARATIONS        **************************/
727 /******************************************************************************/
728
729 /**
730  * Function to process paths received for a new peer addition. The recorded
731  * paths form the initial tunnel, which can be optimized later.
732  * Called on each result obtained for the DHT search.
733  *
734  * @param cls closure
735  * @param exp when will this value expire
736  * @param key key of the result
737  * @param type type of the result
738  * @param size number of bytes in data
739  * @param data pointer to the result data
740  */
741 static void
742 dht_get_id_handler (void *cls, struct GNUNET_TIME_Absolute exp,
743                     const struct GNUNET_HashCode * key,
744                     const struct GNUNET_PeerIdentity *get_path,
745                     unsigned int get_path_length,
746                     const struct GNUNET_PeerIdentity *put_path,
747                     unsigned int put_path_length, enum GNUNET_BLOCK_Type type,
748                     size_t size, const void *data);
749
750
751 /**
752  * Retrieve the MeshPeerInfo stucture associated with the peer, create one
753  * and insert it in the appropiate structures if the peer is not known yet.
754  *
755  * @param peer Full identity of the peer.
756  *
757  * @return Existing or newly created peer info.
758  */
759 static struct MeshPeerInfo *
760 peer_get (const struct GNUNET_PeerIdentity *peer);
761
762
763 /**
764  * Retrieve the MeshPeerInfo stucture associated with the peer, create one
765  * and insert it in the appropiate structures if the peer is not known yet.
766  *
767  * @param peer Short identity of the peer.
768  *
769  * @return Existing or newly created peer info.
770  */
771 static struct MeshPeerInfo *
772 peer_get_short (const GNUNET_PEER_Id peer);
773
774
775 /**
776  * Build a PeerPath from the paths returned from the DHT, reversing the paths
777  * to obtain a local peer -> destination path and interning the peer ids.
778  *
779  * @return Newly allocated and created path
780  */
781 static struct MeshPeerPath *
782 path_build_from_dht (const struct GNUNET_PeerIdentity *get_path,
783                      unsigned int get_path_length,
784                      const struct GNUNET_PeerIdentity *put_path,
785                      unsigned int put_path_length);
786
787
788 /**
789  * Adds a path to the peer_infos of all the peers in the path
790  *
791  * @param p Path to process.
792  * @param confirmed Whether we know if the path works or not.
793  */
794 static void
795 path_add_to_peers (struct MeshPeerPath *p, int confirmed);
796
797
798
799 /**
800  * Search for a tunnel by global ID using full PeerIdentities.
801  *
802  * @param oid owner of the tunnel.
803  * @param tid global tunnel number.
804  *
805  * @return tunnel handler, NULL if doesn't exist.
806  */
807 static struct MeshTunnel *
808 tunnel_get (const struct GNUNET_PeerIdentity *oid, MESH_TunnelNumber tid);
809
810
811 /**
812  * Delete an active client from the tunnel.
813  *
814  * @param t Tunnel.
815  * @param c Client.
816  */
817 static void
818 tunnel_delete_active_client (struct MeshTunnel *t, const struct MeshClient *c);
819
820 /**
821  * Notify a tunnel that a connection has broken that affects at least
822  * some of its peers.
823  *
824  * @param t Tunnel affected.
825  * @param p1 Peer that got disconnected from p2.
826  * @param p2 Peer that got disconnected from p1.
827  *
828  * @return Short ID of the peer disconnected (either p1 or p2).
829  *         0 if the tunnel remained unaffected.
830  */
831 static GNUNET_PEER_Id
832 tunnel_notify_connection_broken (struct MeshTunnel *t, GNUNET_PEER_Id p1,
833                                  GNUNET_PEER_Id p2);
834
835
836 /**
837  * Get the current ack value for a tunnel, for data going from root to leaves,
838  * taking in account the tunnel mode and the status of all children and clients.
839  *
840  * @param t Tunnel.
841  *
842  * @return Maximum PID allowed.
843  */
844 static uint32_t
845 tunnel_get_fwd_ack (struct MeshTunnel *t);
846
847
848 /**
849  * Add a client to a tunnel, initializing all needed data structures.
850  * 
851  * @param t Tunnel to which add the client.
852  * @param c Client which to add to the tunnel.
853  */
854 static void
855 tunnel_add_client (struct MeshTunnel *t, struct MeshClient *c);
856
857
858 /**
859  * Use the given path for the tunnel.
860  * 
861  * @param t Tunnel to update.
862  * @param p Path to use.
863  */
864 static void
865 tunnel_use_path (struct MeshTunnel *t, struct MeshPeerPath *p);
866
867 /**
868  * @brief Queue and pass message to core when possible.
869  * 
870  * If type is payload (UNICAST, TO_ORIGIN, MULTICAST) checks for queue status
871  * and accounts for it. In case the queue is full, the message is dropped and
872  * a break issued.
873  * 
874  * Otherwise, message is treated as internal and allowed to go regardless of 
875  * queue status.
876  *
877  * @param cls Closure (@c type dependant). It will be used by queue_send to
878  *            build the message to be sent if not already prebuilt.
879  * @param type Type of the message, 0 for a raw message.
880  * @param size Size of the message.
881  * @param dst Neighbor to send message to.
882  * @param t Tunnel this message belongs to.
883  */
884 static void
885 queue_add (void *cls, uint16_t type, size_t size,
886            struct MeshPeerInfo *dst, struct MeshTunnel *t);
887
888
889 /**
890  * Free a transmission that was already queued with all resources
891  * associated to the request.
892  *
893  * @param queue Queue handler to cancel.
894  * @param clear_cls Is it necessary to free associated cls?
895  */
896 static void
897 queue_destroy (struct MeshPeerQueue *queue, int clear_cls);
898
899
900 /**
901  * @brief Get the next transmittable message from the queue.
902  *
903  * This will be the head, except in the case of being a data packet
904  * not allowed by the destination peer.
905  *
906  * @param peer Destination peer.
907  *
908  * @return The next viable MeshPeerQueue element to send to that peer.
909  *         NULL when there are no transmittable messages.
910  */
911 struct MeshPeerQueue *
912 queue_get_next (const struct MeshPeerInfo *peer);
913
914
915 /**
916  * Core callback to write a queued packet to core buffer
917  *
918  * @param cls Closure (peer info).
919  * @param size Number of bytes available in buf.
920  * @param buf Where the to write the message.
921  *
922  * @return number of bytes written to buf
923  */
924 static size_t
925 queue_send (void *cls, size_t size, void *buf);
926
927
928 /******************************************************************************/
929 /************************    PERIODIC FUNCTIONS    ****************************/
930 /******************************************************************************/
931
932 /**
933  * Periodically announce self id in the DHT
934  *
935  * @param cls closure
936  * @param tc task context
937  */
938 static void
939 announce_id (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
940 {
941   struct PBlock block;
942
943   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
944   {
945     announce_id_task = GNUNET_SCHEDULER_NO_TASK;
946     return;
947   }
948   /* TODO
949    * - Set data expiration in function of X
950    * - Adapt X to churn
951    */
952   DEBUG_DHT ("DHT_put for ID %s started.\n", GNUNET_i2s (&my_full_id));
953
954   block.id = my_full_id;
955   block.type = htonl (0);
956   GNUNET_DHT_put (dht_handle,   /* DHT handle */
957                   &my_full_id.hashPubKey,       /* Key to use */
958                   dht_replication_level,     /* Replication level */
959                   GNUNET_DHT_RO_RECORD_ROUTE | GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE,    /* DHT options */
960                   GNUNET_BLOCK_TYPE_MESH_PEER,       /* Block type */
961                   sizeof (block),  /* Size of the data */
962                   (const char *) &block, /* Data itself */
963                   GNUNET_TIME_UNIT_FOREVER_ABS,  /* Data expiration */
964                   GNUNET_TIME_UNIT_FOREVER_REL, /* Retry time */
965                   NULL,         /* Continuation */
966                   NULL);        /* Continuation closure */
967   announce_id_task =
968       GNUNET_SCHEDULER_add_delayed (id_announce_time, &announce_id, cls);
969 }
970
971
972 /******************************************************************************/
973 /******************      GENERAL HELPER FUNCTIONS      ************************/
974 /******************************************************************************/
975
976
977 /**
978  * Check if client has registered with the service and has not disconnected
979  *
980  * @param client the client to check
981  *
982  * @return non-NULL if client exists in the global DLL
983  */
984 static struct MeshClient *
985 client_get (struct GNUNET_SERVER_Client *client)
986 {
987   struct MeshClient *c;
988
989   c = clients_head;
990   while (NULL != c)
991   {
992     if (c->handle == client)
993       return c;
994     c = c->next;
995   }
996   return NULL;
997 }
998
999
1000 /**
1001  * Checks if a given client has subscribed to certain message type
1002  *
1003  * @param message_type Type of message to check
1004  * @param c Client to check
1005  *
1006  * @return GNUNET_YES or GNUNET_NO, depending on subscription status
1007  * 
1008  * FIXME: use of crypto_hash slows it down
1009  *  The 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  * Find faster implementation!
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   GNUNET_CRYPTO_hash (&message_type, sizeof (uint16_t), &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 (GNUNET_SCHEDULER_NO_TASK != t->maintenance_task)
3078     GNUNET_SCHEDULER_cancel (t->maintenance_task);
3079   t->maintenance_task =
3080       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply
3081                                     (refresh_path_time, 4), &tunnel_timeout, t);
3082 }
3083
3084
3085 /******************************************************************************/
3086 /****************      MESH NETWORK HANDLER HELPERS     ***********************/
3087 /******************************************************************************/
3088
3089 /**
3090  * Function to send a create path packet to a peer.
3091  *
3092  * @param cls closure
3093  * @param size number of bytes available in buf
3094  * @param buf where the callee should write the message
3095  * @return number of bytes written to buf
3096  */
3097 static size_t
3098 send_core_path_create (void *cls, size_t size, void *buf)
3099 {
3100   struct MeshTunnel *t = cls;
3101   struct GNUNET_MESH_ManipulatePath *msg;
3102   struct GNUNET_PeerIdentity *peer_ptr;
3103   struct MeshPeerPath *p = t->path;
3104   size_t size_needed;
3105   uint32_t opt;
3106   int i;
3107
3108   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "CREATE PATH sending...\n");
3109   size_needed =
3110       sizeof (struct GNUNET_MESH_ManipulatePath) +
3111       p->length * sizeof (struct GNUNET_PeerIdentity);
3112
3113   if (size < size_needed || NULL == buf)
3114   {
3115     GNUNET_break (0);
3116     return 0;
3117   }
3118   msg = (struct GNUNET_MESH_ManipulatePath *) buf;
3119   msg->header.size = htons (size_needed);
3120   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE);
3121   msg->tid = ntohl (t->id.tid);
3122
3123   opt = 0;
3124   if (GNUNET_YES == t->nobuffer)
3125     opt |= MESH_TUNNEL_OPT_NOBUFFER;
3126   msg->opt = htonl(opt);
3127   msg->reserved = 0;
3128
3129   peer_ptr = (struct GNUNET_PeerIdentity *) &msg[1];
3130   for (i = 0; i < p->length; i++)
3131   {
3132     GNUNET_PEER_resolve (p->peers[i], peer_ptr++);
3133   }
3134
3135   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3136               "CREATE PATH (%u bytes long) sent!\n", size_needed);
3137   return size_needed;
3138 }
3139
3140
3141 /**
3142  * Creates a path ack message in buf and frees all unused resources.
3143  *
3144  * @param cls closure (MeshTransmissionDescriptor)
3145  * @param size number of bytes available in buf
3146  * @param buf where the callee should write the message
3147  * @return number of bytes written to buf
3148  */
3149 static size_t
3150 send_core_path_ack (void *cls, size_t size, void *buf)
3151 {
3152   struct MeshTransmissionDescriptor *info = cls;
3153   struct GNUNET_MESH_PathACK *msg = buf;
3154
3155   GNUNET_assert (NULL != info);
3156   if (sizeof (struct GNUNET_MESH_PathACK) > size)
3157   {
3158     GNUNET_break (0);
3159     return 0;
3160   }
3161   msg->header.size = htons (sizeof (struct GNUNET_MESH_PathACK));
3162   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_ACK);
3163   GNUNET_PEER_resolve (info->origin->oid, &msg->oid);
3164   msg->tid = htonl (info->origin->tid);
3165   msg->peer_id = my_full_id;
3166
3167   GNUNET_free (info);
3168   /* TODO add signature */
3169
3170   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "PATH ACK sent!\n");
3171   return sizeof (struct GNUNET_MESH_PathACK);
3172 }
3173
3174
3175 /**
3176  * Free a transmission that was already queued with all resources
3177  * associated to the request.
3178  *
3179  * @param queue Queue handler to cancel.
3180  * @param clear_cls Is it necessary to free associated cls?
3181  */
3182 static void
3183 queue_destroy (struct MeshPeerQueue *queue, int clear_cls)
3184 {
3185   struct MeshTransmissionDescriptor *dd;
3186 //   unsigned int max;
3187
3188   if (GNUNET_YES == clear_cls)
3189   {
3190     switch (queue->type)
3191     {
3192       case GNUNET_MESSAGE_TYPE_MESH_TUNNEL_DESTROY:
3193         GNUNET_log (GNUNET_ERROR_TYPE_INFO, "   cancelling TUNNEL_DESTROY\n");
3194         GNUNET_break (GNUNET_YES == queue->tunnel->destroy);
3195         /* fall through */
3196       case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
3197       case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
3198       case GNUNET_MESSAGE_TYPE_MESH_ACK:
3199       case GNUNET_MESSAGE_TYPE_MESH_POLL:
3200       case GNUNET_MESSAGE_TYPE_MESH_PATH_KEEPALIVE:
3201         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3202                     "   prebuilt message\n");
3203         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3204                     "   type %s\n",
3205                     GNUNET_MESH_DEBUG_M2S(queue->type));
3206         dd = queue->cls;
3207         GNUNET_free (dd->data);
3208         break;
3209       case GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE:
3210         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   type create path\n");
3211         break;
3212       default:
3213         GNUNET_break (0);
3214         GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3215                     "   type %s unknown!\n",
3216                     GNUNET_MESH_DEBUG_M2S(queue->type));
3217     }
3218     GNUNET_free_non_null (queue->cls);
3219   }
3220   GNUNET_CONTAINER_DLL_remove (queue->peer->queue_head,
3221                                queue->peer->queue_tail,
3222                                queue);
3223
3224   /* Delete from child_fc in the appropiate tunnel */
3225 //   max = queue->tunnel->fwd_queue_max;
3226 //   GNUNET_PEER_resolve (queue->peer->id, &id);
3227 //   if (NULL != cinfo)
3228 //   { FIXME
3229 //     for (i = 0; i < cinfo->send_buffer_n; i++)
3230 //     {
3231 //       i2 = (cinfo->send_buffer_start + i) % max;
3232 //       if (cinfo->send_buffer[i2] == queue)
3233 //       {
3234 //         /* Found corresponding entry in the send_buffer. Move all others back. */
3235 //         unsigned int j;
3236 // 
3237 // 
3238 //         for (j = i, j2 = 0, j3 = 0; j < cinfo->send_buffer_n - 1; j++)
3239 //         {
3240 //           j2 = (cinfo->send_buffer_start + j) % max;
3241 //           j3 = (cinfo->send_buffer_start + j + 1) % max;
3242 //           cinfo->send_buffer[j2] = cinfo->send_buffer[j3];
3243 //         }
3244 // 
3245 //         cinfo->send_buffer[j3] = NULL;
3246 //         cinfo->send_buffer_n--;
3247 //       }
3248 //     }
3249 //   }
3250
3251   GNUNET_free (queue);
3252 }
3253
3254
3255 /**
3256  * @brief Get the next transmittable message from the queue.
3257  *
3258  * This will be the head, except in the case of being a data packet
3259  * not allowed by the destination peer.
3260  *
3261  * @param peer Destination peer.
3262  *
3263  * @return The next viable MeshPeerQueue element to send to that peer.
3264  *         NULL when there are no transmittable messages.
3265  */
3266 struct MeshPeerQueue *
3267 queue_get_next (const struct MeshPeerInfo *peer)
3268 {
3269   struct MeshPeerQueue *q;
3270  
3271   struct MeshTransmissionDescriptor *info;
3272 //   struct GNUNET_MESH_Unicast *ucast;
3273 //   struct GNUNET_MESH_ToOrigin *to_orig;
3274   struct GNUNET_PeerIdentity id;
3275 //   uint32_t pid;
3276 //   uint32_t ack; FIXME
3277
3278   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   selecting message\n");
3279   for (q = peer->queue_head; NULL != q; q = q->next)
3280   {
3281 //     t = q->tunnel;
3282     info = q->cls;
3283     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3284                 "*********     %s\n",
3285                 GNUNET_MESH_DEBUG_M2S(q->type));
3286     switch (q->type)
3287     {
3288       case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
3289 //         ucast = (struct GNUNET_MESH_Unicast *) info->mesh_data->data;
3290 //         pid = ntohl (ucast->pid);
3291         GNUNET_PEER_resolve (info->peer->id, &id);
3292 //         ack = cinfo->fwd_ack;
3293         break;
3294       case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
3295 //         to_orig = (struct GNUNET_MESH_ToOrigin *) info->mesh_data->data;
3296 //         pid = ntohl (to_orig->pid);
3297 //         ack = t->bck_ack;
3298         break;
3299       default:
3300         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3301                     "*********   OK!\n");
3302         return q;
3303     }
3304 //     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3305 //                 "*********     ACK: %u, PID: %u\n",
3306 //                 ack, pid);
3307 //     if (GNUNET_NO == GMC_is_pid_bigger(pid, ack))
3308 //     {
3309 //       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3310 //                   "*********   OK!\n");
3311 //       return q;
3312 //     }
3313 //     else
3314 //     {
3315 //       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3316 //                   "*********     NEXT!\n");
3317 //     }
3318   }
3319   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3320                 "*********   nothing found\n");
3321   return NULL;
3322 }
3323
3324
3325 static size_t
3326 queue_send (void *cls, size_t size, void *buf)
3327 {
3328     struct MeshPeerInfo *peer = cls;
3329     struct GNUNET_MessageHeader *msg;
3330     struct MeshPeerQueue *queue;
3331     struct MeshTunnel *t;
3332     struct GNUNET_PeerIdentity dst_id;
3333     struct MeshFlowControl *fc;
3334     size_t data_size;
3335
3336     peer->core_transmit = NULL;
3337
3338     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "********* Queue send\n");
3339     queue = queue_get_next (peer);
3340
3341     /* Queue has no internal mesh traffic nor sendable payload */
3342     if (NULL == queue)
3343     {
3344       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   not ready, return\n");
3345       if (NULL == peer->queue_head)
3346         GNUNET_break (0); /* Core tmt_rdy should've been canceled */
3347       return 0;
3348     }
3349     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   not empty\n");
3350
3351     GNUNET_PEER_resolve (peer->id, &dst_id);
3352     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3353                 "*********   towards %s\n",
3354                 GNUNET_i2s(&dst_id));
3355     /* Check if buffer size is enough for the message */
3356     if (queue->size > size)
3357     {
3358         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3359                     "*********   not enough room, reissue\n");
3360         peer->core_transmit =
3361             GNUNET_CORE_notify_transmit_ready (core_handle,
3362                                                0,
3363                                                0,
3364                                                GNUNET_TIME_UNIT_FOREVER_REL,
3365                                                &dst_id,
3366                                                queue->size,
3367                                                &queue_send,
3368                                                peer);
3369         return 0;
3370     }
3371     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   size ok\n");
3372
3373     t = queue->tunnel;
3374     GNUNET_assert (0 < t->pending_messages);
3375     t->pending_messages--;
3376     if (GNUNET_MESSAGE_TYPE_MESH_UNICAST == queue->type)
3377     {
3378       t->next_fc.queue_n--;
3379       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3380                   "*********   unicast: t->q (%u/%u)\n",
3381                   t->next_fc.queue_n, t->queue_max);
3382     }
3383     else if (GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN == queue->type)
3384     {
3385       t->prev_fc.queue_n--;
3386       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3387                   "*********   to orig: t->q (%u/%u)\n",
3388                   t->prev_fc.queue_n, t->queue_max);
3389     }
3390
3391     /* Fill buf */
3392     switch (queue->type)
3393     {
3394       case 0:
3395       case GNUNET_MESSAGE_TYPE_MESH_ACK:
3396       case GNUNET_MESSAGE_TYPE_MESH_POLL:
3397       case GNUNET_MESSAGE_TYPE_MESH_PATH_BROKEN:
3398       case GNUNET_MESSAGE_TYPE_MESH_PATH_DESTROY:
3399       case GNUNET_MESSAGE_TYPE_MESH_TUNNEL_DESTROY:
3400       case GNUNET_MESSAGE_TYPE_MESH_PATH_KEEPALIVE:
3401         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3402                     "*********   raw: %s\n",
3403                     GNUNET_MESH_DEBUG_M2S (queue->type));
3404         /* Fall through */
3405       case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
3406       case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
3407         data_size = send_core_data_raw (queue->cls, size, buf);
3408         msg = (struct GNUNET_MessageHeader *) buf;
3409         switch (ntohs (msg->type)) // Type of preconstructed message
3410         {
3411           case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
3412             tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_UNICAST);
3413             break;
3414           case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
3415             tunnel_send_bck_ack (t, GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN);
3416             break;
3417           default:
3418               break;
3419         }
3420         break;
3421       case GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE:
3422         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   path create\n");
3423         data_size = send_core_path_create (queue->cls, size, buf);
3424         break;
3425       case GNUNET_MESSAGE_TYPE_MESH_PATH_ACK:
3426         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   path ack\n");
3427         data_size = send_core_path_ack (queue->cls, size, buf);
3428         break;
3429       default:
3430         GNUNET_break (0);
3431         GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3432                     "*********   type unknown: %u\n",
3433                     queue->type);
3434         data_size = 0;
3435     }
3436     switch (queue->type)
3437     {
3438       case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
3439       case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
3440 //         if (cinfo->send_buffer[cinfo->send_buffer_start] != queue)
3441 //         { FIXME
3442 //           GNUNET_break (0);
3443 //           GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3444 //                       "at pos %u (%p) != %p\n",
3445 //                       cinfo->send_buffer_start,
3446 //                       cinfo->send_buffer[cinfo->send_buffer_start],
3447 //                       queue);
3448 //         }
3449 //         if (cinfo->send_buffer_n > 0)
3450 //         {
3451 //           cinfo->send_buffer[cinfo->send_buffer_start] = NULL;
3452 //           cinfo->send_buffer_n--;
3453 //           cinfo->send_buffer_start++;
3454 //           cinfo->send_buffer_start %= t->fwd_queue_max;
3455 //         }
3456 //         else
3457 //         {
3458 //           GNUNET_break (0);
3459 //         }
3460         break;
3461       default:
3462         break;
3463     }
3464
3465     /* Free queue, but cls was freed by send_core_* */
3466     queue_destroy (queue, GNUNET_NO);
3467
3468     if (GNUNET_YES == t->destroy && 0 == t->pending_messages)
3469     {
3470       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********  destroying tunnel!\n");
3471       tunnel_destroy (t);
3472     }
3473
3474     /* If more data in queue, send next */
3475     queue = queue_get_next (peer);
3476     if (NULL != queue)
3477     {
3478         struct GNUNET_PeerIdentity id;
3479
3480         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   more data!\n");
3481         GNUNET_PEER_resolve (peer->id, &id);
3482         peer->core_transmit =
3483             GNUNET_CORE_notify_transmit_ready(core_handle,
3484                                               0,
3485                                               0,
3486                                               GNUNET_TIME_UNIT_FOREVER_REL,
3487                                               &id,
3488                                               queue->size,
3489                                               &queue_send,
3490                                               peer);
3491     }
3492     else
3493     {
3494       if (NULL != peer->queue_head)
3495       {
3496         GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3497                     "*********   %s stalled\n",
3498                     GNUNET_i2s(&my_full_id));
3499         if (peer->id == t->next_hop)
3500           fc = &t->next_fc;
3501         else
3502           fc = &t->prev_fc;
3503         if (GNUNET_SCHEDULER_NO_TASK == fc->poll_task)
3504         {
3505           fc->t = t;
3506           fc->poll_task = GNUNET_SCHEDULER_add_delayed (fc->poll_time,
3507                                                         &tunnel_poll, fc);
3508         }
3509       }
3510     }
3511     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   return %d\n", data_size);
3512     return data_size;
3513 }
3514
3515
3516 /**
3517  * @brief Queue and pass message to core when possible.
3518  * 
3519  * If type is payload (UNICAST, TO_ORIGIN) checks for queue status and
3520  * accounts for it. In case the queue is full, the message is dropped and
3521  * a break issued.
3522  * 
3523  * Otherwise, message is treated as internal and allowed to go regardless of 
3524  * queue status.
3525  *
3526  * @param cls Closure (@c type dependant). It will be used by queue_send to
3527  *            build the message to be sent if not already prebuilt.
3528  * @param type Type of the message, 0 for a raw message.
3529  * @param size Size of the message.
3530  * @param dst Neighbor to send message to.
3531  * @param t Tunnel this message belongs to.
3532  */
3533 static void
3534 queue_add (void *cls, uint16_t type, size_t size,
3535            struct MeshPeerInfo *dst, struct MeshTunnel *t)
3536 {
3537   struct MeshPeerQueue *queue;
3538   struct GNUNET_PeerIdentity id;
3539   unsigned int *n;
3540
3541   n = NULL;
3542   if (GNUNET_MESSAGE_TYPE_MESH_UNICAST == type)
3543   {
3544     n = &t->next_fc.queue_n;
3545   }
3546   else if (GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN == type)
3547   {
3548     n = &t->prev_fc.queue_n;
3549   }
3550   if (NULL != n)
3551   {
3552     if (*n >= t->queue_max)
3553     {
3554       GNUNET_break(0);
3555       GNUNET_STATISTICS_update(stats,
3556                                "# messages dropped (buffer full)",
3557                                1, GNUNET_NO);
3558       return; // Drop message
3559     }
3560     (*n)++;
3561   }
3562   queue = GNUNET_malloc (sizeof (struct MeshPeerQueue));
3563   queue->cls = cls;
3564   queue->type = type;
3565   queue->size = size;
3566   queue->peer = dst;
3567   queue->tunnel = t;
3568   GNUNET_CONTAINER_DLL_insert_tail (dst->queue_head, dst->queue_tail, queue);
3569   if (NULL == dst->core_transmit)
3570   {
3571     GNUNET_PEER_resolve (dst->id, &id);
3572     dst->core_transmit =
3573         GNUNET_CORE_notify_transmit_ready (core_handle,
3574                                            0,
3575                                            0,
3576                                            GNUNET_TIME_UNIT_FOREVER_REL,
3577                                            &id,
3578                                            size,
3579                                            &queue_send,
3580                                            dst);
3581   }
3582   t->pending_messages++;
3583 }
3584
3585
3586 /******************************************************************************/
3587 /********************      MESH NETWORK HANDLERS     **************************/
3588 /******************************************************************************/
3589
3590
3591 /**
3592  * Core handler for path creation
3593  *
3594  * @param cls closure
3595  * @param message message
3596  * @param peer peer identity this notification is about
3597  *
3598  * @return GNUNET_OK to keep the connection open,
3599  *         GNUNET_SYSERR to close it (signal serious error)
3600  */
3601 static int
3602 handle_mesh_path_create (void *cls, const struct GNUNET_PeerIdentity *peer,
3603                          const struct GNUNET_MessageHeader *message)
3604 {
3605   unsigned int own_pos;
3606   uint16_t size;
3607   uint16_t i;
3608   MESH_TunnelNumber tid;
3609   struct GNUNET_MESH_ManipulatePath *msg;
3610   struct GNUNET_PeerIdentity *pi;
3611   struct GNUNET_HashCode hash;
3612   struct MeshPeerPath *path;
3613   struct MeshPeerInfo *dest_peer_info;
3614   struct MeshPeerInfo *orig_peer_info;
3615   struct MeshTunnel *t;
3616
3617   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3618               "Received a path create msg [%s]\n",
3619               GNUNET_i2s (&my_full_id));
3620   size = ntohs (message->size);
3621   if (size < sizeof (struct GNUNET_MESH_ManipulatePath))
3622   {
3623     GNUNET_break_op (0);
3624     return GNUNET_OK;
3625   }
3626
3627   size -= sizeof (struct GNUNET_MESH_ManipulatePath);
3628   if (size % sizeof (struct GNUNET_PeerIdentity))
3629   {
3630     GNUNET_break_op (0);
3631     return GNUNET_OK;
3632   }
3633   size /= sizeof (struct GNUNET_PeerIdentity);
3634   if (size < 2)
3635   {
3636     GNUNET_break_op (0);
3637     return GNUNET_OK;
3638   }
3639   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "    path has %u hops.\n", size);
3640   msg = (struct GNUNET_MESH_ManipulatePath *) message;
3641
3642   tid = ntohl (msg->tid);
3643   pi = (struct GNUNET_PeerIdentity *) &msg[1];
3644   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3645               "    path is for tunnel %s [%X].\n", GNUNET_i2s (pi), tid);
3646   t = tunnel_get (pi, tid);
3647   if (NULL == t) // FIXME only for INCOMING tunnels?
3648   {
3649     uint32_t opt;
3650
3651     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Creating tunnel\n");
3652     t = tunnel_new (GNUNET_PEER_intern (pi), tid, NULL, 0);
3653     if (NULL == t)
3654     {
3655       // FIXME notify failure
3656       return GNUNET_OK;
3657     }
3658     opt = ntohl (msg->opt);
3659     if (0 != (opt & MESH_TUNNEL_OPT_NOBUFFER))
3660     {
3661       t->nobuffer = GNUNET_YES;
3662       t->prev_fc.last_ack_sent = t->prev_fc.last_pid_recv + 1;
3663     }
3664     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  nobuffer:%d\n", t->nobuffer);
3665
3666     if (GNUNET_YES == t->nobuffer)
3667     {
3668       t->queue_max = 1;
3669     }
3670
3671     // FIXME only assign a local tid if a local client is interested (on demand)
3672     while (NULL != tunnel_get_incoming (next_local_tid))
3673       next_local_tid = (next_local_tid + 1) | GNUNET_MESH_LOCAL_TUNNEL_ID_SERV;
3674     t->local_tid_dest = next_local_tid++;
3675     next_local_tid = next_local_tid | GNUNET_MESH_LOCAL_TUNNEL_ID_SERV;
3676     // FIXME end
3677
3678     tunnel_reset_timeout (t);
3679     GNUNET_CRYPTO_hash (&t->local_tid_dest, sizeof (MESH_TunnelNumber), &hash);
3680     if (GNUNET_OK !=
3681         GNUNET_CONTAINER_multihashmap_put (incoming_tunnels, &hash, t,
3682                                            GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
3683     {
3684       tunnel_destroy (t);
3685       GNUNET_break (0);
3686       return GNUNET_OK;
3687     }
3688   }
3689   dest_peer_info =
3690       GNUNET_CONTAINER_multihashmap_get (peers, &pi[size - 1].hashPubKey);
3691   if (NULL == dest_peer_info)
3692   {
3693     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3694                 "  Creating PeerInfo for destination.\n");
3695     dest_peer_info = GNUNET_malloc (sizeof (struct MeshPeerInfo));
3696     dest_peer_info->id = GNUNET_PEER_intern (&pi[size - 1]);
3697     GNUNET_CONTAINER_multihashmap_put (peers, &pi[size - 1].hashPubKey,
3698                                        dest_peer_info,
3699                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
3700   }
3701   orig_peer_info = GNUNET_CONTAINER_multihashmap_get (peers, &pi->hashPubKey);
3702   if (NULL == orig_peer_info)
3703   {
3704     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3705                 "  Creating PeerInfo for origin.\n");
3706     orig_peer_info = GNUNET_malloc (sizeof (struct MeshPeerInfo));
3707     orig_peer_info->id = GNUNET_PEER_intern (pi);
3708     GNUNET_CONTAINER_multihashmap_put (peers, &pi->hashPubKey, orig_peer_info,
3709                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
3710   }
3711   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Creating path...\n");
3712   path = path_new (size);
3713   own_pos = 0;
3714   for (i = 0; i < size; i++)
3715   {
3716     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  ... adding %s\n",
3717                 GNUNET_i2s (&pi[i]));
3718     path->peers[i] = GNUNET_PEER_intern (&pi[i]);
3719     if (path->peers[i] == myid)
3720       own_pos = i;
3721   }
3722   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Own position: %u\n", own_pos);
3723   if (own_pos == 0)
3724   {
3725     /* cannot be self, must be 'not found' */
3726     /* create path: self not found in path through self */
3727     GNUNET_break_op (0);
3728     path_destroy (path);
3729     tunnel_destroy (t);
3730     return GNUNET_OK;
3731   }
3732   path_add_to_peers (path, GNUNET_NO);
3733   t->prev_hop = path->peers[own_pos - 1];
3734   GNUNET_PEER_change_rc (t->prev_hop, 1);
3735   if (own_pos == size - 1)
3736   {
3737     /* It is for us! Send ack. */
3738     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  It's for us!\n");
3739     peer_info_add_path_to_origin (orig_peer_info, path, GNUNET_NO);
3740     t->dest = myid;
3741     send_path_ack (t);
3742   }
3743   else
3744   {
3745     struct MeshPeerPath *path2;
3746
3747     t->next_hop = path->peers[own_pos + 1];
3748     GNUNET_PEER_change_rc(t->next_hop, 1);
3749
3750     /* It's for somebody else! Retransmit. */
3751     path2 = path_duplicate (path);
3752     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Retransmitting.\n");
3753     peer_info_add_path (dest_peer_info, path2, GNUNET_NO);
3754     path2 = path_duplicate (path);
3755     peer_info_add_path_to_origin (orig_peer_info, path2, GNUNET_NO);
3756     send_create_path (dest_peer_info, path, t);
3757   }
3758   return GNUNET_OK;
3759 }
3760
3761
3762 /**
3763  * Core handler for path destruction
3764  *
3765  * @param cls closure
3766  * @param message message
3767  * @param peer peer identity this notification is about
3768  *
3769  * @return GNUNET_OK to keep the connection open,
3770  *         GNUNET_SYSERR to close it (signal serious error)
3771  */
3772 static int
3773 handle_mesh_path_destroy (void *cls, const struct GNUNET_PeerIdentity *peer,
3774                           const struct GNUNET_MessageHeader *message)
3775 {
3776   struct GNUNET_MESH_ManipulatePath *msg;
3777   struct GNUNET_PeerIdentity *pi;
3778   struct MeshPeerPath *path;
3779   struct MeshTunnel *t;
3780   unsigned int own_pos;
3781   unsigned int i;
3782   size_t size;
3783
3784   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3785               "Received a PATH DESTROY msg from %s\n", GNUNET_i2s (peer));
3786   size = ntohs (message->size);
3787   if (size < sizeof (struct GNUNET_MESH_ManipulatePath))
3788   {
3789     GNUNET_break_op (0);
3790     return GNUNET_OK;
3791   }
3792
3793   size -= sizeof (struct GNUNET_MESH_ManipulatePath);
3794   if (size % sizeof (struct GNUNET_PeerIdentity))
3795   {
3796     GNUNET_break_op (0);
3797     return GNUNET_OK;
3798   }
3799   size /= sizeof (struct GNUNET_PeerIdentity);
3800   if (size < 2)
3801   {
3802     GNUNET_break_op (0);
3803     return GNUNET_OK;
3804   }
3805   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "    path has %u hops.\n", size);
3806
3807   msg = (struct GNUNET_MESH_ManipulatePath *) message;
3808   pi = (struct GNUNET_PeerIdentity *) &msg[1];
3809   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3810               "    path is for tunnel %s [%X].\n", GNUNET_i2s (pi),
3811               msg->tid);
3812   t = tunnel_get (pi, ntohl (msg->tid));
3813   if (NULL == t)
3814   {
3815     /* TODO notify back: we don't know this tunnel */
3816     GNUNET_break_op (0);
3817     return GNUNET_OK;
3818   }
3819   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Creating path...\n");
3820   path = path_new (size);
3821   own_pos = 0;
3822   for (i = 0; i < size; i++)
3823   {
3824     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  ... adding %s\n",
3825                 GNUNET_i2s (&pi[i]));
3826     path->peers[i] = GNUNET_PEER_intern (&pi[i]);
3827     if (path->peers[i] == myid)
3828       own_pos = i;
3829   }
3830   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Own position: %u\n", own_pos);
3831   if (own_pos < path->length - 1)
3832     send_prebuilt_message (message, path->peers[own_pos + 1], t);
3833   else
3834     send_client_tunnel_disconnect(t, NULL);
3835
3836 //   tunnel_delete_peer (t, path->peers[path->length - 1]); FIXME
3837   path_destroy (path);
3838   return GNUNET_OK;
3839 }
3840
3841
3842 /**
3843  * Core handler for notifications of broken paths
3844  *
3845  * @param cls closure
3846  * @param message message
3847  * @param peer peer identity this notification is about
3848  *
3849  * @return GNUNET_OK to keep the connection open,
3850  *         GNUNET_SYSERR to close it (signal serious error)
3851  */
3852 static int
3853 handle_mesh_path_broken (void *cls, const struct GNUNET_PeerIdentity *peer,
3854                          const struct GNUNET_MessageHeader *message)
3855 {
3856   struct GNUNET_MESH_PathBroken *msg;
3857   struct MeshTunnel *t;
3858
3859   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3860               "Received a PATH BROKEN msg from %s\n", GNUNET_i2s (peer));
3861   msg = (struct GNUNET_MESH_PathBroken *) message;
3862   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  regarding %s\n",
3863               GNUNET_i2s (&msg->peer1));
3864   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  regarding %s\n",
3865               GNUNET_i2s (&msg->peer2));
3866   t = tunnel_get (&msg->oid, ntohl (msg->tid));
3867   if (NULL == t)
3868   {
3869     GNUNET_break_op (0);
3870     return GNUNET_OK;
3871   }
3872   tunnel_notify_connection_broken (t, GNUNET_PEER_search (&msg->peer1),
3873                                    GNUNET_PEER_search (&msg->peer2));
3874   return GNUNET_OK;
3875
3876 }
3877
3878
3879 /**
3880  * Core handler for tunnel destruction
3881  *
3882  * @param cls closure
3883  * @param message message
3884  * @param peer peer identity this notification is about
3885  *
3886  * @return GNUNET_OK to keep the connection open,
3887  *         GNUNET_SYSERR to close it (signal serious error)
3888  */
3889 static int
3890 handle_mesh_tunnel_destroy (void *cls, const struct GNUNET_PeerIdentity *peer,
3891                             const struct GNUNET_MessageHeader *message)
3892 {
3893   struct GNUNET_MESH_TunnelDestroy *msg;
3894   struct MeshTunnel *t;
3895   GNUNET_PEER_Id pid;
3896
3897   msg = (struct GNUNET_MESH_TunnelDestroy *) message;
3898   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3899               "Got a TUNNEL DESTROY packet from %s\n",
3900               GNUNET_i2s (peer));
3901   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3902               "  for tunnel %s [%u]\n",
3903               GNUNET_i2s (&msg->oid), ntohl (msg->tid));
3904   t = tunnel_get (&msg->oid, ntohl (msg->tid));
3905   /* Check signature */
3906   if (NULL == t)
3907   {
3908     /* Probably already got the message from another path,
3909      * destroyed the tunnel and retransmitted to children.
3910      * Safe to ignore.
3911      */
3912     GNUNET_STATISTICS_update (stats, "# control on unknown tunnel",
3913                               1, GNUNET_NO);
3914     return GNUNET_OK;
3915   }
3916   pid = GNUNET_PEER_search (peer);
3917   if (pid != t->prev_hop && 0 < t->nclients)
3918   {
3919     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3920                 "still in use by %u clients\n",
3921                 t->nclients);
3922     return GNUNET_OK;
3923   }
3924   if (t->local_tid_dest >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
3925   {
3926     /* Tunnel was incoming, notify clients */
3927     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "INCOMING TUNNEL %X %X\n",
3928                 t->local_tid, t->local_tid_dest);
3929     send_clients_tunnel_destroy (t);
3930   }
3931   tunnel_send_destroy (t);
3932   t->destroy = GNUNET_YES;
3933   // TODO: add timeout to destroy the tunnel anyway
3934   return GNUNET_OK;
3935 }
3936
3937
3938 /**
3939  * Core handler for mesh network traffic going from the origin to a peer
3940  *
3941  * @param cls closure
3942  * @param peer peer identity this notification is about
3943  * @param message message
3944  * @return GNUNET_OK to keep the connection open,
3945  *         GNUNET_SYSERR to close it (signal serious error)
3946  */
3947 static int
3948 handle_mesh_data_unicast (void *cls, const struct GNUNET_PeerIdentity *peer,
3949                           const struct GNUNET_MessageHeader *message)
3950 {
3951   struct GNUNET_MESH_Unicast *msg;
3952   struct MeshTunnel *t;
3953   uint32_t pid;
3954   uint32_t ttl;
3955   size_t size;
3956
3957   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a unicast packet from %s\n",
3958               GNUNET_i2s (peer));
3959   /* Check size */
3960   size = ntohs (message->size);
3961   if (size <
3962       sizeof (struct GNUNET_MESH_Unicast) +
3963       sizeof (struct GNUNET_MessageHeader))
3964   {
3965     GNUNET_break (0);
3966     return GNUNET_OK;
3967   }
3968   msg = (struct GNUNET_MESH_Unicast *) message;
3969   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " of type %s\n",
3970               GNUNET_MESH_DEBUG_M2S (ntohs (msg[1].header.type)));
3971   /* Check tunnel */
3972   t = tunnel_get (&msg->oid, ntohl (msg->tid));
3973   if (NULL == t)
3974   {
3975     /* TODO notify back: we don't know this tunnel */
3976     GNUNET_STATISTICS_update (stats, "# data on unknown tunnel", 1, GNUNET_NO);
3977     GNUNET_break_op (0);
3978     return GNUNET_OK;
3979   }
3980   pid = ntohl (msg->pid);
3981   if (t->prev_fc.last_pid_recv == pid)
3982   {
3983     GNUNET_STATISTICS_update (stats, "# duplicate PID drops", 1, GNUNET_NO);
3984     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3985                 " Already seen pid %u, DROPPING!\n", pid);
3986     return GNUNET_OK;
3987   }
3988   else
3989   {
3990     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3991                 " pid %u not seen yet, forwarding\n", pid);
3992   }
3993
3994   t->prev_fc.last_pid_recv = pid;
3995
3996   if (GMC_is_pid_bigger (pid, t->prev_fc.last_ack_sent))
3997   {
3998     GNUNET_STATISTICS_update (stats, "# unsolicited unicast", 1, GNUNET_NO);
3999     GNUNET_break_op (0);
4000     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4001                 "Received PID %u, ACK %u\n",
4002                 pid, t->prev_fc.last_ack_sent);
4003     return GNUNET_OK;
4004   }
4005
4006   tunnel_reset_timeout (t);
4007   if (t->dest == myid)
4008   {
4009     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4010                 "  it's for us! sending to clients...\n");
4011     GNUNET_STATISTICS_update (stats, "# unicast received", 1, GNUNET_NO);
4012     send_subscribed_clients (message, &msg[1].header, t);
4013     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_UNICAST);
4014     return GNUNET_OK;
4015   }
4016   ttl = ntohl (msg->ttl);
4017   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   ttl: %u\n", ttl);
4018   if (ttl == 0)
4019   {
4020     GNUNET_STATISTICS_update (stats, "# TTL drops", 1, GNUNET_NO);
4021     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, " TTL is 0, DROPPING!\n");
4022     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_ACK);
4023     return GNUNET_OK;
4024   }
4025   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4026               "  not for us, retransmitting...\n");
4027
4028   if (GNUNET_YES == t->nobuffer &&
4029       GNUNET_YES == GMC_is_pid_bigger (pid, t->next_fc.last_ack_recv))
4030   {
4031     GNUNET_STATISTICS_update (stats, "# unsolicited unicast", 1, GNUNET_NO);
4032     GNUNET_log (GNUNET_ERROR_TYPE_INFO, "  %u > %u\n",
4033                 pid, t->next_fc.last_ack_recv);
4034     GNUNET_break_op (0);
4035     return GNUNET_OK;
4036   }
4037   send_prebuilt_message (message, t->next_hop, t);
4038   GNUNET_STATISTICS_update (stats, "# unicast forwarded", 1, GNUNET_NO);
4039   return GNUNET_OK;
4040 }
4041
4042
4043 /**
4044  * Core handler for mesh network traffic toward the owner of a tunnel
4045  *
4046  * @param cls closure
4047  * @param message message
4048  * @param peer peer identity this notification is about
4049  *
4050  * @return GNUNET_OK to keep the connection open,
4051  *         GNUNET_SYSERR to close it (signal serious error)
4052  */
4053 static int
4054 handle_mesh_data_to_orig (void *cls, const struct GNUNET_PeerIdentity *peer,
4055                           const struct GNUNET_MessageHeader *message)
4056 {
4057   struct GNUNET_MESH_ToOrigin *msg;
4058   struct MeshPeerInfo *peer_info;
4059   struct MeshTunnel *t;
4060   size_t size;
4061   uint32_t pid;
4062
4063   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a ToOrigin packet from %s\n",
4064               GNUNET_i2s (peer));
4065   size = ntohs (message->size);
4066   if (size < sizeof (struct GNUNET_MESH_ToOrigin) +     /* Payload must be */
4067       sizeof (struct GNUNET_MessageHeader))     /* at least a header */
4068   {
4069     GNUNET_break_op (0);
4070     return GNUNET_OK;
4071   }
4072   msg = (struct GNUNET_MESH_ToOrigin *) message;
4073   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " of type %s\n",
4074               GNUNET_MESH_DEBUG_M2S (ntohs (msg[1].header.type)));
4075   t = tunnel_get (&msg->oid, ntohl (msg->tid));
4076   pid = ntohl (msg->pid);
4077
4078   if (NULL == t)
4079   {
4080     /* TODO notify that we dont know this tunnel (whom)? */
4081     GNUNET_STATISTICS_update (stats, "# data on unknown tunnel", 1, GNUNET_NO);
4082     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4083                 "Received to_origin with PID %u on unknown tunnel %s [%u]\n",
4084                 pid, GNUNET_i2s (&msg->oid), ntohl (msg->tid));
4085     return GNUNET_OK;
4086   }
4087
4088
4089   if (t->next_fc.last_pid_recv == pid)
4090   {
4091     /* already seen this packet, drop */
4092     GNUNET_STATISTICS_update (stats, "# duplicate PID drops BCK", 1, GNUNET_NO);
4093     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4094                 " Already seen pid %u, DROPPING!\n", pid);
4095     tunnel_send_bck_ack (t, GNUNET_MESSAGE_TYPE_MESH_ACK);
4096     return GNUNET_OK;
4097   }
4098
4099   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4100               " pid %u not seen yet, forwarding\n", pid);
4101   t->next_fc.last_pid_recv = pid;
4102
4103   if (NULL != t->owner)
4104   {
4105     char cbuf[size];
4106     struct GNUNET_MESH_ToOrigin *copy;
4107
4108     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4109                 "  it's for us! sending to clients...\n");
4110     /* TODO signature verification */
4111     memcpy (cbuf, message, size);
4112     copy = (struct GNUNET_MESH_ToOrigin *) cbuf;
4113     copy->tid = htonl (t->local_tid);
4114     GNUNET_STATISTICS_update (stats, "# to origin received", 1, GNUNET_NO);
4115     GNUNET_SERVER_notification_context_unicast (nc, t->owner->handle,
4116                                                 &copy->header, GNUNET_NO);
4117     tunnel_send_bck_ack (t, GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN);
4118     return GNUNET_OK;
4119   }
4120   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4121               "  not for us, retransmitting...\n");
4122
4123   peer_info = peer_get (&msg->oid);
4124   if (NULL == peer_info)
4125   {
4126     /* unknown origin of tunnel */
4127     GNUNET_break (0);
4128     return GNUNET_OK;
4129   }
4130   if (0 == t->prev_hop) /* No owner AND no prev hop */
4131   {
4132     if (GNUNET_YES == t->destroy)
4133     {
4134       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4135                   "to orig received on a dying tunnel %s [%X]\n",
4136                   GNUNET_i2s (&msg->oid), ntohl(msg->tid));
4137       return GNUNET_OK;
4138     }
4139     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, 
4140                 "unknown to origin at %s\n",
4141                 GNUNET_i2s (&my_full_id));
4142     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, 
4143                 "from peer %s\n",
4144                 GNUNET_i2s (peer));
4145     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, 
4146                 "for tunnel %s [%X]\n",
4147                 GNUNET_i2s (&msg->oid), ntohl(msg->tid));
4148     return GNUNET_OK;
4149   }
4150   send_prebuilt_message (message, t->prev_hop, t);
4151   GNUNET_STATISTICS_update (stats, "# to origin forwarded", 1, GNUNET_NO);
4152
4153   return GNUNET_OK;
4154 }
4155
4156
4157 /**
4158  * Core handler for mesh network traffic point-to-point acks.
4159  *
4160  * @param cls closure
4161  * @param message message
4162  * @param peer peer identity this notification is about
4163  *
4164  * @return GNUNET_OK to keep the connection open,
4165  *         GNUNET_SYSERR to close it (signal serious error)
4166  */
4167 static int
4168 handle_mesh_ack (void *cls, const struct GNUNET_PeerIdentity *peer,
4169                  const struct GNUNET_MessageHeader *message)
4170 {
4171   struct GNUNET_MESH_ACK *msg;
4172   struct MeshTunnel *t;
4173   uint32_t ack;
4174
4175   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got an ACK packet from %s!\n",
4176               GNUNET_i2s (peer));
4177   msg = (struct GNUNET_MESH_ACK *) message;
4178
4179   t = tunnel_get (&msg->oid, ntohl (msg->tid));
4180
4181   if (NULL == t)
4182   {
4183     /* TODO notify that we dont know this tunnel (whom)? */
4184     GNUNET_STATISTICS_update (stats, "# ack on unknown tunnel", 1, GNUNET_NO);
4185     return GNUNET_OK;
4186   }
4187   ack = ntohl (msg->pid);
4188   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  ACK %u\n", ack);
4189
4190   /* Is this a forward or backward ACK? */
4191   if (t->prev_hop != GNUNET_PEER_search (peer))
4192   {
4193     debug_bck_ack++;
4194     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  FWD ACK\n");
4195     if (GNUNET_SCHEDULER_NO_TASK != t->next_fc.poll_task &&
4196         GMC_is_pid_bigger (ack, t->next_fc.last_ack_recv))
4197     {
4198       GNUNET_SCHEDULER_cancel (t->next_fc.poll_task);
4199       t->next_fc.poll_task = GNUNET_SCHEDULER_NO_TASK;
4200       t->next_fc.poll_time = GNUNET_TIME_UNIT_SECONDS;
4201     }
4202     t->next_fc.last_ack_recv = ack;
4203     peer_unlock_queue (t->next_hop);
4204     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_ACK);
4205   }
4206   else
4207   {
4208     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  BCK ACK\n");
4209     if (GNUNET_SCHEDULER_NO_TASK != t->prev_fc.poll_task &&
4210         GMC_is_pid_bigger (ack, t->prev_fc.last_ack_recv))
4211     {
4212       GNUNET_SCHEDULER_cancel (t->prev_fc.poll_task);
4213       t->prev_fc.poll_task = GNUNET_SCHEDULER_NO_TASK;
4214       t->prev_fc.poll_time = GNUNET_TIME_UNIT_SECONDS;
4215     }
4216     t->prev_fc.last_ack_recv = ack;
4217     peer_unlock_queue (t->prev_hop);
4218     tunnel_send_bck_ack (t, GNUNET_MESSAGE_TYPE_MESH_ACK);
4219   }
4220   return GNUNET_OK;
4221 }
4222
4223
4224 /**
4225  * Core handler for mesh network traffic point-to-point ack polls.
4226  *
4227  * @param cls closure
4228  * @param message message
4229  * @param peer peer identity this notification is about
4230  *
4231  * @return GNUNET_OK to keep the connection open,
4232  *         GNUNET_SYSERR to close it (signal serious error)
4233  */
4234 static int
4235 handle_mesh_poll (void *cls, const struct GNUNET_PeerIdentity *peer,
4236                   const struct GNUNET_MessageHeader *message)
4237 {
4238   struct GNUNET_MESH_Poll *msg;
4239   struct MeshTunnel *t;
4240
4241   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got an POLL packet from %s!\n",
4242               GNUNET_i2s (peer));
4243
4244   msg = (struct GNUNET_MESH_Poll *) message;
4245
4246   t = tunnel_get (&msg->oid, ntohl (msg->tid));
4247
4248   if (NULL == t)
4249   {
4250     /* TODO notify that we dont know this tunnel (whom)? */
4251     GNUNET_STATISTICS_update (stats, "# poll on unknown tunnel", 1, GNUNET_NO);
4252     GNUNET_break_op (0);
4253     return GNUNET_OK;
4254   }
4255
4256   /* Is this a forward or backward ACK? */
4257   if (t->prev_hop != GNUNET_PEER_search(peer))
4258   {
4259     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  from FWD\n");
4260     /* FIXME cinfo->bck_ack = cinfo->fwd_pid; // mark as ready to send */
4261     tunnel_send_bck_ack (t, GNUNET_MESSAGE_TYPE_MESH_POLL);
4262   }
4263   else
4264   {
4265     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  from BCK\n");
4266     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_POLL);
4267   }
4268
4269   return GNUNET_OK;
4270 }
4271
4272 /**
4273  * Core handler for path ACKs
4274  *
4275  * @param cls closure
4276  * @param message message
4277  * @param peer peer identity this notification is about
4278  *
4279  * @return GNUNET_OK to keep the connection open,
4280  *         GNUNET_SYSERR to close it (signal serious error)
4281  */
4282 static int
4283 handle_mesh_path_ack (void *cls, const struct GNUNET_PeerIdentity *peer,
4284                       const struct GNUNET_MessageHeader *message)
4285 {
4286   struct GNUNET_MESH_PathACK *msg;
4287   struct MeshPeerInfo *peer_info;
4288   struct MeshPeerPath *p;
4289   struct MeshTunnel *t;
4290
4291   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received a path ACK msg [%s]\n",
4292               GNUNET_i2s (&my_full_id));
4293   msg = (struct GNUNET_MESH_PathACK *) message;
4294   t = tunnel_get (&msg->oid, ntohl(msg->tid));
4295   if (NULL == t)
4296   {
4297     /* TODO notify that we don't know the tunnel */
4298     GNUNET_STATISTICS_update (stats, "# control on unknown tunnel", 1, GNUNET_NO);
4299     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  don't know the tunnel %s [%X]!\n",
4300                 GNUNET_i2s (&msg->oid), ntohl(msg->tid));
4301     return GNUNET_OK;
4302   }
4303   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %s [%X]\n",
4304               GNUNET_i2s (&msg->oid), ntohl(msg->tid));
4305
4306   peer_info = peer_get (&msg->peer_id);
4307   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by peer %s\n",
4308               GNUNET_i2s (&msg->peer_id));
4309   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  via peer %s\n",
4310               GNUNET_i2s (peer));
4311
4312   /* Add path to peers? */
4313   p = t->path;
4314   if (NULL != p)
4315   {
4316     path_add_to_peers (p, GNUNET_YES);
4317   }
4318   else
4319   {
4320     GNUNET_break (0);
4321   }
4322
4323   /* Message for us? */
4324   if (0 == memcmp (&msg->oid, &my_full_id, sizeof (struct GNUNET_PeerIdentity)))
4325   {
4326     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  It's for us!\n");
4327     if (NULL == t->owner)
4328     {
4329       GNUNET_break_op (0);
4330       return GNUNET_OK;
4331     }
4332     if (NULL != peer_info->dhtget)
4333     {
4334       GNUNET_DHT_get_stop (peer_info->dhtget);
4335       peer_info->dhtget = NULL;
4336     }
4337     return GNUNET_OK;
4338   }
4339
4340   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4341               "  not for us, retransmitting...\n");
4342   peer_info = peer_get (&msg->oid);
4343   send_prebuilt_message (message, t->prev_hop, t);
4344   return GNUNET_OK;
4345 }
4346
4347
4348 /**
4349  * Core handler for mesh keepalives.
4350  *
4351  * @param cls closure
4352  * @param message message
4353  * @param peer peer identity this notification is about
4354  * @return GNUNET_OK to keep the connection open,
4355  *         GNUNET_SYSERR to close it (signal serious error)
4356  *
4357  * TODO: Check who we got this from, to validate route.
4358  */
4359 static int
4360 handle_mesh_keepalive (void *cls, const struct GNUNET_PeerIdentity *peer,
4361                        const struct GNUNET_MessageHeader *message)
4362 {
4363   struct GNUNET_MESH_TunnelKeepAlive *msg;
4364   struct MeshTunnel *t;
4365
4366   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a keepalive packet from %s\n",
4367               GNUNET_i2s (peer));
4368
4369   msg = (struct GNUNET_MESH_TunnelKeepAlive *) message;
4370   t = tunnel_get (&msg->oid, ntohl (msg->tid));
4371
4372   if (NULL == t)
4373   {
4374     /* TODO notify that we dont know that tunnel */
4375     GNUNET_STATISTICS_update (stats, "# keepalive on unknown tunnel", 1,
4376                               GNUNET_NO);
4377     return GNUNET_OK;
4378   }
4379
4380   tunnel_reset_timeout (t);
4381
4382   GNUNET_STATISTICS_update (stats, "# keepalives forwarded", 1, GNUNET_NO);
4383   send_prebuilt_message (message, t->next_hop, t);
4384   return GNUNET_OK;
4385   }
4386
4387
4388
4389 /**
4390  * Functions to handle messages from core
4391  */
4392 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
4393   {&handle_mesh_path_create, GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE, 0},
4394   {&handle_mesh_path_destroy, GNUNET_MESSAGE_TYPE_MESH_PATH_DESTROY, 0},
4395   {&handle_mesh_path_broken, GNUNET_MESSAGE_TYPE_MESH_PATH_BROKEN,
4396    sizeof (struct GNUNET_MESH_PathBroken)},
4397   {&handle_mesh_tunnel_destroy, GNUNET_MESSAGE_TYPE_MESH_TUNNEL_DESTROY,
4398    sizeof (struct GNUNET_MESH_TunnelDestroy)},
4399   {&handle_mesh_data_unicast, GNUNET_MESSAGE_TYPE_MESH_UNICAST, 0},
4400   {&handle_mesh_keepalive, GNUNET_MESSAGE_TYPE_MESH_PATH_KEEPALIVE,
4401     sizeof (struct GNUNET_MESH_TunnelKeepAlive)},
4402   {&handle_mesh_data_to_orig, GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN, 0},
4403   {&handle_mesh_ack, GNUNET_MESSAGE_TYPE_MESH_ACK,
4404     sizeof (struct GNUNET_MESH_ACK)},
4405   {&handle_mesh_poll, GNUNET_MESSAGE_TYPE_MESH_POLL,
4406     sizeof (struct GNUNET_MESH_Poll)},
4407   {&handle_mesh_path_ack, GNUNET_MESSAGE_TYPE_MESH_PATH_ACK,
4408    sizeof (struct GNUNET_MESH_PathACK)},
4409   {NULL, 0, 0}
4410 };
4411
4412
4413
4414 /******************************************************************************/
4415 /****************       MESH LOCAL HANDLER HELPERS      ***********************/
4416 /******************************************************************************/
4417
4418
4419 #if LATER
4420 /**
4421  * notify_client_connection_failure: notify a client that the connection to the
4422  * requested remote peer is not possible (for instance, no route found)
4423  * Function called when the socket is ready to queue more data. "buf" will be
4424  * NULL and "size" zero if the socket was closed for writing in the meantime.
4425  *
4426  * @param cls closure
4427  * @param size number of bytes available in buf
4428  * @param buf where the callee should write the message
4429  * @return number of bytes written to buf
4430  */
4431 static size_t
4432 notify_client_connection_failure (void *cls, size_t size, void *buf)
4433 {
4434   int size_needed;
4435   struct MeshPeerInfo *peer_info;
4436   struct GNUNET_MESH_PeerControl *msg;
4437   struct GNUNET_PeerIdentity id;
4438
4439   if (0 == size && NULL == buf)
4440   {
4441     // TODO retry? cancel?
4442     return 0;
4443   }
4444
4445   size_needed = sizeof (struct GNUNET_MESH_PeerControl);
4446   peer_info = (struct MeshPeerInfo *) cls;
4447   msg = (struct GNUNET_MESH_PeerControl *) buf;
4448   msg->header.size = htons (sizeof (struct GNUNET_MESH_PeerControl));
4449   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_DISCONNECTED);
4450 //     msg->tunnel_id = htonl(peer_info->t->tid);
4451   GNUNET_PEER_resolve (peer_info->id, &id);
4452   memcpy (&msg->peer, &id, sizeof (struct GNUNET_PeerIdentity));
4453
4454   return size_needed;
4455 }
4456 #endif
4457
4458
4459 /**
4460  * Send keepalive packets for a tunnel.
4461  *
4462  * @param cls Closure (tunnel for which to send the keepalive).
4463  * @param tc Notification context.
4464  */
4465 static void
4466 path_refresh (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
4467 {
4468   struct MeshTunnel *t = cls;
4469   struct GNUNET_MESH_TunnelKeepAlive *msg;
4470   size_t size = sizeof (struct GNUNET_MESH_TunnelKeepAlive);
4471   char cbuf[size];
4472
4473   t->maintenance_task = GNUNET_SCHEDULER_NO_TASK;
4474   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
4475   {
4476     return;
4477   }
4478
4479   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4480               "sending keepalive for tunnel %d\n", t->id.tid);
4481
4482   msg = (struct GNUNET_MESH_TunnelKeepAlive *) cbuf;
4483   msg->header.size = htons (size);
4484   // FIXME change to tunnel keepalive
4485   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_KEEPALIVE);
4486   msg->oid = my_full_id;
4487   msg->tid = htonl (t->id.tid);
4488   send_prebuilt_message (&msg->header, t->next_hop, t);
4489
4490   t->maintenance_task =
4491       GNUNET_SCHEDULER_add_delayed (refresh_path_time, &path_refresh, t);
4492   tunnel_reset_timeout (t);
4493 }
4494
4495
4496 /**
4497  * Function to process paths received for a new peer addition. The recorded
4498  * paths form the initial tunnel, which can be optimized later.
4499  * Called on each result obtained for the DHT search.
4500  *
4501  * @param cls closure
4502  * @param exp when will this value expire
4503  * @param key key of the result
4504  * @param get_path path of the get request
4505  * @param get_path_length lenght of get_path
4506  * @param put_path path of the put request
4507  * @param put_path_length length of the put_path
4508  * @param type type of the result
4509  * @param size number of bytes in data
4510  * @param data pointer to the result data
4511  *
4512  * TODO: re-issue the request after certain time? cancel after X results?
4513  */
4514 static void
4515 dht_get_id_handler (void *cls, struct GNUNET_TIME_Absolute exp,
4516                     const struct GNUNET_HashCode * key,
4517                     const struct GNUNET_PeerIdentity *get_path,
4518                     unsigned int get_path_length,
4519                     const struct GNUNET_PeerIdentity *put_path,
4520                     unsigned int put_path_length, enum GNUNET_BLOCK_Type type,
4521                     size_t size, const void *data)
4522 {
4523   struct MeshPeerInfo *peer = cls;
4524   struct MeshPeerPath *p;
4525   struct GNUNET_PeerIdentity pi;
4526   int i;
4527
4528   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got results from DHT!\n");
4529   GNUNET_PEER_resolve (peer->id, &pi);
4530   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  for %s\n", GNUNET_i2s (&pi));
4531
4532   p = path_build_from_dht (get_path, get_path_length,
4533                            put_path, put_path_length);
4534   path_add_to_peers (p, GNUNET_NO);
4535   path_destroy (p);
4536   for (i = 0; i < peer->ntunnels; i++)
4537   {
4538     peer_connect (peer, peer->tunnels[i]); // FIXME add if
4539   }
4540
4541   return;
4542 }
4543
4544
4545 /******************************************************************************/
4546 /*********************       MESH LOCAL HANDLES      **************************/
4547 /******************************************************************************/
4548
4549
4550 /**
4551  * Handler for client disconnection
4552  *
4553  * @param cls closure
4554  * @param client identification of the client; NULL
4555  *        for the last call when the server is destroyed
4556  */
4557 static void
4558 handle_local_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
4559 {
4560   struct MeshClient *c;
4561   struct MeshClient *next;
4562
4563   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "client disconnected\n");
4564   if (client == NULL)
4565   {
4566     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   (SERVER DOWN)\n");
4567     return;
4568   }
4569
4570   c = clients_head;
4571   while (NULL != c)
4572   {
4573     if (c->handle != client)
4574     {
4575       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   ... searching\n");
4576       c = c->next;
4577       continue;
4578     }
4579     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "matching client found (%u)\n",
4580                 c->id);
4581     GNUNET_SERVER_client_drop (c->handle);
4582     c->shutting_down = GNUNET_YES;
4583     GNUNET_CONTAINER_multihashmap_iterate (c->own_tunnels,
4584                                            &tunnel_destroy_iterator, c);
4585     GNUNET_CONTAINER_multihashmap_iterate (c->incoming_tunnels,
4586                                            &tunnel_destroy_iterator, c);
4587     GNUNET_CONTAINER_multihashmap_iterate (c->ignore_tunnels,
4588                                            &tunnel_destroy_iterator, c);
4589     GNUNET_CONTAINER_multihashmap_destroy (c->own_tunnels);
4590     GNUNET_CONTAINER_multihashmap_destroy (c->incoming_tunnels);
4591     GNUNET_CONTAINER_multihashmap_destroy (c->ignore_tunnels);
4592
4593     if (NULL != c->types)
4594       GNUNET_CONTAINER_multihashmap_destroy (c->types);
4595     next = c->next;
4596     GNUNET_CONTAINER_DLL_remove (clients_head, clients_tail, c);
4597     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  CLIENT FREE at %p\n", c);
4598     GNUNET_free (c);
4599     GNUNET_STATISTICS_update (stats, "# clients", -1, GNUNET_NO);
4600     c = next;
4601   }
4602   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "done!\n");
4603   return;
4604 }
4605
4606
4607 /**
4608  * Handler for new clients
4609  *
4610  * @param cls closure
4611  * @param client identification of the client
4612  * @param message the actual message, which includes messages the client wants
4613  */
4614 static void
4615 handle_local_new_client (void *cls, struct GNUNET_SERVER_Client *client,
4616                          const struct GNUNET_MessageHeader *message)
4617 {
4618   struct GNUNET_MESH_ClientConnect *cc_msg;
4619   struct MeshClient *c;
4620   unsigned int size;
4621   uint16_t ntypes;
4622   uint16_t *t;
4623   uint16_t i;
4624
4625   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new client connected\n");
4626
4627   /* Check data sanity */
4628   size = ntohs (message->size) - sizeof (struct GNUNET_MESH_ClientConnect);
4629   cc_msg = (struct GNUNET_MESH_ClientConnect *) message;
4630   ntypes = ntohs (cc_msg->types);
4631   if (size != ntypes * sizeof (uint16_t))
4632   {
4633     GNUNET_break (0);
4634     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4635     return;
4636   }
4637
4638   /* Create new client structure */
4639   c = GNUNET_malloc (sizeof (struct MeshClient));
4640   c->id = next_client_id++; // overflow not important: just for debug
4641   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  CLIENT NEW %u\n", c->id);
4642   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  client has %u types\n", ntypes);
4643   c->handle = client;
4644   GNUNET_SERVER_client_keep (client);
4645   if (ntypes > 0)
4646   {
4647     uint16_t u16;
4648     struct GNUNET_HashCode hc;
4649
4650     t = (uint16_t *) &cc_msg[1];
4651     c->types = GNUNET_CONTAINER_multihashmap_create (ntypes, GNUNET_NO);
4652     for (i = 0; i < ntypes; i++)
4653     {
4654       u16 = ntohs (t[i]);
4655       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "    msg type: %u\n", u16);
4656       GNUNET_CRYPTO_hash (&u16, sizeof (u16), &hc); // FIXME pseudo hash
4657
4658       /* store in clients hashmap */
4659       GNUNET_CONTAINER_multihashmap_put (c->types, &hc, c,
4660                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
4661       /* store in global hashmap */
4662       GNUNET_CONTAINER_multihashmap_put (types, &hc, c,
4663                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
4664     }
4665   }
4666
4667   GNUNET_CONTAINER_DLL_insert (clients_head, clients_tail, c);
4668   c->own_tunnels = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
4669   c->incoming_tunnels = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
4670   c->ignore_tunnels = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
4671   GNUNET_SERVER_notification_context_add (nc, client);
4672   GNUNET_STATISTICS_update (stats, "# clients", 1, GNUNET_NO);
4673
4674   GNUNET_SERVER_receive_done (client, GNUNET_OK);
4675   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new client processed\n");
4676 }
4677
4678
4679 /**
4680  * Handler for requests of new tunnels
4681  *
4682  * @param cls Closure.
4683  * @param client Identification of the client.
4684  * @param message The actual message.
4685  */
4686 static void
4687 handle_local_tunnel_create (void *cls, struct GNUNET_SERVER_Client *client,
4688                             const struct GNUNET_MessageHeader *message)
4689 {
4690   struct GNUNET_MESH_TunnelMessage *t_msg;
4691   struct MeshPeerInfo *peer_info;
4692   struct MeshTunnel *t;
4693   struct MeshClient *c;
4694   MESH_TunnelNumber tid;
4695
4696   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new tunnel requested\n");
4697
4698   /* Sanity check for client registration */
4699   if (NULL == (c = client_get (client)))
4700   {
4701     GNUNET_break (0);
4702     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4703     return;
4704   }
4705   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
4706
4707   /* Message sanity check */
4708   if (sizeof (struct GNUNET_MESH_TunnelMessage) != ntohs (message->size))
4709   {
4710     GNUNET_break (0);
4711     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4712     return;
4713   }
4714
4715   t_msg = (struct GNUNET_MESH_TunnelMessage *) message;
4716   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  towards %s\n",
4717               GNUNET_i2s (&t_msg->peer));
4718   /* Sanity check for tunnel numbering */
4719   tid = ntohl (t_msg->tunnel_id);
4720   if (0 == (tid & GNUNET_MESH_LOCAL_TUNNEL_ID_CLI))
4721   {
4722     GNUNET_break (0);
4723     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4724     return;
4725   }
4726   /* Sanity check for duplicate tunnel IDs */
4727   if (NULL != tunnel_get_by_local_id (c, tid))
4728   {
4729     GNUNET_break (0);
4730     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4731     return;
4732   }
4733
4734   while (NULL != tunnel_get_by_pi (myid, next_tid))
4735     next_tid = (next_tid + 1) & ~GNUNET_MESH_LOCAL_TUNNEL_ID_CLI;
4736   t = tunnel_new (myid, next_tid, c, tid);
4737   next_tid = (next_tid + 1) & ~GNUNET_MESH_LOCAL_TUNNEL_ID_CLI;
4738   if (NULL == t)
4739   {
4740     GNUNET_break (0);
4741     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4742     return;
4743   }
4744   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "CREATED TUNNEL %s [%x] (%x)\n",
4745               GNUNET_i2s (&my_full_id), t->id.tid, t->local_tid);
4746
4747   peer_info = peer_get (&t_msg->peer);
4748   GNUNET_array_append (peer_info->tunnels, peer_info->ntunnels, t);
4749   peer_connect (peer_info, t);
4750   GNUNET_SERVER_receive_done (client, GNUNET_OK);
4751   return;
4752 }
4753
4754
4755 /**
4756  * Handler for requests of deleting tunnels
4757  *
4758  * @param cls closure
4759  * @param client identification of the client
4760  * @param message the actual message
4761  */
4762 static void
4763 handle_local_tunnel_destroy (void *cls, struct GNUNET_SERVER_Client *client,
4764                              const struct GNUNET_MessageHeader *message)
4765 {
4766   struct GNUNET_MESH_TunnelMessage *tunnel_msg;
4767   struct MeshClient *c;
4768   struct MeshTunnel *t;
4769   MESH_TunnelNumber tid;
4770
4771   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4772               "Got a DESTROY TUNNEL from client!\n");
4773
4774   /* Sanity check for client registration */
4775   if (NULL == (c = client_get (client)))
4776   {
4777     GNUNET_break (0);
4778     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4779     return;
4780   }
4781   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
4782
4783   /* Message sanity check */
4784   if (sizeof (struct GNUNET_MESH_TunnelMessage) != ntohs (message->size))
4785   {
4786     GNUNET_break (0);
4787     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4788     return;
4789   }
4790
4791   tunnel_msg = (struct GNUNET_MESH_TunnelMessage *) message;
4792
4793   /* Retrieve tunnel */
4794   tid = ntohl (tunnel_msg->tunnel_id);
4795   t = tunnel_get_by_local_id(c, tid);
4796   if (NULL == t)
4797   {
4798     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "  tunnel %X not found\n", tid);
4799     GNUNET_break (0);
4800     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4801     return;
4802   }
4803   if (c != t->owner || tid >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
4804   {
4805     client_ignore_tunnel (c, t);
4806     tunnel_destroy_empty (t);
4807     GNUNET_SERVER_receive_done (client, GNUNET_OK);
4808     return;
4809   }
4810   send_client_tunnel_disconnect (t, c);
4811   client_delete_tunnel (c, t);
4812
4813   /* Don't try to ACK the client about the tunnel_destroy multicast packet */
4814   t->owner = NULL;
4815   tunnel_send_destroy (t);
4816   peer_remove_tunnel (peer_get_short(t->dest), t);
4817   t->destroy = GNUNET_YES;
4818   /* The tunnel will be destroyed when the last message is transmitted. */
4819   GNUNET_SERVER_receive_done (client, GNUNET_OK);
4820   return;
4821 }
4822
4823
4824 /**
4825  * Handler for requests of seeting tunnel's buffering policy.
4826  *
4827  * @param cls Closure (unused).
4828  * @param client Identification of the client.
4829  * @param message The actual message.
4830  */
4831 static void
4832 handle_local_tunnel_buffer (void *cls, struct GNUNET_SERVER_Client *client,
4833                             const struct GNUNET_MessageHeader *message)
4834 {
4835   struct GNUNET_MESH_TunnelMessage *tunnel_msg;
4836   struct MeshClient *c;
4837   struct MeshTunnel *t;
4838   MESH_TunnelNumber tid;
4839
4840   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4841               "Got a BUFFER request from client!\n");
4842
4843   /* Sanity check for client registration */
4844   if (NULL == (c = client_get (client)))
4845   {
4846     GNUNET_break (0);
4847     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4848     return;
4849   }
4850   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
4851
4852   tunnel_msg = (struct GNUNET_MESH_TunnelMessage *) message;
4853
4854   /* Retrieve tunnel */
4855   tid = ntohl (tunnel_msg->tunnel_id);
4856   t = tunnel_get_by_local_id(c, tid);
4857   if (NULL == t)
4858   {
4859     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "  tunnel %X not found\n", tid);
4860     GNUNET_break (0);
4861     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4862     return;
4863   }
4864
4865   switch (ntohs(message->type))
4866   {
4867       case GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_BUFFER:
4868           t->nobuffer = GNUNET_NO;
4869           break;
4870       case GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_NOBUFFER:
4871           t->nobuffer = GNUNET_YES;
4872           break;
4873       default:
4874           GNUNET_break (0);
4875   }
4876
4877   GNUNET_SERVER_receive_done (client, GNUNET_OK);
4878 }
4879
4880
4881 /**
4882  * Handler for client traffic directed to one peer
4883  *
4884  * @param cls closure
4885  * @param client identification of the client
4886  * @param message the actual message
4887  */
4888 static void
4889 handle_local_unicast (void *cls, struct GNUNET_SERVER_Client *client,
4890                       const struct GNUNET_MessageHeader *message)
4891 {
4892   struct MeshClient *c;
4893   struct MeshTunnel *t;
4894   struct GNUNET_MESH_Unicast *data_msg;
4895   MESH_TunnelNumber tid;
4896   size_t size;
4897
4898   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4899               "Got a unicast request from a client!\n");
4900
4901   /* Sanity check for client registration */
4902   if (NULL == (c = client_get (client)))
4903   {
4904     GNUNET_break (0);
4905     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4906     return;
4907   }
4908   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
4909
4910   data_msg = (struct GNUNET_MESH_Unicast *) message;
4911
4912   /* Sanity check for message size */
4913   size = ntohs (message->size);
4914   if (sizeof (struct GNUNET_MESH_Unicast) +
4915       sizeof (struct GNUNET_MessageHeader) > size)
4916   {
4917     GNUNET_break (0);
4918     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4919     return;
4920   }
4921
4922   /* Tunnel exists? */
4923   tid = ntohl (data_msg->tid);
4924   t = tunnel_get_by_local_id (c, tid);
4925   if (NULL == t)
4926   {
4927     GNUNET_break (0);
4928     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4929     return;
4930   }
4931
4932   /*  Is it a local tunnel? Then, does client own the tunnel? */
4933   if (t->owner->handle != client)
4934   {
4935     GNUNET_break (0);
4936     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4937     return;
4938   }
4939
4940   /* PID should be as expected: client<->service communication */
4941   if (ntohl (data_msg->pid) != t->prev_fc.last_pid_recv + 1)
4942   {
4943     GNUNET_break (0);
4944     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4945               "Unicast PID, expected %u, got %u\n",
4946               t->prev_fc.last_pid_recv + 1, ntohl (data_msg->pid));
4947     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4948     return;
4949   }
4950
4951   /* Ok, everything is correct, send the message
4952    * (pretend we got it from a mesh peer)
4953    */
4954   {
4955     /* Work around const limitation */
4956     char buf[ntohs (message->size)] GNUNET_ALIGN;
4957     struct GNUNET_MESH_Unicast *copy;
4958
4959     copy = (struct GNUNET_MESH_Unicast *) buf;
4960     memcpy (buf, data_msg, size);
4961     copy->oid = my_full_id;
4962     copy->tid = htonl (t->id.tid);
4963     copy->ttl = htonl (default_ttl);
4964     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4965                 "  calling generic handler...\n");
4966     handle_mesh_data_unicast (NULL, &my_full_id, &copy->header);
4967   }
4968   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "receive done OK\n");
4969   GNUNET_SERVER_receive_done (client, GNUNET_OK);
4970
4971   return;
4972 }
4973
4974
4975 /**
4976  * Handler for client traffic directed to the origin
4977  *
4978  * @param cls closure
4979  * @param client identification of the client
4980  * @param message the actual message
4981  */
4982 static void
4983 handle_local_to_origin (void *cls, struct GNUNET_SERVER_Client *client,
4984                         const struct GNUNET_MessageHeader *message)
4985 {
4986   struct GNUNET_MESH_ToOrigin *data_msg;
4987   struct MeshTunnelClientInfo *clinfo;
4988   struct MeshClient *c;
4989   struct MeshTunnel *t;
4990   MESH_TunnelNumber tid;
4991   size_t size;
4992
4993   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4994               "Got a ToOrigin request from a client!\n");
4995   /* Sanity check for client registration */
4996   if (NULL == (c = client_get (client)))
4997   {
4998     GNUNET_break (0);
4999     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5000     return;
5001   }
5002   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
5003
5004   data_msg = (struct GNUNET_MESH_ToOrigin *) message;
5005
5006   /* Sanity check for message size */
5007   size = ntohs (message->size);
5008   if (sizeof (struct GNUNET_MESH_ToOrigin) +
5009       sizeof (struct GNUNET_MessageHeader) > size)
5010   {
5011     GNUNET_break (0);
5012     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5013     return;
5014   }
5015
5016   /* Tunnel exists? */
5017   tid = ntohl (data_msg->tid);
5018   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %X\n", tid);
5019   if (tid < GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
5020   {
5021     GNUNET_break (0);
5022     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5023     return;
5024   }
5025   t = tunnel_get_by_local_id (c, tid);
5026   if (NULL == t)
5027   {
5028     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Tunnel %X unknown.\n", tid);
5029     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "  for client %u.\n", c->id);
5030     GNUNET_break (0);
5031     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5032     return;
5033   }
5034
5035   /*  It should be sent by someone who has this as incoming tunnel. */
5036   if (GNUNET_NO == client_knows_tunnel (c, t))
5037   {
5038     GNUNET_break (0);
5039     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5040     return;
5041   }
5042
5043   /* PID should be as expected */
5044   clinfo = tunnel_get_client_fc (t, c);
5045   if (ntohl (data_msg->pid) != clinfo->bck_pid + 1)
5046   {
5047     GNUNET_break (0);
5048     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
5049                 "To Origin PID, expected %u, got %u\n",
5050                 clinfo->bck_pid + 1,
5051                 ntohl (data_msg->pid));
5052     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5053     return;
5054   }
5055   clinfo->bck_pid++;
5056
5057   /* Ok, everything is correct, send the message
5058    * (pretend we got it from a mesh peer)
5059    */
5060   {
5061     char buf[ntohs (message->size)] GNUNET_ALIGN;
5062     struct GNUNET_MESH_ToOrigin *copy;
5063
5064     /* Work around 'const' limitation */
5065     copy = (struct GNUNET_MESH_ToOrigin *) buf;
5066     memcpy (buf, data_msg, size);
5067     GNUNET_PEER_resolve (t->id.oid, &copy->oid);
5068     copy->tid = htonl (t->id.tid);
5069     copy->ttl = htonl (default_ttl);
5070     copy->pid = htonl (t->prev_fc.last_pid_sent + 1);
5071
5072     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5073                 "  calling generic handler...\n");
5074     handle_mesh_data_to_orig (NULL, &my_full_id, &copy->header);
5075   }
5076   GNUNET_SERVER_receive_done (client, GNUNET_OK);
5077
5078   return;
5079 }
5080
5081
5082 /**
5083  * Handler for client's ACKs for payload traffic.
5084  *
5085  * @param cls Closure (unused).
5086  * @param client Identification of the client.
5087  * @param message The actual message.
5088  */
5089 static void
5090 handle_local_ack (void *cls, struct GNUNET_SERVER_Client *client,
5091                   const struct GNUNET_MessageHeader *message)
5092 {
5093   struct GNUNET_MESH_LocalAck *msg;
5094   struct MeshTunnel *t;
5095   struct MeshClient *c;
5096   MESH_TunnelNumber tid;
5097   uint32_t ack;
5098
5099   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a local ACK\n");
5100   /* Sanity check for client registration */
5101   if (NULL == (c = client_get (client)))
5102   {
5103     GNUNET_break (0);
5104     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5105     return;
5106   }
5107   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
5108
5109   msg = (struct GNUNET_MESH_LocalAck *) message;
5110
5111   /* Tunnel exists? */
5112   tid = ntohl (msg->tunnel_id);
5113   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %X\n", tid);
5114   t = tunnel_get_by_local_id (c, tid);
5115   if (NULL == t)
5116   {
5117     GNUNET_break (0);
5118     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Tunnel %X unknown.\n", tid);
5119     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "  for client %u.\n", c->id);
5120     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5121     return;
5122   }
5123
5124   ack = ntohl (msg->max_pid);
5125   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  ack %u\n", ack);
5126
5127   /* Does client own tunnel? I.E: Is this an ACK for BCK traffic? */
5128   if (NULL != t->owner && t->owner->handle == client)
5129   {
5130     /* The client owns the tunnel, ACK is for data to_origin, send BCK ACK. */
5131     t->next_fc.last_ack_sent = ack;
5132     tunnel_send_bck_ack(t, GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK);
5133   }
5134   else
5135   {
5136     /* The client doesn't own the tunnel, this ACK is for FWD traffic. */
5137     tunnel_set_client_fwd_ack (t, c, ack);
5138     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK);
5139   }
5140
5141   GNUNET_SERVER_receive_done (client, GNUNET_OK);
5142
5143   return;
5144 }
5145
5146
5147
5148 /**
5149  * Iterator over all tunnels to send a monitoring client info about each tunnel.
5150  *
5151  * @param cls Closure (client handle).
5152  * @param key Key (hashed tunnel ID, unused).
5153  * @param value Tunnel info.
5154  *
5155  * @return GNUNET_YES, to keep iterating.
5156  */
5157 static int
5158 monitor_all_tunnels_iterator (void *cls,
5159                               const struct GNUNET_HashCode * key,
5160                               void *value)
5161 {
5162   struct GNUNET_SERVER_Client *client = cls;
5163   struct MeshTunnel *t = value;
5164   struct GNUNET_MESH_LocalMonitor *msg;
5165
5166   msg = GNUNET_malloc (sizeof(struct GNUNET_MESH_LocalMonitor));
5167   GNUNET_PEER_resolve(t->id.oid, &msg->owner);
5168   msg->tunnel_id = htonl (t->id.tid);
5169   msg->header.size = htons (sizeof (struct GNUNET_MESH_LocalMonitor));
5170   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_INFO_TUNNELS);
5171   GNUNET_PEER_resolve (t->dest, &msg->destination);
5172
5173   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
5174               "*  sending info about tunnel %s [%u]\n",
5175               GNUNET_i2s (&msg->owner), t->id.tid);
5176
5177   GNUNET_SERVER_notification_context_unicast (nc, client,
5178                                               &msg->header, GNUNET_NO);
5179   return GNUNET_YES;
5180 }
5181
5182
5183 /**
5184  * Handler for client's MONITOR request.
5185  *
5186  * @param cls Closure (unused).
5187  * @param client Identification of the client.
5188  * @param message The actual message.
5189  */
5190 static void
5191 handle_local_get_tunnels (void *cls, struct GNUNET_SERVER_Client *client,
5192                           const struct GNUNET_MessageHeader *message)
5193 {
5194   struct MeshClient *c;
5195
5196   /* Sanity check for client registration */
5197   if (NULL == (c = client_get (client)))
5198   {
5199     GNUNET_break (0);
5200     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5201     return;
5202   }
5203
5204   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
5205               "Received get tunnels request from client %u\n",
5206               c->id);
5207   GNUNET_CONTAINER_multihashmap_iterate (tunnels,
5208                                          monitor_all_tunnels_iterator,
5209                                          client);
5210   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
5211               "Get tunnels request from client %u completed\n",
5212               c->id);
5213   GNUNET_SERVER_receive_done (client, GNUNET_OK);
5214 }
5215
5216
5217 /**
5218  * Handler for client's MONITOR_TUNNEL request.
5219  *
5220  * @param cls Closure (unused).
5221  * @param client Identification of the client.
5222  * @param message The actual message.
5223  */
5224 static void
5225 handle_local_show_tunnel (void *cls, struct GNUNET_SERVER_Client *client,
5226                           const struct GNUNET_MessageHeader *message)
5227 {
5228   const struct GNUNET_MESH_LocalMonitor *msg;
5229   struct GNUNET_MESH_LocalMonitor *resp;
5230   struct MeshClient *c;
5231   struct MeshTunnel *t;
5232
5233   /* Sanity check for client registration */
5234   if (NULL == (c = client_get (client)))
5235   {
5236     GNUNET_break (0);
5237     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5238     return;
5239   }
5240
5241   msg = (struct GNUNET_MESH_LocalMonitor *) message;
5242   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
5243               "Received tunnel info request from client %u for tunnel %s[%X]\n",
5244               c->id,
5245               &msg->owner,
5246               ntohl (msg->tunnel_id));
5247   t = tunnel_get (&msg->owner, ntohl (msg->tunnel_id));
5248   if (NULL == t)
5249   {
5250     /* We don't know the tunnel FIXME */
5251     struct GNUNET_MESH_LocalMonitor warn;
5252
5253     warn = *msg;
5254     GNUNET_SERVER_notification_context_unicast (nc, client,
5255                                                 &warn.header,
5256                                                 GNUNET_NO);
5257     GNUNET_SERVER_receive_done (client, GNUNET_OK);
5258     return;
5259   }
5260
5261   /* Initialize context */
5262   resp = GNUNET_malloc (sizeof (struct GNUNET_MESH_LocalMonitor));
5263   *resp = *msg;
5264   GNUNET_PEER_resolve (t->dest, &resp->destination);
5265   resp->header.size = htons (sizeof (struct GNUNET_MESH_LocalMonitor));
5266   GNUNET_SERVER_notification_context_unicast (nc, c->handle,
5267                                               &resp->header, GNUNET_NO);
5268   GNUNET_free (resp);
5269
5270   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
5271               "Monitor tunnel request from client %u completed\n",
5272               c->id);
5273   GNUNET_SERVER_receive_done (client, GNUNET_OK);
5274 }
5275
5276
5277 /**
5278  * Functions to handle messages from clients
5279  */
5280 static struct GNUNET_SERVER_MessageHandler client_handlers[] = {
5281   {&handle_local_new_client, NULL,
5282    GNUNET_MESSAGE_TYPE_MESH_LOCAL_CONNECT, 0},
5283   {&handle_local_tunnel_create, NULL,
5284    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_CREATE,
5285    sizeof (struct GNUNET_MESH_TunnelMessage)},
5286   {&handle_local_tunnel_destroy, NULL,
5287    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_DESTROY,
5288    sizeof (struct GNUNET_MESH_TunnelMessage)},
5289   {&handle_local_tunnel_buffer, NULL,
5290    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_BUFFER,
5291    sizeof (struct GNUNET_MESH_TunnelMessage)},
5292   {&handle_local_tunnel_buffer, NULL,
5293    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_NOBUFFER,
5294    sizeof (struct GNUNET_MESH_TunnelMessage)},
5295   {&handle_local_unicast, NULL,
5296    GNUNET_MESSAGE_TYPE_MESH_UNICAST, 0},
5297   {&handle_local_to_origin, NULL,
5298    GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN, 0},
5299   {&handle_local_ack, NULL,
5300    GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK,
5301    sizeof (struct GNUNET_MESH_LocalAck)},
5302   {&handle_local_get_tunnels, NULL,
5303    GNUNET_MESSAGE_TYPE_MESH_LOCAL_INFO_TUNNELS,
5304    sizeof (struct GNUNET_MessageHeader)},
5305   {&handle_local_show_tunnel, NULL,
5306    GNUNET_MESSAGE_TYPE_MESH_LOCAL_INFO_TUNNEL,
5307      sizeof (struct GNUNET_MESH_LocalMonitor)},
5308   {NULL, NULL, 0, 0}
5309 };
5310
5311
5312 /**
5313  * To be called on core init/fail.
5314  *
5315  * @param cls service closure
5316  * @param server handle to the server for this service
5317  * @param identity the public identity of this peer
5318  */
5319 static void
5320 core_init (void *cls, struct GNUNET_CORE_Handle *server,
5321            const struct GNUNET_PeerIdentity *identity)
5322 {
5323   static int i = 0;
5324   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Core init\n");
5325   core_handle = server;
5326   if (0 != memcmp (identity, &my_full_id, sizeof (my_full_id)) ||
5327       NULL == server)
5328   {
5329     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _("Wrong CORE service\n"));
5330     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
5331                 " core id %s\n",
5332                 GNUNET_i2s (identity));
5333     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
5334                 " my id %s\n",
5335                 GNUNET_i2s (&my_full_id));
5336     GNUNET_SCHEDULER_shutdown (); // Try gracefully
5337     if (10 < i++)
5338       GNUNET_abort(); // Try harder
5339   }
5340   return;
5341 }
5342
5343
5344 /**
5345  * Method called whenever a given peer connects.
5346  *
5347  * @param cls closure
5348  * @param peer peer identity this notification is about
5349  */
5350 static void
5351 core_connect (void *cls, const struct GNUNET_PeerIdentity *peer)
5352 {
5353   struct MeshPeerInfo *peer_info;
5354   struct MeshPeerPath *path;
5355
5356   DEBUG_CONN ("Peer connected\n");
5357   DEBUG_CONN ("     %s\n", GNUNET_i2s (&my_full_id));
5358   peer_info = peer_get (peer);
5359   if (myid == peer_info->id)
5360   {
5361     DEBUG_CONN ("     (self)\n");
5362     return;
5363   }
5364   else
5365   {
5366     DEBUG_CONN ("     %s\n", GNUNET_i2s (peer));
5367   }
5368   path = path_new (2);
5369   path->peers[0] = myid;
5370   path->peers[1] = peer_info->id;
5371   GNUNET_PEER_change_rc (myid, 1);
5372   GNUNET_PEER_change_rc (peer_info->id, 1);
5373   peer_info_add_path (peer_info, path, GNUNET_YES);
5374   GNUNET_STATISTICS_update (stats, "# peers", 1, GNUNET_NO);
5375   return;
5376 }
5377
5378
5379 /**
5380  * Method called whenever a peer disconnects.
5381  *
5382  * @param cls closure
5383  * @param peer peer identity this notification is about
5384  */
5385 static void
5386 core_disconnect (void *cls, const struct GNUNET_PeerIdentity *peer)
5387 {
5388   struct MeshPeerInfo *pi;
5389   struct MeshPeerQueue *q;
5390   struct MeshPeerQueue *n;
5391
5392   DEBUG_CONN ("Peer disconnected\n");
5393   pi = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
5394   if (NULL == pi)
5395   {
5396     GNUNET_break (0);
5397     return;
5398   }
5399   q = pi->queue_head;
5400   while (NULL != q)
5401   {
5402       n = q->next;
5403       /* TODO try to reroute this traffic instead */
5404       queue_destroy(q, GNUNET_YES);
5405       q = n;
5406   }
5407   if (NULL != pi->core_transmit)
5408   {
5409     GNUNET_CORE_notify_transmit_ready_cancel(pi->core_transmit);
5410     pi->core_transmit = NULL;
5411   }
5412     peer_remove_path (pi, pi->id, myid);
5413   if (myid == pi->id)
5414   {
5415     DEBUG_CONN ("     (self)\n");
5416   }
5417   GNUNET_STATISTICS_update (stats, "# peers", -1, GNUNET_NO);
5418   return;
5419 }
5420
5421
5422 /******************************************************************************/
5423 /************************      MAIN FUNCTIONS      ****************************/
5424 /******************************************************************************/
5425
5426 /**
5427  * Iterator over tunnel hash map entries to destroy the tunnel during shutdown.
5428  *
5429  * @param cls closure
5430  * @param key current key code
5431  * @param value value in the hash map
5432  * @return GNUNET_YES if we should continue to iterate,
5433  *         GNUNET_NO if not.
5434  */
5435 static int
5436 shutdown_tunnel (void *cls, const struct GNUNET_HashCode * key, void *value)
5437 {
5438   struct MeshTunnel *t = value;
5439
5440   tunnel_destroy (t);
5441   return GNUNET_YES;
5442 }
5443
5444 /**
5445  * Iterator over peer hash map entries to destroy the tunnel during shutdown.
5446  *
5447  * @param cls closure
5448  * @param key current key code
5449  * @param value value in the hash map
5450  * @return GNUNET_YES if we should continue to iterate,
5451  *         GNUNET_NO if not.
5452  */
5453 static int
5454 shutdown_peer (void *cls, const struct GNUNET_HashCode * key, void *value)
5455 {
5456   struct MeshPeerInfo *p = value;
5457   struct MeshPeerQueue *q;
5458   struct MeshPeerQueue *n;
5459
5460   q = p->queue_head;
5461   while (NULL != q)
5462   {
5463       n = q->next;
5464       if (q->peer == p)
5465       {
5466         queue_destroy(q, GNUNET_YES);
5467       }
5468       q = n;
5469   }
5470   peer_info_destroy (p);
5471   return GNUNET_YES;
5472 }
5473
5474
5475 /**
5476  * Task run during shutdown.
5477  *
5478  * @param cls unused
5479  * @param tc unused
5480  */
5481 static void
5482 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
5483 {
5484   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shutting down\n");
5485
5486   if (core_handle != NULL)
5487   {
5488     GNUNET_CORE_disconnect (core_handle);
5489     core_handle = NULL;
5490   }
5491   if (NULL != keygen)
5492   {
5493     GNUNET_CRYPTO_ecc_key_create_stop (keygen);
5494     keygen = NULL;
5495   }
5496   GNUNET_CONTAINER_multihashmap_iterate (tunnels, &shutdown_tunnel, NULL);
5497   GNUNET_CONTAINER_multihashmap_iterate (peers, &shutdown_peer, NULL);
5498   if (dht_handle != NULL)
5499   {
5500     GNUNET_DHT_disconnect (dht_handle);
5501     dht_handle = NULL;
5502   }
5503   if (nc != NULL)
5504   {
5505     GNUNET_SERVER_notification_context_destroy (nc);
5506     nc = NULL;
5507   }
5508   if (GNUNET_SCHEDULER_NO_TASK != announce_id_task)
5509   {
5510     GNUNET_SCHEDULER_cancel (announce_id_task);
5511     announce_id_task = GNUNET_SCHEDULER_NO_TASK;
5512   }
5513   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shut down\n");
5514 }
5515
5516
5517 /**
5518  * Callback for hostkey read/generation.
5519  *
5520  * @param cls Closure (Configuration handle).
5521  * @param pk The ECC private key.
5522  * @param emsg Error message, if any.
5523  */
5524 static void
5525 key_generation_cb (void *cls,
5526                    struct GNUNET_CRYPTO_EccPrivateKey *pk,
5527                    const char *emsg)
5528 {
5529   const struct GNUNET_CONFIGURATION_Handle *c = cls;
5530   struct MeshPeerInfo *peer;
5531   struct MeshPeerPath *p;
5532
5533   keygen = NULL;  
5534   if (NULL == pk)
5535   {
5536     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
5537                 _("Mesh service could not access hostkey: %s. Exiting.\n"),
5538                 emsg);
5539     GNUNET_SCHEDULER_shutdown ();
5540     return;
5541   }
5542   my_private_key = pk;
5543   GNUNET_CRYPTO_ecc_key_get_public (my_private_key, &my_public_key);
5544   GNUNET_CRYPTO_hash (&my_public_key, sizeof (my_public_key),
5545                       &my_full_id.hashPubKey);
5546   myid = GNUNET_PEER_intern (&my_full_id);
5547   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
5548               "Mesh for peer [%s] starting\n",
5549               GNUNET_i2s(&my_full_id));
5550
5551   core_handle = GNUNET_CORE_connect (c, /* Main configuration */
5552                                      NULL,      /* Closure passed to MESH functions */
5553                                      &core_init,        /* Call core_init once connected */
5554                                      &core_connect,     /* Handle connects */
5555                                      &core_disconnect,  /* remove peers on disconnects */
5556                                      NULL,      /* Don't notify about all incoming messages */
5557                                      GNUNET_NO, /* For header only in notification */
5558                                      NULL,      /* Don't notify about all outbound messages */
5559                                      GNUNET_NO, /* For header-only out notification */
5560                                      core_handlers);    /* Register these handlers */
5561   
5562   if (core_handle == NULL)
5563   {
5564     GNUNET_break (0);
5565     GNUNET_SCHEDULER_shutdown ();
5566     return;
5567   }
5568
5569   next_tid = 0;
5570   next_local_tid = GNUNET_MESH_LOCAL_TUNNEL_ID_SERV;
5571
5572
5573   GNUNET_SERVER_add_handlers (server_handle, client_handlers);
5574   nc = GNUNET_SERVER_notification_context_create (server_handle, 1);
5575   GNUNET_SERVER_disconnect_notify (server_handle,
5576                                    &handle_local_client_disconnect, NULL);
5577
5578
5579   clients_head = NULL;
5580   clients_tail = NULL;
5581   next_client_id = 0;
5582
5583   announce_id_task = GNUNET_SCHEDULER_add_now (&announce_id, cls);
5584
5585   /* Create a peer_info for the local peer */
5586   peer = peer_get (&my_full_id);
5587   p = path_new (1);
5588   p->peers[0] = myid;
5589   GNUNET_PEER_change_rc (myid, 1);
5590   peer_info_add_path (peer, p, GNUNET_YES);
5591   GNUNET_SERVER_resume (server_handle);
5592   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Mesh service running\n");
5593 }
5594
5595
5596 /**
5597  * Process mesh requests.
5598  *
5599  * @param cls closure
5600  * @param server the initialized server
5601  * @param c configuration to use
5602  */
5603 static void
5604 run (void *cls, struct GNUNET_SERVER_Handle *server,
5605      const struct GNUNET_CONFIGURATION_Handle *c)
5606 {
5607   char *keyfile;
5608
5609   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "starting to run\n");
5610   server_handle = server;
5611
5612   if (GNUNET_OK !=
5613       GNUNET_CONFIGURATION_get_value_filename (c, "PEER", "PRIVATE_KEY",
5614                                                &keyfile))
5615   {
5616     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
5617                 _
5618                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
5619                 "mesh", "peer/privatekey");
5620     GNUNET_SCHEDULER_shutdown ();
5621     return;
5622   }
5623
5624   if (GNUNET_OK !=
5625       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "REFRESH_PATH_TIME",
5626                                            &refresh_path_time))
5627   {
5628     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
5629                 _
5630                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
5631                 "mesh", "refresh path time");
5632     GNUNET_SCHEDULER_shutdown ();
5633     return;
5634   }
5635
5636   if (GNUNET_OK !=
5637       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "ID_ANNOUNCE_TIME",
5638                                            &id_announce_time))
5639   {
5640     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
5641                 _
5642                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
5643                 "mesh", "id announce time");
5644     GNUNET_SCHEDULER_shutdown ();
5645     return;
5646   }
5647
5648   if (GNUNET_OK !=
5649       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "CONNECT_TIMEOUT",
5650                                            &connect_timeout))
5651   {
5652     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
5653                 _
5654                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
5655                 "mesh", "connect timeout");
5656     GNUNET_SCHEDULER_shutdown ();
5657     return;
5658   }
5659
5660   if (GNUNET_OK !=
5661       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_MSGS_QUEUE",
5662                                              &max_msgs_queue))
5663   {
5664     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
5665                 _
5666                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
5667                 "mesh", "max msgs queue");
5668     GNUNET_SCHEDULER_shutdown ();
5669     return;
5670   }
5671
5672   if (GNUNET_OK !=
5673       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_TUNNELS",
5674                                              &max_tunnels))
5675   {
5676     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
5677                 _
5678                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
5679                 "mesh", "max tunnels");
5680     GNUNET_SCHEDULER_shutdown ();
5681     return;
5682   }
5683
5684   if (GNUNET_OK !=
5685       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DEFAULT_TTL",
5686                                              &default_ttl))
5687   {
5688     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
5689                 _
5690                 ("%s service is lacking key configuration settings (%s). Using default (%u).\n"),
5691                 "mesh", "default ttl", 64);
5692     default_ttl = 64;
5693   }
5694
5695   if (GNUNET_OK !=
5696       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_PEERS",
5697                                              &max_peers))
5698   {
5699     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
5700                 _("%s service is lacking key configuration settings (%s). Using default (%u).\n"),
5701                 "mesh", "max peers", 1000);
5702     max_peers = 1000;
5703   }
5704
5705   if (GNUNET_OK !=
5706       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DHT_REPLICATION_LEVEL",
5707                                              &dht_replication_level))
5708   {
5709     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
5710                 _
5711                 ("%s service is lacking key configuration settings (%s). Using default (%u).\n"),
5712                 "mesh", "dht replication level", 3);
5713     dht_replication_level = 3;
5714   }
5715
5716   tunnels = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
5717   incoming_tunnels = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
5718   peers = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
5719   types = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
5720
5721   dht_handle = GNUNET_DHT_connect (c, 64);
5722   if (NULL == dht_handle)
5723   {
5724     GNUNET_break (0);
5725   }
5726   stats = GNUNET_STATISTICS_create ("mesh", c);
5727
5728   GNUNET_SERVER_suspend (server_handle);
5729   /* Scheduled the task to clean up when shutdown is called */
5730   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
5731                                 NULL);
5732   keygen = GNUNET_CRYPTO_ecc_key_create_start (keyfile,
5733                                                &key_generation_cb,
5734                                                (void *) c);
5735   GNUNET_free (keyfile);
5736 }
5737
5738
5739 /**
5740  * The main function for the mesh service.
5741  *
5742  * @param argc number of arguments from the command line
5743  * @param argv command line arguments
5744  * @return 0 ok, 1 on error
5745  */
5746 int
5747 main (int argc, char *const *argv)
5748 {
5749   int ret;
5750   int r;
5751
5752   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "main()\n");
5753   r = GNUNET_SERVICE_run (argc, argv, "mesh", GNUNET_SERVICE_OPTION_NONE, &run,
5754                           NULL);
5755   ret = (GNUNET_OK == r) ? 0 : 1;
5756   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "main() END\n");
5757
5758   INTERVAL_SHOW;
5759
5760   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
5761               "Mesh for peer [%s] FWD ACKs %u, BCK ACKs %u\n",
5762               GNUNET_i2s(&my_full_id), debug_fwd_ack, debug_bck_ack);
5763
5764   return ret;
5765 }