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