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