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