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