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