- debug
[oweals/gnunet.git] / src / mesh / gnunet-service-mesh-enc.c
1 /*
2      This file is part of GNUnet.
3      (C) 2001-2013 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-enc.c
23  * @brief GNUnet MESH service with encryption
24  * @author Bartlomiej Polot
25  *
26  *  FIXME in progress:
27  * - when sending in-order buffered data, wait for client ACKs
28  * - add signatures
29  * - add encryption
30  * - set connection IDs independently from tunnel, tunnel has no ID
31  *
32  * TODO:
33  * - relay corking down to core
34  * - set ttl relative to path length
35  * TODO END
36  * 
37  * Dictionary:
38  * - peer: other mesh instance. If there is direct connection it's a neighbor.
39  * - tunnel: encrypted connection to a peer, neighbor or not.
40  * - channel: connection between two clients, on the same or different peers.
41  *            have properties like reliability.
42  * - path: series of directly connected peer from one peer to another.
43  * - connection: path which is being used in a tunnel.
44  */
45
46 #include "platform.h"
47 #include "gnunet_crypto_lib.h"
48 #include "mesh_enc.h"
49 #include "mesh_protocol_enc.h"
50 #include "mesh_path.h"
51 #include "block_mesh.h"
52 #include "gnunet_dht_service.h"
53 #include "gnunet_statistics_service.h"
54
55 #define MESH_BLOOM_SIZE         128
56 #define MESH_MAX_POLL_TIME      GNUNET_TIME_relative_multiply (\
57                                   GNUNET_TIME_UNIT_MINUTES,\
58                                   10)
59 #define MESH_RETRANSMIT_TIME    GNUNET_TIME_UNIT_SECONDS
60 #define MESH_RETRANSMIT_MARGIN  4
61
62 #define MESH_DEBUG_DHT          GNUNET_NO
63 #define MESH_DEBUG_CONNECTION   GNUNET_NO
64 #define MESH_DEBUG_TIMING       __LINUX__ && GNUNET_NO
65
66 #if MESH_DEBUG_DHT
67 #define DEBUG_DHT(...) GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, __VA_ARGS__)
68 #else
69 #define DEBUG_DHT(...)
70 #endif
71
72 #if MESH_DEBUG_CONNECTION
73 #define DEBUG_CONN(...) GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, __VA_ARGS__)
74 #else
75 #define DEBUG_CONN(...)
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  * All the states a tunnel can be in.
104  */
105 enum MeshTunnelState
106 {
107     /**
108      * Uninitialized status, should never appear in operation.
109      */
110   MESH_TUNNEL_NEW,
111
112     /**
113      * Path to the peer not known yet
114      */
115   MESH_TUNNEL_SEARCHING,
116
117     /**
118      * Request sent, not yet answered.
119      */
120   MESH_TUNNEL_WAITING,
121
122     /**
123      * Peer connected and ready to accept data
124      */
125   MESH_TUNNEL_READY,
126
127     /**
128      * Peer connected previosly but not responding
129      */
130   MESH_TUNNEL_RECONNECTING
131 };
132
133
134 /**
135  * All the states a connection can be in.
136  */
137 enum MeshConnectionState
138 {
139   /**
140    * Uninitialized status, should never appear in operation.
141    */
142   MESH_CONNECTION_NEW,
143
144   /**
145    * Connection create message sent, waiting for ACK.
146    */
147   MESH_CONNECTION_SENT,
148
149   /**
150    * Connection ACK sent, waiting for ACK.
151    */
152   MESH_CONNECTION_ACK,
153
154   /**
155    * Connection confirmed, ready to carry traffic.
156    */
157   MESH_CONNECTION_READY,
158 };
159
160
161 /**
162  * All the states a connection can be in.
163  */
164 enum MeshChannelState
165 {
166   /**
167    * Uninitialized status, should never appear in operation.
168    */
169   MESH_CHANNEL_NEW,
170
171   /**
172    * Connection create message sent, waiting for ACK.
173    */
174   MESH_CHANNEL_SENT,
175
176   /**
177    * Connection confirmed, ready to carry traffic..
178    */
179   MESH_CHANNEL_READY,
180 };
181
182
183 /******************************************************************************/
184 /************************      DATA STRUCTURES     ****************************/
185 /******************************************************************************/
186
187 /** FWD declaration */
188 struct MeshClient;
189 struct MeshPeer;
190 struct MeshTunnel2;
191 struct MeshConnection;
192 struct MeshChannel;
193 struct MeshChannelReliability;
194
195
196 /**
197  * Struct containing info about a queued transmission to this peer
198  */
199 struct MeshPeerQueue
200 {
201     /**
202       * DLL next
203       */
204   struct MeshPeerQueue *next;
205
206     /**
207       * DLL previous
208       */
209   struct MeshPeerQueue *prev;
210
211     /**
212      * Peer this transmission is directed to.
213      */
214   struct MeshPeer *peer;
215
216     /**
217      * Connection this message belongs to.
218      */
219   struct MeshConnection *c;
220
221     /**
222      * Is FWD in c?
223      */
224   int fwd;
225
226     /**
227      * Channel this message belongs to, if known.
228      */
229   struct MeshChannel *ch;
230
231     /**
232      * Pointer to info stucture used as cls.
233      */
234   void *cls;
235
236     /**
237      * Type of message
238      */
239   uint16_t type;
240
241     /**
242      * Size of the message
243      */
244   size_t size;
245 };
246
247
248 /**
249  * Struct to encapsulate all the Flow Control information to a peer to which
250  * we are directly connected (on a core level).
251  */
252 struct MeshFlowControl
253 {
254   /**
255    * Connection this controls.
256    */
257   struct MeshConnection *c;
258
259   /**
260    * How many messages are in the queue on this connection.
261    */
262   unsigned int queue_n;
263
264   /**
265    * How many messages do we accept in the queue.
266    */
267   unsigned int queue_max;
268
269   /**
270    * Next ID to use.
271    */
272   uint32_t next_pid;
273
274   /**
275    * ID of the last packet sent towards the peer.
276    */
277   uint32_t last_pid_sent;
278
279   /**
280    * ID of the last packet received from the peer.
281    */
282   uint32_t last_pid_recv;
283
284   /**
285    * Last ACK sent to the peer (peer can't send more than this PID).
286    */
287   uint32_t last_ack_sent;
288
289   /**
290    * Last ACK sent towards the origin (for traffic towards leaf node).
291    */
292   uint32_t last_ack_recv;
293
294   /**
295    * Task to poll the peer in case of a lost ACK causes stall.
296    */
297   GNUNET_SCHEDULER_TaskIdentifier poll_task;
298
299   /**
300    * How frequently to poll for ACKs.
301    */
302   struct GNUNET_TIME_Relative poll_time;
303 };
304
305
306 /**
307  * Struct containing all information regarding a given peer
308  */
309 struct MeshPeer
310 {
311     /**
312      * ID of the peer
313      */
314   GNUNET_PEER_Id id;
315
316     /**
317      * Last time we heard from this peer
318      */
319   struct GNUNET_TIME_Absolute last_contact;
320
321     /**
322      * Paths to reach the peer, ordered by ascending hop count
323      */
324   struct MeshPeerPath *path_head;
325
326     /**
327      * Paths to reach the peer, ordered by ascending hop count
328      */
329   struct MeshPeerPath *path_tail;
330
331     /**
332      * Handle to stop the DHT search for paths to this peer
333      */
334   struct GNUNET_DHT_GetHandle *dhtget;
335
336     /**
337      * Tunnel to this peer, if any.
338      */
339   struct MeshTunnel2 *tunnel;
340
341     /**
342      * Connections that go through this peer, indexed by tid;
343      */
344   struct GNUNET_CONTAINER_MultiHashMap *connections;
345
346     /**
347      * Handle for queued transmissions
348      */
349   struct GNUNET_CORE_TransmitHandle *core_transmit;
350
351   /**
352    * Transmission queue to core DLL head
353    */
354   struct MeshPeerQueue *queue_head;
355   
356   /**
357    * Transmission queue to core DLL tail
358    */
359   struct MeshPeerQueue *queue_tail;
360
361   /**
362    * How many messages are in the queue to this peer.
363    */
364   unsigned int queue_n;
365 };
366
367
368 /**
369  * Info needed to retry a message in case it gets lost.
370  */
371 struct MeshReliableMessage
372 {
373     /**
374      * Double linked list, FIFO style
375      */
376   struct MeshReliableMessage    *next;
377   struct MeshReliableMessage    *prev;
378
379     /**
380      * Type of message (payload, channel management).
381      */
382   int16_t type;
383
384     /**
385      * Tunnel Reliability queue this message is in.
386      */
387   struct MeshChannelReliability  *rel;
388
389     /**
390      * ID of the message (ACK needed to free)
391      */
392   uint32_t                      mid;
393
394     /**
395      * When was this message issued (to calculate ACK delay)
396      */
397   struct GNUNET_TIME_Absolute   timestamp;
398
399   /* struct GNUNET_MESH_Data with payload */
400 };
401
402
403 /**
404  * Info about the traffic state for a client in a channel.
405  */
406 struct MeshChannelReliability
407 {
408     /**
409      * Channel this is about.
410      */
411   struct MeshChannel *ch;
412
413     /**
414      * DLL of messages sent and not yet ACK'd.
415      */
416   struct MeshReliableMessage        *head_sent;
417   struct MeshReliableMessage        *tail_sent;
418
419     /**
420      * Messages pending to send.
421      */
422   unsigned int                      n_sent;
423
424     /**
425      * DLL of messages received out of order.
426      */
427   struct MeshReliableMessage        *head_recv;
428   struct MeshReliableMessage        *tail_recv;
429
430     /**
431      * Messages received.
432      */
433   unsigned int                      n_recv;
434
435     /**
436      * Next MID to use for outgoing traffic.
437      */
438   uint32_t                          mid_send;
439
440     /**
441      * Next MID expected for incoming traffic.
442      */
443   uint32_t                          mid_recv;
444
445     /**
446      * Can we send data to the client?
447      */
448   int                               client_ready;
449
450     /**
451      * Task to resend/poll in case no ACK is received.
452      */
453   GNUNET_SCHEDULER_TaskIdentifier   retry_task;
454
455     /**
456      * Counter for exponential backoff.
457      */
458   struct GNUNET_TIME_Relative       retry_timer;
459
460     /**
461      * How long does it usually take to get an ACK.
462      */
463   struct GNUNET_TIME_Relative       expected_delay;
464 };
465
466
467 /**
468  * Struct containing all information regarding a channel to a remote client.
469  */
470 struct MeshChannel
471 {
472     /**
473      * Tunnel this channel is in.
474      */
475   struct MeshTunnel2 *t;
476
477     /**
478      * Double linked list.
479      */
480   struct MeshChannel    *next;
481   struct MeshChannel    *prev;
482
483     /**
484      * Destination port of the channel.
485      */
486   uint32_t port;
487
488     /**
489      * Global channel number ( < GNUNET_MESH_LOCAL_CHANNEL_ID_CLI)
490      */
491   MESH_ChannelNumber gid;
492
493     /**
494      * Local tunnel number for root (owner) client.
495      * ( >= GNUNET_MESH_LOCAL_CHANNEL_ID_CLI or 0 )
496      */
497   MESH_ChannelNumber lid_root;
498
499     /**
500      * Local tunnel number for local destination clients (incoming number)
501      * ( >= GNUNET_MESH_LOCAL_CHANNEL_ID_SERV or 0).
502      */
503   MESH_ChannelNumber lid_dest;
504
505     /**
506      * Channel state.
507      */
508   enum MeshChannelState state;
509
510     /**
511      * Is the tunnel bufferless (minimum latency)?
512      */
513   int nobuffer;
514
515     /**
516      * Is the tunnel reliable?
517      */
518   int reliable;
519
520     /**
521      * Last time the channel was used
522      */
523   struct GNUNET_TIME_Absolute timestamp;
524
525     /**
526      * Client owner of the tunnel, if any
527      */
528   struct MeshClient *root;
529
530     /**
531      * Client destination of the tunnel, if any.
532      */
533   struct MeshClient *dest;
534
535     /**
536      * Flag to signal the destruction of the channel.
537      * If this is set GNUNET_YES the channel will be destroyed
538      * when the queue is empty.
539      */
540   int destroy;
541
542     /**
543      * Total messages pending for this channel, payload or not.
544      */
545   unsigned int pending_messages;
546
547     /**
548      * Reliability data.
549      * Only present (non-NULL) at the owner of a tunnel.
550      */
551   struct MeshChannelReliability *root_rel;
552
553     /**
554      * Reliability data.
555      * Only present (non-NULL) at the destination of a tunnel.
556      */
557   struct MeshChannelReliability *dest_rel;
558
559 };
560
561
562 /**
563  * Struct containing all information regarding a connection to a peer.
564  */
565 struct MeshConnection
566 {
567   /**
568    * DLL
569    */
570   struct MeshConnection *next;
571   struct MeshConnection *prev;
572
573   /**
574    * Tunnel this connection is part of.
575    */
576   struct MeshTunnel2 *t;
577
578   /**
579    * Flow control information for traffic fwd.
580    */
581   struct MeshFlowControl fwd_fc;
582
583   /**
584    * Flow control information for traffic bck.
585    */
586   struct MeshFlowControl bck_fc;
587
588   /**
589    * ID of the connection.
590    */
591   struct GNUNET_HashCode id;
592
593   /**
594    * State of the connection.
595    */
596   enum MeshConnectionState state;
597
598   /**
599    * Path being used for the tunnel.
600    */
601   struct MeshPeerPath *path;
602
603   /**
604    * Position of the local peer in the path.
605    */
606   unsigned int own_pos;
607
608   /**
609    * Task to keep the used paths alive at the owner,
610    * time tunnel out on all the other peers.
611    */
612   GNUNET_SCHEDULER_TaskIdentifier fwd_maintenance_task;
613
614   /**
615    * Task to keep the used paths alive at the destination,
616    * time tunnel out on all the other peers.
617    */
618   GNUNET_SCHEDULER_TaskIdentifier bck_maintenance_task;
619
620   /**
621    * Pending message count.
622    */
623   int pending_messages;
624
625   /**
626    * Destroy flag: if true, destroy on last message.
627    */
628   int destroy;
629 };
630
631
632 /**
633  * Struct used to queue messages in a tunnel.
634  */
635 struct MeshTunnelQueue
636 {
637   /**
638    * DLL
639    */
640   struct MeshTunnelQueue *next;
641   struct MeshTunnelQueue *prev;
642
643   /**
644    * Channel.
645    */
646   struct MeshChannel *ch;
647
648   /**
649    * Message to send.
650    */
651   /* struct GNUNET_MessageHeader *msg; */
652 };
653
654
655 /**
656  * Struct containing all information regarding a tunnel to a peer.
657  */
658 struct MeshTunnel2
659 {
660     /**
661      * Endpoint of the tunnel.
662      */
663   struct MeshPeer *peer;
664
665     /**
666      * State of the tunnel.
667      */
668   enum MeshTunnelState state;
669
670   /**
671    * Local peer ephemeral private key
672    */
673   struct GNUNET_CRYPTO_EccPrivateKey *my_eph_key;
674
675   /**
676    * Local peer ephemeral public key
677    */
678   struct GNUNET_CRYPTO_EccPublicKey *my_eph;
679
680   /**
681    * Remote peer's public key.
682    */
683   struct GNUNET_CRYPTO_EccPublicKey *peers_eph;
684
685   /**
686    * Encryption ("our") key.
687    */
688   struct GNUNET_CRYPTO_AesSessionKey e_key;
689
690   /**
691    * Decryption ("their") key.
692    */
693   struct GNUNET_CRYPTO_AesSessionKey d_key;
694
695   /**
696    * Paths that are actively used to reach the destination peer.
697    */
698   struct MeshConnection *connection_head;
699   struct MeshConnection *connection_tail;
700
701   /**
702    * Next connection number.
703    */
704   uint32_t next_cid;
705
706   /**
707    * Channels inside this tunnel.
708    */
709   struct MeshChannel *channel_head;
710   struct MeshChannel *channel_tail;
711
712   /**
713    * Channel ID for the next created channel.
714    */
715   MESH_ChannelNumber next_chid;
716
717   /**
718    * Channel ID for the next incoming channel.
719    */
720   MESH_ChannelNumber next_local_chid;
721
722   /**
723    * Pending message count.
724    */
725   int pending_messages;
726
727   /**
728    * Destroy flag: if true, destroy on last message.
729    */
730   int destroy;
731
732   /**
733    * Queued messages, to transmit once tunnel gets connected.
734    */
735   struct MeshTunnelQueue *tq_head;
736   struct MeshTunnelQueue *tq_tail;
737 };
738
739
740
741 /**
742  * Struct containing information about a client of the service
743  * 
744  * TODO: add a list of 'waiting' ports
745  */
746 struct MeshClient
747 {
748     /**
749      * Linked list next
750      */
751   struct MeshClient *next;
752
753     /**
754      * Linked list prev
755      */
756   struct MeshClient *prev;
757
758     /**
759      * Tunnels that belong to this client, indexed by local id
760      */
761   struct GNUNET_CONTAINER_MultiHashMap32 *own_channels;
762
763    /**
764      * Tunnels this client has accepted, indexed by incoming local id
765      */
766   struct GNUNET_CONTAINER_MultiHashMap32 *incoming_channels;
767
768     /**
769      * Handle to communicate with the client
770      */
771   struct GNUNET_SERVER_Client *handle;
772
773     /**
774      * Ports that this client has declared interest in.
775      * Indexed by port, contains *Client.
776      */
777   struct GNUNET_CONTAINER_MultiHashMap32 *ports;
778
779     /**
780      * Whether the client is active or shutting down (don't send confirmations
781      * to a client that is shutting down.
782      */
783   int shutting_down;
784
785     /**
786      * ID of the client, mainly for debug messages
787      */
788   unsigned int id;
789 };
790
791
792 /******************************************************************************/
793 /************************      DEBUG FUNCTIONS     ****************************/
794 /******************************************************************************/
795
796 #if MESH_DEBUG
797 /**
798  * GNUNET_SCHEDULER_Task for printing a message after some operation is done
799  * @param cls string to print
800  * @param success  GNUNET_OK if the PUT was transmitted,
801  *                GNUNET_NO on timeout,
802  *                GNUNET_SYSERR on disconnect from service
803  *                after the PUT message was transmitted
804  *                (so we don't know if it was received or not)
805  */
806
807 #if 0
808 static void
809 mesh_debug (void *cls, int success)
810 {
811   char *s = cls;
812
813   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "%s (%d)\n", s, success);
814 }
815 #endif
816
817 #endif
818
819 /******************************************************************************/
820 /***********************      GLOBAL VARIABLES     ****************************/
821 /******************************************************************************/
822
823 /************************** Configuration parameters **************************/
824
825 /**
826  * How often to send path keepalives. Paths timeout after 4 missed.
827  */
828 static struct GNUNET_TIME_Relative refresh_connection_time;
829
830 /**
831  * How often to PUT own ID in the DHT.
832  */
833 static struct GNUNET_TIME_Relative id_announce_time;
834
835 /**
836  * Maximum time allowed to connect to a peer found by string.
837  */
838 static struct GNUNET_TIME_Relative connect_timeout;
839
840 /**
841  * Default TTL for payload packets.
842  */
843 static unsigned long long default_ttl;
844
845 /**
846  * DHT replication level, see DHT API: GNUNET_DHT_get_start, GNUNET_DHT_put.
847  */
848 static unsigned long long dht_replication_level;
849
850 /**
851  * How many connections are we willing to maintain.
852  * Local connections are always allowed, even if there are more connections than max.
853  */
854 static unsigned long long max_connections;
855
856 /**
857  * How many messages *in total* are we willing to queue, divide by number of 
858  * connections to get connection queue size.
859  */
860 static unsigned long long max_msgs_queue;
861
862 /**
863  * How many peers do we want to remember?
864  */
865 static unsigned long long max_peers;
866
867 /**
868  * Percentage of messages that will be dropped (for test purposes only).
869  */
870 static unsigned long long drop_percent;
871
872 /*************************** Static global variables **************************/
873
874 /**
875  * DLL with all the clients, head.
876  */
877 static struct MeshClient *clients_head;
878
879 /**
880  * DLL with all the clients, tail.
881  */
882 static struct MeshClient *clients_tail;
883
884 /**
885  * Connections known, indexed by cid (MeshConnection).
886  */
887 static struct GNUNET_CONTAINER_MultiHashMap *connections;
888
889 /**
890  * Peers known, indexed by PeerIdentity (MeshPeer).
891  */
892 static struct GNUNET_CONTAINER_MultiHashMap *peers;
893
894 /**
895  * Handle to communicate with core.
896  */
897 static struct GNUNET_CORE_Handle *core_handle;
898
899 /**
900  * Handle to use DHT.
901  */
902 static struct GNUNET_DHT_Handle *dht_handle;
903
904 /**
905  * Handle to server lib.
906  */
907 static struct GNUNET_SERVER_Handle *server_handle;
908
909 /**
910  * Handle to the statistics service.
911  */
912 static struct GNUNET_STATISTICS_Handle *stats;
913
914 /**
915  * Notification context, to send messages to local clients.
916  */
917 static struct GNUNET_SERVER_NotificationContext *nc;
918
919 /**
920  * Local peer own ID (memory efficient handle).
921  */
922 static GNUNET_PEER_Id myid;
923
924 /**
925  * Local peer own ID (full value).
926  */
927 static struct GNUNET_PeerIdentity my_full_id;
928
929 /**
930  * Own private key.
931  */
932 static struct GNUNET_CRYPTO_EccPrivateKey *my_private_key;
933
934 /**
935  * Own public key.
936  */
937 static struct GNUNET_CRYPTO_EccPublicKey my_public_key;
938
939 /**
940  * All ports clients of this peer have opened.
941  */
942 static struct GNUNET_CONTAINER_MultiHashMap32 *ports;
943
944 /**
945  * Task to periodically announce itself in the network.
946  */
947 GNUNET_SCHEDULER_TaskIdentifier announce_id_task;
948
949 /**
950  * Next ID to assign to a client.
951  */
952 unsigned int next_client_id;
953
954
955 /******************************************************************************/
956 /***********************         DECLARATIONS        **************************/
957 /******************************************************************************/
958
959 /**
960  * Function to process paths received for a new peer addition. The recorded
961  * paths form the initial tunnel, which can be optimized later.
962  * Called on each result obtained for the DHT search.
963  *
964  * @param cls closure
965  * @param exp when will this value expire
966  * @param key key of the result
967  * @param type type of the result
968  * @param size number of bytes in data
969  * @param data pointer to the result data
970  */
971 static void
972 dht_get_id_handler (void *cls, struct GNUNET_TIME_Absolute exp,
973                     const struct GNUNET_HashCode * key,
974                     const struct GNUNET_PeerIdentity *get_path,
975                     unsigned int get_path_length,
976                     const struct GNUNET_PeerIdentity *put_path,
977                     unsigned int put_path_length, enum GNUNET_BLOCK_Type type,
978                     size_t size, const void *data);
979
980
981 /**
982  * Retrieve the MeshPeer stucture associated with the peer, create one
983  * and insert it in the appropriate structures if the peer is not known yet.
984  *
985  * @param peer Full identity of the peer.
986  *
987  * @return Existing or newly created peer info.
988  */
989 static struct MeshPeer *
990 peer_get (const struct GNUNET_PeerIdentity *peer);
991
992
993 /**
994  * Retrieve the MeshPeer stucture associated with the peer, create one
995  * and insert it in the appropriate structures if the peer is not known yet.
996  *
997  * @param peer Short identity of the peer.
998  *
999  * @return Existing or newly created peer info.
1000  */
1001 static struct MeshPeer *
1002 peer_get_short (const GNUNET_PEER_Id peer);
1003
1004
1005 /**
1006  * Build a PeerPath from the paths returned from the DHT, reversing the paths
1007  * to obtain a local peer -> destination path and interning the peer ids.
1008  *
1009  * @return Newly allocated and created path
1010  */
1011 static struct MeshPeerPath *
1012 path_build_from_dht (const struct GNUNET_PeerIdentity *get_path,
1013                      unsigned int get_path_length,
1014                      const struct GNUNET_PeerIdentity *put_path,
1015                      unsigned int put_path_length);
1016
1017
1018 /**
1019  * Adds a path to the data structs of all the peers in the path
1020  *
1021  * @param p Path to process.
1022  * @param confirmed Whether we know if the path works or not.
1023  */
1024 static void
1025 path_add_to_peers (struct MeshPeerPath *p, int confirmed);
1026
1027
1028 /**
1029  * Search for a tunnel by global ID using full PeerIdentities.
1030  *
1031  * @param t Tunnel containing the channel.
1032  * @param chid Public channel number.
1033  *
1034  * @return channel handler, NULL if doesn't exist
1035  */
1036 static struct MeshChannel *
1037 channel_get (struct MeshTunnel2 *t, MESH_ChannelNumber chid);
1038
1039 /**
1040  * Modify the data message ID from global to local and send to client.
1041  * 
1042  * @param ch Channel on which to send the message.
1043  * @param msg Message to modify and send.
1044  * @param fwd Forward?
1045  */
1046 static void
1047 channel_send_client_data (struct MeshChannel *ch,
1048                           const struct GNUNET_MESH_Data *msg,
1049                           int fwd);
1050
1051
1052 /**
1053  * Change the tunnel state.
1054  *
1055  * @param t Tunnel whose state to change.
1056  * @param state New state.
1057  */
1058 static void
1059 tunnel_change_state (struct MeshTunnel2 *t, enum MeshTunnelState state);
1060
1061
1062 /**
1063  * Notify a tunnel that a connection has broken that affects at least
1064  * some of its peers.
1065  *
1066  * @param t Tunnel affected.
1067  * @param p1 Peer that got disconnected from p2.
1068  * @param p2 Peer that got disconnected from p1.
1069  *
1070  * @return Short ID of the peer disconnected (either p1 or p2).
1071  *         0 if the tunnel remained unaffected.
1072  */
1073 static GNUNET_PEER_Id
1074 tunnel_notify_connection_broken (struct MeshTunnel2 *t,
1075                                  GNUNET_PEER_Id p1, GNUNET_PEER_Id p2);
1076
1077 /**
1078  * @brief Use the given path for the tunnel.
1079  * Update the next and prev hops (and RCs).
1080  * (Re)start the path refresh in case the tunnel is locally owned.
1081  * 
1082  * @param t Tunnel to update.
1083  * @param p Path to use.
1084  *
1085  * @return Connection created.
1086  */
1087 static struct MeshConnection *
1088 tunnel_use_path (struct MeshTunnel2 *t, struct MeshPeerPath *p);
1089
1090 /**
1091  * Tunnel is empty: destroy it.
1092  * 
1093  * Notifies all participants (peers, cleints) about the destruction.
1094  * 
1095  * @param t Tunnel to destroy. 
1096  */
1097 static void
1098 tunnel_destroy_empty (struct MeshTunnel2 *t);
1099
1100 /**
1101  * Destroy the tunnel.
1102  *
1103  * This function does not generate any warning traffic to clients or peers.
1104  *
1105  * Tasks:
1106  * Cancel messages belonging to this tunnel queued to neighbors.
1107  * Free any allocated resources linked to the tunnel.
1108  *
1109  * @param t The tunnel to destroy.
1110  */
1111 static void
1112 tunnel_destroy (struct MeshTunnel2 *t);
1113
1114 /**
1115  * Create a connection.
1116  *
1117  * @param cid Connection ID.
1118  */
1119 static struct MeshConnection *
1120 connection_new (const struct GNUNET_HashCode *cid);
1121
1122 /**
1123  * Connection is no longer needed: destroy it and remove from tunnel.
1124  *
1125  * @param c Connection to destroy.
1126  */
1127 static void
1128 connection_destroy (struct MeshConnection *c);
1129
1130 /**
1131  * Send FWD keepalive packets for a connection.
1132  *
1133  * @param cls Closure (connection for which to send the keepalive).
1134  * @param tc Notification context.
1135  */
1136 static void
1137 connection_fwd_keepalive (void *cls,
1138                           const struct GNUNET_SCHEDULER_TaskContext *tc);
1139
1140 /**
1141  * Send BCK keepalive packets for a connection.
1142  *
1143  * @param cls Closure (connection for which to send the keepalive).
1144  * @param tc Notification context.
1145  */
1146 static void
1147 connection_bck_keepalive (void *cls,
1148                           const struct GNUNET_SCHEDULER_TaskContext *tc);
1149
1150
1151 /**
1152  * Change the tunnel state.
1153  *
1154  * @param c Connection whose state to change.
1155  * @param state New state.
1156  */
1157 static void
1158 connection_change_state (struct MeshConnection* c,
1159                          enum MeshConnectionState state);
1160
1161
1162
1163 /**
1164  * @brief Queue and pass message to core when possible.
1165  *
1166  * @param cls Closure (@c type dependant). It will be used by queue_send to
1167  *            build the message to be sent if not already prebuilt.
1168  * @param type Type of the message, 0 for a raw message.
1169  * @param size Size of the message.
1170  * @param c Connection this message belongs to (cannot be NULL).
1171  * @param ch Channel this message belongs to, if applicable (otherwise NULL).
1172  * @param fwd Is this a message going root->dest? (FWD ACK are NOT FWD!)
1173  */
1174 static void
1175 queue_add (void* cls,
1176            uint16_t type,
1177            size_t size,
1178            struct MeshConnection* c,
1179            struct MeshChannel* ch,
1180            int fwd);
1181
1182
1183 /**
1184  * Free a transmission that was already queued with all resources
1185  * associated to the request.
1186  *
1187  * @param queue Queue handler to cancel.
1188  * @param clear_cls Is it necessary to free associated cls?
1189  */
1190 static void
1191 queue_destroy (struct MeshPeerQueue *queue, int clear_cls);
1192
1193
1194 /**
1195  * Core callback to write a queued packet to core buffer
1196  *
1197  * @param cls Closure (peer info).
1198  * @param size Number of bytes available in buf.
1199  * @param buf Where the to write the message.
1200  *
1201  * @return number of bytes written to buf
1202  */
1203 static size_t
1204 queue_send (void *cls, size_t size, void *buf);
1205
1206
1207 /**
1208  * Demultiplex by message type and call appropriate handler for a message
1209  * towards a channel of a local tunnel.
1210  *
1211  * @param t Tunnel this message came on.
1212  * @param msgh Message header.
1213  * @param fwd Is this message fwd?
1214  */
1215 static void
1216 handle_decrypted (struct MeshTunnel2 *t,
1217                   const struct GNUNET_MessageHeader *msgh,
1218                   int fwd);
1219
1220
1221 /**
1222  * Dummy function to separate declarations from definitions in function list.
1223  */
1224 void
1225 __mesh_divider______________________________________________________________();
1226
1227
1228 /**
1229  * Get string description for tunnel state.
1230  *
1231  * @param s Tunnel state.
1232  *
1233  * @return String representation. 
1234  */
1235 static const char *
1236 GNUNET_MESH_DEBUG_TS2S (enum MeshTunnelState s)
1237 {
1238   static char buf[128];
1239
1240   switch (s)
1241   {
1242     case MESH_TUNNEL_NEW:
1243       return "MESH_TUNNEL_NEW";
1244     case MESH_TUNNEL_SEARCHING:
1245       return "MESH_TUNNEL_SEARCHING";
1246     case MESH_TUNNEL_WAITING:
1247       return "MESH_TUNNEL_WAITING";
1248     case MESH_TUNNEL_READY:
1249       return "MESH_TUNNEL_READY";
1250     case MESH_TUNNEL_RECONNECTING:
1251       return "MESH_TUNNEL_RECONNECTING";
1252
1253     default:
1254       sprintf (buf, "%u (UNKNOWN STATE)", s);
1255       return buf;
1256   }
1257 }
1258
1259
1260 /**
1261  * Get string description for tunnel state.
1262  *
1263  * @param s Tunnel state.
1264  *
1265  * @return String representation. 
1266  */
1267 static const char *
1268 GNUNET_MESH_DEBUG_CS2S (enum MeshTunnelState s)
1269 {
1270   switch (s) 
1271   {
1272     case MESH_CONNECTION_NEW:
1273       return "MESH_CONNECTION_NEW";
1274     case MESH_CONNECTION_SENT:
1275       return "MESH_CONNECTION_SENT";
1276     case MESH_CONNECTION_ACK:
1277       return "MESH_CONNECTION_ACK";
1278     case MESH_CONNECTION_READY:
1279       return "MESH_CONNECTION_READY";
1280     default:
1281       return "MESH_CONNECTION_STATE_ERROR";
1282   }
1283 }
1284
1285
1286
1287 /******************************************************************************/
1288 /************************    PERIODIC FUNCTIONS    ****************************/
1289 /******************************************************************************/
1290
1291 /**
1292  * Periodically announce self id in the DHT
1293  *
1294  * @param cls closure
1295  * @param tc task context
1296  */
1297 static void
1298 announce_id (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1299 {
1300   struct PBlock block;
1301
1302   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1303   {
1304     announce_id_task = GNUNET_SCHEDULER_NO_TASK;
1305     return;
1306   }
1307   /* TODO
1308    * - Set data expiration in function of X
1309    * - Adapt X to churn
1310    */
1311   DEBUG_DHT ("DHT_put for ID %s started.\n", GNUNET_i2s (&my_full_id));
1312
1313   block.id = my_full_id;
1314   GNUNET_DHT_put (dht_handle,   /* DHT handle */
1315                   &my_full_id.hashPubKey,       /* Key to use */
1316                   dht_replication_level,     /* Replication level */
1317                   GNUNET_DHT_RO_RECORD_ROUTE | GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE,    /* DHT options */
1318                   GNUNET_BLOCK_TYPE_MESH_PEER,       /* Block type */
1319                   sizeof (block),  /* Size of the data */
1320                   (const char *) &block, /* Data itself */
1321                   GNUNET_TIME_UNIT_FOREVER_ABS,  /* Data expiration */
1322                   GNUNET_TIME_UNIT_FOREVER_REL, /* Retry time */
1323                   NULL,         /* Continuation */
1324                   NULL);        /* Continuation closure */
1325   announce_id_task =
1326       GNUNET_SCHEDULER_add_delayed (id_announce_time, &announce_id, cls);
1327 }
1328
1329
1330 /******************************************************************************/
1331 /******************      GENERAL HELPER FUNCTIONS      ************************/
1332 /******************************************************************************/
1333
1334
1335 /**
1336  * Get the static string for a peer ID.
1337  *
1338  * @param peer Peer.
1339  *
1340  * @return Static string for it's ID.
1341  */
1342 static const char *
1343 peer2s (const struct MeshPeer *peer)
1344 {
1345   if (NULL == peer)
1346     return "(NULL)";
1347   return GNUNET_i2s (GNUNET_PEER_resolve2 (peer->id));
1348 }
1349
1350
1351 /**
1352  * Get the previous hop in a connection
1353  *
1354  * @param c Connection.
1355  *
1356  * @return Previous peer in the connection.
1357  */
1358 static struct MeshPeer *
1359 connection_get_prev_hop (struct MeshConnection *c)
1360 {
1361   GNUNET_PEER_Id id;
1362
1363   if (0 == c->own_pos || c->path->length < 2)
1364     id = c->path->peers[0];
1365   else
1366     id = c->path->peers[c->own_pos - 1];
1367
1368   return peer_get_short (id);
1369 }
1370
1371
1372 /**
1373  * Get the next hop in a connection
1374  *
1375  * @param c Connection.
1376  *
1377  * @return Next peer in the connection. 
1378  */
1379 static struct MeshPeer *
1380 connection_get_next_hop (struct MeshConnection *c)
1381 {
1382   GNUNET_PEER_Id id;
1383
1384   if ((c->path->length - 1) == c->own_pos || c->path->length < 2)
1385     id = c->path->peers[c->path->length - 1];
1386   else
1387     id = c->path->peers[c->own_pos + 1];
1388
1389   return peer_get_short (id);
1390 }
1391
1392
1393 /**
1394  * Get the hop in a connection.
1395  *
1396  * @param c Connection.
1397  * @param fwd Next hop?
1398  *
1399  * @return Next peer in the connection. 
1400  */
1401 static struct MeshPeer *
1402 connection_get_hop (struct MeshConnection *c, int fwd)
1403 {
1404   if (fwd)
1405     return connection_get_next_hop (c);
1406   return connection_get_prev_hop (c);
1407 }
1408
1409 /**
1410  * Check if client has registered with the service and has not disconnected
1411  *
1412  * @param client the client to check
1413  *
1414  * @return non-NULL if client exists in the global DLL
1415  */
1416 static struct MeshClient *
1417 client_get (struct GNUNET_SERVER_Client *client)
1418 {
1419   return GNUNET_SERVER_client_get_user_context (client, struct MeshClient);
1420 }
1421
1422
1423 /**
1424  * Deletes a tunnel from a client (either owner or destination).
1425  *
1426  * @param c Client whose tunnel to delete.
1427  * @param ch Channel which should be deleted.
1428  */
1429 static void
1430 client_delete_channel (struct MeshClient *c, struct MeshChannel *ch)
1431 {
1432   int res;
1433
1434   if (c == ch->root)
1435   {
1436     res = GNUNET_CONTAINER_multihashmap32_remove (c->own_channels,
1437                                                   ch->lid_root, ch);
1438     if (GNUNET_YES != res)
1439       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "client_delete_channel owner KO\n");
1440   }
1441   if (c == ch->dest)
1442   {
1443     res = GNUNET_CONTAINER_multihashmap32_remove (c->incoming_channels,
1444                                                   ch->lid_dest, ch);
1445     if (GNUNET_YES != res)
1446       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "client_delete_tunnel client KO\n");
1447   }
1448 }
1449
1450
1451 /**
1452  * Notify the appropriate client that a new incoming channel was created.
1453  *
1454  * @param ch Channel that was created.
1455  */
1456 static void
1457 send_local_channel_create (struct MeshChannel *ch)
1458 {
1459   struct GNUNET_MESH_ChannelMessage msg;
1460   struct MeshTunnel2 *t = ch->t;
1461
1462   if (NULL == ch->dest)
1463     return;
1464   msg.header.size = htons (sizeof (msg));
1465   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_CREATE);
1466   msg.channel_id = htonl (ch->lid_dest);
1467   msg.port = htonl (ch->port);
1468   msg.opt = 0;
1469   msg.opt |= GNUNET_YES == ch->reliable ? GNUNET_MESH_OPTION_RELIABLE : 0;
1470   msg.opt |= GNUNET_YES == ch->nobuffer ? GNUNET_MESH_OPTION_NOBUFFER : 0;
1471   msg.opt = htonl (msg.opt);
1472   GNUNET_PEER_resolve (t->peer->id, &msg.peer);
1473   GNUNET_SERVER_notification_context_unicast (nc, ch->dest->handle,
1474                                               &msg.header, GNUNET_NO);
1475 }
1476
1477
1478 /**
1479  * Notify a client that the incoming tunnel is no longer valid.
1480  *
1481  * @param ch Channel that is destroyed.
1482  * @param fwd Forward notification (owner->dest)?
1483  */
1484 static void
1485 send_local_channel_destroy (struct MeshChannel *ch, int fwd)
1486 {
1487   struct GNUNET_MESH_ChannelMessage msg;
1488   struct MeshClient *c;
1489
1490   c = fwd ? ch->dest : ch->root;
1491   if (NULL == c)
1492   {
1493     GNUNET_break (0);
1494     return;
1495   }
1496   msg.header.size = htons (sizeof (msg));
1497   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_DESTROY);
1498   msg.channel_id = htonl (fwd ? ch->lid_dest : ch->lid_root);
1499   msg.port = htonl (0);
1500   memset (&msg.peer, 0, sizeof (msg.peer));
1501   msg.opt = htonl (0);
1502   GNUNET_SERVER_notification_context_unicast (nc, c->handle,
1503                                               &msg.header, GNUNET_NO);
1504 }
1505
1506
1507 /**
1508  * Build a local ACK message and send it to a local client, if needed.
1509  *
1510  * If the client was already allowed to send data, do nothing.
1511  *
1512  * @param ch Channel on which to send the ACK.
1513  * @param c Client to whom send the ACK.
1514  * @param fwd Set to GNUNET_YES for FWD ACK (dest->root)
1515  */
1516 static void
1517 send_local_ack (struct MeshChannel *ch, int fwd)
1518 {
1519   struct GNUNET_MESH_LocalAck msg;
1520   struct MeshChannelReliability *rel;
1521   struct MeshClient *c;
1522
1523   c   = fwd ? ch->root     : ch->dest;
1524   rel = fwd ? ch->root_rel : ch->dest_rel;
1525
1526   if (GNUNET_YES == rel->client_ready)
1527     return; /* don't send double ACKs to client */
1528
1529   rel->client_ready = GNUNET_YES;
1530
1531   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1532               "send local %s ack on %s:%X towards %p\n",
1533               fwd ? "FWD" : "BCK", peer2s (ch->t->peer), ch->gid, c);
1534
1535   if (NULL == c
1536       || ( fwd && (0 == ch->lid_root || c != ch->root))
1537       || (!fwd && (0 == ch->lid_dest || c != ch->dest)) )
1538   {
1539     GNUNET_break (0);
1540     return;
1541   }
1542   msg.header.size = htons (sizeof (msg));
1543   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK);
1544   msg.channel_id = htonl (fwd ? ch->lid_root : ch->lid_dest);
1545   GNUNET_SERVER_notification_context_unicast (nc,
1546                                               c->handle,
1547                                               &msg.header,
1548                                               GNUNET_NO);
1549
1550 }
1551
1552
1553 /**
1554  * Count established (ready) connections of a tunnel.
1555  *
1556  * @param t Tunnel on which to send the message.
1557  *
1558  * @return Number of connections.
1559  */
1560 static unsigned int
1561 tunnel_count_connections (struct MeshTunnel2 *t)
1562 {
1563   struct MeshConnection *c;
1564   unsigned int i;
1565
1566   for (c = t->connection_head, i = 0; NULL != c; c = c->next, i++);
1567
1568   return i;
1569 }
1570
1571
1572 /**
1573  * Pick a connection on which send the next data message.
1574  *
1575  * @param t Tunnel on which to send the message.
1576  * @param fwd Is this a fwd message?
1577  *
1578  * @return The connection on which to send the next message.
1579  */
1580 static struct MeshConnection *
1581 tunnel_get_connection (struct MeshTunnel2 *t, int fwd)
1582 {
1583   struct MeshConnection *c;
1584   struct MeshConnection *best;
1585   struct MeshFlowControl *fc;
1586   unsigned int lowest_q;
1587
1588   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "tunnel_get_connection %s\n",
1589               peer2s (t->peer));
1590   best = NULL;
1591   lowest_q = UINT_MAX;
1592   for (c = t->connection_head; NULL != c; c = c->next)
1593   {
1594     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  connection %s: %u\n",
1595                 GNUNET_h2s (&c->id), c->state);
1596     if (MESH_CONNECTION_READY == c->state)
1597     {
1598       fc = fwd ? &c->fwd_fc : &c->bck_fc;
1599       if (NULL == fc)
1600       {
1601         GNUNET_break (0);
1602         continue;
1603       }
1604       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "    q_n %u, \n", fc->queue_n);
1605       if (fc->queue_n < lowest_q)
1606       {
1607         best = c;
1608         lowest_q = fc->queue_n;
1609       }
1610     }
1611   }
1612   return best;
1613 }
1614
1615
1616 /**
1617  * Is this peer the first one on the connection?
1618  *
1619  * @param c Connection.
1620  * @param fwd Is this about fwd traffic?
1621  *
1622  * @return GNUNET_YES if origin, GNUNET_NO if relay/terminal.
1623  */
1624 static int
1625 connection_is_origin (struct MeshConnection *c, int fwd)
1626 {
1627   if (!fwd && c->own_pos == c->path->length - 1)
1628     return GNUNET_YES;
1629   if (fwd && c->own_pos == 0)
1630     return GNUNET_YES;
1631   return GNUNET_NO;
1632 }
1633
1634
1635 /**
1636  * Is this peer the last one on the connection?
1637  *
1638  * @param c Connection.
1639  * @param fwd Is this about fwd traffic?
1640  *            Note that the ROOT is the terminal for BCK traffic!
1641  *
1642  * @return GNUNET_YES if terminal, GNUNET_NO if relay/origin.
1643  */
1644 static int
1645 connection_is_terminal (struct MeshConnection *c, int fwd)
1646 {
1647   if (fwd && c->own_pos == c->path->length - 1)
1648     return GNUNET_YES;
1649   if (!fwd && c->own_pos == 0)
1650     return GNUNET_YES;
1651   return GNUNET_NO;
1652 }
1653
1654
1655 /**
1656  * Is the recipient client for this channel on this peer?
1657  *
1658  * @param ch Channel.
1659  * @param fwd Is this for fwd traffic?
1660  *
1661  * @return GNUNET_YES in case it is.
1662  */
1663 static int
1664 channel_is_terminal (struct MeshChannel *ch, int fwd)
1665 {
1666   if (NULL == ch->t || NULL == ch->t->connection_head)
1667   {
1668     GNUNET_break (0);
1669     return GNUNET_NO;
1670   }
1671   return connection_is_terminal (ch->t->connection_head, fwd);
1672 }
1673
1674
1675 /**
1676  * Get free buffer space towards the client on a specific channel.
1677  *
1678  * @param ch Channel.
1679  * @param fwd Is query about FWD traffic?
1680  *
1681  * @return Free buffer space [0 - 64]
1682  */
1683 static unsigned int
1684 channel_get_buffer (struct MeshChannel *ch, int fwd)
1685 {
1686   struct MeshChannelReliability *rel;
1687   
1688   rel = fwd ? ch->dest_rel : ch->root_rel;
1689
1690   /* If rel is NULL it means that the end is not yet created,
1691    * most probably is a loopback channel at the point of sending
1692    * the ChannelCreate to itself.
1693    */
1694   if (NULL == rel)
1695     return 64;
1696
1697   return (64 - rel->n_recv);
1698 }
1699
1700
1701 /**
1702  * Get free buffer space in a connection.
1703  *
1704  * @param c Connection.
1705  * @param fwd Is query about FWD traffic?
1706  *
1707  * @return Free buffer space [0 - max_msgs_queue/max_connections]
1708  */
1709 static unsigned int
1710 connection_get_buffer (struct MeshConnection *c, int fwd)
1711 {
1712   struct MeshFlowControl *fc;
1713   
1714   fc = fwd ? &c->fwd_fc : &c->bck_fc;
1715   
1716   return (fc->queue_max - fc->queue_n);
1717 }
1718
1719
1720 /**
1721  * Get the total buffer space for a tunnel.
1722  */
1723 static unsigned int
1724 tunnel_get_buffer (struct MeshTunnel2 *t, int fwd)
1725 {
1726   struct MeshConnection *c;
1727   struct MeshFlowControl *fc;
1728   unsigned int buffer;
1729
1730   c = t->connection_head;
1731   buffer = 0;
1732
1733   if (NULL == c)
1734   {
1735     GNUNET_break (0);
1736     return 0;
1737   }
1738
1739   /* If terminal, return biggest channel buffer */
1740   if (connection_is_terminal (c, fwd))
1741   {
1742     struct MeshChannel *ch;
1743     unsigned int ch_buf;
1744
1745     if (NULL == t->channel_head)
1746       return 64;
1747
1748     for (ch = t->channel_head; NULL != ch; ch = ch->next)
1749     {
1750       ch_buf = channel_get_buffer (ch, fwd);
1751       if (ch_buf > buffer)
1752         buffer = ch_buf;
1753     }
1754     return buffer;
1755   }
1756
1757   /* If not terminal, return sum of connection buffers */
1758   while (NULL != c)
1759   {
1760     if (c->state != MESH_CONNECTION_READY)
1761     {
1762       c = c->next;
1763       continue;
1764     }
1765
1766     fc = fwd ? &c->fwd_fc : &c->bck_fc;
1767     buffer += fc->last_ack_recv - fc->last_pid_sent;
1768     c = c->next;
1769   }
1770
1771   return buffer;
1772 }
1773
1774
1775 /**
1776  * FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME 
1777  * Encrypt data with the tunnel key.
1778  *
1779  * @param t Tunnel whose key to use.
1780  * @param dst Destination for the encrypted data.
1781  * @param src Source of the plaintext.
1782  * @param size Size of the plaintext.
1783  * @param iv Initialization Vector to use.
1784  * @param fwd Is this a fwd message?
1785  */
1786 static void
1787 tunnel_encrypt (struct MeshTunnel2 *t,
1788                 void *dst, const void *src,
1789                 size_t size, uint64_t iv, int fwd)
1790 {
1791   memcpy (dst, src, size);
1792 }
1793
1794
1795 /**
1796  * FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME 
1797  * Decrypt data with the tunnel key.
1798  *
1799  * @param t Tunnel whose key to use.
1800  * @param dst Destination for the plaintext.
1801  * @param src Source of the encrypted data.
1802  * @param size Size of the encrypted data.
1803  * @param iv Initialization Vector to use.
1804  * @param fwd Is this a fwd message?
1805  */
1806 static void
1807 tunnel_decrypt (struct MeshTunnel2 *t,
1808                 void *dst, const void *src,
1809                 size_t size, uint64_t iv, int fwd)
1810 {
1811   memcpy (dst, src, size);
1812 }
1813
1814
1815 /**
1816  * Sends an already built message on a connection, properly registering
1817  * all used resources.
1818  *
1819  * @param message Message to send. Function makes a copy of it.
1820  *                If message is not hop-by-hop, decrements TTL of copy.
1821  * @param c Connection on which this message is transmitted.
1822  * @param ch Channel on which this message is transmitted, or NULL.
1823  * @param fwd Is this a fwd message?
1824  */
1825 static void
1826 send_prebuilt_message_connection (const struct GNUNET_MessageHeader *message,
1827                                   struct MeshConnection *c,
1828                                   struct MeshChannel *ch,
1829                                   int fwd)
1830 {
1831   void *data;
1832   size_t size;
1833   uint16_t type;
1834
1835   size = ntohs (message->size);
1836   data = GNUNET_malloc (size);
1837   memcpy (data, message, size);
1838   type = ntohs (message->type);
1839   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Send %s (%u) on connection %s\n",
1840               GNUNET_MESH_DEBUG_M2S (type), size, GNUNET_h2s (&c->id));
1841
1842   switch (type)
1843   {
1844     struct GNUNET_MESH_Encrypted *emsg;
1845     struct GNUNET_MESH_ACK       *amsg;
1846     struct GNUNET_MESH_Poll      *pmsg;
1847     struct GNUNET_MESH_ConnectionDestroy *dmsg;
1848     struct GNUNET_MESH_ConnectionBroken  *bmsg;
1849     uint32_t ttl;
1850
1851     case GNUNET_MESSAGE_TYPE_MESH_FWD:
1852     case GNUNET_MESSAGE_TYPE_MESH_BCK:
1853       emsg = (struct GNUNET_MESH_Encrypted *) data;
1854       ttl = ntohl (emsg->ttl);
1855       if (0 == ttl)
1856       {
1857         GNUNET_break_op (0);
1858         return;
1859       }
1860       emsg->cid = c->id;
1861       emsg->ttl = htonl (ttl - 1);
1862       emsg->pid = htonl (fwd ? c->fwd_fc.next_pid++ : c->bck_fc.next_pid++);
1863       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " pid %u\n", ntohl (emsg->pid));
1864       break;
1865
1866     case GNUNET_MESSAGE_TYPE_MESH_ACK:
1867       amsg = (struct GNUNET_MESH_ACK *) data;
1868       amsg->cid = c->id;
1869       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " ack %u\n", ntohl (amsg->ack));
1870       break;
1871
1872     case GNUNET_MESSAGE_TYPE_MESH_POLL:
1873       pmsg = (struct GNUNET_MESH_Poll *) data;
1874       pmsg->cid = c->id;
1875       pmsg->pid = htonl (fwd ? c->fwd_fc.last_pid_sent : c->bck_fc.last_pid_sent);
1876       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " poll %u\n", ntohl (pmsg->pid));
1877       break;
1878
1879     case GNUNET_MESSAGE_TYPE_MESH_TUNNEL_DESTROY:
1880       dmsg = (struct GNUNET_MESH_ConnectionDestroy *) data;
1881       dmsg->cid = c->id;
1882       dmsg->reserved = 0;
1883       break;
1884
1885     case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_BROKEN:
1886       bmsg = (struct GNUNET_MESH_ConnectionBroken *) data;
1887       bmsg->cid = c->id;
1888       bmsg->reserved = 0;
1889       break;
1890
1891     case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_CREATE:
1892     case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_ACK:
1893       break;
1894
1895     default:
1896       GNUNET_break (0);
1897   }
1898
1899   queue_add (data,
1900              type,
1901              size,
1902              c,
1903              ch,
1904              fwd);
1905 }
1906
1907
1908 /**
1909  * Sends an already built message on a tunnel, choosing the best connection.
1910  *
1911  * @param message Message to send. Function modifies it.
1912  * @param t Tunnel on which this message is transmitted.
1913  * @param ch Channel on which this message is transmitted.
1914  * @param fwd Is this a fwd message?
1915  */
1916 static void
1917 send_prebuilt_message_tunnel (struct GNUNET_MESH_Encrypted *msg,
1918                               struct MeshTunnel2 *t,
1919                               struct MeshChannel *ch,
1920                               int fwd)
1921 {
1922   struct MeshConnection *c;
1923   uint16_t type;
1924
1925   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Send on Tunnel %s\n",
1926               peer2s (t->peer));
1927   c = tunnel_get_connection (t, fwd);
1928   if (NULL == c)
1929   {
1930     GNUNET_break (GNUNET_YES == t->destroy);
1931     return;
1932   }
1933   type = ntohs (msg->header.type);
1934   switch (type)
1935   {
1936     case GNUNET_MESSAGE_TYPE_MESH_FWD:
1937     case GNUNET_MESSAGE_TYPE_MESH_BCK:
1938     case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_CREATE:
1939     case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_DESTROY:
1940       msg->cid = c->id;
1941       msg->ttl = htonl (default_ttl);
1942       break;
1943     default:
1944       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "unkown type %s\n",
1945                   GNUNET_MESH_DEBUG_M2S (type));
1946       GNUNET_break (0);
1947   }
1948   msg->reserved = 0;
1949
1950   send_prebuilt_message_connection (&msg->header, c, ch, fwd);
1951 }
1952
1953
1954 /**
1955  * Sends an already built message on a channel, properly registering
1956  * all used resources and encrypting the message with the tunnel's key.
1957  *
1958  * @param message Message to send. Function makes a copy of it.
1959  * @param ch Channel on which this message is transmitted.
1960  * @param fwd Is this a fwd message?
1961  */
1962 static void
1963 send_prebuilt_message_channel (const struct GNUNET_MessageHeader *message,
1964                                struct MeshChannel *ch,
1965                                int fwd)
1966 {
1967   struct GNUNET_MESH_Encrypted *msg;
1968   size_t size = ntohs (message->size);
1969   char *cbuf[sizeof (struct GNUNET_MESH_Encrypted) + size];
1970   uint16_t type;
1971   uint64_t iv;
1972
1973   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Send on Channel %s:%X %s\n",
1974               peer2s (ch->t->peer), ch->gid, fwd ? "FWD" : "BCK");
1975   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  %s\n",
1976               GNUNET_MESH_DEBUG_M2S (ntohs (message->type)));
1977
1978   if (channel_is_terminal (ch, fwd))
1979   {
1980     handle_decrypted (ch->t, message, fwd);
1981     return;
1982   }
1983   
1984   type = fwd ? GNUNET_MESSAGE_TYPE_MESH_FWD : GNUNET_MESSAGE_TYPE_MESH_BCK;
1985   iv = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_NONCE, UINT64_MAX);
1986
1987   msg = (struct GNUNET_MESH_Encrypted *) cbuf;
1988   msg->header.type = htons (type);
1989   msg->header.size = htons (sizeof (struct GNUNET_MESH_Encrypted) + size);
1990   msg->iv = GNUNET_htonll (iv);
1991   tunnel_encrypt (ch->t, &msg[1], message, size, iv, fwd);
1992   send_prebuilt_message_tunnel (msg, ch->t, ch, fwd);
1993 }
1994
1995
1996 /**
1997  * Sends a CREATE CONNECTION message for a path to a peer.
1998  * Changes the connection and tunnel states if necessary.
1999  *
2000  * @param connection Connection to create.
2001  */
2002 static void
2003 send_connection_create (struct MeshConnection *connection)
2004 {
2005   struct MeshTunnel2 *t;
2006
2007   t = connection->t;
2008   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Send connection create\n");
2009   queue_add (NULL,
2010              GNUNET_MESSAGE_TYPE_MESH_CONNECTION_CREATE,
2011              sizeof (struct GNUNET_MESH_ConnectionCreate) +
2012                 (connection->path->length *
2013                  sizeof (struct GNUNET_PeerIdentity)),
2014              connection,
2015              NULL,
2016              GNUNET_YES);
2017   if (NULL != t &&
2018       (MESH_TUNNEL_SEARCHING == t->state || MESH_TUNNEL_NEW == t->state))
2019     tunnel_change_state (t, MESH_TUNNEL_WAITING);
2020   if (MESH_CONNECTION_NEW == connection->state)
2021     connection_change_state (connection, MESH_CONNECTION_SENT);
2022 }
2023
2024
2025 /**
2026  * Sends a CONNECTION ACK message in reponse to a received CONNECTION_CREATE
2027  * directed to us.
2028  *
2029  * @param connection Connection to confirm.
2030  * @param fwd Is this a fwd ACK? (First is bck (SYNACK), second is fwd (ACK))
2031  */
2032 static void
2033 send_connection_ack (struct MeshConnection *connection, int fwd) 
2034 {
2035   struct MeshTunnel2 *t;
2036
2037   t = connection->t;
2038   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Send connection ack\n");
2039   queue_add (NULL,
2040              GNUNET_MESSAGE_TYPE_MESH_CONNECTION_ACK,
2041              sizeof (struct GNUNET_MESH_ConnectionACK),
2042              connection,
2043              NULL,
2044              fwd);
2045   if (MESH_TUNNEL_NEW == t->state)
2046     tunnel_change_state (t, MESH_TUNNEL_WAITING);
2047   if (MESH_CONNECTION_READY != connection->state)
2048     connection_change_state (connection, MESH_CONNECTION_SENT);
2049 }
2050
2051
2052 /**
2053   * Core callback to write a pre-constructed data packet to core buffer
2054   *
2055   * @param cls Closure (MeshTransmissionDescriptor with data in "data" member).
2056   * @param size Number of bytes available in buf.
2057   * @param buf Where the to write the message.
2058   *
2059   * @return number of bytes written to buf
2060   */
2061 static size_t
2062 send_core_data_raw (void *cls, size_t size, void *buf)
2063 {
2064   struct GNUNET_MessageHeader *msg = cls;
2065   size_t total_size;
2066
2067   GNUNET_assert (NULL != msg);
2068   total_size = ntohs (msg->size);
2069
2070   if (total_size > size)
2071   {
2072     GNUNET_break (0);
2073     return 0;
2074   }
2075   memcpy (buf, msg, total_size);
2076   GNUNET_free (cls);
2077   return total_size;
2078 }
2079
2080
2081 /**
2082  * Function to send a create connection message to a peer.
2083  *
2084  * @param c Connection to create.
2085  * @param size number of bytes available in buf
2086  * @param buf where the callee should write the message
2087  * @return number of bytes written to buf
2088  */
2089 static size_t
2090 send_core_connection_create (struct MeshConnection *c, size_t size, void *buf)
2091 {
2092   struct GNUNET_MESH_ConnectionCreate *msg;
2093   struct GNUNET_PeerIdentity *peer_ptr;
2094   struct MeshPeerPath *p = c->path;
2095   size_t size_needed;
2096   int i;
2097
2098   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending CONNECTION CREATE...\n");
2099   size_needed =
2100       sizeof (struct GNUNET_MESH_ConnectionCreate) +
2101       p->length * sizeof (struct GNUNET_PeerIdentity);
2102
2103   if (size < size_needed || NULL == buf)
2104   {
2105     GNUNET_break (0);
2106     return 0;
2107   }
2108   msg = (struct GNUNET_MESH_ConnectionCreate *) buf;
2109   msg->header.size = htons (size_needed);
2110   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_CONNECTION_CREATE);
2111   msg->cid = c->id;
2112
2113   peer_ptr = (struct GNUNET_PeerIdentity *) &msg[1];
2114   for (i = 0; i < p->length; i++)
2115   {
2116     GNUNET_PEER_resolve (p->peers[i], peer_ptr++);
2117   }
2118
2119   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2120               "CONNECTION CREATE (%u bytes long) sent!\n", size_needed);
2121   return size_needed;
2122 }
2123
2124
2125 /**
2126  * Creates a path ack message in buf and frees all unused resources.
2127  *
2128  * @param c Connection to send an ACK on.
2129  * @param size number of bytes available in buf
2130  * @param buf where the callee should write the message
2131  *
2132  * @return number of bytes written to buf
2133  */
2134 static size_t
2135 send_core_connection_ack (struct MeshConnection *c, size_t size, void *buf)
2136 {
2137   struct GNUNET_MESH_ConnectionACK *msg = buf;
2138   struct MeshTunnel2 *t = c->t;
2139
2140   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending CONNECTION ACK...\n");
2141   GNUNET_assert (NULL != t);
2142   if (sizeof (struct GNUNET_MESH_ConnectionACK) > size)
2143   {
2144     GNUNET_break (0);
2145     return 0;
2146   }
2147   msg->header.size = htons (sizeof (struct GNUNET_MESH_ConnectionACK));
2148   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_CONNECTION_ACK);
2149   msg->cid = c->id;
2150   msg->reserved = 0;
2151
2152   /* TODO add signature */
2153
2154   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "CONNECTION ACK sent!\n");
2155   return sizeof (struct GNUNET_MESH_ConnectionACK);
2156 }
2157
2158
2159 /**
2160  * Destroy the peer_info and free any allocated resources linked to it
2161  *
2162  * @param peer The peer_info to destroy.
2163  *
2164  * @return GNUNET_OK on success
2165  */
2166 static int
2167 peer_destroy (struct MeshPeer *peer)
2168 {
2169   struct GNUNET_PeerIdentity id;
2170   struct MeshPeerPath *p;
2171   struct MeshPeerPath *nextp;
2172
2173   GNUNET_PEER_resolve (peer->id, &id);
2174   GNUNET_PEER_change_rc (peer->id, -1);
2175
2176   if (GNUNET_YES !=
2177       GNUNET_CONTAINER_multihashmap_remove (peers, &id.hashPubKey, peer))
2178   {
2179     GNUNET_break (0);
2180     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2181                 "removing peer %s, not in hashmap\n", GNUNET_i2s (&id));
2182   }
2183   if (NULL != peer->dhtget)
2184   {
2185     GNUNET_DHT_get_stop (peer->dhtget);
2186   }
2187   p = peer->path_head;
2188   while (NULL != p)
2189   {
2190     nextp = p->next;
2191     GNUNET_CONTAINER_DLL_remove (peer->path_head, peer->path_tail, p);
2192     path_destroy (p);
2193     p = nextp;
2194   }
2195   tunnel_destroy_empty (peer->tunnel);
2196   GNUNET_free (peer);
2197   return GNUNET_OK;
2198 }
2199
2200
2201 /**
2202  * Returns if peer is used (has a tunnel, is neighbor).
2203  *
2204  * @peer Peer to check.
2205  *
2206  * @return GNUNET_YES if peer is in use.
2207  */
2208 static int
2209 peer_is_used (struct MeshPeer *peer)
2210 {
2211   struct MeshPeerPath *p;
2212
2213   if (NULL != peer->tunnel)
2214     return GNUNET_YES;
2215
2216   for (p = peer->path_head; NULL != p; p = p->next)
2217   {
2218     if (p->length < 3)
2219       return GNUNET_YES;
2220   }
2221   return GNUNET_NO;
2222 }
2223
2224 /**
2225  * Iterator over all the peers to get the oldest timestamp.
2226  *
2227  * @param cls Closure (unsued).
2228  * @param key ID of the peer.
2229  * @param value Peer_Info of the peer.
2230  */
2231 static int
2232 peer_get_oldest (void *cls,
2233                  const struct GNUNET_HashCode *key,
2234                  void *value)
2235 {
2236   struct MeshPeer *p = value;
2237   struct GNUNET_TIME_Absolute *abs = cls;
2238
2239   /* Don't count active peers */
2240   if (GNUNET_YES == peer_is_used (p))
2241     return GNUNET_YES;
2242
2243   if (abs->abs_value_us < p->last_contact.abs_value_us)
2244     abs->abs_value_us = p->last_contact.abs_value_us;
2245
2246   return GNUNET_YES;
2247 }
2248
2249
2250 /**
2251  * Iterator over all the peers to remove the oldest entry.
2252  *
2253  * @param cls Closure (unsued).
2254  * @param key ID of the peer.
2255  * @param value Peer_Info of the peer.
2256  */
2257 static int
2258 peer_timeout (void *cls,
2259               const struct GNUNET_HashCode *key,
2260               void *value)
2261 {
2262   struct MeshPeer *p = value;
2263   struct GNUNET_TIME_Absolute *abs = cls;
2264
2265   if (p->last_contact.abs_value_us == abs->abs_value_us &&
2266       GNUNET_NO == peer_is_used (p))
2267   {
2268     peer_destroy (p);
2269     return GNUNET_NO;
2270   }
2271   return GNUNET_YES;
2272 }
2273
2274
2275 /**
2276  * Delete oldest unused peer.
2277  */
2278 static void
2279 peer_delete_oldest (void)
2280 {
2281   struct GNUNET_TIME_Absolute abs;
2282
2283   abs = GNUNET_TIME_UNIT_FOREVER_ABS;
2284
2285   GNUNET_CONTAINER_multihashmap_iterate (peers,
2286                                          &peer_get_oldest,
2287                                          &abs);
2288   GNUNET_CONTAINER_multihashmap_iterate (peers,
2289                                          &peer_timeout,
2290                                          &abs);
2291 }
2292
2293
2294 /**
2295  * Retrieve the MeshPeer stucture associated with the peer, create one
2296  * and insert it in the appropriate structures if the peer is not known yet.
2297  *
2298  * @param peer Full identity of the peer.
2299  *
2300  * @return Existing or newly created peer info.
2301  */
2302 static struct MeshPeer *
2303 peer_get (const struct GNUNET_PeerIdentity *peer_id)
2304 {
2305   struct MeshPeer *peer;
2306
2307   peer = GNUNET_CONTAINER_multihashmap_get (peers, &peer_id->hashPubKey);
2308   if (NULL == peer)
2309   {
2310     peer = GNUNET_new (struct MeshPeer);
2311     if (GNUNET_CONTAINER_multihashmap_size (peers) > max_peers)
2312     {
2313       peer_delete_oldest ();
2314     }
2315     GNUNET_CONTAINER_multihashmap_put (peers, &peer_id->hashPubKey, peer,
2316                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
2317     peer->id = GNUNET_PEER_intern (peer_id);
2318   }
2319   peer->last_contact = GNUNET_TIME_absolute_get();
2320
2321   return peer;
2322 }
2323
2324
2325 /**
2326  * Retrieve the MeshPeer stucture associated with the peer, create one
2327  * and insert it in the appropriate structures if the peer is not known yet.
2328  *
2329  * @param peer Short identity of the peer.
2330  *
2331  * @return Existing or newly created peer info.
2332  */
2333 static struct MeshPeer *
2334 peer_get_short (const GNUNET_PEER_Id peer)
2335 {
2336   return peer_get (GNUNET_PEER_resolve2 (peer));
2337 }
2338
2339
2340 /**
2341  * Get a cost of a path for a peer considering existing tunnel connections.
2342  *
2343  * @param peer Peer towards which the path is considered.
2344  * @param path Candidate path.
2345  *
2346  * @return Cost of the path (path length + number of overlapping nodes)
2347  */
2348 static unsigned int
2349 peer_get_path_cost (const struct MeshPeer *peer,
2350                     const struct MeshPeerPath *path)
2351 {
2352   struct MeshConnection *c;
2353   unsigned int overlap;
2354   unsigned int i;
2355   unsigned int j;
2356
2357   if (NULL == path)
2358     return 0;
2359
2360   overlap = 0;
2361   GNUNET_assert (NULL != peer->tunnel);
2362
2363   for (i = 0; i < path->length; i++)
2364   {
2365     for (c = peer->tunnel->connection_head; NULL != c; c = c->next)
2366     {
2367       for (j = 0; j < c->path->length; j++)
2368       {
2369         if (path->peers[i] == c->path->peers[j])
2370         {
2371           overlap++;
2372           break;
2373         }
2374       }
2375     }
2376   }
2377   return (path->length + overlap) * (path->score * -1);
2378 }
2379
2380
2381 /**
2382  * Choose the best path towards a peer considering the tunnel properties.
2383  *
2384  * @param peer The destination peer.
2385  *
2386  * @return Best current known path towards the peer, if any.
2387  */
2388 static struct MeshPeerPath *
2389 peer_get_best_path (const struct MeshPeer *peer)
2390 {
2391   struct MeshPeerPath *best_p;
2392   struct MeshPeerPath *p;
2393   struct MeshConnection *c;
2394   unsigned int best_cost;
2395   unsigned int cost;
2396
2397   best_cost = UINT_MAX;
2398   best_p = NULL;
2399   for (p = peer->path_head; NULL != p; p = p->next)
2400   {
2401     for (c = peer->tunnel->connection_head; NULL != c; c = c->next)
2402       if (c->path == p)
2403         break;
2404     if (NULL != c)
2405       continue; /* If path is in use in a connection, skip it. */
2406
2407     if ((cost = peer_get_path_cost (peer, p)) < best_cost)
2408     {
2409       best_cost = cost;
2410       best_p = p;
2411     }
2412   }
2413   return best_p;
2414 }
2415
2416 static int
2417 queue_is_sendable (struct MeshPeerQueue *q)
2418 {
2419   struct MeshFlowControl *fc;
2420
2421   /* Is PID-independent? */
2422   switch (q->type)
2423   {
2424     case GNUNET_MESSAGE_TYPE_MESH_ACK:
2425     case GNUNET_MESSAGE_TYPE_MESH_POLL:
2426       return GNUNET_YES;
2427   }
2428
2429   /* Is PID allowed? */
2430   fc = q->fwd ? &q->c->fwd_fc : &q->c->bck_fc;
2431   if (GMC_is_pid_bigger (fc->last_ack_recv, fc->last_pid_sent))
2432     return GNUNET_YES;
2433
2434   return GNUNET_NO;
2435 }
2436
2437
2438 /**
2439  * Get first sendable message.
2440  *
2441  * @param peer The destination peer.
2442  *
2443  * @return Best current known path towards the peer, if any.
2444  */
2445 static struct MeshPeerQueue *
2446 peer_get_first_message (const struct MeshPeer *peer)
2447 {
2448   struct MeshPeerQueue *q;
2449
2450   for (q = peer->queue_head; NULL != q; q = q->next)
2451   {
2452     if (queue_is_sendable (q))
2453       return q;
2454   }
2455
2456   return NULL;
2457 }
2458
2459
2460 /**
2461  * Try to establish a new connection to this peer in the given tunnel.
2462  * If the peer doesn't have any path to it yet, try to get one.
2463  * If the peer already has some path, send a CREATE CONNECTION towards it.
2464  *
2465  * @param peer PeerInfo of the peer.
2466  */
2467 static void
2468 peer_connect (struct MeshPeer *peer)
2469 {
2470   struct MeshTunnel2 *t;
2471   struct MeshPeerPath *p;
2472   struct MeshConnection *c;
2473   int rerun_dhtget;
2474
2475   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2476               "peer_connect towards %s\n",
2477               peer2s (peer));
2478   t = peer->tunnel;
2479   c = NULL;
2480   rerun_dhtget = GNUNET_NO;
2481
2482   if (NULL != peer->path_head)
2483   {
2484     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "path exists\n");
2485     p = peer_get_best_path (peer);
2486     if (NULL != p)
2487     {
2488       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  %u hops\n", p->length);
2489       c = tunnel_use_path (t, p);
2490       if (NULL == c)
2491       {
2492         /* This case can happen when the path includes a first hop that is
2493          * not yet known to be connected.
2494          * 
2495          * This happens quite often during testing when running mesh
2496          * under valgrind: core connect notifications come very late and the
2497          * DHT result has already come and created a valid path.
2498          * In this case, the peer->connections hashmap will be NULL and
2499          * tunnel_use_path will not be able to create a connection from that
2500          * path.
2501          *
2502          * Re-running the DHT GET should give core time to callback.
2503          */
2504         GNUNET_break(0);
2505         rerun_dhtget = GNUNET_YES;
2506       }
2507       else
2508       {
2509         send_connection_create (c);
2510         return;
2511       }
2512     }
2513   }
2514
2515   if (NULL != peer->dhtget && GNUNET_YES == rerun_dhtget)
2516   {
2517     GNUNET_DHT_get_stop (peer->dhtget);
2518     peer->dhtget = NULL;
2519     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2520                 "  Stopping DHT GET for peer %s\n", peer2s (peer));
2521   }
2522
2523   if (NULL == peer->dhtget)
2524   {
2525     const struct GNUNET_PeerIdentity *id;
2526
2527     id = GNUNET_PEER_resolve2 (peer->id);
2528     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2529                 "  Starting DHT GET for peer %s\n", peer2s (peer));
2530     peer->dhtget = GNUNET_DHT_get_start (dht_handle,    /* handle */
2531                                          GNUNET_BLOCK_TYPE_MESH_PEER, /* type */
2532                                          &id->hashPubKey,     /* key to search */
2533                                          dht_replication_level, /* replication level */
2534                                          GNUNET_DHT_RO_RECORD_ROUTE |
2535                                          GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE,
2536                                          NULL,       /* xquery */
2537                                          0,     /* xquery bits */
2538                                          &dht_get_id_handler, peer);
2539     if (MESH_TUNNEL_NEW == t->state)
2540       tunnel_change_state (t, MESH_TUNNEL_SEARCHING);
2541   }
2542 }
2543
2544
2545 /**
2546  * Get the first transmittable message for a connection.
2547  *
2548  * @param c Connection.
2549  * @param fwd Is this FWD?
2550  *
2551  * @return First transmittable message.
2552  */
2553 static struct MeshPeerQueue *
2554 connection_get_first_message (struct MeshConnection *c, int fwd)
2555 {
2556   struct MeshPeerQueue *q;
2557   struct MeshPeer *p;
2558
2559   p = connection_get_hop (c, fwd);
2560
2561   for (q = p->queue_head; NULL != q; q = q->next)
2562   {
2563     if (q->c != c)
2564       continue;
2565     if (queue_is_sendable (q))
2566       return q;
2567   }
2568
2569   return NULL;
2570 }
2571
2572
2573 /**
2574  * @brief Re-initiate traffic on this connection if necessary.
2575  *
2576  * Check if there is traffic queued towards this peer
2577  * and the core transmit handle is NULL (traffic was stalled).
2578  * If so, call core tmt rdy.
2579  *
2580  * @param c Connection on which initiate traffic.
2581  * @param fwd Is this about fwd traffic?
2582  */
2583 static void
2584 connection_unlock_queue (struct MeshConnection *c, int fwd)
2585 {
2586   struct MeshPeer *peer;
2587   struct MeshPeerQueue *q;
2588   size_t size;
2589
2590   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2591               "connection_unlock_queue %s on %s\n",
2592               fwd ? "FWD" : "BCK", GNUNET_h2s (&c->id));
2593
2594   if (connection_is_origin (c, fwd))
2595   {
2596     struct MeshTunnel2 *t = c->t;
2597     struct MeshChannel *ch;
2598     struct MeshChannelReliability *rel;
2599
2600     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " is origin!\n");
2601     /* FIXME randomize channel selection, not always first channel */
2602     for (ch = t->channel_head; NULL != ch; ch = ch->next)
2603     {
2604       rel = fwd ? ch->root_rel : ch->dest_rel;
2605
2606       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  channel %X - %s\n",
2607                   ch->gid, rel->client_ready ? "ready " : "not ready");
2608       if (GNUNET_NO == rel->client_ready)
2609       {
2610         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "    sending local ack!\n");
2611         send_local_ack (ch, fwd);
2612         return; /* FIXME authorize all channels? */
2613       }
2614     }
2615     return;
2616   }
2617
2618   peer = connection_get_hop (c, fwd);
2619
2620   if (NULL != peer->core_transmit)
2621   {
2622     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  already unlocked!\n");
2623     return; /* Already unlocked */
2624   }
2625
2626   q = connection_get_first_message (c, fwd);
2627   if (NULL == q)
2628   {
2629     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  queue empty!\n");
2630     return; /* Nothing to transmit */
2631   }
2632
2633   size = q->size;
2634   peer->core_transmit =
2635       GNUNET_CORE_notify_transmit_ready (core_handle,
2636                                          GNUNET_NO,
2637                                          0,
2638                                          GNUNET_TIME_UNIT_FOREVER_REL,
2639                                          GNUNET_PEER_resolve2 (peer->id),
2640                                          size,
2641                                          &queue_send,
2642                                          peer);
2643 }
2644
2645
2646 /**
2647  * Cancel all transmissions that belong to a certain connection.
2648  *
2649  * @param c Connection which to cancel.
2650  * @param fwd Cancel fwd traffic?
2651  */
2652 static void
2653 connection_cancel_queues (struct MeshConnection *c, int fwd)
2654 {
2655   struct MeshPeerQueue *q;
2656   struct MeshPeerQueue *next;
2657   struct MeshFlowControl *fc;
2658   struct MeshPeer *peer;
2659
2660   if (NULL == c)
2661   {
2662     GNUNET_break (0);
2663     return;
2664   }
2665   fc = fwd ? &c->fwd_fc : &c->bck_fc;
2666   peer = connection_get_hop (c, fwd);
2667
2668   for (q = peer->queue_head; NULL != q; q = next)
2669   {
2670     next = q->next;
2671     if (q->c == c)
2672     {
2673       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2674                   "connection_cancel_queue %s\n",
2675                   GNUNET_MESH_DEBUG_M2S (q->type));
2676       queue_destroy (q, GNUNET_YES);
2677     }
2678   }
2679   if (NULL == peer->queue_head)
2680   {
2681     if (NULL != peer->core_transmit)
2682     {
2683       GNUNET_CORE_notify_transmit_ready_cancel (peer->core_transmit);
2684       peer->core_transmit = NULL;
2685     }
2686     if (GNUNET_SCHEDULER_NO_TASK != fc->poll_task)
2687     {
2688       GNUNET_SCHEDULER_cancel (fc->poll_task);
2689       fc->poll_task = GNUNET_SCHEDULER_NO_TASK;
2690     }
2691   }
2692 }
2693
2694
2695 /**
2696  * Add the path to the peer and update the path used to reach it in case this
2697  * is the shortest.
2698  *
2699  * @param peer_info Destination peer to add the path to.
2700  * @param path New path to add. Last peer must be the peer in arg 1.
2701  *             Path will be either used of freed if already known.
2702  * @param trusted Do we trust that this path is real?
2703  */
2704 void
2705 peer_add_path (struct MeshPeer *peer_info, struct MeshPeerPath *path,
2706                     int trusted)
2707 {
2708   struct MeshPeerPath *aux;
2709   unsigned int l;
2710   unsigned int l2;
2711
2712   if ((NULL == peer_info) || (NULL == path))
2713   {
2714     GNUNET_break (0);
2715     path_destroy (path);
2716     return;
2717   }
2718   if (path->peers[path->length - 1] != peer_info->id)
2719   {
2720     GNUNET_break (0);
2721     path_destroy (path);
2722     return;
2723   }
2724   if (2 >= path->length && GNUNET_NO == trusted)
2725   {
2726     /* Only allow CORE to tell us about direct paths */
2727     path_destroy (path);
2728     return;
2729   }
2730   for (l = 1; l < path->length; l++)
2731   {
2732     if (path->peers[l] == myid)
2733     {
2734       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shortening path by %u\n", l);
2735       for (l2 = 0; l2 < path->length - l; l2++)
2736       {
2737         path->peers[l2] = path->peers[l + l2];
2738       }
2739       path->length -= l;
2740       l = 1;
2741       path->peers =
2742           GNUNET_realloc (path->peers, path->length * sizeof (GNUNET_PEER_Id));
2743     }
2744   }
2745
2746   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "adding path [%u] to peer %s\n",
2747               path->length, peer2s (peer_info));
2748
2749   l = path_get_length (path);
2750   if (0 == l)
2751   {
2752     path_destroy (path);
2753     return;
2754   }
2755
2756   GNUNET_assert (peer_info->id == path->peers[path->length - 1]);
2757   for (aux = peer_info->path_head; aux != NULL; aux = aux->next)
2758   {
2759     l2 = path_get_length (aux);
2760     if (l2 > l)
2761     {
2762       GNUNET_CONTAINER_DLL_insert_before (peer_info->path_head,
2763                                           peer_info->path_tail, aux, path);
2764       return;
2765     }
2766     else
2767     {
2768       if (l2 == l && memcmp (path->peers, aux->peers, l) == 0)
2769       {
2770         path_destroy (path);
2771         return;
2772       }
2773     }
2774   }
2775   GNUNET_CONTAINER_DLL_insert_tail (peer_info->path_head, peer_info->path_tail,
2776                                     path);
2777   return;
2778 }
2779
2780
2781 /**
2782  * Add the path to the origin peer and update the path used to reach it in case
2783  * this is the shortest.
2784  * The path is given in peer_info -> destination, therefore we turn the path
2785  * upside down first.
2786  *
2787  * @param peer_info Peer to add the path to, being the origin of the path.
2788  * @param path New path to add after being inversed.
2789  *             Path will be either used or freed.
2790  * @param trusted Do we trust that this path is real?
2791  */
2792 static void
2793 peer_add_path_to_origin (struct MeshPeer *peer_info,
2794                          struct MeshPeerPath *path, int trusted)
2795 {
2796   if (NULL == path)
2797     return;
2798   path_invert (path);
2799   peer_add_path (peer_info, path, trusted);
2800 }
2801
2802
2803
2804 /**
2805  * Function called if a connection has been stalled for a while,
2806  * possibly due to a missed ACK. Poll the neighbor about its ACK status.
2807  *
2808  * @param cls Closure (poll ctx).
2809  * @param tc TaskContext.
2810  */
2811 static void
2812 connection_poll (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2813 {
2814   struct MeshFlowControl *fc = cls;
2815   struct GNUNET_MESH_Poll msg;
2816   struct MeshConnection *c;
2817
2818   fc->poll_task = GNUNET_SCHEDULER_NO_TASK;
2819   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
2820   {
2821     return;
2822   }
2823
2824   c = fc->c;
2825   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " *** Polling!\n");
2826   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " *** connection %s[%X]\n", 
2827               peer2s (c->t->peer), c->id);
2828   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " ***   %s\n", 
2829               fc == &c->fwd_fc ? "FWD" : "BCK");
2830
2831   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_POLL);
2832   msg.header.size = htons (sizeof (msg));
2833   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " *** pid (%u)!\n", fc->last_pid_sent);
2834   send_prebuilt_message_connection (&msg.header, c, NULL, fc == &c->fwd_fc);
2835   fc->poll_time = GNUNET_TIME_STD_BACKOFF (fc->poll_time);
2836   fc->poll_task = GNUNET_SCHEDULER_add_delayed (fc->poll_time,
2837                                                 &connection_poll, fc);
2838 }
2839
2840
2841 /**
2842  * Build a PeerPath from the paths returned from the DHT, reversing the paths
2843  * to obtain a local peer -> destination path and interning the peer ids.
2844  *
2845  * @return Newly allocated and created path
2846  */
2847 static struct MeshPeerPath *
2848 path_build_from_dht (const struct GNUNET_PeerIdentity *get_path,
2849                      unsigned int get_path_length,
2850                      const struct GNUNET_PeerIdentity *put_path,
2851                      unsigned int put_path_length)
2852 {
2853   struct MeshPeerPath *p;
2854   GNUNET_PEER_Id id;
2855   int i;
2856
2857   p = path_new (1);
2858   p->peers[0] = myid;
2859   GNUNET_PEER_change_rc (myid, 1);
2860   i = get_path_length;
2861   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   GET has %d hops.\n", i);
2862   for (i--; i >= 0; i--)
2863   {
2864     id = GNUNET_PEER_intern (&get_path[i]);
2865     if (p->length > 0 && id == p->peers[p->length - 1])
2866     {
2867       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   Optimizing 1 hop out.\n");
2868       GNUNET_PEER_change_rc (id, -1);
2869     }
2870     else
2871     {
2872       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   Adding from GET: %s.\n",
2873                   GNUNET_i2s (&get_path[i]));
2874       p->length++;
2875       p->peers = GNUNET_realloc (p->peers, sizeof (GNUNET_PEER_Id) * p->length);
2876       p->peers[p->length - 1] = id;
2877     }
2878   }
2879   i = put_path_length;
2880   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   PUT has %d hops.\n", i);
2881   for (i--; i >= 0; i--)
2882   {
2883     id = GNUNET_PEER_intern (&put_path[i]);
2884     if (id == myid)
2885     {
2886       /* PUT path went through us, so discard the path up until now and start
2887        * from here to get a much shorter (and loop-free) path.
2888        */
2889       path_destroy (p);
2890       p = path_new (0);
2891     }
2892     if (p->length > 0 && id == p->peers[p->length - 1])
2893     {
2894       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   Optimizing 1 hop out.\n");
2895       GNUNET_PEER_change_rc (id, -1);
2896     }
2897     else
2898     {
2899       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   Adding from PUT: %s.\n",
2900                   GNUNET_i2s (&put_path[i]));
2901       p->length++;
2902       p->peers = GNUNET_realloc (p->peers, sizeof (GNUNET_PEER_Id) * p->length);
2903       p->peers[p->length - 1] = id;
2904     }
2905   }
2906 #if MESH_DEBUG
2907   if (get_path_length > 0)
2908     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   (first of GET: %s)\n",
2909                 GNUNET_i2s (&get_path[0]));
2910   if (put_path_length > 0)
2911     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   (first of PUT: %s)\n",
2912                 GNUNET_i2s (&put_path[0]));
2913   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   In total: %d hops\n",
2914               p->length);
2915   for (i = 0; i < p->length; i++)
2916   {
2917     struct GNUNET_PeerIdentity peer_id;
2918
2919     GNUNET_PEER_resolve (p->peers[i], &peer_id);
2920     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "       %u: %s\n", p->peers[i],
2921                 GNUNET_i2s (&peer_id));
2922   }
2923 #endif
2924   return p;
2925 }
2926
2927
2928 /**
2929  * Adds a path to the peer_infos of all the peers in the path
2930  *
2931  * @param p Path to process.
2932  * @param confirmed Whether we know if the path works or not.
2933  */
2934 static void
2935 path_add_to_peers (struct MeshPeerPath *p, int confirmed)
2936 {
2937   unsigned int i;
2938
2939   /* TODO: invert and add */
2940   for (i = 0; i < p->length && p->peers[i] != myid; i++) /* skip'em */ ;
2941   for (i++; i < p->length; i++)
2942   {
2943     struct MeshPeer *aux;
2944     struct MeshPeerPath *copy;
2945
2946     aux = peer_get_short (p->peers[i]);
2947     copy = path_duplicate (p);
2948     copy->length = i + 1;
2949     peer_add_path (aux, copy, p->length < 3 ? GNUNET_NO : confirmed);
2950   }
2951 }
2952
2953
2954 /**
2955  * Search for a channel among the channels for a client
2956  *
2957  * @param c the client whose channels to search in
2958  * @param chid the local id of the channel
2959  *
2960  * @return channel handler, NULL if doesn't exist
2961  */
2962 static struct MeshChannel *
2963 channel_get_by_local_id (struct MeshClient *c, MESH_ChannelNumber chid)
2964 {
2965   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   -- get CHID %X\n", chid);
2966   if (0 == (chid & GNUNET_MESH_LOCAL_CHANNEL_ID_CLI))
2967   {
2968     GNUNET_break_op (0);
2969     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "CHID %X not a local chid\n", chid);
2970     return NULL;
2971   }
2972   if (chid >= GNUNET_MESH_LOCAL_CHANNEL_ID_SERV)
2973     return GNUNET_CONTAINER_multihashmap32_get (c->incoming_channels, chid);
2974   return GNUNET_CONTAINER_multihashmap32_get (c->own_channels, chid);
2975 }
2976
2977 #if 0
2978
2979 static void
2980 channel_debug (struct MeshChannel *ch)
2981 {
2982   if (NULL == ch)
2983   {
2984     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*** DEBUG NULL CHANNEL ***\n");
2985     return;
2986   }
2987   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Channel %s:%X\n",
2988               peer2s (ch->t->peer), ch->gid);
2989   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  root %p/%p\n",
2990               ch->root, ch->root_rel);
2991   if (NULL != ch->root)
2992   {
2993     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  cli %u\n", ch->root->id);
2994     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  ready %s\n",
2995                 ch->root_rel->client_ready ? "YES" : "NO");
2996     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  id %X\n", ch->lid_root);
2997   }
2998   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  root %p/%p\n",
2999               ch->dest, ch->dest_rel);
3000   if (NULL != ch->dest)
3001   {
3002     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  cli %u\n", ch->dest->id);
3003     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  ready %s\n",
3004                 ch->dest_rel->client_ready ? "YES" : "NO");
3005     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  id %X\n", ch->lid_dest);
3006   }
3007 }
3008
3009 static void
3010 fc_debug (struct MeshFlowControl *fc)
3011 {
3012   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "    IN: %u/%u\n",
3013               fc->last_pid_recv, fc->last_ack_sent);
3014   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "    OUT: %u/%u\n",
3015               fc->last_pid_sent, fc->last_ack_recv);
3016   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "    QUEUE: %u/%u\n",
3017               fc->queue_n, fc->queue_max);
3018 }
3019
3020 static void
3021 connection_debug (struct MeshConnection *c)
3022 {
3023   if (NULL == c)
3024   {
3025     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*** DEBUG NULL CONNECTION ***\n");
3026     return;
3027   }
3028   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Connection %s:%X\n",
3029               peer2s (c->t->peer), GNUNET_h2s (&c->id));
3030   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  state: %u, pending msgs: %u\n", 
3031               c->state, c->pending_messages);
3032   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  FWD FC\n");
3033   fc_debug (&c->fwd_fc);
3034   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  BCK FC\n");
3035   fc_debug (&c->bck_fc);
3036 }
3037
3038 #endif
3039
3040 static struct MeshChannel *
3041 channel_get (struct MeshTunnel2 *t, MESH_ChannelNumber chid)
3042 {
3043   struct MeshChannel *ch;
3044
3045   if (NULL == t)
3046     return NULL;
3047
3048   for (ch = t->channel_head; NULL != ch; ch = ch->next)
3049   {
3050     if (ch->gid == chid)
3051       break;
3052   }
3053
3054   return ch;
3055 }
3056
3057
3058 /**
3059  * Change the tunnel state.
3060  *
3061  * @param t Tunnel whose state to change.
3062  * @param state New state.
3063  */
3064 static void
3065 tunnel_change_state (struct MeshTunnel2* t, enum MeshTunnelState state)
3066 {
3067   if (NULL == t)
3068     return;
3069   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3070               "Tunnel %s state was %s\n",
3071               peer2s (t->peer),
3072               GNUNET_MESH_DEBUG_TS2S (t->state));
3073   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3074               "Tunnel %s state is now %s\n",
3075               peer2s (t->peer),
3076               GNUNET_MESH_DEBUG_TS2S (state));
3077   t->state = state;
3078 }
3079
3080
3081 /**
3082  * Cache a message to be sent once tunnel is online.
3083  *
3084  * @param t Tunnel to hold the message.
3085  * @param ch Channel the message is about.
3086  * @param msg Message itself (copy will be made).
3087  * @param fwd Is this fwd?
3088  */
3089 static void
3090 tunnel_queue_data (struct MeshTunnel2 *t,
3091                    struct MeshChannel *ch,
3092                    struct GNUNET_MessageHeader *msg,
3093                    int fwd)
3094 {
3095   struct MeshTunnelQueue *tq;
3096   uint16_t size = ntohs (msg->size);
3097
3098   tq = GNUNET_malloc (sizeof (struct MeshTunnelQueue) + size);
3099
3100   tq->ch = ch;
3101   memcpy (&tq[1], msg, size);
3102   GNUNET_CONTAINER_DLL_insert_tail (t->tq_head, t->tq_tail, tq);
3103 }
3104
3105
3106 /**
3107  * Send all cached messages that we can, tunnel is online.
3108  *
3109  * @param t Tunnel that holds the messages.
3110  * @param fwd Is this fwd?
3111  */
3112 static void
3113 tunnel_send_queued_data (struct MeshTunnel2 *t, int fwd)
3114 {
3115   struct MeshTunnelQueue *tq;
3116   struct MeshTunnelQueue *next;
3117   unsigned int room;
3118
3119   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3120               "tunnel_send_queued_data on tunnel %s\n",
3121               peer2s (t->peer));
3122   room = tunnel_get_buffer (t, fwd);
3123   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  buffer space: %u\n", room);
3124   for (tq = t->tq_head; NULL != tq && room > 0; tq = next)
3125   {
3126     next = tq->next;
3127     room--;
3128     GNUNET_CONTAINER_DLL_remove (t->tq_head, t->tq_tail, tq);
3129     send_prebuilt_message_channel ((struct GNUNET_MessageHeader *) &tq[1],
3130                                    tq->ch, fwd);
3131
3132     GNUNET_free (tq);
3133   }
3134 }
3135
3136
3137 static void
3138 connection_change_state (struct MeshConnection* c,
3139                          enum MeshConnectionState state)
3140 {
3141   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3142               "Connection %s state was %s\n",
3143               GNUNET_h2s (&c->id), GNUNET_MESH_DEBUG_CS2S (c->state));
3144   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3145               "Connection %s state is now %s\n",
3146               GNUNET_h2s (&c->id), GNUNET_MESH_DEBUG_CS2S (state));
3147   c->state = state;
3148 }
3149
3150
3151 /**
3152  * Add a client to a channel, initializing all needed data structures.
3153  * 
3154  * @param ch Channel to which add the client.
3155  * @param c Client which to add to the channel.
3156  */
3157 static void
3158 channel_add_client (struct MeshChannel *ch, struct MeshClient *c)
3159 {
3160   struct MeshTunnel2 *t = ch->t;
3161
3162   if (NULL != ch->dest)
3163   {
3164     GNUNET_break (0);
3165     return;
3166   }
3167
3168   /* Assign local id as destination */
3169   while (NULL != channel_get_by_local_id (c, t->next_local_chid))
3170     t->next_local_chid = (t->next_local_chid + 1) | GNUNET_MESH_LOCAL_CHANNEL_ID_SERV;
3171   ch->lid_dest = t->next_local_chid++;
3172   t->next_local_chid = t->next_local_chid | GNUNET_MESH_LOCAL_CHANNEL_ID_SERV;
3173
3174   /* Store in client's hashmap */
3175   if (GNUNET_OK !=
3176       GNUNET_CONTAINER_multihashmap32_put (c->incoming_channels,
3177                                            ch->lid_dest, ch,
3178                                            GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
3179   {
3180     GNUNET_break (0);
3181     return;
3182   }
3183
3184   GNUNET_break (NULL == ch->dest_rel);
3185   ch->dest_rel = GNUNET_new (struct MeshChannelReliability);
3186   ch->dest_rel->ch = ch;
3187   ch->dest_rel->expected_delay = MESH_RETRANSMIT_TIME;
3188
3189   ch->dest = c;
3190 }
3191
3192
3193 static struct MeshConnection *
3194 tunnel_use_path (struct MeshTunnel2 *t, struct MeshPeerPath *p)
3195 {
3196   struct MeshConnection *c;
3197   struct GNUNET_HashCode cid;
3198   struct MeshPeer *peer;
3199   unsigned int own_pos;
3200
3201   if (NULL == t || NULL == p)
3202   {
3203     GNUNET_break (0);
3204     return NULL;
3205   }
3206
3207   GNUNET_CRYPTO_hash_create_random (GNUNET_CRYPTO_QUALITY_NONCE, &cid);
3208
3209   c = connection_new (&cid);
3210   c->t = t;
3211   GNUNET_CONTAINER_DLL_insert (t->connection_head, t->connection_tail, c);
3212   for (own_pos = 0; own_pos < p->length; own_pos++)
3213   {
3214     if (p->peers[own_pos] == myid)
3215       break;
3216   }
3217   if (own_pos > p->length - 1)
3218   {
3219     GNUNET_break (0);
3220     connection_destroy (c);
3221     return NULL;
3222   }
3223   c->own_pos = own_pos;
3224   c->path = p;
3225
3226   if (0 == own_pos)
3227   {
3228     c->fwd_maintenance_task =
3229         GNUNET_SCHEDULER_add_delayed (refresh_connection_time,
3230                                       &connection_fwd_keepalive, c);
3231   }
3232
3233   peer = connection_get_next_hop (c);
3234   if (NULL == peer->connections)
3235   {
3236     connection_destroy (c);
3237     return NULL;
3238   }
3239   GNUNET_CONTAINER_multihashmap_put (peer->connections, &c->id, c,
3240                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
3241   peer = connection_get_prev_hop (c);
3242   if (NULL == peer->connections)
3243   {
3244     connection_destroy (c);
3245     return NULL;
3246   }
3247   GNUNET_CONTAINER_multihashmap_put (peer->connections, &c->id, c,
3248                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
3249   return c;
3250 }
3251
3252
3253 /**
3254  * Notifies a tunnel that a connection has broken that affects at least
3255  * some of its peers. Sends a notification towards the root of the tree.
3256  * In case the peer is the owner of the tree, notifies the client that owns
3257  * the tunnel and tries to reconnect.
3258  * 
3259  * FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME 
3260  *
3261  * @param t Tunnel affected.
3262  * @param p1 Peer that got disconnected from p2.
3263  * @param p2 Peer that got disconnected from p1.
3264  *
3265  * @return Short ID of the peer disconnected (either p1 or p2).
3266  *         0 if the tunnel remained unaffected.
3267  */
3268 static GNUNET_PEER_Id
3269 tunnel_notify_connection_broken (struct MeshTunnel2* t,
3270                                  GNUNET_PEER_Id p1, GNUNET_PEER_Id p2)
3271 {
3272 //   if (myid != p1 && myid != p2) FIXME
3273 //   {
3274 //     return;
3275 //   }
3276 // 
3277 //   if (tree_get_predecessor (t->tree) != 0)
3278 //   {
3279 //     /* We are the peer still connected, notify owner of the disconnection. */
3280 //     struct GNUNET_MESH_PathBroken msg;
3281 //     struct GNUNET_PeerIdentity neighbor;
3282 // 
3283 //     msg.header.size = htons (sizeof (msg));
3284 //     msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_BROKEN);
3285 //     GNUNET_PEER_resolve (t->id.oid, &msg.oid);
3286 //     msg.tid = htonl (t->id.tid);
3287 //     msg.peer1 = my_full_id;
3288 //     GNUNET_PEER_resolve (pid, &msg.peer2);
3289 //     GNUNET_PEER_resolve (tree_get_predecessor (t->tree), &neighbor);
3290 //     send_prebuilt_message (&msg.header, &neighbor, t);
3291 //   }
3292   return 0;
3293 }
3294
3295
3296 /**
3297  * Send an end-to-end ACK message for the most recent in-sequence payload.
3298  *
3299  * If channel is not reliable, do nothing.
3300  *
3301  * @param ch Channel this is about.
3302  * @param fwd Is for FWD traffic? (ACK dest->owner)
3303  */
3304 static void
3305 channel_send_data_ack (struct MeshChannel *ch, int fwd)
3306 {
3307   struct GNUNET_MESH_DataACK msg;
3308   struct MeshChannelReliability *rel;
3309   struct MeshReliableMessage *copy;
3310   unsigned int delta;
3311   uint64_t mask;
3312   uint16_t type;
3313
3314   if (GNUNET_NO == ch->reliable)
3315   {
3316     return;
3317   }
3318   rel = fwd ? ch->dest_rel : ch->root_rel;
3319   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3320               "send_data_ack for %u\n",
3321               rel->mid_recv - 1);
3322
3323   type = GNUNET_MESSAGE_TYPE_MESH_DATA_ACK;
3324   msg.header.type = htons (type);
3325   msg.header.size = htons (sizeof (msg));
3326   msg.chid = htonl (ch->gid);
3327   msg.mid = htonl (rel->mid_recv - 1);
3328   msg.futures = 0;
3329   for (copy = rel->head_recv; NULL != copy; copy = copy->next)
3330   {
3331     if (copy->type != type)
3332       continue;
3333     delta = copy->mid - rel->mid_recv;
3334     if (63 < delta)
3335       break;
3336     mask = 0x1LL << delta;
3337     msg.futures |= mask;
3338     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3339                 " setting bit for %u (delta %u) (%llX) -> %llX\n",
3340                 copy->mid, delta, mask, msg.futures);
3341   }
3342   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " final futures %llX\n", msg.futures);
3343
3344   send_prebuilt_message_channel (&msg.header, ch, fwd);
3345   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "send_data_ack END\n");
3346 }
3347
3348
3349 /**
3350  * Send an ACK informing the predecessor about the available buffer space.
3351  *
3352  * Note that for fwd ack, the FWD mean forward *traffic* (root->dest),
3353  * the ACK itself goes "back" (dest->root).
3354  *
3355  * @param c Connection on which to send the ACK.
3356  * @param buffer How much space free to advertise?
3357  * @param fwd Is this FWD ACK? (Going dest->owner)
3358  */
3359 static void
3360 connection_send_ack (struct MeshConnection *c, unsigned int buffer, int fwd)
3361 {
3362   struct MeshFlowControl *next_fc;
3363   struct MeshFlowControl *prev_fc;
3364   struct GNUNET_MESH_ACK msg;
3365   uint32_t ack;
3366   int delta;
3367
3368   next_fc = fwd ? &c->fwd_fc : &c->bck_fc;
3369   prev_fc = fwd ? &c->bck_fc : &c->fwd_fc;
3370
3371   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3372               "connection send %s ack on %s\n",
3373               fwd ? "FWD" : "BCK", GNUNET_h2s (&c->id));
3374
3375   /* Check if we need to transmit the ACK */
3376   if (prev_fc->last_ack_sent - prev_fc->last_pid_recv > 3)
3377   {
3378     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Not sending ACK, buffer > 3\n");
3379     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3380                 "  last pid recv: %u, last ack sent: %u\n",
3381                 prev_fc->last_pid_recv, prev_fc->last_ack_sent);
3382     return;
3383   }
3384
3385   /* Ok, ACK might be necessary, what PID to ACK? */
3386   delta = next_fc->queue_max - next_fc->queue_n;
3387   ack = prev_fc->last_pid_recv + delta;
3388   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " ACK %u\n", ack);
3389   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3390               " last pid %u, last ack %u, qmax %u, q %u\n",
3391               prev_fc->last_pid_recv, prev_fc->last_ack_sent,
3392               next_fc->queue_max, next_fc->queue_n);
3393   if (ack == prev_fc->last_ack_sent)
3394   {
3395     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Not sending FWD ACK, not needed\n");
3396     return;
3397   }
3398
3399   prev_fc->last_ack_sent = ack;
3400
3401   /* Build ACK message and send on connection */
3402   msg.header.size = htons (sizeof (msg));
3403   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_ACK);
3404   msg.ack = htonl (ack);
3405   msg.cid = c->id;
3406
3407   send_prebuilt_message_connection (&msg.header, c, NULL, !fwd);
3408 }
3409
3410
3411 /**
3412  * Modify the mesh message TID from global to local and send to client.
3413  * 
3414  * @param ch Channel on which to send the message.
3415  * @param msg Message to modify and send.
3416  * @param c Client to send to.
3417  * @param tid Tunnel ID to use (c can be both owner and client).
3418  */
3419 static void
3420 channel_send_client_to_tid (struct MeshChannel *ch,
3421                              const struct GNUNET_MESH_Data *msg,
3422                              struct MeshClient *c, MESH_ChannelNumber id)
3423 {
3424   struct GNUNET_MESH_LocalData *copy;
3425   uint16_t size = ntohs (msg->header.size) - sizeof (struct GNUNET_MESH_Data);
3426   char cbuf[size + sizeof (struct GNUNET_MESH_LocalData)];
3427
3428   if (size < sizeof (struct GNUNET_MessageHeader))
3429   {
3430     GNUNET_break_op (0);
3431     return;
3432   }
3433   if (NULL == c)
3434   {
3435     GNUNET_break (0);
3436     return;
3437   }
3438   copy = (struct GNUNET_MESH_LocalData *) cbuf;
3439   memcpy (&copy[1], &msg[1], size);
3440   copy->header.size = htons (sizeof (struct GNUNET_MESH_LocalData) + size);
3441   copy->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_DATA);
3442   copy->id = htonl (id);
3443   GNUNET_SERVER_notification_context_unicast (nc, c->handle,
3444                                               &copy->header, GNUNET_NO);
3445 }
3446
3447
3448 /**
3449  * We have received a message out of order, or the client is not ready.
3450  * Buffer it until we receive an ACK from the client or the missing
3451  * message from the channel.
3452  *
3453  * @param msg Message to buffer (MUST be of type MESH_DATA).
3454  * @param rel Reliability data to the corresponding direction.
3455  */
3456 static void
3457 channel_rel_add_buffered_data (const struct GNUNET_MESH_Data *msg,
3458                                struct MeshChannelReliability *rel)
3459 {
3460   struct MeshReliableMessage *copy;
3461   struct MeshReliableMessage *prev;
3462   uint32_t mid;
3463   uint16_t size;
3464   
3465   size = ntohs (msg->header.size);
3466   mid = ntohl (msg->mid);
3467   
3468   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "add_buffered_data %u\n", mid);
3469   
3470   copy = GNUNET_malloc (sizeof (*copy) + size);
3471   copy->mid = mid;
3472   copy->rel = rel;
3473   memcpy (&copy[1], msg, size);
3474   
3475   rel->n_recv++;
3476   
3477   // FIXME do something better than O(n), although n < 64...
3478   // FIXME start from the end (most messages are the latest ones)
3479   for (prev = rel->head_recv; NULL != prev; prev = prev->next)
3480   {
3481     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " prev %u\n", prev->mid);
3482     if (GMC_is_pid_bigger (prev->mid, mid))
3483     {
3484       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " bingo!\n");
3485       GNUNET_CONTAINER_DLL_insert_before (rel->head_recv, rel->tail_recv,
3486                                           prev, copy);
3487       return;
3488     }
3489   }
3490     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " insert at tail!\n");
3491     GNUNET_CONTAINER_DLL_insert_tail (rel->head_recv, rel->tail_recv, copy);
3492     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "add_buffered_data END\n");
3493 }
3494
3495
3496 static void
3497 channel_send_client_data (struct MeshChannel *ch,
3498                           const struct GNUNET_MESH_Data *msg,
3499                           int fwd)
3500 {
3501   if (fwd)
3502   {
3503     if (ch->dest_rel->client_ready)
3504       channel_send_client_to_tid (ch, msg, ch->dest, ch->lid_dest);
3505     else
3506       channel_rel_add_buffered_data (msg, ch->dest_rel);
3507   }
3508   else
3509   {
3510     if (ch->root_rel->client_ready)
3511       channel_send_client_to_tid (ch, msg, ch->root, ch->lid_root);
3512     else
3513       channel_rel_add_buffered_data (msg, ch->root_rel);
3514   }
3515 }
3516
3517
3518 /**
3519  * Send a buffered message to the client, for in order delivery or
3520  * as result of client ACK.
3521  *
3522  * @param ch Channel on which to empty the message buffer.
3523  * @param c Client to send to.
3524  * @param rel Reliability structure to corresponding peer.
3525  *            If rel == bck_rel, this is FWD data.
3526  */
3527 static void
3528 channel_send_client_buffered_data (struct MeshChannel *ch,
3529                                    struct MeshClient *c,
3530                                    int fwd)
3531 {
3532   struct MeshReliableMessage *copy;
3533   struct MeshChannelReliability *rel;
3534
3535   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "send_buffered_data\n");
3536   rel = fwd ? ch->dest_rel : ch->root_rel;
3537   if (GNUNET_NO == rel->client_ready)
3538   {
3539     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "client not ready\n");
3540     return;
3541   }
3542
3543   copy = rel->head_recv;
3544   /* We never buffer channel management messages */
3545   if (NULL != copy)
3546   {
3547     if (copy->mid == rel->mid_recv || GNUNET_NO == ch->reliable)
3548     {
3549       struct GNUNET_MESH_Data *msg = (struct GNUNET_MESH_Data *) &copy[1];
3550
3551       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3552                   " have %u! now expecting %u\n",
3553                   copy->mid, rel->mid_recv + 1);
3554       channel_send_client_data (ch, msg, fwd);
3555       rel->n_recv--;
3556       rel->mid_recv++;
3557       GNUNET_CONTAINER_DLL_remove (rel->head_recv, rel->tail_recv, copy);
3558       GNUNET_free (copy);
3559     }
3560     else
3561     {
3562       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3563                   " reliable && don't have %u, next is %u\n",
3564                   rel->mid_recv,
3565                   copy->mid);
3566       return;
3567     }
3568   }
3569   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "send_buffered_data END\n");
3570 }
3571
3572
3573 /**
3574  * Destroy a reliable message after it has been acknowledged, either by
3575  * direct mid ACK or bitfield. Updates the appropriate data structures and
3576  * timers and frees all memory.
3577  * 
3578  * @param copy Message that is no longer needed: remote peer got it.
3579  */
3580 static void
3581 rel_message_free (struct MeshReliableMessage *copy)
3582 {
3583   struct MeshChannelReliability *rel;
3584   struct GNUNET_TIME_Relative time;
3585
3586   rel = copy->rel;
3587   time = GNUNET_TIME_absolute_get_duration (copy->timestamp);
3588   rel->expected_delay.rel_value_us *= 7;
3589   rel->expected_delay.rel_value_us += time.rel_value_us;
3590   rel->expected_delay.rel_value_us /= 8;
3591   rel->n_sent--;
3592   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! Freeing %u\n", copy->mid);
3593   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "    n_sent %u\n", rel->n_sent);
3594   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!!  took %s\n",
3595               GNUNET_STRINGS_relative_time_to_string (time, GNUNET_NO));
3596   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!!  new expected delay %s\n",
3597               GNUNET_STRINGS_relative_time_to_string (rel->expected_delay,
3598                                                       GNUNET_NO));
3599   rel->retry_timer = rel->expected_delay;
3600   GNUNET_CONTAINER_DLL_remove (rel->head_sent, rel->tail_sent, copy);
3601   GNUNET_free (copy);
3602 }
3603
3604
3605 /**
3606  * Destroy all reliable messages queued for a channel,
3607  * during a channel destruction.
3608  * Frees the reliability structure itself.
3609  *
3610  * @param rel Reliability data for a channel.
3611  */
3612 static void
3613 channel_rel_free_all (struct MeshChannelReliability *rel)
3614 {
3615   struct MeshReliableMessage *copy;
3616   struct MeshReliableMessage *next;
3617
3618   if (NULL == rel)
3619     return;
3620
3621   for (copy = rel->head_recv; NULL != copy; copy = next)
3622   {
3623     next = copy->next;
3624     GNUNET_CONTAINER_DLL_remove (rel->head_recv, rel->tail_recv, copy);
3625     GNUNET_free (copy);
3626   }
3627   for (copy = rel->head_sent; NULL != copy; copy = next)
3628   {
3629     next = copy->next;
3630     GNUNET_CONTAINER_DLL_remove (rel->head_sent, rel->tail_sent, copy);
3631     GNUNET_free (copy);
3632   }
3633   if (GNUNET_SCHEDULER_NO_TASK != rel->retry_task)
3634     GNUNET_SCHEDULER_cancel (rel->retry_task);
3635   GNUNET_free (rel);
3636 }
3637
3638
3639 /**
3640  * Mark future messages as ACK'd.
3641  *
3642  * @param rel Reliability data.
3643  * @param msg DataACK message with a bitfield of future ACK'd messages.
3644  */
3645 static void
3646 channel_rel_free_sent (struct MeshChannelReliability *rel,
3647                        const struct GNUNET_MESH_DataACK *msg)
3648 {
3649   struct MeshReliableMessage *copy;
3650   struct MeshReliableMessage *next;
3651   uint64_t bitfield;
3652   uint64_t mask;
3653   uint32_t mid;
3654   uint32_t target;
3655   unsigned int i;
3656
3657   bitfield = msg->futures;
3658   mid = ntohl (msg->mid);
3659   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3660               "free_sent_reliable %u %llX\n",
3661               mid, bitfield);
3662   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3663               " rel %p, head %p\n",
3664               rel, rel->head_sent);
3665   for (i = 0, copy = rel->head_sent;
3666        i < 64 && NULL != copy && 0 != bitfield;
3667        i++)
3668   {
3669     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3670                 " trying bit %u (mid %u)\n",
3671                 i, mid + i + 1);
3672     mask = 0x1LL << i;
3673     if (0 == (bitfield & mask))
3674      continue;
3675
3676     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " set!\n");
3677     /* Bit was set, clear the bit from the bitfield */
3678     bitfield &= ~mask;
3679
3680     /* The i-th bit was set. Do we have that copy? */
3681     /* Skip copies with mid < target */
3682     target = mid + i + 1;
3683     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " target %u\n", target);
3684     while (NULL != copy && GMC_is_pid_bigger (target, copy->mid))
3685      copy = copy->next;
3686
3687     /* Did we run out of copies? (previously freed, it's ok) */
3688     if (NULL == copy)
3689     {
3690      GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "run out of copies...\n");
3691      return;
3692     }
3693
3694     /* Did we overshoot the target? (previously freed, it's ok) */
3695     if (GMC_is_pid_bigger (copy->mid, target))
3696     {
3697      GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " next copy %u\n", copy->mid);
3698      continue;
3699     }
3700
3701     /* Now copy->mid == target, free it */
3702     next = copy->next;
3703     rel_message_free (copy);
3704     copy = next;
3705   }
3706   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "free_sent_reliable END\n");
3707 }
3708
3709
3710 /**
3711  * We haven't received an ACK after a certain time: restransmit the message.
3712  *
3713  * @param cls Closure (MeshReliableMessage with the message to restransmit)
3714  * @param tc TaskContext.
3715  */
3716 static void
3717 channel_retransmit_message (void *cls,
3718                             const struct GNUNET_SCHEDULER_TaskContext *tc)
3719 {
3720   struct MeshChannelReliability *rel = cls;
3721   struct MeshReliableMessage *copy;
3722   struct MeshPeerQueue *q;
3723   struct MeshChannel *ch;
3724   struct MeshConnection *c;
3725   struct GNUNET_MESH_Data *payload;
3726   struct MeshPeer *hop;
3727   int fwd;
3728
3729   rel->retry_task = GNUNET_SCHEDULER_NO_TASK;
3730   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
3731     return;
3732
3733   ch = rel->ch;
3734   copy = rel->head_sent;
3735   if (NULL == copy)
3736   {
3737     GNUNET_break (0);
3738     return;
3739   }
3740
3741   /* Search the message to be retransmitted in the outgoing queue.
3742    * Check only the queue for the connection that is going to be used,
3743    * if the message is stuck in some other connection's queue we shouldn't
3744    * act upon it:
3745    * - cancelling it and sending the new one doesn't guarantee it's delivery,
3746    *   the old connection could be temporary stalled or the queue happened to
3747    *   be long at time of insertion.
3748    * - not sending the new one could cause terrible delays the old connection
3749    *   is stalled.
3750    */
3751   payload = (struct GNUNET_MESH_Data *) &copy[1];
3752   fwd = (rel == ch->root_rel);
3753   c = tunnel_get_connection (ch->t, fwd);
3754   hop = connection_get_hop (c, fwd);
3755   for (q = hop->queue_head; NULL != q; q = q->next)
3756   {
3757     if (ntohs (payload->header.type) == q->type && ch == q->ch)
3758     {
3759       struct GNUNET_MESH_Data *queued_data = q->cls;
3760
3761       if (queued_data->mid == payload->mid)
3762         break;
3763     }
3764   }
3765
3766   /* Message not found in the queue that we are going to use. */
3767   if (NULL == q)
3768   {
3769     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! RETRANSMIT %u\n", copy->mid);
3770
3771     send_prebuilt_message_channel (&payload->header, ch, fwd);
3772     GNUNET_STATISTICS_update (stats, "# data retransmitted", 1, GNUNET_NO);
3773   }
3774   else
3775   {
3776     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! ALREADY IN QUEUE %u\n", copy->mid);
3777   }
3778
3779   rel->retry_timer = GNUNET_TIME_STD_BACKOFF (rel->retry_timer);
3780   rel->retry_task = GNUNET_SCHEDULER_add_delayed (rel->retry_timer,
3781                                                   &channel_retransmit_message,
3782                                                   cls);
3783 }
3784
3785
3786 /**
3787  * Send ACK on one or more connections due to buffer space to the client.
3788  *
3789  * Iterates all connections of the tunnel and sends ACKs appropriately.
3790  *
3791  * @param ch Channel which has some free buffer space.
3792  * @param fwd Is this in for FWD traffic? (ACK goes dest->root)
3793  */
3794 static void
3795 channel_send_connections_ack (struct MeshChannel *ch,
3796                               unsigned int buffer,
3797                               int fwd)
3798 {
3799   struct MeshTunnel2 *t = ch->t;
3800   struct MeshConnection *c;
3801   struct MeshFlowControl *fc;
3802   uint32_t allowed;
3803   uint32_t to_allow;
3804   uint32_t allow_per_connection;
3805   unsigned int cs;
3806
3807   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3808               "Channel send connection %s ack on %s:%X\n",
3809               fwd ? "FWD" : "BCK", peer2s (ch->t->peer), ch->gid);
3810
3811   /* Count connections, how many messages are already allowed */
3812   for (cs = 0, allowed = 0, c = t->connection_head; NULL != c; c = c->next)
3813   {
3814     fc = fwd ? &c->fwd_fc : &c->bck_fc;
3815     if (GMC_is_pid_bigger(fc->last_pid_recv, fc->last_ack_sent))
3816     {
3817       GNUNET_break (0);
3818       continue;
3819     }
3820     allowed += fc->last_ack_sent - fc->last_pid_recv;
3821     cs++;
3822   }
3823
3824   /* Make sure there is no overflow */
3825   if (allowed > buffer)
3826   {
3827     GNUNET_break (0);
3828     return;
3829   }
3830
3831   /* Authorize connections to send more data */
3832   to_allow = buffer - allowed;
3833
3834   for (c = t->connection_head; NULL != c && to_allow > 0; c = c->next)
3835   {
3836     allow_per_connection = to_allow/cs;
3837     to_allow -= allow_per_connection;
3838     cs--;
3839     fc = fwd ? &c->fwd_fc : &c->bck_fc;
3840     if (fc->last_ack_sent - fc->last_pid_recv > 64 / 3)
3841     {
3842       continue;
3843     }
3844     connection_send_ack (c, allow_per_connection, fwd);
3845   }
3846
3847   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3848                 "Channel send connection %s ack on %s:%X\n",
3849                 fwd ? "FWD" : "BCK", peer2s (ch->t->peer), ch->gid);
3850   GNUNET_break (to_allow == 0);
3851 }
3852
3853
3854 /**
3855  * Send an ACK on the appropriate connection/channel, depending on
3856  * the direction and the position of the peer.
3857  *
3858  * @param c Which connection to send the hop-by-hop ACK.
3859  * @param ch Channel, if any.
3860  * @param fwd Is this a fwd ACK? (will go dest->root)
3861  */
3862 static void
3863 send_ack (struct MeshConnection *c, struct MeshChannel *ch, int fwd)
3864 {
3865   unsigned int buffer;
3866
3867   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3868               "send ack %s on %p %p\n",
3869               fwd ? "FWD" : "BCK", c, ch);
3870   if (NULL == c || connection_is_terminal (c, fwd))
3871   {
3872     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  getting from Channel\n");
3873     buffer = tunnel_get_buffer (NULL == c ? ch->t : c->t, fwd);
3874   }
3875   else
3876   {
3877     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  getting from Connection\n");
3878     GNUNET_assert (NULL != c);
3879     buffer = connection_get_buffer (c, fwd);
3880   }
3881   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  buffer available: %u\n", buffer);
3882
3883   if (NULL == c)
3884   {
3885     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  sending on all connections\n");
3886     GNUNET_assert (NULL != ch);
3887     channel_send_connections_ack (ch, buffer, fwd);
3888   }
3889   else if (connection_is_origin (c, fwd))
3890   {
3891     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  sending on channel...\n");
3892     if (0 < buffer)
3893     {
3894       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  really sending!\n");
3895       GNUNET_assert (NULL != ch);
3896       send_local_ack (ch, fwd);
3897     }
3898   }
3899   else
3900   {
3901     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  sending on connection\n");
3902     connection_send_ack (c, buffer, fwd);
3903   }
3904 }
3905
3906
3907 /**
3908  * Channel was ACK'd by remote peer, mark as ready and cancel retransmission.
3909  *
3910  * @param ch Channel to mark as ready.
3911  * @param fwd Was the CREATE message sent fwd?
3912  */
3913 static void
3914 channel_confirm (struct MeshChannel *ch, int fwd)
3915 {
3916   struct MeshChannelReliability *rel;
3917   struct MeshReliableMessage *copy;
3918   struct MeshReliableMessage *next;
3919
3920   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3921               "  channel confirm %s %s:%X\n",
3922               fwd ? "FWD" : "BCK", peer2s (ch->t->peer), ch->gid);
3923   ch->state = MESH_CHANNEL_READY;
3924
3925   rel = fwd ? ch->root_rel : ch->dest_rel;
3926   for (copy = rel->head_sent; NULL != copy; copy = next)
3927   {
3928     struct GNUNET_MessageHeader *msg;
3929
3930     next = copy->next;
3931     msg = (struct GNUNET_MessageHeader *) &copy[1];
3932     if (ntohs (msg->type) == GNUNET_MESSAGE_TYPE_MESH_CHANNEL_CREATE)
3933     {
3934       rel_message_free (copy);
3935       /* TODO return? */
3936     }
3937   }
3938   if (GNUNET_NO == rel->client_ready)
3939     send_local_ack (ch, fwd);
3940 }
3941
3942
3943 /**
3944  * Save a copy to retransmit in case it gets lost.
3945  *
3946  * Initializes all needed callbacks and timers.
3947  *
3948  * @param ch Channel this message goes on.
3949  * @param msg Message to copy.
3950  * @param fwd Is this fwd traffic?
3951  */
3952 static void
3953 channel_save_copy (struct MeshChannel *ch,
3954                    const struct GNUNET_MessageHeader *msg,
3955                    int fwd)
3956 {
3957   struct MeshChannelReliability *rel;
3958   struct MeshReliableMessage *copy;
3959   uint32_t mid;
3960   uint16_t type;
3961   uint16_t size;
3962
3963   rel = fwd ? ch->root_rel : ch->dest_rel;
3964   mid = rel->mid_send;
3965   type = ntohs (msg->type);
3966   size = ntohs (msg->size);
3967
3968   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! SAVE %u\n", mid);
3969   copy = GNUNET_malloc (sizeof (struct MeshReliableMessage) + size);
3970   copy->mid = mid;
3971   copy->timestamp = GNUNET_TIME_absolute_get ();
3972   copy->rel = rel;
3973   copy->type = type;
3974   memcpy (&copy[1], msg, size);
3975   rel->n_sent++;
3976   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " n_sent %u\n", rel->n_sent);
3977   GNUNET_CONTAINER_DLL_insert_tail (rel->head_sent, rel->tail_sent, copy);
3978   if (GNUNET_SCHEDULER_NO_TASK == rel->retry_task)
3979   {
3980     rel->retry_timer =
3981         GNUNET_TIME_relative_multiply (rel->expected_delay,
3982                                         MESH_RETRANSMIT_MARGIN);
3983     rel->retry_task =
3984         GNUNET_SCHEDULER_add_delayed (rel->retry_timer,
3985                                       &channel_retransmit_message,
3986                                       rel);
3987   }
3988 }
3989
3990
3991 /**
3992  * Send keepalive packets for a connection.
3993  *
3994  * @param c Connection to keep alive..
3995  * @param fwd Is this a FWD keepalive? (owner -> dest).
3996  */
3997 static void
3998 connection_keepalive (struct MeshConnection *c, int fwd)
3999 {
4000   struct GNUNET_MESH_ConnectionKeepAlive *msg;
4001   size_t size = sizeof (struct GNUNET_MESH_ConnectionKeepAlive);
4002   char cbuf[size];
4003   uint16_t type;
4004
4005   type = fwd ? GNUNET_MESSAGE_TYPE_MESH_FWD_KEEPALIVE :
4006                GNUNET_MESSAGE_TYPE_MESH_BCK_KEEPALIVE;
4007
4008   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4009               "sending %s keepalive for connection %s[%d]\n",
4010               fwd ? "FWD" : "BCK",
4011               peer2s (c->t->peer),
4012               c->id);
4013
4014   msg = (struct GNUNET_MESH_ConnectionKeepAlive *) cbuf;
4015   msg->header.size = htons (size);
4016   msg->header.type = htons (type);
4017   msg->cid = c->id;
4018
4019   send_prebuilt_message_connection (&msg->header, c, NULL, fwd);
4020 }
4021
4022
4023 /**
4024  * Send CONNECTION_{CREATE/ACK} packets for a connection.
4025  *
4026  * @param c Connection for which to send the message.
4027  * @param fwd If GNUNET_YES, send CREATE, otherwise send ACK.
4028  */
4029 static void
4030 connection_recreate (struct MeshConnection *c, int fwd)
4031 {
4032   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "sending connection recreate\n");
4033   if (fwd)
4034     send_connection_create (c);
4035   else
4036     send_connection_ack (c, GNUNET_NO);
4037 }
4038
4039
4040 /**
4041  * Generic connection timer management.
4042  * Depending on the role of the peer in the connection will send the
4043  * appropriate message (build or keepalive)
4044  *
4045  * @param c Conncetion to maintain.
4046  * @param fwd Is FWD?
4047  */
4048 static void
4049 connection_maintain (struct MeshConnection *c, int fwd)
4050 {
4051   if (MESH_TUNNEL_SEARCHING == c->t->state)
4052   {
4053     /* TODO DHT GET with RO_BART */
4054     return;
4055   }
4056   switch (c->state)
4057   {
4058     case MESH_CONNECTION_NEW:
4059       GNUNET_break (0);
4060     case MESH_CONNECTION_SENT:
4061       connection_recreate (c, fwd);
4062       break;
4063     case MESH_CONNECTION_READY:
4064       connection_keepalive (c, fwd);
4065       break;
4066     default:
4067       break;
4068   }
4069 }
4070
4071
4072 static void
4073 connection_fwd_keepalive (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
4074 {
4075   struct MeshConnection *c = cls;
4076
4077   c->fwd_maintenance_task = GNUNET_SCHEDULER_NO_TASK;
4078   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
4079     return;
4080
4081   connection_maintain (c, GNUNET_YES);
4082   c->fwd_maintenance_task = GNUNET_SCHEDULER_add_delayed (refresh_connection_time,
4083                                                           &connection_fwd_keepalive,
4084                                                           c);
4085 }
4086
4087
4088 static void
4089 connection_bck_keepalive (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
4090 {
4091   struct MeshConnection *c = cls;
4092
4093   c->bck_maintenance_task = GNUNET_SCHEDULER_NO_TASK;
4094   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
4095     return;
4096
4097   connection_maintain (c, GNUNET_NO);
4098   c->bck_maintenance_task = GNUNET_SCHEDULER_add_delayed (refresh_connection_time,
4099                                                           &connection_bck_keepalive,
4100                                                           c);
4101 }
4102
4103
4104 /**
4105  * Send a message to all peers in this connection that the connection
4106  * is no longer valid.
4107  *
4108  * If some peer should not receive the message, it should be zero'ed out
4109  * before calling this function.
4110  *
4111  * @param c The connection whose peers to notify.
4112  */
4113 static void
4114 connection_send_destroy (struct MeshConnection *c)
4115 {
4116   struct GNUNET_MESH_ConnectionDestroy msg;
4117
4118   msg.header.size = htons (sizeof (msg));
4119   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_TUNNEL_DESTROY);;
4120   msg.cid = c->id;
4121   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4122               "  sending connection destroy for connection %s[%X]\n",
4123               peer2s (c->t->peer),
4124               c->id);
4125
4126   if (GNUNET_NO == connection_is_terminal (c, GNUNET_YES))
4127     send_prebuilt_message_connection (&msg.header, c, NULL, GNUNET_YES);
4128   if (GNUNET_NO == connection_is_terminal (c, GNUNET_NO))
4129     send_prebuilt_message_connection (&msg.header, c, NULL, GNUNET_NO);
4130   c->destroy = GNUNET_YES;
4131 }
4132
4133
4134 /**
4135  * Confirm we got a channel create.
4136  *
4137  * @param ch The channel to confirm.
4138  * @param fwd Should we send the ACK fwd?
4139  */
4140 static void
4141 channel_send_ack (struct MeshChannel *ch, int fwd)
4142 {
4143   struct GNUNET_MESH_ChannelManage msg;
4144
4145   msg.header.size = htons (sizeof (msg));
4146   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_CHANNEL_ACK);
4147   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4148               "  sending channel %s ack for channel %s:%X\n",
4149               fwd ? "FWD" : "BCK", peer2s (ch->t->peer),
4150               ch->gid);
4151
4152   msg.chid = htonl (ch->gid);
4153   send_prebuilt_message_channel (&msg.header, ch, !fwd);
4154 }
4155
4156
4157 /**
4158  * Send a message to all clients (local and remote) of this channel
4159  * notifying that the channel is no longer valid.
4160  *
4161  * If some peer or client should not receive the message,
4162  * should be zero'ed out before calling this function.
4163  *
4164  * @param ch The channel whose clients to notify.
4165  */
4166 static void
4167 channel_send_destroy (struct MeshChannel *ch)
4168 {
4169   struct GNUNET_MESH_ChannelManage msg;
4170
4171   msg.header.size = htons (sizeof (msg));
4172   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_CHANNEL_DESTROY);
4173   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4174               "  sending channel destroy for channel %s:%X\n",
4175               peer2s (ch->t->peer),
4176               ch->gid);
4177
4178   if (channel_is_terminal (ch, GNUNET_NO))
4179   {
4180     if (NULL != ch->root && GNUNET_NO == ch->root->shutting_down)
4181     {
4182       msg.chid = htonl (ch->lid_root);
4183       send_local_channel_destroy (ch, GNUNET_NO);
4184     }
4185   }
4186   else
4187   {
4188     msg.chid = htonl (ch->gid);
4189     send_prebuilt_message_channel (&msg.header, ch, GNUNET_NO);
4190   }
4191
4192   if (channel_is_terminal (ch, GNUNET_YES))
4193   {
4194     if (NULL != ch->dest && GNUNET_NO == ch->dest->shutting_down)
4195     {
4196       msg.chid = htonl (ch->lid_dest);
4197       send_local_channel_destroy (ch, GNUNET_YES);
4198     }
4199   }
4200   else
4201   {
4202     msg.chid = htonl (ch->gid);
4203     send_prebuilt_message_channel (&msg.header, ch, GNUNET_YES);
4204   }
4205 }
4206
4207
4208 /**
4209  * Create a tunnel.
4210  */
4211 static struct MeshTunnel2 *
4212 tunnel_new (void)
4213 {
4214   struct MeshTunnel2 *t;
4215
4216   t = GNUNET_new (struct MeshTunnel2);
4217   t->next_chid = 0;
4218   t->next_local_chid = GNUNET_MESH_LOCAL_CHANNEL_ID_SERV;
4219 //   if (GNUNET_OK !=
4220 //       GNUNET_CONTAINER_multihashmap_put (tunnels, tid, t,
4221 //                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
4222 //   {
4223 //     GNUNET_break (0);
4224 //     tunnel_destroy (t);
4225 //     return NULL;
4226 //   }
4227
4228 //   char salt[] = "salt";
4229 //   GNUNET_CRYPTO_kdf (&t->e_key, sizeof (struct GNUNET_CRYPTO_AesSessionKey),
4230 //                      salt, sizeof (salt),
4231 //                      &t->e_key, sizeof (struct GNUNET_CRYPTO_AesSessionKey),
4232 //                      &my_full_id, sizeof (struct GNUNET_PeerIdentity),
4233 //                      GNUNET_PEER_resolve2 (t->peer->id), sizeof (struct GNUNET_PeerIdentity),
4234 //                      NULL);
4235 //   GNUNET_CRYPTO_kdf (&t->d_key, sizeof (struct GNUNET_CRYPTO_AesSessionKey),
4236 //                      salt, sizeof (salt),
4237 //                      &t->d_key, sizeof (struct GNUNET_CRYPTO_AesSessionKey),
4238 //                      GNUNET_PEER_resolve2 (t->peer->id), sizeof (struct GNUNET_PeerIdentity),
4239 //                      &my_full_id, sizeof (struct GNUNET_PeerIdentity),
4240 //                      NULL);
4241
4242   return t;
4243 }
4244
4245
4246 /**
4247  * Add a connection to a tunnel.
4248  *
4249  * @param t Tunnel.
4250  * @param c Connection.
4251  */
4252 static void
4253 tunnel_add_connection (struct MeshTunnel2 *t, struct MeshConnection *c)
4254 {
4255   struct MeshConnection *aux;
4256   c->t = t;
4257   for (aux = t->connection_head; aux != NULL; aux = aux->next)
4258     if (aux == c)
4259       return;
4260   GNUNET_CONTAINER_DLL_insert_tail (t->connection_head, t->connection_tail, c);
4261 }
4262
4263
4264 /**
4265  * Initialize a Flow Control structure to the initial state.
4266  * 
4267  * @param fc Flow Control structure to initialize.
4268  */
4269 static void
4270 fc_init (struct MeshFlowControl *fc)
4271 {
4272   fc->next_pid = 0;
4273   fc->last_pid_sent = (uint32_t) -1; /* Next (expected) = 0 */
4274   fc->last_pid_recv = (uint32_t) -1;
4275   fc->last_ack_sent = (uint32_t) 0;
4276   fc->last_ack_recv = (uint32_t) 0;
4277   fc->poll_task = GNUNET_SCHEDULER_NO_TASK;
4278   fc->poll_time = GNUNET_TIME_UNIT_SECONDS;
4279   fc->queue_n = 0;
4280   fc->queue_max = (max_msgs_queue / max_connections) + 1;
4281 }
4282
4283
4284 static struct MeshConnection *
4285 connection_new (const struct GNUNET_HashCode *cid)
4286 {
4287   struct MeshConnection *c;
4288
4289   c = GNUNET_new (struct MeshConnection);
4290   c->id = *cid;
4291   GNUNET_CONTAINER_multihashmap_put (connections, &c->id, c,
4292                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
4293   fc_init (&c->fwd_fc);
4294   fc_init (&c->bck_fc);
4295   c->fwd_fc.c = c;
4296   c->bck_fc.c = c;
4297
4298   return c;
4299 }
4300
4301
4302 /**
4303  * Find a connection.
4304  *
4305  * @param cid Connection ID.
4306  */
4307 static struct MeshConnection *
4308 connection_get (const struct GNUNET_HashCode *cid)
4309 {
4310   return GNUNET_CONTAINER_multihashmap_get (connections, cid);
4311 }
4312
4313
4314 static void
4315 connection_destroy (struct MeshConnection *c)
4316 {
4317   struct MeshPeer *peer;
4318
4319   if (NULL == c)
4320     return;
4321
4322   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "destroying connection %s[%X]\n",
4323               peer2s (c->t->peer),
4324               c->id);
4325
4326   /* Cancel all traffic */
4327   connection_cancel_queues (c, GNUNET_YES);
4328   connection_cancel_queues (c, GNUNET_NO);
4329
4330   /* Cancel maintainance task (keepalive/timeout) */
4331   if (GNUNET_SCHEDULER_NO_TASK != c->fwd_maintenance_task)
4332     GNUNET_SCHEDULER_cancel (c->fwd_maintenance_task);
4333   if (GNUNET_SCHEDULER_NO_TASK != c->bck_maintenance_task)
4334     GNUNET_SCHEDULER_cancel (c->bck_maintenance_task);
4335
4336   /* Deregister from neighbors */
4337   peer = connection_get_next_hop (c);
4338   if (NULL != peer && NULL != peer->connections)
4339     GNUNET_CONTAINER_multihashmap_remove (peer->connections, &c->id, c);
4340   peer = connection_get_prev_hop (c);
4341   if (NULL != peer && NULL != peer->connections)
4342     GNUNET_CONTAINER_multihashmap_remove (peer->connections, &c->id, c);
4343
4344   /* Delete */
4345   GNUNET_STATISTICS_update (stats, "# connections", -1, GNUNET_NO);
4346   GNUNET_CONTAINER_DLL_remove (c->t->connection_head, c->t->connection_tail, c);
4347   GNUNET_free (c);
4348 }
4349
4350
4351 static void
4352 tunnel_destroy (struct MeshTunnel2 *t)
4353 {
4354   struct MeshConnection *c;
4355   struct MeshConnection *next;
4356
4357   if (NULL == t)
4358     return;
4359
4360   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "destroying tunnel %s\n",
4361               peer2s (t->peer));
4362
4363 //   if (GNUNET_YES != GNUNET_CONTAINER_multihashmap_remove (tunnels, &t->id, t))
4364 //     GNUNET_break (0);
4365
4366   for (c = t->connection_head; NULL != c; c = next)
4367   {
4368     next = c->next;
4369     connection_destroy (c);
4370   }
4371
4372   GNUNET_STATISTICS_update (stats, "# tunnels", -1, GNUNET_NO);
4373
4374   GNUNET_free (t);
4375 }
4376
4377
4378 /**
4379  * Tunnel is empty: destroy it.
4380  *
4381  * Notifies all connections about the destruction.
4382  *
4383  * @param t Tunnel to destroy. 
4384  */
4385 static void
4386 tunnel_destroy_empty (struct MeshTunnel2 *t)
4387 {
4388   struct MeshConnection *c;
4389
4390   for (c = t->connection_head; NULL != c; c = c->next)
4391   {
4392     if (GNUNET_NO == c->destroy)
4393       connection_send_destroy (c);
4394   }
4395
4396   if (0 == t->pending_messages)
4397     tunnel_destroy (t);
4398   else
4399     t->destroy = GNUNET_YES;
4400 }
4401
4402
4403 /**
4404  * Destroy tunnel if empty (no more channels).
4405  *
4406  * @param t Tunnel to destroy if empty.
4407  */
4408 static void
4409 tunnel_destroy_if_empty (struct MeshTunnel2 *t)
4410 {
4411   if (NULL != t->channel_head)
4412     return;
4413
4414   tunnel_destroy_empty (t);
4415 }
4416
4417
4418 /**
4419  * Destroy a channel and free all resources.
4420  * 
4421  * @param ch Channel to destroy.
4422  */
4423 static void
4424 channel_destroy (struct MeshChannel *ch)
4425 {
4426   struct MeshClient *c;
4427
4428   if (NULL == ch)
4429     return;
4430
4431   c = ch->root;
4432   if (NULL != c)
4433   {
4434     if (GNUNET_YES != GNUNET_CONTAINER_multihashmap32_remove (c->own_channels,
4435                                                               ch->lid_root, ch))
4436     {
4437       GNUNET_break (0);
4438     }
4439   }
4440
4441   c = ch->dest;
4442   if (NULL != c)
4443   {
4444     if (GNUNET_YES !=
4445         GNUNET_CONTAINER_multihashmap32_remove (c->incoming_channels,
4446                                                 ch->lid_dest, ch))
4447     {
4448       GNUNET_break (0);
4449     }
4450   }
4451
4452   channel_rel_free_all (ch->root_rel);
4453   channel_rel_free_all (ch->dest_rel);
4454
4455   GNUNET_CONTAINER_DLL_remove (ch->t->channel_head, ch->t->channel_tail, ch);
4456   GNUNET_STATISTICS_update (stats, "# channels", -1, GNUNET_NO);
4457
4458   GNUNET_free (ch);
4459 }
4460
4461 /**
4462  * Create a new channel.
4463  *
4464  * @param t Tunnel this channel is in.
4465  * @param owner Client that owns the channel, NULL for foreign channels.
4466  * @param lid_root Local ID for root client.
4467  *
4468  * @return A new initialized channel. NULL on error.
4469  */
4470 static struct MeshChannel *
4471 channel_new (struct MeshTunnel2 *t,
4472              struct MeshClient *owner, MESH_ChannelNumber lid_root)
4473 {
4474   struct MeshChannel *ch;
4475
4476   ch = GNUNET_new (struct MeshChannel);
4477   ch->root = owner;
4478   ch->lid_root = lid_root;
4479   ch->t = t;
4480
4481   GNUNET_CONTAINER_DLL_insert (t->channel_head, t->channel_tail, ch);
4482
4483   GNUNET_STATISTICS_update (stats, "# channels", 1, GNUNET_NO);
4484
4485   if (NULL != owner)
4486   {
4487     while (NULL != channel_get (t, t->next_chid))
4488       t->next_chid = (t->next_chid + 1) & ~GNUNET_MESH_LOCAL_CHANNEL_ID_CLI;
4489     ch->gid = t->next_chid;
4490     t->next_chid = (t->next_chid + 1) & ~GNUNET_MESH_LOCAL_CHANNEL_ID_CLI;
4491
4492     if(GNUNET_OK !=
4493        GNUNET_CONTAINER_multihashmap32_put (owner->own_channels, lid_root, ch,
4494                                            GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
4495     {
4496       GNUNET_break (0);
4497       channel_destroy (ch);
4498       GNUNET_SERVER_receive_done (owner->handle, GNUNET_SYSERR);
4499       return NULL;
4500     }
4501   }
4502
4503   return ch;
4504 }
4505
4506
4507 /**
4508  * Set options in a channel, extracted from a bit flag field
4509  * 
4510  * @param ch Channel to set options to.
4511  * @param options Bit array in host byte order.
4512  */
4513 static void
4514 channel_set_options (struct MeshChannel *ch, uint32_t options)
4515 {
4516   ch->nobuffer = (options & GNUNET_MESH_OPTION_NOBUFFER) != 0 ?
4517                  GNUNET_YES : GNUNET_NO;
4518   ch->reliable = (options & GNUNET_MESH_OPTION_RELIABLE) != 0 ?
4519                  GNUNET_YES : GNUNET_NO;
4520 }
4521
4522
4523 /**
4524  * Iterator for deleting each channel whose client endpoint disconnected.
4525  *
4526  * @param cls Closure (client that has disconnected).
4527  * @param key The local channel id (used to access the hashmap).
4528  * @param value The value stored at the key (channel to destroy).
4529  *
4530  * @return GNUNET_OK, keep iterating.
4531  */
4532 static int
4533 channel_destroy_iterator (void *cls,
4534                           uint32_t key,
4535                           void *value)
4536 {
4537   struct MeshChannel *ch = value;
4538   struct MeshClient *c = cls;
4539   struct MeshTunnel2 *t;
4540
4541   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4542               " Channel %X (%X / %X) destroy, due to client %u shutdown.\n",
4543               ch->gid, ch->lid_root, ch->lid_dest, c->id);
4544
4545   if (c == ch->dest)
4546   {
4547     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Client %u is destination.\n", c->id);
4548   }
4549   if (c == ch->root)
4550   {
4551     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Client %u is owner.\n", c->id);
4552   }
4553
4554   t = ch->t;
4555   channel_send_destroy (ch);
4556   channel_destroy (ch);
4557   tunnel_destroy_if_empty (t);
4558
4559   return GNUNET_OK;
4560 }
4561
4562
4563 /**
4564  * Remove client's ports from the global hashmap on disconnect.
4565  *
4566  * @param cls Closure (unused).
4567  * @param key Port.
4568  * @param value Client structure.
4569  *
4570  * @return GNUNET_OK, keep iterating.
4571  */
4572 static int
4573 client_release_ports (void *cls,
4574                       uint32_t key,
4575                       void *value)
4576 {
4577   int res;
4578
4579   res = GNUNET_CONTAINER_multihashmap32_remove (ports, key, value);
4580   if (GNUNET_YES != res)
4581   {
4582     GNUNET_break (0);
4583     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4584                 "Port %u by client %p was not registered.\n",
4585                 key, value);
4586   }
4587   return GNUNET_OK;
4588 }
4589
4590
4591 /**
4592  * Timeout function due to lack of keepalive/traffic from the owner.
4593  * Destroys connection if called.
4594  *
4595  * @param cls Closure (connection to destroy).
4596  * @param tc TaskContext.
4597  */
4598 static void
4599 connection_fwd_timeout (void *cls,
4600                         const struct GNUNET_SCHEDULER_TaskContext *tc)
4601 {
4602   struct MeshConnection *c = cls;
4603
4604   c->fwd_maintenance_task = GNUNET_SCHEDULER_NO_TASK;
4605   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
4606     return;
4607   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4608               "Connection %s[%X] FWD timed out. Destroying.\n",
4609               peer2s (c->t->peer),
4610               c->id);
4611
4612   if (connection_is_origin (c, GNUNET_YES)) /* If local, leave. */
4613     return;
4614
4615   connection_destroy (c);
4616 }
4617
4618
4619 /**
4620  * Timeout function due to lack of keepalive/traffic from the destination.
4621  * Destroys connection if called.
4622  *
4623  * @param cls Closure (connection to destroy).
4624  * @param tc TaskContext
4625  */
4626 static void
4627 connection_bck_timeout (void *cls,
4628                         const struct GNUNET_SCHEDULER_TaskContext *tc)
4629 {
4630   struct MeshConnection *c = cls;
4631
4632   c->bck_maintenance_task = GNUNET_SCHEDULER_NO_TASK;
4633   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
4634     return;
4635
4636   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4637               "Connection %s[%X] FWD timed out. Destroying.\n",
4638               peer2s (c->t->peer),
4639               c->id);
4640
4641   if (connection_is_origin (c, GNUNET_NO)) /* If local, leave. */
4642     return;
4643
4644   connection_destroy (c);
4645 }
4646
4647
4648 /**
4649  * Resets the connection timeout task, some other message has done the
4650  * task's job.
4651  * - For the first peer on the direction this means to send
4652  *   a keepalive or a path confirmation message (either create or ACK).
4653  * - For all other peers, this means to destroy the connection,
4654  *   due to lack of activity.
4655  * Starts the tiemout if no timeout was running (connection just created).
4656  *
4657  * @param c Connection whose timeout to reset.
4658  * @param fwd Is this forward?
4659  *
4660  * TODO use heap to improve efficiency of scheduler.
4661  */
4662 static void
4663 connection_reset_timeout (struct MeshConnection *c, int fwd)
4664 {
4665   GNUNET_SCHEDULER_TaskIdentifier *ti;
4666   GNUNET_SCHEDULER_Task f;
4667
4668   ti = fwd ? &c->fwd_maintenance_task : &c->bck_maintenance_task;
4669
4670   if (GNUNET_SCHEDULER_NO_TASK != *ti)
4671     GNUNET_SCHEDULER_cancel (*ti);
4672
4673   if (connection_is_origin (c, fwd)) /* Endpoint */
4674   {
4675     f  = fwd ? &connection_fwd_keepalive : &connection_bck_keepalive;
4676     *ti = GNUNET_SCHEDULER_add_delayed (refresh_connection_time, f, c);
4677   }
4678   else /* Relay */
4679   {
4680     struct GNUNET_TIME_Relative delay;
4681
4682     delay = GNUNET_TIME_relative_multiply (refresh_connection_time, 4);
4683     f  = fwd ? &connection_fwd_timeout : &connection_bck_timeout;
4684     *ti = GNUNET_SCHEDULER_add_delayed (delay, f, c);
4685   }
4686 }
4687
4688
4689 /**
4690  * Iterator to notify all connections of a broken link. Mark connections
4691  * to destroy after all traffic has been sent.
4692  *
4693  * @param cls Closure (peer disconnected).
4694  * @param key Current key code (tid).
4695  * @param value Value in the hash map (connection).
4696  *
4697  * @return GNUNET_YES if we should continue to iterate,
4698  *         GNUNET_NO if not.
4699  */
4700 static int
4701 connection_broken (void *cls,
4702                    const struct GNUNET_HashCode *key,
4703                    void *value)
4704 {
4705   struct MeshPeer *peer = cls;
4706   struct MeshConnection *c = value;
4707   struct GNUNET_MESH_ConnectionBroken msg;
4708   int fwd;
4709
4710   fwd = peer == connection_get_prev_hop (c);
4711
4712   connection_cancel_queues (c, !fwd);
4713   if (connection_is_terminal (c, fwd))
4714   {
4715     /* Local shutdown, no one to notify about this. */
4716     connection_destroy (c);
4717     return GNUNET_YES;
4718   }
4719
4720   msg.header.size = htons (sizeof (struct GNUNET_MESH_ConnectionBroken));
4721   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_CONNECTION_BROKEN);
4722   msg.cid = c->id;
4723   msg.peer1 = my_full_id;
4724   msg.peer2 = *GNUNET_PEER_resolve2 (peer->id);
4725   send_prebuilt_message_connection (&msg.header, c, NULL, fwd);
4726   c->destroy = GNUNET_YES;
4727
4728   return GNUNET_YES;
4729 }
4730
4731 /******************************************************************************/
4732 /****************      MESH NETWORK HANDLER HELPERS     ***********************/
4733 /******************************************************************************/
4734
4735 /**
4736  * Free a transmission that was already queued with all resources
4737  * associated to the request.
4738  *
4739  * @param queue Queue handler to cancel.
4740  * @param clear_cls Is it necessary to free associated cls?
4741  */
4742 static void
4743 queue_destroy (struct MeshPeerQueue *queue, int clear_cls)
4744 {
4745   struct MeshPeer *peer;
4746   struct MeshFlowControl *fc;
4747   int fwd;
4748
4749   fwd = queue->fwd;
4750   peer = queue->peer;
4751   GNUNET_assert (NULL != queue->c);
4752   fc = fwd ? &queue->c->fwd_fc : &queue->c->bck_fc;
4753
4754   if (GNUNET_YES == clear_cls)
4755   {
4756     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   queue destroy type %s\n",
4757                 GNUNET_MESH_DEBUG_M2S (queue->type));
4758     switch (queue->type)
4759     {
4760       case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_DESTROY:
4761       case GNUNET_MESSAGE_TYPE_MESH_TUNNEL_DESTROY:
4762         GNUNET_log (GNUNET_ERROR_TYPE_INFO, "destroying a DESTROY message\n");
4763         GNUNET_break (GNUNET_YES == queue->c->destroy);
4764         /* fall through */
4765       case GNUNET_MESSAGE_TYPE_MESH_FWD:
4766       case GNUNET_MESSAGE_TYPE_MESH_BCK:
4767       case GNUNET_MESSAGE_TYPE_MESH_ACK:
4768       case GNUNET_MESSAGE_TYPE_MESH_POLL:
4769       case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_ACK:
4770       case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_CREATE:
4771       case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_BROKEN:
4772         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   prebuilt message\n");;
4773         GNUNET_free_non_null (queue->cls);
4774         break;
4775
4776       default:
4777         GNUNET_break (0);
4778         GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "   type %s unknown!\n",
4779                     GNUNET_MESH_DEBUG_M2S (queue->type));
4780     }
4781
4782   }
4783   GNUNET_CONTAINER_DLL_remove (peer->queue_head, peer->queue_tail, queue);
4784
4785   if (queue->type != GNUNET_MESSAGE_TYPE_MESH_ACK &&
4786       queue->type != GNUNET_MESSAGE_TYPE_MESH_POLL)
4787   {
4788     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Q_N- %p %u\n", fc, fc->queue_n);
4789     fc->queue_n--;
4790     peer->queue_n--;
4791   }
4792   if (NULL != queue->c)
4793   {
4794     queue->c->pending_messages--;
4795     if (NULL != queue->c->t)
4796     {
4797       queue->c->t->pending_messages--;
4798     }
4799   }
4800
4801   GNUNET_free (queue);
4802 }
4803
4804
4805 static size_t
4806 queue_send (void *cls, size_t size, void *buf)
4807 {
4808   struct MeshPeer *peer = cls;
4809   struct MeshFlowControl *fc;
4810   struct MeshConnection *c;
4811   struct GNUNET_MessageHeader *msg;
4812   struct MeshPeerQueue *queue;
4813   struct MeshTunnel2 *t;
4814   struct MeshChannel *ch;
4815   const struct GNUNET_PeerIdentity *dst_id;
4816   size_t data_size;
4817   uint32_t pid;
4818   uint16_t type;
4819   int fwd;
4820
4821   peer->core_transmit = NULL;
4822   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* Queue send (max %u)\n", size);
4823
4824   if (NULL == buf || 0 == size)
4825   {
4826     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* Buffer size 0.\n");
4827     return 0;
4828   }
4829
4830   /* Initialize */
4831   queue = peer_get_first_message (peer);
4832   if (NULL == queue)
4833   {
4834     GNUNET_break (0); /* Core tmt_rdy should've been canceled */
4835     return 0;
4836   }
4837   c = queue->c;
4838   fwd = queue->fwd;
4839   fc = fwd ? &c->fwd_fc : &c->bck_fc;
4840
4841
4842   dst_id = GNUNET_PEER_resolve2 (peer->id);
4843   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*   towards %s\n", GNUNET_i2s (dst_id));
4844   /* Check if buffer size is enough for the message */
4845   if (queue->size > size)
4846   {
4847       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*   not enough room, reissue\n");
4848       peer->core_transmit =
4849           GNUNET_CORE_notify_transmit_ready (core_handle,
4850                                              GNUNET_NO,
4851                                              0,
4852                                              GNUNET_TIME_UNIT_FOREVER_REL,
4853                                              dst_id,
4854                                              queue->size,
4855                                              &queue_send,
4856                                              peer);
4857       return 0;
4858   }
4859   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*   size %u ok\n", queue->size);
4860
4861   t = (NULL != c) ? c->t : NULL;
4862   type = 0;
4863
4864   /* Fill buf */
4865   switch (queue->type)
4866   {
4867     case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_DESTROY:
4868     case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_BROKEN:
4869     case GNUNET_MESSAGE_TYPE_MESH_FWD:
4870     case GNUNET_MESSAGE_TYPE_MESH_BCK:
4871     case GNUNET_MESSAGE_TYPE_MESH_ACK:
4872     case GNUNET_MESSAGE_TYPE_MESH_POLL:
4873       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4874                   "*   raw: %s\n",
4875                   GNUNET_MESH_DEBUG_M2S (queue->type));
4876       data_size = send_core_data_raw (queue->cls, size, buf);
4877       msg = (struct GNUNET_MessageHeader *) buf;
4878       type = ntohs (msg->type);
4879       break;
4880     case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_CREATE:
4881       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*   path create\n");
4882       if (connection_is_origin (c, GNUNET_YES))
4883         data_size = send_core_connection_create (queue->c, size, buf);
4884       else
4885         data_size = send_core_data_raw (queue->cls, size, buf);
4886       break;
4887     case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_ACK:
4888       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*   path ack\n");
4889       if (connection_is_origin (c, GNUNET_NO) ||
4890           connection_is_origin (c, GNUNET_YES))
4891         data_size = send_core_connection_ack (queue->c, size, buf);
4892       else
4893         data_size = send_core_data_raw (queue->cls, size, buf);
4894       break;
4895     case GNUNET_MESSAGE_TYPE_MESH_DATA:
4896     case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_CREATE:
4897     case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_DESTROY:
4898       /* This should be encapsulted */
4899       GNUNET_break (0);
4900       data_size = 0;
4901       break;
4902     default:
4903       GNUNET_break (0);
4904       GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "*   type unknown: %u\n",
4905                   queue->type);
4906       data_size = 0;
4907   }
4908
4909   if (0 < drop_percent &&
4910       GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, 101) < drop_percent)
4911   {
4912     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4913                 "Dropping message of type %s\n",
4914                 GNUNET_MESH_DEBUG_M2S (queue->type));
4915     data_size = 0;
4916   }
4917
4918   /* Free queue, but cls was freed by send_core_* */
4919   ch = queue->ch;
4920   queue_destroy (queue, GNUNET_NO);
4921
4922   /* Send ACK if needed, after accounting for sent ID in fc->queue_n */
4923   switch (type)
4924   {
4925     case GNUNET_MESSAGE_TYPE_MESH_FWD:
4926     case GNUNET_MESSAGE_TYPE_MESH_BCK:
4927       pid = ntohl ( ((struct GNUNET_MESH_Encrypted *) buf)->pid );
4928       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*   accounting pid %u\n", pid);
4929       fc->last_pid_sent = pid;
4930       send_ack (c, ch, fwd);
4931       break;
4932     default:
4933       break;
4934   }
4935
4936   /* If more data in queue, send next */
4937   queue = peer_get_first_message (peer);
4938   if (NULL != queue)
4939   {
4940     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*   more data!\n");
4941     if (NULL == peer->core_transmit) {
4942       peer->core_transmit =
4943           GNUNET_CORE_notify_transmit_ready(core_handle,
4944                                             0,
4945                                             0,
4946                                             GNUNET_TIME_UNIT_FOREVER_REL,
4947                                             dst_id,
4948                                             queue->size,
4949                                             &queue_send,
4950                                             peer);
4951     }
4952     else
4953     {
4954       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4955                   "*   tmt rdy called somewhere else\n");
4956     }
4957     if (GNUNET_SCHEDULER_NO_TASK == fc->poll_task)
4958     {
4959       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*   starting poll timeout\n");
4960       fc->poll_task =
4961           GNUNET_SCHEDULER_add_delayed (fc->poll_time, &connection_poll, fc);
4962     }
4963   }
4964   else
4965   {
4966     if (GNUNET_SCHEDULER_NO_TASK != fc->poll_task)
4967     {
4968       GNUNET_SCHEDULER_cancel (fc->poll_task);
4969       fc->poll_task = GNUNET_SCHEDULER_NO_TASK;
4970     }
4971   }
4972   if (NULL != c)
4973   {
4974     c->pending_messages--;
4975     if (GNUNET_YES == c->destroy && 0 == c->pending_messages)
4976     {
4977       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*  destroying connection!\n");
4978       connection_destroy (c);
4979     }
4980   }
4981
4982   if (NULL != t)
4983   {
4984     t->pending_messages--;
4985     if (GNUNET_YES == t->destroy && 0 == t->pending_messages)
4986     {
4987 //       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*  destroying tunnel!\n");
4988       tunnel_destroy (t);
4989     }
4990   }
4991   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*  Return %d\n", data_size);
4992   return data_size;
4993 }
4994
4995
4996 static void
4997 queue_add (void *cls, uint16_t type, size_t size,
4998            struct MeshConnection *c,
4999            struct MeshChannel *ch,
5000            int fwd)
5001 {
5002   struct MeshPeerQueue *queue;
5003   struct MeshFlowControl *fc;
5004   struct MeshPeer *peer;
5005   int priority;
5006   int call_core;
5007
5008   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5009               "queue add %s %s (%u) on c %p, ch %p\n",
5010               fwd ? "FWD" : "BCK",  GNUNET_MESH_DEBUG_M2S (type), size, c, ch);
5011   GNUNET_assert (NULL != c);
5012
5013   fc   = fwd ? &c->fwd_fc : &c->bck_fc;
5014   peer = fwd ? connection_get_next_hop (c) : connection_get_prev_hop (c);
5015
5016   if (NULL == fc)
5017   {
5018     GNUNET_break (0);
5019     return;
5020   }
5021
5022   priority = 0;
5023
5024   if (GNUNET_MESSAGE_TYPE_MESH_POLL == type ||
5025       GNUNET_MESSAGE_TYPE_MESH_ACK == type)
5026   {
5027     priority = 100;
5028   }
5029
5030   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "priority %d\n", priority);
5031   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "fc %p\n", fc);
5032   if (fc->queue_n >= fc->queue_max && 0 == priority)
5033   {
5034     GNUNET_STATISTICS_update (stats, "# messages dropped (buffer full)",
5035                               1, GNUNET_NO);
5036     GNUNET_break (0);
5037     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5038                 "queue full: %u/%u\n",
5039                 fc->queue_n, fc->queue_max);
5040     return; /* Drop this message */
5041   }
5042
5043   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "last pid %u\n", fc->last_pid_sent);
5044   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "     ack %u\n", fc->last_ack_recv);
5045   if (GMC_is_pid_bigger (fc->last_pid_sent + 1, fc->last_ack_recv))
5046   {
5047     call_core = GNUNET_NO;
5048     if (GNUNET_SCHEDULER_NO_TASK == fc->poll_task &&
5049         GNUNET_MESSAGE_TYPE_MESH_POLL != type)
5050     {
5051       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5052                   "no buffer space (%u > %u): starting poll\n",
5053                   fc->last_pid_sent + 1, fc->last_ack_recv);
5054       fc->poll_task = GNUNET_SCHEDULER_add_delayed (fc->poll_time,
5055                                                     &connection_poll,
5056                                                     fc);
5057     }
5058   }
5059   else
5060     call_core = GNUNET_YES;
5061   queue = GNUNET_malloc (sizeof (struct MeshPeerQueue));
5062   queue->cls = cls;
5063   queue->type = type;
5064   queue->size = size;
5065   queue->peer = peer;
5066   queue->c = c;
5067   queue->ch = ch;
5068   queue->fwd = fwd;
5069   if (100 <= priority)
5070   {
5071     GNUNET_CONTAINER_DLL_insert (peer->queue_head, peer->queue_tail, queue);
5072   }
5073   else
5074   {
5075     GNUNET_CONTAINER_DLL_insert_tail (peer->queue_head, peer->queue_tail, queue);
5076     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Q_N+ %p %u\n", fc, fc->queue_n);
5077     fc->queue_n++;
5078     peer->queue_n++;
5079   }
5080
5081   if (NULL == peer->core_transmit && GNUNET_YES == call_core)
5082   {
5083     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5084                 "calling core tmt rdy towards %s for %u bytes\n",
5085                 peer2s (peer), size);
5086     peer->core_transmit =
5087         GNUNET_CORE_notify_transmit_ready (core_handle,
5088                                            0,
5089                                            0,
5090                                            GNUNET_TIME_UNIT_FOREVER_REL,
5091                                            GNUNET_PEER_resolve2 (peer->id),
5092                                            size,
5093                                            &queue_send,
5094                                            peer);
5095   }
5096   else
5097   {
5098     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5099                 "core tmt rdy towards %s already called\n",
5100                 peer2s (peer));
5101
5102   }
5103   c->pending_messages++;
5104   if (NULL != c->t)
5105     c->t->pending_messages++;
5106 }
5107
5108
5109 /******************************************************************************/
5110 /********************      MESH NETWORK HANDLERS     **************************/
5111 /******************************************************************************/
5112
5113
5114 /**
5115  * Generic handler for mesh network payload traffic.
5116  *
5117  * @param t Tunnel on which we got this message.
5118  * @param message Unencryted data message.
5119  * @param fwd Is this FWD traffic? GNUNET_YES : GNUNET_NO;
5120  */
5121 static void
5122 handle_data (struct MeshTunnel2 *t, const struct GNUNET_MESH_Data *msg, int fwd)
5123 {
5124   struct MeshChannelReliability *rel;
5125   struct MeshChannel *ch;
5126   struct MeshClient *c;
5127   uint32_t mid;
5128   uint16_t type;
5129   size_t size;
5130
5131   /* Check size */
5132   size = ntohs (msg->header.size);
5133   if (size <
5134       sizeof (struct GNUNET_MESH_Data) +
5135       sizeof (struct GNUNET_MessageHeader))
5136   {
5137     GNUNET_break (0);
5138     return;
5139   }
5140   type = ntohs (msg->header.type);
5141   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a %s message\n",
5142               GNUNET_MESH_DEBUG_M2S (type));
5143   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " payload of type %s\n",
5144               GNUNET_MESH_DEBUG_M2S (ntohs (msg[1].header.type)));
5145
5146   /* Check channel */
5147   ch = channel_get (t, ntohl (msg->chid));
5148   if (NULL == ch)
5149   {
5150     GNUNET_STATISTICS_update (stats, "# data on unknown channel", 1, GNUNET_NO);
5151     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel unknown\n");
5152     return;
5153   }
5154
5155   /*  Initialize FWD/BCK data */
5156   c        = fwd ? ch->dest     : ch->root;
5157   rel      = fwd ? ch->dest_rel : ch->root_rel;
5158
5159   if (NULL == c)
5160   {
5161     GNUNET_break (0);
5162     return;
5163   }
5164
5165   tunnel_change_state (t, MESH_TUNNEL_READY);
5166
5167   GNUNET_STATISTICS_update (stats, "# data received", 1, GNUNET_NO);
5168
5169   mid = ntohl (msg->mid);
5170   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " mid %u\n", mid);
5171
5172   if (GNUNET_NO == ch->reliable ||
5173       ( !GMC_is_pid_bigger (rel->mid_recv, mid) &&
5174         GMC_is_pid_bigger (rel->mid_recv + 64, mid) ) )
5175   {
5176     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! RECV %u\n", mid);
5177     if (GNUNET_YES == ch->reliable)
5178     {
5179       /* Is this the exact next expected messasge? */
5180       if (mid == rel->mid_recv)
5181       {
5182         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "as expected\n");
5183         rel->mid_recv++;
5184         channel_send_client_data (ch, msg, fwd);
5185       }
5186       else
5187       {
5188         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "save for later\n");
5189         channel_rel_add_buffered_data (msg, rel);
5190       }
5191     }
5192     else
5193     {
5194       /* Tunnel is unreliable: send to clients directly */
5195       /* FIXME: accept Out Of Order traffic */
5196       rel->mid_recv = mid + 1;
5197       channel_send_client_data (ch, msg, fwd);
5198     }
5199   }
5200   else
5201   {
5202     GNUNET_break_op (0);
5203     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5204                 " MID %u not expected (%u - %u), dropping!\n",
5205                 mid, rel->mid_recv, rel->mid_recv + 64);
5206   }
5207
5208   channel_send_data_ack (ch, fwd);
5209 }
5210
5211 /**
5212  * Handler for mesh network traffic end-to-end ACKs.
5213  *
5214  * @param t Tunnel on which we got this message.
5215  * @param message Data message.
5216  * @param fwd Is this a fwd ACK? (dest->orig)
5217  */
5218 static void
5219 handle_data_ack (struct MeshTunnel2 *t,
5220                  const struct GNUNET_MESH_DataACK *msg, int fwd)
5221 {
5222   struct MeshChannelReliability *rel;
5223   struct MeshReliableMessage *copy;
5224   struct MeshReliableMessage *next;
5225   struct MeshChannel *ch;
5226   uint32_t ack;
5227   uint16_t type;
5228   int work;
5229
5230   type = ntohs (msg->header.type);
5231   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a %s message!\n",
5232               GNUNET_MESH_DEBUG_M2S (type));
5233   ch = channel_get (t, ntohl (msg->chid));
5234   if (NULL == ch)
5235   {
5236     GNUNET_STATISTICS_update (stats, "# ack on unknown channel", 1, GNUNET_NO);
5237     return;
5238   }
5239   ack = ntohl (msg->mid);
5240   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! %s ACK %u\n",
5241               (GNUNET_YES == fwd) ? "FWD" : "BCK", ack);
5242
5243   if (GNUNET_YES == fwd)
5244   {
5245     rel = ch->root_rel;
5246   }
5247   else
5248   {
5249     rel = ch->dest_rel;
5250   }
5251   if (NULL == rel)
5252   {
5253     GNUNET_break (0);
5254     return;
5255   }
5256
5257   for (work = GNUNET_NO, copy = rel->head_sent; copy != NULL; copy = next)
5258   {
5259     if (GMC_is_pid_bigger (copy->mid, ack))
5260     {
5261       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!!  head %u, out!\n", copy->mid);
5262       channel_rel_free_sent (rel, msg);
5263       break;
5264     }
5265     work = GNUNET_YES;
5266     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!!  id %u\n", copy->mid);
5267     next = copy->next;
5268     rel_message_free (copy);
5269   }
5270   /* ACK client if needed */
5271 //   channel_send_ack (t, type, GNUNET_MESSAGE_TYPE_MESH_UNICAST_ACK == type);
5272
5273   /* If some message was free'd, update the retransmission delay*/
5274   if (GNUNET_YES == work)
5275   {
5276     if (GNUNET_SCHEDULER_NO_TASK != rel->retry_task)
5277     {
5278       GNUNET_SCHEDULER_cancel (rel->retry_task);
5279       if (NULL == rel->head_sent)
5280       {
5281         rel->retry_task = GNUNET_SCHEDULER_NO_TASK;
5282       }
5283       else
5284       {
5285         struct GNUNET_TIME_Absolute new_target;
5286         struct GNUNET_TIME_Relative delay;
5287
5288         delay = GNUNET_TIME_relative_multiply (rel->retry_timer,
5289                                                MESH_RETRANSMIT_MARGIN);
5290         new_target = GNUNET_TIME_absolute_add (rel->head_sent->timestamp,
5291                                                delay);
5292         delay = GNUNET_TIME_absolute_get_remaining (new_target);
5293         rel->retry_task =
5294             GNUNET_SCHEDULER_add_delayed (delay,
5295                                           &channel_retransmit_message,
5296                                           rel);
5297       }
5298     }
5299     else
5300       GNUNET_break (0);
5301   }
5302 }
5303
5304
5305 /**
5306  * Core handler for connection creation.
5307  *
5308  * @param cls Closure (unused).
5309  * @param peer Sender (neighbor).
5310  * @param message Message.
5311  *
5312  * @return GNUNET_OK to keep the connection open,
5313  *         GNUNET_SYSERR to close it (signal serious error)
5314  */
5315 static int
5316 handle_mesh_connection_create (void *cls,
5317                                const struct GNUNET_PeerIdentity *peer,
5318                                const struct GNUNET_MessageHeader *message)
5319 {
5320   struct GNUNET_MESH_ConnectionCreate *msg;
5321   struct GNUNET_PeerIdentity *id;
5322   struct GNUNET_HashCode *cid;
5323   struct MeshPeerPath *path;
5324   struct MeshPeer *dest_peer;
5325   struct MeshPeer *orig_peer;
5326   struct MeshConnection *c;
5327   unsigned int own_pos;
5328   uint16_t size;
5329   uint16_t i;
5330
5331   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "\n\n");
5332   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received a connection create msg\n");
5333
5334   /* Check size */
5335   size = ntohs (message->size);
5336   if (size < sizeof (struct GNUNET_MESH_ConnectionCreate))
5337   {
5338     GNUNET_break_op (0);
5339     return GNUNET_OK;
5340   }
5341
5342   /* Calculate hops */
5343   size -= sizeof (struct GNUNET_MESH_ConnectionCreate);
5344   if (size % sizeof (struct GNUNET_PeerIdentity))
5345   {
5346     GNUNET_break_op (0);
5347     return GNUNET_OK;
5348   }
5349   size /= sizeof (struct GNUNET_PeerIdentity);
5350   if (1 > size)
5351   {
5352     GNUNET_break_op (0);
5353     return GNUNET_OK;
5354   }
5355   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "    path has %u hops.\n", size);
5356
5357   /* Get parameters */
5358   msg = (struct GNUNET_MESH_ConnectionCreate *) message;
5359   cid = &msg->cid;
5360   id = (struct GNUNET_PeerIdentity *) &msg[1];
5361   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5362               "    connection %s (%s).\n",
5363               GNUNET_h2s (cid), GNUNET_i2s (id));
5364
5365   /* Create connection */
5366   c = connection_get (cid);
5367   if (NULL == c)
5368   {
5369     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Creating connection\n");
5370     c = connection_new (cid);
5371     if (NULL == c)
5372       return GNUNET_OK;
5373     connection_reset_timeout (c, GNUNET_YES);
5374
5375     /* Create path */
5376     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Creating path...\n");
5377     path = path_new (size);
5378     own_pos = 0;
5379     for (i = 0; i < size; i++)
5380     {
5381       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  ... adding %s\n",
5382                   GNUNET_i2s (&id[i]));
5383       path->peers[i] = GNUNET_PEER_intern (&id[i]);
5384       if (path->peers[i] == myid)
5385         own_pos = i;
5386     }
5387     if (own_pos == 0 && path->peers[own_pos] != myid)
5388     {
5389       /* create path: self not found in path through self */
5390       GNUNET_break_op (0);
5391       path_destroy (path);
5392       connection_destroy (c);
5393       return GNUNET_OK;
5394     }
5395     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Own position: %u\n", own_pos);
5396     path_add_to_peers (path, GNUNET_NO);
5397     c->path = path_duplicate (path);
5398     c->own_pos = own_pos;
5399   }
5400   else
5401   {
5402     path = NULL;
5403   }
5404   if (MESH_CONNECTION_NEW == c->state)
5405     connection_change_state (c, MESH_CONNECTION_SENT);
5406
5407   /* Remember peers */
5408   dest_peer = peer_get (&id[size - 1]);
5409   orig_peer = peer_get (&id[0]);
5410
5411   /* Is it a connection to us? */
5412   if (c->own_pos == size - 1)
5413   {
5414     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  It's for us!\n");
5415     peer_add_path_to_origin (orig_peer, path, GNUNET_YES);
5416
5417     if (NULL == orig_peer->tunnel)
5418     {
5419       orig_peer->tunnel = tunnel_new ();
5420       orig_peer->tunnel->peer = orig_peer;
5421     }
5422     tunnel_add_connection (orig_peer->tunnel, c);
5423     if (MESH_TUNNEL_NEW == c->t->state)
5424       tunnel_change_state (c->t,  MESH_TUNNEL_WAITING);
5425
5426     send_connection_ack (c, GNUNET_NO);
5427     if (MESH_CONNECTION_SENT == c->state)
5428       connection_change_state (c, MESH_CONNECTION_ACK);
5429
5430     /* Keep tunnel alive in direction dest->owner*/
5431     connection_reset_timeout (c, GNUNET_NO);
5432   }
5433   else
5434   {
5435     /* It's for somebody else! Retransmit. */
5436     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Retransmitting.\n");
5437     peer_add_path (dest_peer, path_duplicate (path), GNUNET_NO);
5438     peer_add_path_to_origin (orig_peer, path, GNUNET_NO);
5439     send_prebuilt_message_connection (message, c, NULL, GNUNET_YES);
5440   }
5441   return GNUNET_OK;
5442 }
5443
5444
5445 /**
5446  * Core handler for path ACKs
5447  *
5448  * @param cls closure
5449  * @param message message
5450  * @param peer peer identity this notification is about
5451  *
5452  * @return GNUNET_OK to keep the connection open,
5453  *         GNUNET_SYSERR to close it (signal serious error)
5454  */
5455 static int
5456 handle_mesh_connection_ack (void *cls, const struct GNUNET_PeerIdentity *peer,
5457                             const struct GNUNET_MessageHeader *message)
5458 {
5459   struct GNUNET_MESH_ConnectionACK *msg;
5460   struct MeshConnection *c;
5461   struct MeshPeerPath *p;
5462   struct MeshPeer *pi;
5463   int fwd;
5464
5465   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "\n\n");
5466   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received a connection ACK msg\n");
5467   msg = (struct GNUNET_MESH_ConnectionACK *) message;
5468   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on connection %s\n",
5469               GNUNET_h2s (&msg->cid));
5470   c = connection_get (&msg->cid);
5471   if (NULL == c)
5472   {
5473     GNUNET_STATISTICS_update (stats, "# control on unknown connection",
5474                               1, GNUNET_NO);
5475     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  don't know the connection!\n");
5476     return GNUNET_OK;
5477   }
5478
5479
5480   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  via peer %s\n",
5481               GNUNET_i2s (peer));
5482   pi = peer_get (peer);
5483   if (connection_get_next_hop (c) == pi)
5484   {
5485     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  SYNACK\n");
5486     fwd = GNUNET_NO;
5487     if (MESH_CONNECTION_SENT == c->state)
5488       connection_change_state (c, MESH_CONNECTION_ACK);
5489   }
5490   else if (connection_get_prev_hop (c) == pi)
5491   {
5492     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  ACK\n");
5493     fwd = GNUNET_YES;
5494     connection_change_state (c, MESH_CONNECTION_READY);
5495   }
5496   else
5497   {
5498     GNUNET_break_op (0);
5499     return GNUNET_OK;
5500   }
5501   connection_reset_timeout (c, fwd);
5502
5503   /* Add path to peers? */
5504   p = c->path;
5505   if (NULL != p)
5506   {
5507     path_add_to_peers (p, GNUNET_YES);
5508   }
5509   else
5510   {
5511     GNUNET_break (0);
5512   }
5513
5514   /* Message for us as creator? */
5515   if (connection_is_origin (c, GNUNET_YES))
5516   {
5517     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Connection (SYN)ACK for us!\n");
5518     connection_change_state (c, MESH_CONNECTION_READY);
5519     if (MESH_TUNNEL_READY != c->t->state)
5520       tunnel_change_state (c->t, MESH_TUNNEL_READY);
5521     send_connection_ack (c, GNUNET_YES);
5522     tunnel_send_queued_data (c->t, GNUNET_YES);
5523     if (3 <= tunnel_count_connections (c->t) && NULL != c->t->peer->dhtget)
5524     {
5525       GNUNET_DHT_get_stop (c->t->peer->dhtget);
5526       c->t->peer->dhtget = NULL;
5527     }
5528     return GNUNET_OK;
5529   }
5530
5531   /* Message for us as destination? */
5532   if (connection_is_terminal (c, GNUNET_YES))
5533   {
5534     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Connection ACK for us!\n");
5535     if (MESH_TUNNEL_READY != c->t->state)
5536       tunnel_change_state (c->t, MESH_TUNNEL_READY);
5537     connection_change_state (c, MESH_CONNECTION_READY);
5538     tunnel_send_queued_data (c->t, GNUNET_NO);
5539     return GNUNET_OK;
5540   }
5541
5542   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  not for us, retransmitting...\n");
5543   send_prebuilt_message_connection (message, c, NULL, fwd);
5544   return GNUNET_OK;
5545 }
5546
5547
5548 /**
5549  * Core handler for notifications of broken paths
5550  *
5551  * @param cls Closure (unused).
5552  * @param peer Peer identity of sending neighbor.
5553  * @param message Message.
5554  *
5555  * @return GNUNET_OK to keep the connection open,
5556  *         GNUNET_SYSERR to close it (signal serious error)
5557  */
5558 static int
5559 handle_mesh_connection_broken (void *cls, const struct GNUNET_PeerIdentity *peer,
5560                                const struct GNUNET_MessageHeader *message)
5561 {
5562   struct GNUNET_MESH_ConnectionBroken *msg;
5563   struct MeshConnection *c;
5564
5565   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5566               "Received a CONNECTION BROKEN msg from %s\n", GNUNET_i2s (peer));
5567   msg = (struct GNUNET_MESH_ConnectionBroken *) message;
5568   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  regarding %s\n",
5569               GNUNET_i2s (&msg->peer1));
5570   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  regarding %s\n",
5571               GNUNET_i2s (&msg->peer2));
5572   c = connection_get (&msg->cid);
5573   if (NULL == c)
5574   {
5575     GNUNET_break_op (0);
5576     return GNUNET_OK;
5577   }
5578   tunnel_notify_connection_broken (c->t, GNUNET_PEER_search (&msg->peer1),
5579                                    GNUNET_PEER_search (&msg->peer2));
5580   return GNUNET_OK;
5581
5582 }
5583
5584
5585 /**
5586  * Core handler for tunnel destruction
5587  *
5588  * @param cls Closure (unused).
5589  * @param peer Peer identity of sending neighbor.
5590  * @param message Message.
5591  *
5592  * @return GNUNET_OK to keep the connection open,
5593  *         GNUNET_SYSERR to close it (signal serious error)
5594  */
5595 static int
5596 handle_mesh_connection_destroy (void *cls,
5597                                 const struct GNUNET_PeerIdentity *peer,
5598                                 const struct GNUNET_MessageHeader *message)
5599 {
5600   struct GNUNET_MESH_ConnectionDestroy *msg;
5601   struct MeshConnection *c;
5602   GNUNET_PEER_Id id;
5603   int fwd;
5604
5605   msg = (struct GNUNET_MESH_ConnectionDestroy *) message;
5606   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5607               "Got a CONNECTION DESTROY message from %s\n",
5608               GNUNET_i2s (peer));
5609   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5610               "  for connection %s\n",
5611               GNUNET_h2s (&msg->cid));
5612   c = connection_get (&msg->cid);
5613   if (NULL == c)
5614   {
5615     /* Probably already got the message from another path,
5616      * destroyed the tunnel and retransmitted to children.
5617      * Safe to ignore.
5618      */
5619     GNUNET_STATISTICS_update (stats, "# control on unknown tunnel",
5620                               1, GNUNET_NO);
5621     return GNUNET_OK;
5622   }
5623   id = GNUNET_PEER_search (peer);
5624   if (id == connection_get_prev_hop (c)->id)
5625     fwd = GNUNET_YES;
5626   else if (id == connection_get_next_hop (c)->id)
5627     fwd = GNUNET_NO;
5628   else
5629   {
5630     GNUNET_break_op (0);
5631     return GNUNET_OK;
5632   }
5633   send_prebuilt_message_connection (message, c, NULL, fwd);
5634   c->destroy = GNUNET_YES;
5635
5636   return GNUNET_OK;
5637 }
5638
5639
5640 /**
5641  * Handler for channel create messages.
5642  *
5643  * @param t Tunnel this channel is to be created in.
5644  * @param msg Message.
5645  * @param fwd Is this FWD traffic? GNUNET_YES : GNUNET_NO;
5646  */
5647 static void
5648 handle_channel_create (struct MeshTunnel2 *t,
5649                        struct GNUNET_MESH_ChannelCreate *msg,
5650                        int fwd)
5651 {
5652   MESH_ChannelNumber chid;
5653   struct MeshChannel *ch;
5654   struct MeshClient *c;
5655   uint32_t port;
5656
5657   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received Channel Create\n");
5658   /* Check message size */
5659   if (ntohs (msg->header.size) != sizeof (struct GNUNET_MESH_ChannelCreate))
5660   {
5661     GNUNET_break_op (0);
5662     return;
5663   }
5664
5665   /* Check if channel exists */
5666   chid = ntohl (msg->chid);
5667   ch = channel_get (t, chid);
5668   if (NULL != ch)
5669   {
5670     /* Probably a retransmission, safe to ignore */
5671     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   already exists...\n");
5672     if (NULL != ch->dest)
5673     {
5674       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   duplicate CC!!\n");
5675       channel_send_ack (ch, !fwd);
5676       return;
5677     }
5678   }
5679   else
5680   {
5681     /* Create channel */
5682     ch = channel_new (t, NULL, 0);
5683     channel_set_options (ch, ntohl (msg->opt));
5684   }
5685
5686   /* Find a destination client */
5687   port = ntohl (msg->port);
5688   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   port %u\n", port);
5689   c = GNUNET_CONTAINER_multihashmap32_get (ports, port);
5690   if (NULL == c)
5691   {
5692     /* TODO send reject */
5693     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  no client has port registered\n");
5694     /* TODO free ch */
5695     return;
5696   }
5697
5698   channel_add_client (ch, c);
5699   if (GNUNET_YES == ch->reliable)
5700     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! Reliable\n");
5701
5702   send_local_channel_create (ch);
5703   channel_send_ack (ch, fwd);
5704   send_local_ack (ch, !fwd);
5705 }
5706
5707
5708 /**
5709  * Handler for channel ack messages.
5710  *
5711  * @param t Tunnel this channel is to be created in.
5712  * @param msg Message.
5713  * @param fwd Is this FWD traffic? GNUNET_YES : GNUNET_NO;
5714  */
5715 static void
5716 handle_channel_ack (struct MeshTunnel2 *t,
5717                     struct GNUNET_MESH_ChannelManage *msg,
5718                     int fwd)
5719 {
5720   MESH_ChannelNumber chid;
5721   struct MeshChannel *ch;
5722
5723   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received Channel ACK\n");
5724   /* Check message size */
5725   if (ntohs (msg->header.size) != sizeof (struct GNUNET_MESH_ChannelManage))
5726   {
5727     GNUNET_break_op (0);
5728     return;
5729   }
5730
5731   /* Check if channel exists */
5732   chid = ntohl (msg->chid);
5733   ch = channel_get (t, chid);
5734   if (NULL == ch)
5735   {
5736     GNUNET_break_op (0);
5737     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   channel %u unknown!!\n", chid);
5738     return;
5739   }
5740
5741   channel_confirm (ch, !fwd);
5742 }
5743
5744
5745 /**
5746  * Handler for channel destroy messages.
5747  *
5748  * @param t Tunnel this channel is to be destroyed of.
5749  * @param msg Message.
5750  * @param fwd Is this FWD traffic? GNUNET_YES : GNUNET_NO;
5751  */
5752 static void
5753 handle_channel_destroy (struct MeshTunnel2 *t,
5754                         struct GNUNET_MESH_ChannelManage *msg,
5755                         int fwd)
5756 {
5757   MESH_ChannelNumber chid;
5758   struct MeshChannel *ch;
5759
5760   /* Check message size */
5761   if (ntohs (msg->header.size) != sizeof (struct GNUNET_MESH_ChannelManage))
5762   {
5763     GNUNET_break_op (0);
5764     return;
5765   }
5766
5767   /* Check if channel exists */
5768   chid = ntohl (msg->chid);
5769   ch = channel_get (t, chid);
5770   if (NULL == ch)
5771   {
5772     /* Probably a retransmission, safe to ignore */
5773     return;
5774   }
5775
5776   send_local_channel_destroy (ch, fwd);
5777   channel_destroy (ch);
5778 }
5779
5780
5781 static void
5782 handle_decrypted (struct MeshTunnel2 *t,
5783                   const struct GNUNET_MessageHeader *msgh,
5784                   int fwd)
5785 {
5786   switch (ntohs (msgh->type))
5787   {
5788     case GNUNET_MESSAGE_TYPE_MESH_DATA:
5789       /* Don't send hop ACK, wait for client to ACK */
5790       handle_data (t, (struct GNUNET_MESH_Data *) msgh, fwd);
5791       break;
5792
5793     case GNUNET_MESSAGE_TYPE_MESH_DATA_ACK:
5794       handle_data_ack (t, (struct GNUNET_MESH_DataACK *) msgh, fwd);
5795       break;
5796
5797     case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_CREATE:
5798       handle_channel_create (t,
5799                              (struct GNUNET_MESH_ChannelCreate *) msgh,
5800                              fwd);
5801       break;
5802
5803     case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_ACK:
5804       handle_channel_ack (t,
5805                           (struct GNUNET_MESH_ChannelManage *) msgh,
5806                           fwd);
5807       break;
5808
5809     case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_DESTROY:
5810       handle_channel_destroy (t,
5811                               (struct GNUNET_MESH_ChannelManage *) msgh,
5812                               fwd);
5813       break;
5814
5815     default:
5816       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5817                   "end-to-end message not known (%u)\n",
5818                   ntohs (msgh->type));
5819   }
5820 }
5821
5822
5823 /**
5824  * Generic handler for mesh network encrypted traffic.
5825  *
5826  * @param peer Peer identity this notification is about.
5827  * @param message Encrypted message.
5828  * @param fwd Is this FWD traffic? GNUNET_YES : GNUNET_NO;
5829  *
5830  * @return GNUNET_OK to keep the connection open,
5831  *         GNUNET_SYSERR to close it (signal serious error)
5832  */
5833 static int
5834 handle_mesh_encrypted (const struct GNUNET_PeerIdentity *peer,
5835                        const struct GNUNET_MESH_Encrypted *msg,
5836                        int fwd)
5837 {
5838   struct MeshConnection *c;
5839   struct MeshTunnel2 *t;
5840   struct MeshPeer *neighbor;
5841   struct MeshFlowControl *fc;
5842   uint32_t pid;
5843   uint32_t ttl;
5844   uint16_t type;
5845   size_t size;
5846
5847   /* Check size */
5848   size = ntohs (msg->header.size);
5849   if (size <
5850       sizeof (struct GNUNET_MESH_Encrypted) +
5851       sizeof (struct GNUNET_MessageHeader))
5852   {
5853     GNUNET_break_op (0);
5854     return GNUNET_OK;
5855   }
5856   type = ntohs (msg->header.type);
5857   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "\n\n");
5858   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a %s message from %s\n",
5859               GNUNET_MESH_DEBUG_M2S (type), GNUNET_i2s (peer));
5860
5861   /* Check connection */
5862   c = connection_get (&msg->cid);
5863   if (NULL == c)
5864   {
5865     GNUNET_STATISTICS_update (stats, "# unknown connection", 1, GNUNET_NO);
5866     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "WARNING connection unknown\n");
5867     return GNUNET_OK;
5868   }
5869   t = c->t;
5870   fc = fwd ? &c->bck_fc : &c->fwd_fc;
5871
5872   /* Check if origin is as expected */
5873   neighbor = connection_get_hop (c, !fwd);
5874   if (peer_get (peer)->id != neighbor->id)
5875   {
5876     GNUNET_break_op (0);
5877     return GNUNET_OK;
5878   }
5879
5880   /* Check PID */
5881   pid = ntohl (msg->pid);
5882   if (GMC_is_pid_bigger (pid, fc->last_ack_sent))
5883   {
5884     GNUNET_STATISTICS_update (stats, "# unsolicited message", 1, GNUNET_NO);
5885     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5886                 "WARNING Received PID %u, (prev %u), ACK %u\n",
5887                 pid, fc->last_pid_recv, fc->last_ack_sent);
5888     return GNUNET_OK;
5889   }
5890   if (GNUNET_NO == GMC_is_pid_bigger (pid, fc->last_pid_recv))
5891   {
5892     GNUNET_STATISTICS_update (stats, "# duplicate PID", 1, GNUNET_NO);
5893     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5894                 " Pid %u not expected (%u+), dropping!\n",
5895                 pid, fc->last_pid_recv + 1);
5896     return GNUNET_OK;
5897   }
5898   if (MESH_CONNECTION_SENT == c->state)
5899     connection_change_state (c, MESH_CONNECTION_READY);
5900   connection_reset_timeout (c, fwd);
5901   fc->last_pid_recv = pid;
5902
5903   /* Is this message for us? */
5904   if (connection_is_terminal (c, fwd))
5905   {
5906     size_t dsize = size - sizeof (struct GNUNET_MESH_Encrypted);
5907     char cbuf[dsize];
5908     struct GNUNET_MessageHeader *msgh;
5909     unsigned int off;
5910
5911     /* TODO signature verification */
5912     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  message for us!\n");
5913     GNUNET_STATISTICS_update (stats, "# messages received", 1, GNUNET_NO);
5914
5915     fc->last_pid_recv = pid;
5916     tunnel_decrypt (t, cbuf, &msg[1], dsize, msg->iv, fwd);
5917     off = 0;
5918     while (off < dsize)
5919     {
5920       msgh = (struct GNUNET_MessageHeader *) &cbuf[off];
5921       handle_decrypted (t, msgh, fwd);
5922       off += ntohs (msgh->size);
5923     }
5924     send_ack (c, NULL, fwd);
5925     return GNUNET_OK;
5926   }
5927
5928   /* Message not for us: forward to next hop */
5929   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  not for us, retransmitting...\n");
5930   ttl = ntohl (msg->ttl);
5931   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   ttl: %u\n", ttl);
5932   if (ttl == 0)
5933   {
5934     GNUNET_STATISTICS_update (stats, "# TTL drops", 1, GNUNET_NO);
5935     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, " TTL is 0, DROPPING!\n");
5936     send_ack (c, NULL, fwd);
5937     return GNUNET_OK;
5938   }
5939   GNUNET_STATISTICS_update (stats, "# messages forwarded", 1, GNUNET_NO);
5940
5941   send_prebuilt_message_connection (&msg->header, c, NULL, fwd);
5942
5943   return GNUNET_OK;
5944 }
5945
5946
5947 /**
5948  * Core handler for mesh network traffic going orig->dest.
5949  *
5950  * @param cls Closure (unused).
5951  * @param message Message received.
5952  * @param peer Peer who sent the message.
5953  *
5954  * @return GNUNET_OK to keep the connection open,
5955  *         GNUNET_SYSERR to close it (signal serious error)
5956  */
5957 static int
5958 handle_mesh_fwd (void *cls, const struct GNUNET_PeerIdentity *peer,
5959                      const struct GNUNET_MessageHeader *message)
5960 {
5961   return handle_mesh_encrypted (peer,
5962                                 (struct GNUNET_MESH_Encrypted *)message,
5963                                 GNUNET_YES);
5964 }
5965
5966 /**
5967  * Core handler for mesh network traffic going dest->orig.
5968  *
5969  * @param cls Closure (unused).
5970  * @param message Message received.
5971  * @param peer Peer who sent the message.
5972  *
5973  * @return GNUNET_OK to keep the connection open,
5974  *         GNUNET_SYSERR to close it (signal serious error)
5975  */
5976 static int
5977 handle_mesh_bck (void *cls, const struct GNUNET_PeerIdentity *peer,
5978                      const struct GNUNET_MessageHeader *message)
5979 {
5980   return handle_mesh_encrypted (peer,
5981                                 (struct GNUNET_MESH_Encrypted *)message,
5982                                 GNUNET_NO);
5983 }
5984
5985
5986 /**
5987  * Core handler for mesh network traffic point-to-point acks.
5988  *
5989  * @param cls closure
5990  * @param message message
5991  * @param peer peer identity this notification is about
5992  *
5993  * @return GNUNET_OK to keep the connection open,
5994  *         GNUNET_SYSERR to close it (signal serious error)
5995  */
5996 static int
5997 handle_mesh_ack (void *cls, const struct GNUNET_PeerIdentity *peer,
5998                  const struct GNUNET_MessageHeader *message)
5999 {
6000   struct GNUNET_MESH_ACK *msg;
6001   struct MeshConnection *c;
6002   struct MeshFlowControl *fc;
6003   GNUNET_PEER_Id id;
6004   uint32_t ack;
6005
6006   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "\n\n");
6007   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got an ACK packet from %s!\n",
6008               GNUNET_i2s (peer));
6009   msg = (struct GNUNET_MESH_ACK *) message;
6010
6011   c = connection_get (&msg->cid);
6012
6013   if (NULL == c)
6014   {
6015     GNUNET_STATISTICS_update (stats, "# ack on unknown connection", 1,
6016                               GNUNET_NO);
6017     return GNUNET_OK;
6018   }
6019
6020   /* Is this a forward or backward ACK? */
6021   id = GNUNET_PEER_search (peer);
6022   if (connection_get_next_hop (c)->id == id)
6023   {
6024     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  FWD ACK\n");
6025     fc = &c->fwd_fc;
6026   }
6027   else if (connection_get_prev_hop (c)->id == id)
6028   {
6029     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  BCK ACK\n");
6030     fc = &c->bck_fc;
6031   }
6032   else
6033   {
6034     GNUNET_break_op (0);
6035     return GNUNET_OK;
6036   }
6037
6038   ack = ntohl (msg->ack);
6039   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  ACK %u\n", ack);
6040
6041   /* Cancel polling if the ACK is bigger than before. */
6042   if (GNUNET_SCHEDULER_NO_TASK != fc->poll_task &&
6043       GMC_is_pid_bigger (ack, fc->last_ack_recv))
6044   {
6045     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Cancel poll\n");
6046     GNUNET_SCHEDULER_cancel (fc->poll_task);
6047     fc->poll_task = GNUNET_SCHEDULER_NO_TASK;
6048     fc->poll_time = GNUNET_TIME_UNIT_SECONDS;
6049   }
6050
6051   fc->last_ack_recv = ack;
6052   connection_unlock_queue (c, fc == &c->fwd_fc);
6053
6054   return GNUNET_OK;
6055 }
6056
6057
6058 /**
6059  * Core handler for mesh network traffic point-to-point ack polls.
6060  *
6061  * @param cls closure
6062  * @param message message
6063  * @param peer peer identity this notification is about
6064  *
6065  * @return GNUNET_OK to keep the connection open,
6066  *         GNUNET_SYSERR to close it (signal serious error)
6067  */
6068 static int
6069 handle_mesh_poll (void *cls, const struct GNUNET_PeerIdentity *peer,
6070                   const struct GNUNET_MessageHeader *message)
6071 {
6072   struct GNUNET_MESH_Poll *msg;
6073   struct MeshConnection *c;
6074   struct MeshFlowControl *fc;
6075   GNUNET_PEER_Id id;
6076   uint32_t pid;
6077   int fwd;
6078
6079   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "\n\n");
6080   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a POLL packet from %s!\n",
6081               GNUNET_i2s (peer));
6082
6083   msg = (struct GNUNET_MESH_Poll *) message;
6084
6085   c = connection_get (&msg->cid);
6086
6087   if (NULL == c)
6088   {
6089     GNUNET_STATISTICS_update (stats, "# poll on unknown connection", 1,
6090                               GNUNET_NO);
6091     GNUNET_break_op (0);
6092     return GNUNET_OK;
6093   }
6094
6095   /* Is this a forward or backward ACK?
6096    * Note: a poll should never be needed in a loopback case,
6097    * since there is no possiblility of packet loss there, so
6098    * this way of discerining FWD/BCK should not be a problem.
6099    */
6100   id = GNUNET_PEER_search (peer);
6101   if (connection_get_next_hop (c)->id == id)
6102   {
6103     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  FWD ACK\n");
6104     fc = &c->fwd_fc;
6105   }
6106   else if (connection_get_prev_hop (c)->id == id)
6107   {
6108     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  BCK ACK\n");
6109     fc = &c->bck_fc;
6110   }
6111   else
6112   {
6113     GNUNET_break_op (0);
6114     return GNUNET_OK;
6115   }
6116
6117   pid = ntohl (msg->pid);
6118   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  PID %u, OLD %u\n",
6119               pid, fc->last_pid_recv);
6120   fc->last_pid_recv = pid;
6121   fwd = fc == &c->fwd_fc;
6122   send_ack (c, NULL, fwd);
6123
6124   return GNUNET_OK;
6125 }
6126
6127
6128 /**
6129  * Core handler for mesh keepalives.
6130  *
6131  * @param cls closure
6132  * @param message message
6133  * @param peer peer identity this notification is about
6134  * @return GNUNET_OK to keep the connection open,
6135  *         GNUNET_SYSERR to close it (signal serious error)
6136  *
6137  * TODO: Check who we got this from, to validate route.
6138  */
6139 static int
6140 handle_mesh_keepalive (void *cls, const struct GNUNET_PeerIdentity *peer,
6141                        const struct GNUNET_MessageHeader *message)
6142 {
6143   struct GNUNET_MESH_ConnectionKeepAlive *msg;
6144   struct MeshConnection *c;
6145   struct MeshPeer *neighbor;
6146   int fwd;
6147
6148   msg = (struct GNUNET_MESH_ConnectionKeepAlive *) message;
6149   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a keepalive packet from %s\n",
6150               GNUNET_i2s (peer));
6151
6152   c = connection_get (&msg->cid);
6153   if (NULL == c)
6154   {
6155     GNUNET_STATISTICS_update (stats, "# keepalive on unknown connection", 1,
6156                               GNUNET_NO);
6157     return GNUNET_OK;
6158   }
6159
6160   fwd = GNUNET_MESSAGE_TYPE_MESH_FWD_KEEPALIVE == ntohs (message->type) ? 
6161         GNUNET_YES : GNUNET_NO;
6162
6163   /* Check if origin is as expected */
6164   neighbor = connection_get_hop (c, fwd);
6165   if (peer_get (peer)->id != neighbor->id)
6166   {
6167     GNUNET_break_op (0);
6168     return GNUNET_OK;
6169   }
6170
6171   connection_change_state (c, MESH_CONNECTION_READY);
6172   connection_reset_timeout (c, fwd);
6173
6174   if (connection_is_terminal (c, fwd))
6175     return GNUNET_OK;
6176
6177   GNUNET_STATISTICS_update (stats, "# keepalives forwarded", 1, GNUNET_NO);
6178   send_prebuilt_message_connection (message, c, NULL, fwd);
6179
6180   return GNUNET_OK;
6181 }
6182
6183
6184
6185 /**
6186  * Functions to handle messages from core
6187  */
6188 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
6189   {&handle_mesh_connection_create, GNUNET_MESSAGE_TYPE_MESH_CONNECTION_CREATE,
6190     0},
6191   {&handle_mesh_connection_ack, GNUNET_MESSAGE_TYPE_MESH_CONNECTION_ACK,
6192     sizeof (struct GNUNET_MESH_ConnectionACK)},
6193   {&handle_mesh_connection_broken, GNUNET_MESSAGE_TYPE_MESH_CONNECTION_BROKEN,
6194     sizeof (struct GNUNET_MESH_ConnectionBroken)},
6195   {&handle_mesh_connection_destroy, GNUNET_MESSAGE_TYPE_MESH_CONNECTION_DESTROY,
6196     sizeof (struct GNUNET_MESH_ConnectionDestroy)},
6197   {&handle_mesh_keepalive, GNUNET_MESSAGE_TYPE_MESH_FWD_KEEPALIVE,
6198     sizeof (struct GNUNET_MESH_ConnectionKeepAlive)},
6199   {&handle_mesh_keepalive, GNUNET_MESSAGE_TYPE_MESH_BCK_KEEPALIVE,
6200     sizeof (struct GNUNET_MESH_ConnectionKeepAlive)},
6201   {&handle_mesh_ack, GNUNET_MESSAGE_TYPE_MESH_ACK,
6202     sizeof (struct GNUNET_MESH_ACK)},
6203   {&handle_mesh_poll, GNUNET_MESSAGE_TYPE_MESH_POLL,
6204     sizeof (struct GNUNET_MESH_Poll)},
6205   {&handle_mesh_fwd, GNUNET_MESSAGE_TYPE_MESH_FWD, 0},
6206   {&handle_mesh_bck, GNUNET_MESSAGE_TYPE_MESH_BCK, 0},
6207   {NULL, 0, 0}
6208 };
6209
6210
6211 /**
6212  * Function to process paths received for a new peer addition. The recorded
6213  * paths form the initial tunnel, which can be optimized later.
6214  * Called on each result obtained for the DHT search.
6215  *
6216  * @param cls closure
6217  * @param exp when will this value expire
6218  * @param key key of the result
6219  * @param get_path path of the get request
6220  * @param get_path_length lenght of get_path
6221  * @param put_path path of the put request
6222  * @param put_path_length length of the put_path
6223  * @param type type of the result
6224  * @param size number of bytes in data
6225  * @param data pointer to the result data
6226  */
6227 static void
6228 dht_get_id_handler (void *cls, struct GNUNET_TIME_Absolute exp,
6229                     const struct GNUNET_HashCode * key,
6230                     const struct GNUNET_PeerIdentity *get_path,
6231                     unsigned int get_path_length,
6232                     const struct GNUNET_PeerIdentity *put_path,
6233                     unsigned int put_path_length, enum GNUNET_BLOCK_Type type,
6234                     size_t size, const void *data)
6235 {
6236   struct MeshPeer *peer = cls;
6237   struct MeshPeerPath *p;
6238   struct MeshConnection *c;
6239   struct GNUNET_PeerIdentity pi;
6240   int i;
6241
6242   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got results from DHT!\n");
6243   GNUNET_PEER_resolve (peer->id, &pi);
6244   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  for %s\n", GNUNET_i2s (&pi));
6245
6246   p = path_build_from_dht (get_path, get_path_length,
6247                            put_path, put_path_length);
6248   path_add_to_peers (p, GNUNET_NO);
6249   path_destroy (p);
6250
6251   /* Count connections */
6252   for (c = peer->tunnel->connection_head, i = 0; NULL != c; c = c->next, i++);
6253
6254   /* If we already have 3 (or more (?!)) connections, it's enough */
6255   if (3 <= i)
6256     return;
6257
6258   if (peer->tunnel->state == MESH_TUNNEL_SEARCHING)
6259   {
6260     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " ... connect!\n");
6261     peer_connect (peer);
6262   }
6263   return;
6264 }
6265
6266
6267 /******************************************************************************/
6268 /*********************       MESH LOCAL HANDLES      **************************/
6269 /******************************************************************************/
6270
6271
6272 /**
6273  * Handler for client connection.
6274  *
6275  * @param cls Closure (unused).
6276  * @param client Client handler.
6277  */
6278 static void
6279 handle_local_client_connect (void *cls, struct GNUNET_SERVER_Client *client)
6280 {
6281   struct MeshClient *c;
6282
6283   if (NULL == client)
6284     return;
6285   c = GNUNET_malloc (sizeof (struct MeshClient));
6286   c->handle = client;
6287   c->id = next_client_id++; /* overflow not important: just for debug */
6288   GNUNET_SERVER_client_keep (client);
6289   GNUNET_SERVER_client_set_user_context (client, c);
6290   GNUNET_CONTAINER_DLL_insert (clients_head, clients_tail, c);
6291 }
6292
6293
6294 /**
6295  * Handler for client disconnection
6296  *
6297  * @param cls closure
6298  * @param client identification of the client; NULL
6299  *        for the last call when the server is destroyed
6300  */
6301 static void
6302 handle_local_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
6303 {
6304   struct MeshClient *c;
6305
6306   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "client disconnected: %p\n", client);
6307   if (client == NULL)
6308   {
6309     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   (SERVER DOWN)\n");
6310     return;
6311   }
6312
6313   c = client_get (client);
6314   if (NULL != c)
6315   {
6316     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "matching client found (%u, %p)\n",
6317                 c->id, c);
6318     GNUNET_SERVER_client_drop (c->handle);
6319     c->shutting_down = GNUNET_YES;
6320     if (NULL != c->own_channels)
6321     {
6322       GNUNET_CONTAINER_multihashmap32_iterate (c->own_channels,
6323                                                &channel_destroy_iterator, c);
6324       GNUNET_CONTAINER_multihashmap32_destroy (c->own_channels);
6325     }
6326
6327     if (NULL != c->incoming_channels)
6328     {
6329       GNUNET_CONTAINER_multihashmap32_iterate (c->incoming_channels,
6330                                                &channel_destroy_iterator, c);
6331       GNUNET_CONTAINER_multihashmap32_destroy (c->incoming_channels);
6332     }
6333
6334     if (NULL != c->ports)
6335     {
6336       GNUNET_CONTAINER_multihashmap32_iterate (c->ports,
6337                                                &client_release_ports, c);
6338       GNUNET_CONTAINER_multihashmap32_destroy (c->ports);
6339     }
6340     GNUNET_CONTAINER_DLL_remove (clients_head, clients_tail, c);
6341     GNUNET_STATISTICS_update (stats, "# clients", -1, GNUNET_NO);
6342     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  client free (%p)\n", c);
6343     GNUNET_free (c);
6344   }
6345   else
6346   {
6347     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, " context NULL!\n");
6348   }
6349   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "done!\n");
6350   return;
6351 }
6352
6353
6354 /**
6355  * Handler for new clients
6356  *
6357  * @param cls closure
6358  * @param client identification of the client
6359  * @param message the actual message, which includes messages the client wants
6360  */
6361 static void
6362 handle_local_new_client (void *cls, struct GNUNET_SERVER_Client *client,
6363                          const struct GNUNET_MessageHeader *message)
6364 {
6365   struct GNUNET_MESH_ClientConnect *cc_msg;
6366   struct MeshClient *c;
6367   unsigned int size;
6368   uint32_t *p;
6369   unsigned int i;
6370
6371   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new client connected %p\n", client);
6372
6373   /* Check data sanity */
6374   size = ntohs (message->size) - sizeof (struct GNUNET_MESH_ClientConnect);
6375   cc_msg = (struct GNUNET_MESH_ClientConnect *) message;
6376   if (0 != (size % sizeof (uint32_t)))
6377   {
6378     GNUNET_break (0);
6379     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6380     return;
6381   }
6382   size /= sizeof (uint32_t);
6383
6384   /* Initialize new client structure */
6385   c = GNUNET_SERVER_client_get_user_context (client, struct MeshClient);
6386   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  client id %u\n", c->id);
6387   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  client has %u ports\n", size);
6388   if (size > 0)
6389   {
6390     uint32_t u32;
6391
6392     p = (uint32_t *) &cc_msg[1];
6393     c->ports = GNUNET_CONTAINER_multihashmap32_create (size);
6394     for (i = 0; i < size; i++)
6395     {
6396       u32 = ntohl (p[i]);
6397       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "    port: %u\n", u32);
6398
6399       /* store in client's hashmap */
6400       GNUNET_CONTAINER_multihashmap32_put (c->ports, u32, c,
6401                                            GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
6402       /* store in global hashmap */
6403       /* FIXME only allow one client to have the port open,
6404        *       have a backup hashmap with waiting clients */
6405       GNUNET_CONTAINER_multihashmap32_put (ports, u32, c,
6406                                            GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
6407     }
6408   }
6409
6410   c->own_channels = GNUNET_CONTAINER_multihashmap32_create (32);
6411   c->incoming_channels = GNUNET_CONTAINER_multihashmap32_create (32);
6412   GNUNET_SERVER_notification_context_add (nc, client);
6413   GNUNET_STATISTICS_update (stats, "# clients", 1, GNUNET_NO);
6414
6415   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6416   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new client processed\n");
6417 }
6418
6419
6420 /**
6421  * Handler for requests of new tunnels
6422  *
6423  * @param cls Closure.
6424  * @param client Identification of the client.
6425  * @param message The actual message.
6426  */
6427 static void
6428 handle_local_channel_create (void *cls, struct GNUNET_SERVER_Client *client,
6429                             const struct GNUNET_MessageHeader *message)
6430 {
6431   struct GNUNET_MESH_ChannelMessage *msg;
6432   struct MeshPeer *peer;
6433   struct MeshTunnel2 *t;
6434   struct MeshChannel *ch;
6435   struct MeshClient *c;
6436   MESH_ChannelNumber chid;
6437
6438   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new channel requested\n");
6439
6440   /* Sanity check for client registration */
6441   if (NULL == (c = client_get (client)))
6442   {
6443     GNUNET_break (0);
6444     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6445     return;
6446   }
6447   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6448
6449   /* Message size sanity check */
6450   if (sizeof (struct GNUNET_MESH_ChannelMessage) != ntohs (message->size))
6451   {
6452     GNUNET_break (0);
6453     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6454     return;
6455   }
6456
6457   msg = (struct GNUNET_MESH_ChannelMessage *) message;
6458   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  towards %s:%u\n",
6459               GNUNET_i2s (&msg->peer), ntohl (msg->port));
6460   chid = ntohl (msg->channel_id);
6461
6462   /* Sanity check for duplicate channel IDs */
6463   if (NULL != channel_get_by_local_id (c, chid))
6464   {
6465     GNUNET_break (0);
6466     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6467     return;
6468   }
6469
6470   peer = peer_get (&msg->peer);
6471   if (NULL == peer->tunnel)
6472   {
6473     peer->tunnel = tunnel_new ();
6474     peer->tunnel->peer = peer;
6475   }
6476   t = peer->tunnel;
6477
6478   /* Create channel */
6479   ch = channel_new (t, c, chid);
6480   if (NULL == ch)
6481   {
6482     GNUNET_break (0);
6483     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6484     return;
6485   }
6486   ch->port = ntohl (msg->port);
6487   channel_set_options (ch, ntohl (msg->opt));
6488
6489   /* In unreliable channels, we'll use the DLL to buffer data for the root */
6490   ch->root_rel = GNUNET_new (struct MeshChannelReliability);
6491   ch->root_rel->ch = ch;
6492   ch->root_rel->expected_delay = MESH_RETRANSMIT_TIME;
6493
6494   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "CREATED CHANNEL %s[%x]:%u (%x)\n",
6495               peer2s (t->peer), ch->gid, ch->port, ch->lid_root);
6496   peer_connect (peer);
6497
6498   /* Send create channel */
6499   {
6500     struct GNUNET_MESH_ChannelCreate msgcc;
6501
6502     msgcc.header.size = htons (sizeof (msgcc));
6503     msgcc.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_CHANNEL_CREATE);
6504     msgcc.chid = htonl (ch->gid);
6505     msgcc.port = msg->port;
6506     msgcc.opt = msg->opt;
6507
6508     tunnel_queue_data (t, ch, &msgcc.header, GNUNET_YES);
6509   }
6510
6511   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6512   return;
6513 }
6514
6515
6516 /**
6517  * Handler for requests of deleting tunnels
6518  *
6519  * @param cls closure
6520  * @param client identification of the client
6521  * @param message the actual message
6522  */
6523 static void
6524 handle_local_channel_destroy (void *cls, struct GNUNET_SERVER_Client *client,
6525                              const struct GNUNET_MessageHeader *message)
6526 {
6527   struct GNUNET_MESH_ChannelMessage *msg;
6528   struct MeshClient *c;
6529   struct MeshChannel *ch;
6530   struct MeshTunnel2 *t;
6531   MESH_ChannelNumber chid;
6532
6533   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6534               "Got a DESTROY CHANNEL from client!\n");
6535
6536   /* Sanity check for client registration */
6537   if (NULL == (c = client_get (client)))
6538   {
6539     GNUNET_break (0);
6540     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6541     return;
6542   }
6543   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6544
6545   /* Message sanity check */
6546   if (sizeof (struct GNUNET_MESH_ChannelMessage) != ntohs (message->size))
6547   {
6548     GNUNET_break (0);
6549     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6550     return;
6551   }
6552
6553   msg = (struct GNUNET_MESH_ChannelMessage *) message;
6554
6555   /* Retrieve tunnel */
6556   chid = ntohl (msg->channel_id);
6557   ch = channel_get_by_local_id (c, chid);
6558   if (NULL == ch)
6559   {
6560     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "  channel %X not found\n", chid);
6561     GNUNET_break (0);
6562     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6563     return;
6564   }
6565
6566   /* Cleanup after the tunnel */
6567   client_delete_channel (c, ch);
6568   if (c == ch->dest && GNUNET_MESH_LOCAL_CHANNEL_ID_SERV <= chid)
6569   {
6570     ch->dest = NULL;
6571   }
6572   else if (c == ch->root && GNUNET_MESH_LOCAL_CHANNEL_ID_SERV > chid)
6573   {
6574     ch->root = NULL;
6575   }
6576   else 
6577   {
6578     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
6579                 "  channel %X client %p (%p, %p)\n",
6580                 chid, c, ch->root, ch->dest);
6581     GNUNET_break (0);
6582   }
6583
6584   t = ch->t;
6585   channel_destroy (ch);
6586   tunnel_destroy_if_empty (t);
6587
6588   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6589   return;
6590 }
6591
6592
6593 /**
6594  * Handler for client traffic
6595  *
6596  * @param cls closure
6597  * @param client identification of the client
6598  * @param message the actual message
6599  */
6600 static void
6601 handle_local_data (void *cls, struct GNUNET_SERVER_Client *client,
6602                    const struct GNUNET_MessageHeader *message)
6603 {
6604   struct GNUNET_MESH_LocalData *msg;
6605   struct MeshClient *c;
6606   struct MeshChannel *ch;
6607   struct MeshChannelReliability *rel;
6608   MESH_ChannelNumber chid;
6609   size_t size;
6610   int fwd;
6611
6612   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6613               "Got data from a client!\n");
6614
6615   /* Sanity check for client registration */
6616   if (NULL == (c = client_get (client)))
6617   {
6618     GNUNET_break (0);
6619     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6620     return;
6621   }
6622   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6623
6624   msg = (struct GNUNET_MESH_LocalData *) message;
6625
6626   /* Sanity check for message size */
6627   size = ntohs (message->size) - sizeof (struct GNUNET_MESH_LocalData);
6628   if (size < sizeof (struct GNUNET_MessageHeader))
6629   {
6630     GNUNET_break (0);
6631     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6632     return;
6633   }
6634
6635   /* Channel exists? */
6636   chid = ntohl (msg->id);
6637   fwd = chid < GNUNET_MESH_LOCAL_CHANNEL_ID_SERV;
6638   ch = channel_get_by_local_id (c, chid);
6639   if (NULL == ch)
6640   {
6641     GNUNET_break (0);
6642     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6643     return;
6644   }
6645
6646   /* Is the client in the channel? */
6647   if ( !( (fwd &&
6648            ch->root &&
6649            ch->root->handle == client)
6650          ||
6651           (!fwd &&
6652            ch->dest && 
6653            ch->dest->handle == client) ) )
6654   {
6655     GNUNET_break (0);
6656     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6657     return;
6658   }
6659
6660   rel = fwd ? ch->root_rel : ch->dest_rel;
6661   rel->client_ready = GNUNET_NO;
6662
6663   /* Ok, everything is correct, send the message. */
6664   {
6665     struct GNUNET_MESH_Data *payload;
6666     uint16_t p2p_size = sizeof(struct GNUNET_MESH_Data) + size;
6667     unsigned char cbuf[p2p_size];
6668
6669     payload = (struct GNUNET_MESH_Data *) cbuf;
6670     payload->mid = htonl (rel->mid_send);
6671     rel->mid_send++;
6672     memcpy (&payload[1], &msg[1], size);
6673     payload->header.size = htons (p2p_size);
6674     payload->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_DATA);
6675     payload->chid = htonl (ch->gid);
6676     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  sending on channel...\n");
6677     send_prebuilt_message_channel (&payload->header, ch, fwd);
6678
6679     if (GNUNET_YES == ch->reliable)
6680       channel_save_copy (ch, &payload->header, fwd);
6681   }
6682   if (tunnel_get_buffer (ch->t, fwd) > 0)
6683     send_local_ack (ch, fwd);
6684   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "receive done OK\n");
6685   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6686
6687   return;
6688 }
6689
6690
6691 /**
6692  * Handler for client's ACKs for payload traffic.
6693  *
6694  * @param cls Closure (unused).
6695  * @param client Identification of the client.
6696  * @param message The actual message.
6697  */
6698 static void
6699 handle_local_ack (void *cls, struct GNUNET_SERVER_Client *client,
6700                   const struct GNUNET_MessageHeader *message)
6701 {
6702   struct GNUNET_MESH_LocalAck *msg;
6703   struct MeshChannelReliability *rel;
6704   struct MeshChannel *ch;
6705   struct MeshClient *c;
6706   MESH_ChannelNumber chid;
6707   int fwd;
6708
6709   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a local ACK\n");
6710
6711   /* Sanity check for client registration */
6712   if (NULL == (c = client_get (client)))
6713   {
6714     GNUNET_break (0);
6715     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6716     return;
6717   }
6718   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6719
6720   msg = (struct GNUNET_MESH_LocalAck *) message;
6721
6722   /* Channel exists? */
6723   chid = ntohl (msg->channel_id);
6724   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on channel %X\n", chid);
6725   ch = channel_get_by_local_id (c, chid);
6726   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   -- ch %p\n", ch);
6727   if (NULL == ch)
6728   {
6729     GNUNET_break (0);
6730     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Channel %X unknown.\n", chid);
6731     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "  for client %u.\n", c->id);
6732     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6733     return;
6734   }
6735
6736   /* If client is root, the ACK is going FWD, therefore this is "BCK". */
6737   /* If client is dest, the ACK is going BCK, therefore this is "FWD" */
6738   fwd = chid >= GNUNET_MESH_LOCAL_CHANNEL_ID_SERV;
6739   rel = fwd ? ch->dest_rel : ch->root_rel;
6740
6741   rel->client_ready = GNUNET_YES;
6742   channel_send_client_buffered_data (ch, c, fwd);
6743   send_ack (NULL, ch, fwd);
6744
6745   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6746
6747   return;
6748 }
6749
6750
6751 /**
6752  * Iterator over all tunnels to send a monitoring client info about each tunnel.
6753  *
6754  * @param cls Closure (client handle).
6755  * @param key Key (hashed tunnel ID, unused).
6756  * @param value Tunnel info.
6757  *
6758  * @return GNUNET_YES, to keep iterating.
6759  */
6760 // static int
6761 // monitor_all_tunnels_iterator (void *cls,
6762 //                               const struct GNUNET_HashCode * key,
6763 //                               void *value)
6764 // {
6765 //   struct GNUNET_SERVER_Client *client = cls;
6766 //   struct MeshChannel *ch = value;
6767 //   struct GNUNET_MESH_LocalMonitor *msg;
6768 // 
6769 //   msg = GNUNET_malloc (sizeof(struct GNUNET_MESH_LocalMonitor));
6770 //   msg->channel_id = htonl (ch->gid);
6771 //   msg->header.size = htons (sizeof (struct GNUNET_MESH_LocalMonitor));
6772 //   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_INFO_TUNNELS);
6773 // 
6774 //   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
6775 //               "*  sending info about tunnel %s\n",
6776 //               GNUNET_i2s (&msg->owner));
6777 // 
6778 //   GNUNET_SERVER_notification_context_unicast (nc, client,
6779 //                                               &msg->header, GNUNET_NO);
6780 //   return GNUNET_YES;
6781 // }
6782
6783
6784 /**
6785  * Handler for client's MONITOR request.
6786  *
6787  * @param cls Closure (unused).
6788  * @param client Identification of the client.
6789  * @param message The actual message.
6790  */
6791 static void
6792 handle_local_get_tunnels (void *cls, struct GNUNET_SERVER_Client *client,
6793                           const struct GNUNET_MessageHeader *message)
6794 {
6795   struct MeshClient *c;
6796
6797   /* Sanity check for client registration */
6798   if (NULL == (c = client_get (client)))
6799   {
6800     GNUNET_break (0);
6801     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6802     return;
6803   }
6804
6805   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
6806               "Received get tunnels request from client %u\n",
6807               c->id);
6808 //   GNUNET_CONTAINER_multihashmap_iterate (tunnels,
6809 //                                          monitor_all_tunnels_iterator,
6810 //                                          client);
6811   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
6812               "Get tunnels request from client %u completed\n",
6813               c->id);
6814   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6815 }
6816
6817
6818 /**
6819  * Handler for client's MONITOR_TUNNEL request.
6820  *
6821  * @param cls Closure (unused).
6822  * @param client Identification of the client.
6823  * @param message The actual message.
6824  */
6825 static void
6826 handle_local_show_tunnel (void *cls, struct GNUNET_SERVER_Client *client,
6827                           const struct GNUNET_MessageHeader *message)
6828 {
6829   const struct GNUNET_MESH_LocalMonitor *msg;
6830   struct GNUNET_MESH_LocalMonitor *resp;
6831   struct MeshClient *c;
6832   struct MeshChannel *ch;
6833
6834   /* Sanity check for client registration */
6835   if (NULL == (c = client_get (client)))
6836   {
6837     GNUNET_break (0);
6838     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6839     return;
6840   }
6841
6842   msg = (struct GNUNET_MESH_LocalMonitor *) message;
6843   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
6844               "Received tunnel info request from client %u for tunnel %s[%X]\n",
6845               c->id,
6846               &msg->owner,
6847               ntohl (msg->channel_id));
6848 //   ch = channel_get (&msg->owner, ntohl (msg->channel_id));
6849   ch = NULL; // FIXME
6850   if (NULL == ch)
6851   {
6852     /* We don't know the tunnel */
6853     struct GNUNET_MESH_LocalMonitor warn;
6854
6855     warn = *msg;
6856     GNUNET_SERVER_notification_context_unicast (nc, client,
6857                                                 &warn.header,
6858                                                 GNUNET_NO);
6859     GNUNET_SERVER_receive_done (client, GNUNET_OK);
6860     return;
6861   }
6862
6863   /* Initialize context */
6864   resp = GNUNET_malloc (sizeof (struct GNUNET_MESH_LocalMonitor));
6865   *resp = *msg;
6866   resp->header.size = htons (sizeof (struct GNUNET_MESH_LocalMonitor));
6867   GNUNET_SERVER_notification_context_unicast (nc, c->handle,
6868                                               &resp->header, GNUNET_NO);
6869   GNUNET_free (resp);
6870
6871   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
6872               "Monitor tunnel request from client %u completed\n",
6873               c->id);
6874   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6875 }
6876
6877
6878 /**
6879  * Functions to handle messages from clients
6880  */
6881 static struct GNUNET_SERVER_MessageHandler client_handlers[] = {
6882   {&handle_local_new_client, NULL,
6883    GNUNET_MESSAGE_TYPE_MESH_LOCAL_CONNECT, 0},
6884   {&handle_local_channel_create, NULL,
6885    GNUNET_MESSAGE_TYPE_MESH_CHANNEL_CREATE,
6886    sizeof (struct GNUNET_MESH_ChannelMessage)},
6887   {&handle_local_channel_destroy, NULL,
6888    GNUNET_MESSAGE_TYPE_MESH_CHANNEL_DESTROY,
6889    sizeof (struct GNUNET_MESH_ChannelMessage)},
6890   {&handle_local_data, NULL,
6891    GNUNET_MESSAGE_TYPE_MESH_LOCAL_DATA, 0},
6892   {&handle_local_ack, NULL,
6893    GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK,
6894    sizeof (struct GNUNET_MESH_LocalAck)},
6895   {&handle_local_get_tunnels, NULL,
6896    GNUNET_MESSAGE_TYPE_MESH_LOCAL_INFO_TUNNELS,
6897    sizeof (struct GNUNET_MessageHeader)},
6898   {&handle_local_show_tunnel, NULL,
6899    GNUNET_MESSAGE_TYPE_MESH_LOCAL_INFO_TUNNEL,
6900      sizeof (struct GNUNET_MESH_LocalMonitor)},
6901   {NULL, NULL, 0, 0}
6902 };
6903
6904
6905 /**
6906  * Method called whenever a given peer connects.
6907  *
6908  * @param cls closure
6909  * @param peer peer identity this notification is about
6910  */
6911 static void
6912 core_connect (void *cls, const struct GNUNET_PeerIdentity *peer)
6913 {
6914   struct MeshPeer *pi;
6915   struct MeshPeerPath *path;
6916
6917   DEBUG_CONN ("Peer connected\n");
6918   DEBUG_CONN ("     %s\n", GNUNET_i2s (&my_full_id));
6919   pi = peer_get (peer);
6920   if (myid == pi->id)
6921   {
6922     DEBUG_CONN ("     (self)\n");
6923     path = path_new (1);
6924   }
6925   else
6926   {
6927     DEBUG_CONN ("     %s\n", GNUNET_i2s (peer));
6928     path = path_new (2);
6929     path->peers[1] = pi->id;
6930     GNUNET_PEER_change_rc (pi->id, 1);
6931     GNUNET_STATISTICS_update (stats, "# peers", 1, GNUNET_NO);
6932   }
6933   path->peers[0] = myid;
6934   GNUNET_PEER_change_rc (myid, 1);
6935   peer_add_path (pi, path, GNUNET_YES);
6936
6937   pi->connections = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_YES);
6938   return;
6939 }
6940
6941
6942 /**
6943  * Method called whenever a peer disconnects.
6944  *
6945  * @param cls closure
6946  * @param peer peer identity this notification is about
6947  */
6948 static void
6949 core_disconnect (void *cls, const struct GNUNET_PeerIdentity *peer)
6950 {
6951   struct MeshPeer *pi;
6952
6953   DEBUG_CONN ("Peer disconnected\n");
6954   pi = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
6955   if (NULL == pi)
6956   {
6957     GNUNET_break (0);
6958     return;
6959   }
6960
6961   GNUNET_CONTAINER_multihashmap_iterate (pi->connections,
6962                                          connection_broken,
6963                                          pi);
6964   GNUNET_CONTAINER_multihashmap_destroy (pi->connections);
6965   pi->connections = NULL;
6966   if (myid == pi->id)
6967   {
6968     DEBUG_CONN ("     (self)\n");
6969   }
6970   GNUNET_STATISTICS_update (stats, "# peers", -1, GNUNET_NO);
6971
6972   return;
6973 }
6974
6975
6976 /**
6977  * Install server (service) handlers and start listening to clients.
6978  */
6979 static void
6980 server_init (void)
6981 {
6982   GNUNET_SERVER_add_handlers (server_handle, client_handlers);
6983   GNUNET_SERVER_connect_notify (server_handle,
6984                                 &handle_local_client_connect, NULL);
6985   GNUNET_SERVER_disconnect_notify (server_handle,
6986                                    &handle_local_client_disconnect, NULL);
6987   nc = GNUNET_SERVER_notification_context_create (server_handle, 1);
6988
6989   clients_head = NULL;
6990   clients_tail = NULL;
6991   next_client_id = 0;
6992   GNUNET_SERVER_resume (server_handle);
6993 }
6994
6995
6996 /**
6997  * To be called on core init/fail.
6998  *
6999  * @param cls Closure (config)
7000  * @param identity the public identity of this peer
7001  */
7002 static void
7003 core_init (void *cls, 
7004            const struct GNUNET_PeerIdentity *identity)
7005 {
7006   const struct GNUNET_CONFIGURATION_Handle *c = cls;
7007   static int i = 0;
7008
7009   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Core init\n");
7010   if (0 != memcmp (identity, &my_full_id, sizeof (my_full_id)))
7011   {
7012     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _("Wrong CORE service\n"));
7013     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7014                 " core id %s\n",
7015                 GNUNET_i2s (identity));
7016     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7017                 " my id %s\n",
7018                 GNUNET_i2s (&my_full_id));
7019     GNUNET_CORE_disconnect (core_handle);
7020     core_handle = GNUNET_CORE_connect (c, /* Main configuration */
7021                                        NULL,      /* Closure passed to MESH functions */
7022                                        &core_init,        /* Call core_init once connected */
7023                                        &core_connect,     /* Handle connects */
7024                                        &core_disconnect,  /* remove peers on disconnects */
7025                                        NULL,      /* Don't notify about all incoming messages */
7026                                        GNUNET_NO, /* For header only in notification */
7027                                        NULL,      /* Don't notify about all outbound messages */
7028                                        GNUNET_NO, /* For header-only out notification */
7029                                        core_handlers);    /* Register these handlers */
7030     if (10 < i++)
7031       GNUNET_abort();
7032   }
7033   server_init ();
7034   return;
7035 }
7036
7037
7038 /******************************************************************************/
7039 /************************      MAIN FUNCTIONS      ****************************/
7040 /******************************************************************************/
7041
7042 /**
7043  * Iterator over tunnel hash map entries to destroy the tunnel during shutdown.
7044  *
7045  * @param cls closure
7046  * @param key current key code
7047  * @param value value in the hash map
7048  * @return GNUNET_YES if we should continue to iterate,
7049  *         GNUNET_NO if not.
7050  */
7051 static int
7052 shutdown_tunnel (void *cls, const struct GNUNET_HashCode * key, void *value)
7053 {
7054   struct MeshPeer *p = value;
7055   struct MeshTunnel2 *t = p->tunnel;
7056
7057   if (NULL != t)
7058     tunnel_destroy (t);
7059   return GNUNET_YES;
7060 }
7061
7062
7063 /**
7064  * Task run during shutdown.
7065  *
7066  * @param cls unused
7067  * @param tc unused
7068  */
7069 static void
7070 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
7071 {
7072   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shutting down\n");
7073
7074   if (core_handle != NULL)
7075   {
7076     GNUNET_CORE_disconnect (core_handle);
7077     core_handle = NULL;
7078   }
7079   GNUNET_CONTAINER_multihashmap_iterate (peers, &shutdown_tunnel, NULL);
7080   if (dht_handle != NULL)
7081   {
7082     GNUNET_DHT_disconnect (dht_handle);
7083     dht_handle = NULL;
7084   }
7085   if (nc != NULL)
7086   {
7087     GNUNET_SERVER_notification_context_destroy (nc);
7088     nc = NULL;
7089   }
7090   if (GNUNET_SCHEDULER_NO_TASK != announce_id_task)
7091   {
7092     GNUNET_SCHEDULER_cancel (announce_id_task);
7093     announce_id_task = GNUNET_SCHEDULER_NO_TASK;
7094   }
7095   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shut down\n");
7096 }
7097
7098
7099 /**
7100  * Process mesh requests.
7101  *
7102  * @param cls closure
7103  * @param server the initialized server
7104  * @param c configuration to use
7105  */
7106 static void
7107 run (void *cls, struct GNUNET_SERVER_Handle *server,
7108      const struct GNUNET_CONFIGURATION_Handle *c)
7109 {
7110   char *keyfile;
7111   struct GNUNET_CRYPTO_EccPrivateKey *pk;
7112
7113   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "starting to run\n");
7114   server_handle = server;
7115   GNUNET_SERVER_suspend (server_handle);
7116
7117   if (GNUNET_OK !=
7118       GNUNET_CONFIGURATION_get_value_filename (c, "PEER", "PRIVATE_KEY",
7119                                                &keyfile))
7120   {
7121     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7122                 _
7123                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
7124                 "mesh", "peer/privatekey");
7125     GNUNET_SCHEDULER_shutdown ();
7126     return;
7127   }
7128
7129   if (GNUNET_OK !=
7130       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "REFRESH_CONNECTION_TIME",
7131                                            &refresh_connection_time))
7132   {
7133     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7134                 _
7135                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
7136                 "mesh", "refresh path time");
7137     GNUNET_SCHEDULER_shutdown ();
7138     return;
7139   }
7140
7141   if (GNUNET_OK !=
7142       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "ID_ANNOUNCE_TIME",
7143                                            &id_announce_time))
7144   {
7145     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7146                 _
7147                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
7148                 "mesh", "id announce time");
7149     GNUNET_SCHEDULER_shutdown ();
7150     return;
7151   }
7152
7153   if (GNUNET_OK !=
7154       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "CONNECT_TIMEOUT",
7155                                            &connect_timeout))
7156   {
7157     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7158                 _
7159                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
7160                 "mesh", "connect timeout");
7161     GNUNET_SCHEDULER_shutdown ();
7162     return;
7163   }
7164
7165   if (GNUNET_OK !=
7166       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_MSGS_QUEUE",
7167                                              &max_msgs_queue))
7168   {
7169     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7170                 _
7171                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
7172                 "mesh", "max msgs queue");
7173     GNUNET_SCHEDULER_shutdown ();
7174     return;
7175   }
7176
7177   if (GNUNET_OK !=
7178       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_CONNECTIONS",
7179                                              &max_connections))
7180   {
7181     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7182                 _
7183                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
7184                 "mesh", "max tunnels");
7185     GNUNET_SCHEDULER_shutdown ();
7186     return;
7187   }
7188
7189   if (GNUNET_OK !=
7190       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DEFAULT_TTL",
7191                                              &default_ttl))
7192   {
7193     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
7194                 _
7195                 ("%s service is lacking key configuration settings (%s). Using default (%u).\n"),
7196                 "mesh", "default ttl", 64);
7197     default_ttl = 64;
7198   }
7199
7200   if (GNUNET_OK !=
7201       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_PEERS",
7202                                              &max_peers))
7203   {
7204     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
7205                 _("%s service is lacking key configuration settings (%s). Using default (%u).\n"),
7206                 "mesh", "max peers", 1000);
7207     max_peers = 1000;
7208   }
7209
7210   if (GNUNET_OK !=
7211       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DROP_PERCENT",
7212                                              &drop_percent))
7213   {
7214     drop_percent = 0;
7215   }
7216   else
7217   {
7218     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
7219                 "Mesh is running with drop mode enabled. "
7220                 "This is NOT a good idea! "
7221                 "Remove the DROP_PERCENT option from your configuration.\n");
7222   }
7223
7224   if (GNUNET_OK !=
7225       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DHT_REPLICATION_LEVEL",
7226                                              &dht_replication_level))
7227   {
7228     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
7229                 _
7230                 ("%s service is lacking key configuration settings (%s). Using default (%u).\n"),
7231                 "mesh", "dht replication level", 3);
7232     dht_replication_level = 3;
7233   }
7234
7235   connections = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_YES);
7236   peers = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
7237   ports = GNUNET_CONTAINER_multihashmap32_create (32);
7238
7239   dht_handle = GNUNET_DHT_connect (c, 64);
7240   if (NULL == dht_handle)
7241   {
7242     GNUNET_break (0);
7243   }
7244   stats = GNUNET_STATISTICS_create ("mesh", c);
7245
7246   /* Scheduled the task to clean up when shutdown is called */
7247   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
7248                                 NULL);
7249   pk = GNUNET_CRYPTO_ecc_key_create_from_file (keyfile);
7250   GNUNET_free (keyfile);
7251   GNUNET_assert (NULL != pk);
7252   my_private_key = pk;
7253   GNUNET_CRYPTO_ecc_key_get_public (my_private_key, &my_public_key);
7254   GNUNET_CRYPTO_hash (&my_public_key, sizeof (my_public_key),
7255                       &my_full_id.hashPubKey);
7256   myid = GNUNET_PEER_intern (&my_full_id);
7257   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
7258               "Mesh for peer [%s] starting\n",
7259               GNUNET_i2s(&my_full_id));
7260
7261   core_handle = GNUNET_CORE_connect (c, /* Main configuration */
7262                                      NULL,      /* Closure passed to MESH functions */
7263                                      &core_init,        /* Call core_init once connected */
7264                                      &core_connect,     /* Handle connects */
7265                                      &core_disconnect,  /* remove peers on disconnects */
7266                                      NULL,      /* Don't notify about all incoming messages */
7267                                      GNUNET_NO, /* For header only in notification */
7268                                      NULL,      /* Don't notify about all outbound messages */
7269                                      GNUNET_NO, /* For header-only out notification */
7270                                      core_handlers);    /* Register these handlers */
7271   if (NULL == core_handle)
7272   {
7273     GNUNET_break (0);
7274     GNUNET_SCHEDULER_shutdown ();
7275     return;
7276   }
7277   announce_id_task = GNUNET_SCHEDULER_add_now (&announce_id, cls);
7278   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Mesh service running\n");
7279 }
7280
7281
7282 /**
7283  * The main function for the mesh service.
7284  *
7285  * @param argc number of arguments from the command line
7286  * @param argv command line arguments
7287  * @return 0 ok, 1 on error
7288  */
7289 int
7290 main (int argc, char *const *argv)
7291 {
7292   int ret;
7293   int r;
7294
7295   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "main()\n");
7296   r = GNUNET_SERVICE_run (argc, argv, "mesh", GNUNET_SERVICE_OPTION_NONE, &run,
7297                           NULL);
7298   ret = (GNUNET_OK == r) ? 0 : 1;
7299   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "main() END\n");
7300
7301   INTERVAL_SHOW;
7302
7303   return ret;
7304 }