- record channel number correctly
[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     {
4489       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Channel %u exists (%p)...\n",
4490                   t->next_chid, channel_get (t, t->next_chid));
4491       t->next_chid = (t->next_chid + 1) & ~GNUNET_MESH_LOCAL_CHANNEL_ID_CLI;
4492     }
4493     ch->gid = t->next_chid;
4494     t->next_chid = (t->next_chid + 1) & ~GNUNET_MESH_LOCAL_CHANNEL_ID_CLI;
4495
4496     if(GNUNET_OK !=
4497        GNUNET_CONTAINER_multihashmap32_put (owner->own_channels, lid_root, ch,
4498                                            GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
4499     {
4500       GNUNET_break (0);
4501       channel_destroy (ch);
4502       GNUNET_SERVER_receive_done (owner->handle, GNUNET_SYSERR);
4503       return NULL;
4504     }
4505   }
4506
4507   return ch;
4508 }
4509
4510
4511 /**
4512  * Set options in a channel, extracted from a bit flag field
4513  * 
4514  * @param ch Channel to set options to.
4515  * @param options Bit array in host byte order.
4516  */
4517 static void
4518 channel_set_options (struct MeshChannel *ch, uint32_t options)
4519 {
4520   ch->nobuffer = (options & GNUNET_MESH_OPTION_NOBUFFER) != 0 ?
4521                  GNUNET_YES : GNUNET_NO;
4522   ch->reliable = (options & GNUNET_MESH_OPTION_RELIABLE) != 0 ?
4523                  GNUNET_YES : GNUNET_NO;
4524 }
4525
4526
4527 /**
4528  * Iterator for deleting each channel whose client endpoint disconnected.
4529  *
4530  * @param cls Closure (client that has disconnected).
4531  * @param key The local channel id (used to access the hashmap).
4532  * @param value The value stored at the key (channel to destroy).
4533  *
4534  * @return GNUNET_OK, keep iterating.
4535  */
4536 static int
4537 channel_destroy_iterator (void *cls,
4538                           uint32_t key,
4539                           void *value)
4540 {
4541   struct MeshChannel *ch = value;
4542   struct MeshClient *c = cls;
4543   struct MeshTunnel2 *t;
4544
4545   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4546               " Channel %X (%X / %X) destroy, due to client %u shutdown.\n",
4547               ch->gid, ch->lid_root, ch->lid_dest, c->id);
4548
4549   if (c == ch->dest)
4550   {
4551     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Client %u is destination.\n", c->id);
4552   }
4553   if (c == ch->root)
4554   {
4555     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Client %u is owner.\n", c->id);
4556   }
4557
4558   t = ch->t;
4559   channel_send_destroy (ch);
4560   channel_destroy (ch);
4561   tunnel_destroy_if_empty (t);
4562
4563   return GNUNET_OK;
4564 }
4565
4566
4567 /**
4568  * Remove client's ports from the global hashmap on disconnect.
4569  *
4570  * @param cls Closure (unused).
4571  * @param key Port.
4572  * @param value Client structure.
4573  *
4574  * @return GNUNET_OK, keep iterating.
4575  */
4576 static int
4577 client_release_ports (void *cls,
4578                       uint32_t key,
4579                       void *value)
4580 {
4581   int res;
4582
4583   res = GNUNET_CONTAINER_multihashmap32_remove (ports, key, value);
4584   if (GNUNET_YES != res)
4585   {
4586     GNUNET_break (0);
4587     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4588                 "Port %u by client %p was not registered.\n",
4589                 key, value);
4590   }
4591   return GNUNET_OK;
4592 }
4593
4594
4595 /**
4596  * Timeout function due to lack of keepalive/traffic from the owner.
4597  * Destroys connection if called.
4598  *
4599  * @param cls Closure (connection to destroy).
4600  * @param tc TaskContext.
4601  */
4602 static void
4603 connection_fwd_timeout (void *cls,
4604                         const struct GNUNET_SCHEDULER_TaskContext *tc)
4605 {
4606   struct MeshConnection *c = cls;
4607
4608   c->fwd_maintenance_task = GNUNET_SCHEDULER_NO_TASK;
4609   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
4610     return;
4611   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4612               "Connection %s[%X] FWD timed out. Destroying.\n",
4613               peer2s (c->t->peer),
4614               c->id);
4615
4616   if (connection_is_origin (c, GNUNET_YES)) /* If local, leave. */
4617     return;
4618
4619   connection_destroy (c);
4620 }
4621
4622
4623 /**
4624  * Timeout function due to lack of keepalive/traffic from the destination.
4625  * Destroys connection if called.
4626  *
4627  * @param cls Closure (connection to destroy).
4628  * @param tc TaskContext
4629  */
4630 static void
4631 connection_bck_timeout (void *cls,
4632                         const struct GNUNET_SCHEDULER_TaskContext *tc)
4633 {
4634   struct MeshConnection *c = cls;
4635
4636   c->bck_maintenance_task = GNUNET_SCHEDULER_NO_TASK;
4637   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
4638     return;
4639
4640   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4641               "Connection %s[%X] FWD timed out. Destroying.\n",
4642               peer2s (c->t->peer),
4643               c->id);
4644
4645   if (connection_is_origin (c, GNUNET_NO)) /* If local, leave. */
4646     return;
4647
4648   connection_destroy (c);
4649 }
4650
4651
4652 /**
4653  * Resets the connection timeout task, some other message has done the
4654  * task's job.
4655  * - For the first peer on the direction this means to send
4656  *   a keepalive or a path confirmation message (either create or ACK).
4657  * - For all other peers, this means to destroy the connection,
4658  *   due to lack of activity.
4659  * Starts the tiemout if no timeout was running (connection just created).
4660  *
4661  * @param c Connection whose timeout to reset.
4662  * @param fwd Is this forward?
4663  *
4664  * TODO use heap to improve efficiency of scheduler.
4665  */
4666 static void
4667 connection_reset_timeout (struct MeshConnection *c, int fwd)
4668 {
4669   GNUNET_SCHEDULER_TaskIdentifier *ti;
4670   GNUNET_SCHEDULER_Task f;
4671
4672   ti = fwd ? &c->fwd_maintenance_task : &c->bck_maintenance_task;
4673
4674   if (GNUNET_SCHEDULER_NO_TASK != *ti)
4675     GNUNET_SCHEDULER_cancel (*ti);
4676
4677   if (connection_is_origin (c, fwd)) /* Endpoint */
4678   {
4679     f  = fwd ? &connection_fwd_keepalive : &connection_bck_keepalive;
4680     *ti = GNUNET_SCHEDULER_add_delayed (refresh_connection_time, f, c);
4681   }
4682   else /* Relay */
4683   {
4684     struct GNUNET_TIME_Relative delay;
4685
4686     delay = GNUNET_TIME_relative_multiply (refresh_connection_time, 4);
4687     f  = fwd ? &connection_fwd_timeout : &connection_bck_timeout;
4688     *ti = GNUNET_SCHEDULER_add_delayed (delay, f, c);
4689   }
4690 }
4691
4692
4693 /**
4694  * Iterator to notify all connections of a broken link. Mark connections
4695  * to destroy after all traffic has been sent.
4696  *
4697  * @param cls Closure (peer disconnected).
4698  * @param key Current key code (tid).
4699  * @param value Value in the hash map (connection).
4700  *
4701  * @return GNUNET_YES if we should continue to iterate,
4702  *         GNUNET_NO if not.
4703  */
4704 static int
4705 connection_broken (void *cls,
4706                    const struct GNUNET_HashCode *key,
4707                    void *value)
4708 {
4709   struct MeshPeer *peer = cls;
4710   struct MeshConnection *c = value;
4711   struct GNUNET_MESH_ConnectionBroken msg;
4712   int fwd;
4713
4714   fwd = peer == connection_get_prev_hop (c);
4715
4716   connection_cancel_queues (c, !fwd);
4717   if (connection_is_terminal (c, fwd))
4718   {
4719     /* Local shutdown, no one to notify about this. */
4720     connection_destroy (c);
4721     return GNUNET_YES;
4722   }
4723
4724   msg.header.size = htons (sizeof (struct GNUNET_MESH_ConnectionBroken));
4725   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_CONNECTION_BROKEN);
4726   msg.cid = c->id;
4727   msg.peer1 = my_full_id;
4728   msg.peer2 = *GNUNET_PEER_resolve2 (peer->id);
4729   send_prebuilt_message_connection (&msg.header, c, NULL, fwd);
4730   c->destroy = GNUNET_YES;
4731
4732   return GNUNET_YES;
4733 }
4734
4735 /******************************************************************************/
4736 /****************      MESH NETWORK HANDLER HELPERS     ***********************/
4737 /******************************************************************************/
4738
4739 /**
4740  * Free a transmission that was already queued with all resources
4741  * associated to the request.
4742  *
4743  * @param queue Queue handler to cancel.
4744  * @param clear_cls Is it necessary to free associated cls?
4745  */
4746 static void
4747 queue_destroy (struct MeshPeerQueue *queue, int clear_cls)
4748 {
4749   struct MeshPeer *peer;
4750   struct MeshFlowControl *fc;
4751   int fwd;
4752
4753   fwd = queue->fwd;
4754   peer = queue->peer;
4755   GNUNET_assert (NULL != queue->c);
4756   fc = fwd ? &queue->c->fwd_fc : &queue->c->bck_fc;
4757
4758   if (GNUNET_YES == clear_cls)
4759   {
4760     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   queue destroy type %s\n",
4761                 GNUNET_MESH_DEBUG_M2S (queue->type));
4762     switch (queue->type)
4763     {
4764       case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_DESTROY:
4765       case GNUNET_MESSAGE_TYPE_MESH_TUNNEL_DESTROY:
4766         GNUNET_log (GNUNET_ERROR_TYPE_INFO, "destroying a DESTROY message\n");
4767         GNUNET_break (GNUNET_YES == queue->c->destroy);
4768         /* fall through */
4769       case GNUNET_MESSAGE_TYPE_MESH_FWD:
4770       case GNUNET_MESSAGE_TYPE_MESH_BCK:
4771       case GNUNET_MESSAGE_TYPE_MESH_ACK:
4772       case GNUNET_MESSAGE_TYPE_MESH_POLL:
4773       case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_ACK:
4774       case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_CREATE:
4775       case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_BROKEN:
4776         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   prebuilt message\n");;
4777         GNUNET_free_non_null (queue->cls);
4778         break;
4779
4780       default:
4781         GNUNET_break (0);
4782         GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "   type %s unknown!\n",
4783                     GNUNET_MESH_DEBUG_M2S (queue->type));
4784     }
4785
4786   }
4787   GNUNET_CONTAINER_DLL_remove (peer->queue_head, peer->queue_tail, queue);
4788
4789   if (queue->type != GNUNET_MESSAGE_TYPE_MESH_ACK &&
4790       queue->type != GNUNET_MESSAGE_TYPE_MESH_POLL)
4791   {
4792     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Q_N- %p %u\n", fc, fc->queue_n);
4793     fc->queue_n--;
4794     peer->queue_n--;
4795   }
4796   if (NULL != queue->c)
4797   {
4798     queue->c->pending_messages--;
4799     if (NULL != queue->c->t)
4800     {
4801       queue->c->t->pending_messages--;
4802     }
4803   }
4804
4805   GNUNET_free (queue);
4806 }
4807
4808
4809 static size_t
4810 queue_send (void *cls, size_t size, void *buf)
4811 {
4812   struct MeshPeer *peer = cls;
4813   struct MeshFlowControl *fc;
4814   struct MeshConnection *c;
4815   struct GNUNET_MessageHeader *msg;
4816   struct MeshPeerQueue *queue;
4817   struct MeshTunnel2 *t;
4818   struct MeshChannel *ch;
4819   const struct GNUNET_PeerIdentity *dst_id;
4820   size_t data_size;
4821   uint32_t pid;
4822   uint16_t type;
4823   int fwd;
4824
4825   peer->core_transmit = NULL;
4826   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* Queue send (max %u)\n", size);
4827
4828   if (NULL == buf || 0 == size)
4829   {
4830     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* Buffer size 0.\n");
4831     return 0;
4832   }
4833
4834   /* Initialize */
4835   queue = peer_get_first_message (peer);
4836   if (NULL == queue)
4837   {
4838     GNUNET_break (0); /* Core tmt_rdy should've been canceled */
4839     return 0;
4840   }
4841   c = queue->c;
4842   fwd = queue->fwd;
4843   fc = fwd ? &c->fwd_fc : &c->bck_fc;
4844
4845
4846   dst_id = GNUNET_PEER_resolve2 (peer->id);
4847   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*   towards %s\n", GNUNET_i2s (dst_id));
4848   /* Check if buffer size is enough for the message */
4849   if (queue->size > size)
4850   {
4851       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*   not enough room, reissue\n");
4852       peer->core_transmit =
4853           GNUNET_CORE_notify_transmit_ready (core_handle,
4854                                              GNUNET_NO,
4855                                              0,
4856                                              GNUNET_TIME_UNIT_FOREVER_REL,
4857                                              dst_id,
4858                                              queue->size,
4859                                              &queue_send,
4860                                              peer);
4861       return 0;
4862   }
4863   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*   size %u ok\n", queue->size);
4864
4865   t = (NULL != c) ? c->t : NULL;
4866   type = 0;
4867
4868   /* Fill buf */
4869   switch (queue->type)
4870   {
4871     case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_DESTROY:
4872     case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_BROKEN:
4873     case GNUNET_MESSAGE_TYPE_MESH_FWD:
4874     case GNUNET_MESSAGE_TYPE_MESH_BCK:
4875     case GNUNET_MESSAGE_TYPE_MESH_ACK:
4876     case GNUNET_MESSAGE_TYPE_MESH_POLL:
4877       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4878                   "*   raw: %s\n",
4879                   GNUNET_MESH_DEBUG_M2S (queue->type));
4880       data_size = send_core_data_raw (queue->cls, size, buf);
4881       msg = (struct GNUNET_MessageHeader *) buf;
4882       type = ntohs (msg->type);
4883       break;
4884     case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_CREATE:
4885       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*   path create\n");
4886       if (connection_is_origin (c, GNUNET_YES))
4887         data_size = send_core_connection_create (queue->c, size, buf);
4888       else
4889         data_size = send_core_data_raw (queue->cls, size, buf);
4890       break;
4891     case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_ACK:
4892       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*   path ack\n");
4893       if (connection_is_origin (c, GNUNET_NO) ||
4894           connection_is_origin (c, GNUNET_YES))
4895         data_size = send_core_connection_ack (queue->c, size, buf);
4896       else
4897         data_size = send_core_data_raw (queue->cls, size, buf);
4898       break;
4899     case GNUNET_MESSAGE_TYPE_MESH_DATA:
4900     case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_CREATE:
4901     case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_DESTROY:
4902       /* This should be encapsulted */
4903       GNUNET_break (0);
4904       data_size = 0;
4905       break;
4906     default:
4907       GNUNET_break (0);
4908       GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "*   type unknown: %u\n",
4909                   queue->type);
4910       data_size = 0;
4911   }
4912
4913   if (0 < drop_percent &&
4914       GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, 101) < drop_percent)
4915   {
4916     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4917                 "Dropping message of type %s\n",
4918                 GNUNET_MESH_DEBUG_M2S (queue->type));
4919     data_size = 0;
4920   }
4921
4922   /* Free queue, but cls was freed by send_core_* */
4923   ch = queue->ch;
4924   queue_destroy (queue, GNUNET_NO);
4925
4926   /* Send ACK if needed, after accounting for sent ID in fc->queue_n */
4927   switch (type)
4928   {
4929     case GNUNET_MESSAGE_TYPE_MESH_FWD:
4930     case GNUNET_MESSAGE_TYPE_MESH_BCK:
4931       pid = ntohl ( ((struct GNUNET_MESH_Encrypted *) buf)->pid );
4932       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*   accounting pid %u\n", pid);
4933       fc->last_pid_sent = pid;
4934       send_ack (c, ch, fwd);
4935       break;
4936     default:
4937       break;
4938   }
4939
4940   /* If more data in queue, send next */
4941   queue = peer_get_first_message (peer);
4942   if (NULL != queue)
4943   {
4944     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*   more data!\n");
4945     if (NULL == peer->core_transmit) {
4946       peer->core_transmit =
4947           GNUNET_CORE_notify_transmit_ready(core_handle,
4948                                             0,
4949                                             0,
4950                                             GNUNET_TIME_UNIT_FOREVER_REL,
4951                                             dst_id,
4952                                             queue->size,
4953                                             &queue_send,
4954                                             peer);
4955     }
4956     else
4957     {
4958       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4959                   "*   tmt rdy called somewhere else\n");
4960     }
4961     if (GNUNET_SCHEDULER_NO_TASK == fc->poll_task)
4962     {
4963       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*   starting poll timeout\n");
4964       fc->poll_task =
4965           GNUNET_SCHEDULER_add_delayed (fc->poll_time, &connection_poll, fc);
4966     }
4967   }
4968   else
4969   {
4970     if (GNUNET_SCHEDULER_NO_TASK != fc->poll_task)
4971     {
4972       GNUNET_SCHEDULER_cancel (fc->poll_task);
4973       fc->poll_task = GNUNET_SCHEDULER_NO_TASK;
4974     }
4975   }
4976   if (NULL != c)
4977   {
4978     c->pending_messages--;
4979     if (GNUNET_YES == c->destroy && 0 == c->pending_messages)
4980     {
4981       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*  destroying connection!\n");
4982       connection_destroy (c);
4983     }
4984   }
4985
4986   if (NULL != t)
4987   {
4988     t->pending_messages--;
4989     if (GNUNET_YES == t->destroy && 0 == t->pending_messages)
4990     {
4991 //       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*  destroying tunnel!\n");
4992       tunnel_destroy (t);
4993     }
4994   }
4995   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*  Return %d\n", data_size);
4996   return data_size;
4997 }
4998
4999
5000 static void
5001 queue_add (void *cls, uint16_t type, size_t size,
5002            struct MeshConnection *c,
5003            struct MeshChannel *ch,
5004            int fwd)
5005 {
5006   struct MeshPeerQueue *queue;
5007   struct MeshFlowControl *fc;
5008   struct MeshPeer *peer;
5009   int priority;
5010   int call_core;
5011
5012   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5013               "queue add %s %s (%u) on c %p, ch %p\n",
5014               fwd ? "FWD" : "BCK",  GNUNET_MESH_DEBUG_M2S (type), size, c, ch);
5015   GNUNET_assert (NULL != c);
5016
5017   fc   = fwd ? &c->fwd_fc : &c->bck_fc;
5018   peer = fwd ? connection_get_next_hop (c) : connection_get_prev_hop (c);
5019
5020   if (NULL == fc)
5021   {
5022     GNUNET_break (0);
5023     return;
5024   }
5025
5026   priority = 0;
5027
5028   if (GNUNET_MESSAGE_TYPE_MESH_POLL == type ||
5029       GNUNET_MESSAGE_TYPE_MESH_ACK == type)
5030   {
5031     priority = 100;
5032   }
5033
5034   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "priority %d\n", priority);
5035   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "fc %p\n", fc);
5036   if (fc->queue_n >= fc->queue_max && 0 == priority)
5037   {
5038     GNUNET_STATISTICS_update (stats, "# messages dropped (buffer full)",
5039                               1, GNUNET_NO);
5040     GNUNET_break (0);
5041     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5042                 "queue full: %u/%u\n",
5043                 fc->queue_n, fc->queue_max);
5044     return; /* Drop this message */
5045   }
5046
5047   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "last pid %u\n", fc->last_pid_sent);
5048   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "     ack %u\n", fc->last_ack_recv);
5049   if (GMC_is_pid_bigger (fc->last_pid_sent + 1, fc->last_ack_recv))
5050   {
5051     call_core = GNUNET_NO;
5052     if (GNUNET_SCHEDULER_NO_TASK == fc->poll_task &&
5053         GNUNET_MESSAGE_TYPE_MESH_POLL != type)
5054     {
5055       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5056                   "no buffer space (%u > %u): starting poll\n",
5057                   fc->last_pid_sent + 1, fc->last_ack_recv);
5058       fc->poll_task = GNUNET_SCHEDULER_add_delayed (fc->poll_time,
5059                                                     &connection_poll,
5060                                                     fc);
5061     }
5062   }
5063   else
5064     call_core = GNUNET_YES;
5065   queue = GNUNET_malloc (sizeof (struct MeshPeerQueue));
5066   queue->cls = cls;
5067   queue->type = type;
5068   queue->size = size;
5069   queue->peer = peer;
5070   queue->c = c;
5071   queue->ch = ch;
5072   queue->fwd = fwd;
5073   if (100 <= priority)
5074   {
5075     GNUNET_CONTAINER_DLL_insert (peer->queue_head, peer->queue_tail, queue);
5076   }
5077   else
5078   {
5079     GNUNET_CONTAINER_DLL_insert_tail (peer->queue_head, peer->queue_tail, queue);
5080     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Q_N+ %p %u\n", fc, fc->queue_n);
5081     fc->queue_n++;
5082     peer->queue_n++;
5083   }
5084
5085   if (NULL == peer->core_transmit && GNUNET_YES == call_core)
5086   {
5087     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5088                 "calling core tmt rdy towards %s for %u bytes\n",
5089                 peer2s (peer), size);
5090     peer->core_transmit =
5091         GNUNET_CORE_notify_transmit_ready (core_handle,
5092                                            0,
5093                                            0,
5094                                            GNUNET_TIME_UNIT_FOREVER_REL,
5095                                            GNUNET_PEER_resolve2 (peer->id),
5096                                            size,
5097                                            &queue_send,
5098                                            peer);
5099   }
5100   else
5101   {
5102     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5103                 "core tmt rdy towards %s already called\n",
5104                 peer2s (peer));
5105
5106   }
5107   c->pending_messages++;
5108   if (NULL != c->t)
5109     c->t->pending_messages++;
5110 }
5111
5112
5113 /******************************************************************************/
5114 /********************      MESH NETWORK HANDLERS     **************************/
5115 /******************************************************************************/
5116
5117
5118 /**
5119  * Generic handler for mesh network payload traffic.
5120  *
5121  * @param t Tunnel on which we got this message.
5122  * @param message Unencryted data message.
5123  * @param fwd Is this FWD traffic? GNUNET_YES : GNUNET_NO;
5124  */
5125 static void
5126 handle_data (struct MeshTunnel2 *t, const struct GNUNET_MESH_Data *msg, int fwd)
5127 {
5128   struct MeshChannelReliability *rel;
5129   struct MeshChannel *ch;
5130   struct MeshClient *c;
5131   uint32_t mid;
5132   uint16_t type;
5133   size_t size;
5134
5135   /* Check size */
5136   size = ntohs (msg->header.size);
5137   if (size <
5138       sizeof (struct GNUNET_MESH_Data) +
5139       sizeof (struct GNUNET_MessageHeader))
5140   {
5141     GNUNET_break (0);
5142     return;
5143   }
5144   type = ntohs (msg->header.type);
5145   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a %s message\n",
5146               GNUNET_MESH_DEBUG_M2S (type));
5147   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " payload of type %s\n",
5148               GNUNET_MESH_DEBUG_M2S (ntohs (msg[1].header.type)));
5149
5150   /* Check channel */
5151   ch = channel_get (t, ntohl (msg->chid));
5152   if (NULL == ch)
5153   {
5154     GNUNET_STATISTICS_update (stats, "# data on unknown channel", 1, GNUNET_NO);
5155     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
5156                 ntohl (msg->chid));
5157     return;
5158   }
5159
5160   /*  Initialize FWD/BCK data */
5161   c        = fwd ? ch->dest     : ch->root;
5162   rel      = fwd ? ch->dest_rel : ch->root_rel;
5163
5164   if (NULL == c)
5165   {
5166     GNUNET_break (0);
5167     return;
5168   }
5169
5170   tunnel_change_state (t, MESH_TUNNEL_READY);
5171
5172   GNUNET_STATISTICS_update (stats, "# data received", 1, GNUNET_NO);
5173
5174   mid = ntohl (msg->mid);
5175   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " mid %u\n", mid);
5176
5177   if (GNUNET_NO == ch->reliable ||
5178       ( !GMC_is_pid_bigger (rel->mid_recv, mid) &&
5179         GMC_is_pid_bigger (rel->mid_recv + 64, mid) ) )
5180   {
5181     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! RECV %u\n", mid);
5182     if (GNUNET_YES == ch->reliable)
5183     {
5184       /* Is this the exact next expected messasge? */
5185       if (mid == rel->mid_recv)
5186       {
5187         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "as expected\n");
5188         rel->mid_recv++;
5189         channel_send_client_data (ch, msg, fwd);
5190       }
5191       else
5192       {
5193         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "save for later\n");
5194         channel_rel_add_buffered_data (msg, rel);
5195       }
5196     }
5197     else
5198     {
5199       /* Tunnel is unreliable: send to clients directly */
5200       /* FIXME: accept Out Of Order traffic */
5201       rel->mid_recv = mid + 1;
5202       channel_send_client_data (ch, msg, fwd);
5203     }
5204   }
5205   else
5206   {
5207     GNUNET_break_op (0);
5208     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5209                 " MID %u not expected (%u - %u), dropping!\n",
5210                 mid, rel->mid_recv, rel->mid_recv + 64);
5211   }
5212
5213   channel_send_data_ack (ch, fwd);
5214 }
5215
5216 /**
5217  * Handler for mesh network traffic end-to-end ACKs.
5218  *
5219  * @param t Tunnel on which we got this message.
5220  * @param message Data message.
5221  * @param fwd Is this a fwd ACK? (dest->orig)
5222  */
5223 static void
5224 handle_data_ack (struct MeshTunnel2 *t,
5225                  const struct GNUNET_MESH_DataACK *msg, int fwd)
5226 {
5227   struct MeshChannelReliability *rel;
5228   struct MeshReliableMessage *copy;
5229   struct MeshReliableMessage *next;
5230   struct MeshChannel *ch;
5231   uint32_t ack;
5232   uint16_t type;
5233   int work;
5234
5235   type = ntohs (msg->header.type);
5236   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a %s message!\n",
5237               GNUNET_MESH_DEBUG_M2S (type));
5238   ch = channel_get (t, ntohl (msg->chid));
5239   if (NULL == ch)
5240   {
5241     GNUNET_STATISTICS_update (stats, "# ack on unknown channel", 1, GNUNET_NO);
5242     return;
5243   }
5244   ack = ntohl (msg->mid);
5245   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! %s ACK %u\n",
5246               (GNUNET_YES == fwd) ? "FWD" : "BCK", ack);
5247
5248   if (GNUNET_YES == fwd)
5249   {
5250     rel = ch->root_rel;
5251   }
5252   else
5253   {
5254     rel = ch->dest_rel;
5255   }
5256   if (NULL == rel)
5257   {
5258     GNUNET_break (0);
5259     return;
5260   }
5261
5262   for (work = GNUNET_NO, copy = rel->head_sent; copy != NULL; copy = next)
5263   {
5264     if (GMC_is_pid_bigger (copy->mid, ack))
5265     {
5266       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!!  head %u, out!\n", copy->mid);
5267       channel_rel_free_sent (rel, msg);
5268       break;
5269     }
5270     work = GNUNET_YES;
5271     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!!  id %u\n", copy->mid);
5272     next = copy->next;
5273     rel_message_free (copy);
5274   }
5275   /* ACK client if needed */
5276 //   channel_send_ack (t, type, GNUNET_MESSAGE_TYPE_MESH_UNICAST_ACK == type);
5277
5278   /* If some message was free'd, update the retransmission delay*/
5279   if (GNUNET_YES == work)
5280   {
5281     if (GNUNET_SCHEDULER_NO_TASK != rel->retry_task)
5282     {
5283       GNUNET_SCHEDULER_cancel (rel->retry_task);
5284       if (NULL == rel->head_sent)
5285       {
5286         rel->retry_task = GNUNET_SCHEDULER_NO_TASK;
5287       }
5288       else
5289       {
5290         struct GNUNET_TIME_Absolute new_target;
5291         struct GNUNET_TIME_Relative delay;
5292
5293         delay = GNUNET_TIME_relative_multiply (rel->retry_timer,
5294                                                MESH_RETRANSMIT_MARGIN);
5295         new_target = GNUNET_TIME_absolute_add (rel->head_sent->timestamp,
5296                                                delay);
5297         delay = GNUNET_TIME_absolute_get_remaining (new_target);
5298         rel->retry_task =
5299             GNUNET_SCHEDULER_add_delayed (delay,
5300                                           &channel_retransmit_message,
5301                                           rel);
5302       }
5303     }
5304     else
5305       GNUNET_break (0);
5306   }
5307 }
5308
5309
5310 /**
5311  * Core handler for connection creation.
5312  *
5313  * @param cls Closure (unused).
5314  * @param peer Sender (neighbor).
5315  * @param message Message.
5316  *
5317  * @return GNUNET_OK to keep the connection open,
5318  *         GNUNET_SYSERR to close it (signal serious error)
5319  */
5320 static int
5321 handle_mesh_connection_create (void *cls,
5322                                const struct GNUNET_PeerIdentity *peer,
5323                                const struct GNUNET_MessageHeader *message)
5324 {
5325   struct GNUNET_MESH_ConnectionCreate *msg;
5326   struct GNUNET_PeerIdentity *id;
5327   struct GNUNET_HashCode *cid;
5328   struct MeshPeerPath *path;
5329   struct MeshPeer *dest_peer;
5330   struct MeshPeer *orig_peer;
5331   struct MeshConnection *c;
5332   unsigned int own_pos;
5333   uint16_t size;
5334   uint16_t i;
5335
5336   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "\n\n");
5337   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received a connection create msg\n");
5338
5339   /* Check size */
5340   size = ntohs (message->size);
5341   if (size < sizeof (struct GNUNET_MESH_ConnectionCreate))
5342   {
5343     GNUNET_break_op (0);
5344     return GNUNET_OK;
5345   }
5346
5347   /* Calculate hops */
5348   size -= sizeof (struct GNUNET_MESH_ConnectionCreate);
5349   if (size % sizeof (struct GNUNET_PeerIdentity))
5350   {
5351     GNUNET_break_op (0);
5352     return GNUNET_OK;
5353   }
5354   size /= sizeof (struct GNUNET_PeerIdentity);
5355   if (1 > size)
5356   {
5357     GNUNET_break_op (0);
5358     return GNUNET_OK;
5359   }
5360   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "    path has %u hops.\n", size);
5361
5362   /* Get parameters */
5363   msg = (struct GNUNET_MESH_ConnectionCreate *) message;
5364   cid = &msg->cid;
5365   id = (struct GNUNET_PeerIdentity *) &msg[1];
5366   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5367               "    connection %s (%s).\n",
5368               GNUNET_h2s (cid), GNUNET_i2s (id));
5369
5370   /* Create connection */
5371   c = connection_get (cid);
5372   if (NULL == c)
5373   {
5374     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Creating connection\n");
5375     c = connection_new (cid);
5376     if (NULL == c)
5377       return GNUNET_OK;
5378     connection_reset_timeout (c, GNUNET_YES);
5379
5380     /* Create path */
5381     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Creating path...\n");
5382     path = path_new (size);
5383     own_pos = 0;
5384     for (i = 0; i < size; i++)
5385     {
5386       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  ... adding %s\n",
5387                   GNUNET_i2s (&id[i]));
5388       path->peers[i] = GNUNET_PEER_intern (&id[i]);
5389       if (path->peers[i] == myid)
5390         own_pos = i;
5391     }
5392     if (own_pos == 0 && path->peers[own_pos] != myid)
5393     {
5394       /* create path: self not found in path through self */
5395       GNUNET_break_op (0);
5396       path_destroy (path);
5397       connection_destroy (c);
5398       return GNUNET_OK;
5399     }
5400     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Own position: %u\n", own_pos);
5401     path_add_to_peers (path, GNUNET_NO);
5402     c->path = path_duplicate (path);
5403     c->own_pos = own_pos;
5404   }
5405   else
5406   {
5407     path = NULL;
5408   }
5409   if (MESH_CONNECTION_NEW == c->state)
5410     connection_change_state (c, MESH_CONNECTION_SENT);
5411
5412   /* Remember peers */
5413   dest_peer = peer_get (&id[size - 1]);
5414   orig_peer = peer_get (&id[0]);
5415
5416   /* Is it a connection to us? */
5417   if (c->own_pos == size - 1)
5418   {
5419     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  It's for us!\n");
5420     peer_add_path_to_origin (orig_peer, path, GNUNET_YES);
5421
5422     if (NULL == orig_peer->tunnel)
5423     {
5424       orig_peer->tunnel = tunnel_new ();
5425       orig_peer->tunnel->peer = orig_peer;
5426     }
5427     tunnel_add_connection (orig_peer->tunnel, c);
5428     if (MESH_TUNNEL_NEW == c->t->state)
5429       tunnel_change_state (c->t,  MESH_TUNNEL_WAITING);
5430
5431     send_connection_ack (c, GNUNET_NO);
5432     if (MESH_CONNECTION_SENT == c->state)
5433       connection_change_state (c, MESH_CONNECTION_ACK);
5434
5435     /* Keep tunnel alive in direction dest->owner*/
5436     connection_reset_timeout (c, GNUNET_NO);
5437   }
5438   else
5439   {
5440     /* It's for somebody else! Retransmit. */
5441     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Retransmitting.\n");
5442     peer_add_path (dest_peer, path_duplicate (path), GNUNET_NO);
5443     peer_add_path_to_origin (orig_peer, path, GNUNET_NO);
5444     send_prebuilt_message_connection (message, c, NULL, GNUNET_YES);
5445   }
5446   return GNUNET_OK;
5447 }
5448
5449
5450 /**
5451  * Core handler for path ACKs
5452  *
5453  * @param cls closure
5454  * @param message message
5455  * @param peer peer identity this notification is about
5456  *
5457  * @return GNUNET_OK to keep the connection open,
5458  *         GNUNET_SYSERR to close it (signal serious error)
5459  */
5460 static int
5461 handle_mesh_connection_ack (void *cls, const struct GNUNET_PeerIdentity *peer,
5462                             const struct GNUNET_MessageHeader *message)
5463 {
5464   struct GNUNET_MESH_ConnectionACK *msg;
5465   struct MeshConnection *c;
5466   struct MeshPeerPath *p;
5467   struct MeshPeer *pi;
5468   int fwd;
5469
5470   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "\n\n");
5471   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received a connection ACK msg\n");
5472   msg = (struct GNUNET_MESH_ConnectionACK *) message;
5473   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on connection %s\n",
5474               GNUNET_h2s (&msg->cid));
5475   c = connection_get (&msg->cid);
5476   if (NULL == c)
5477   {
5478     GNUNET_STATISTICS_update (stats, "# control on unknown connection",
5479                               1, GNUNET_NO);
5480     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  don't know the connection!\n");
5481     return GNUNET_OK;
5482   }
5483
5484
5485   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  via peer %s\n",
5486               GNUNET_i2s (peer));
5487   pi = peer_get (peer);
5488   if (connection_get_next_hop (c) == pi)
5489   {
5490     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  SYNACK\n");
5491     fwd = GNUNET_NO;
5492     if (MESH_CONNECTION_SENT == c->state)
5493       connection_change_state (c, MESH_CONNECTION_ACK);
5494   }
5495   else if (connection_get_prev_hop (c) == pi)
5496   {
5497     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  ACK\n");
5498     fwd = GNUNET_YES;
5499     connection_change_state (c, MESH_CONNECTION_READY);
5500   }
5501   else
5502   {
5503     GNUNET_break_op (0);
5504     return GNUNET_OK;
5505   }
5506   connection_reset_timeout (c, fwd);
5507
5508   /* Add path to peers? */
5509   p = c->path;
5510   if (NULL != p)
5511   {
5512     path_add_to_peers (p, GNUNET_YES);
5513   }
5514   else
5515   {
5516     GNUNET_break (0);
5517   }
5518
5519   /* Message for us as creator? */
5520   if (connection_is_origin (c, GNUNET_YES))
5521   {
5522     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Connection (SYN)ACK for us!\n");
5523     connection_change_state (c, MESH_CONNECTION_READY);
5524     if (MESH_TUNNEL_READY != c->t->state)
5525       tunnel_change_state (c->t, MESH_TUNNEL_READY);
5526     send_connection_ack (c, GNUNET_YES);
5527     tunnel_send_queued_data (c->t, GNUNET_YES);
5528     if (3 <= tunnel_count_connections (c->t) && NULL != c->t->peer->dhtget)
5529     {
5530       GNUNET_DHT_get_stop (c->t->peer->dhtget);
5531       c->t->peer->dhtget = NULL;
5532     }
5533     return GNUNET_OK;
5534   }
5535
5536   /* Message for us as destination? */
5537   if (connection_is_terminal (c, GNUNET_YES))
5538   {
5539     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Connection ACK for us!\n");
5540     if (MESH_TUNNEL_READY != c->t->state)
5541       tunnel_change_state (c->t, MESH_TUNNEL_READY);
5542     connection_change_state (c, MESH_CONNECTION_READY);
5543     tunnel_send_queued_data (c->t, GNUNET_NO);
5544     return GNUNET_OK;
5545   }
5546
5547   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  not for us, retransmitting...\n");
5548   send_prebuilt_message_connection (message, c, NULL, fwd);
5549   return GNUNET_OK;
5550 }
5551
5552
5553 /**
5554  * Core handler for notifications of broken paths
5555  *
5556  * @param cls Closure (unused).
5557  * @param peer Peer identity of sending neighbor.
5558  * @param message Message.
5559  *
5560  * @return GNUNET_OK to keep the connection open,
5561  *         GNUNET_SYSERR to close it (signal serious error)
5562  */
5563 static int
5564 handle_mesh_connection_broken (void *cls, const struct GNUNET_PeerIdentity *peer,
5565                                const struct GNUNET_MessageHeader *message)
5566 {
5567   struct GNUNET_MESH_ConnectionBroken *msg;
5568   struct MeshConnection *c;
5569
5570   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5571               "Received a CONNECTION BROKEN msg from %s\n", GNUNET_i2s (peer));
5572   msg = (struct GNUNET_MESH_ConnectionBroken *) message;
5573   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  regarding %s\n",
5574               GNUNET_i2s (&msg->peer1));
5575   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  regarding %s\n",
5576               GNUNET_i2s (&msg->peer2));
5577   c = connection_get (&msg->cid);
5578   if (NULL == c)
5579   {
5580     GNUNET_break_op (0);
5581     return GNUNET_OK;
5582   }
5583   tunnel_notify_connection_broken (c->t, GNUNET_PEER_search (&msg->peer1),
5584                                    GNUNET_PEER_search (&msg->peer2));
5585   return GNUNET_OK;
5586
5587 }
5588
5589
5590 /**
5591  * Core handler for tunnel destruction
5592  *
5593  * @param cls Closure (unused).
5594  * @param peer Peer identity of sending neighbor.
5595  * @param message Message.
5596  *
5597  * @return GNUNET_OK to keep the connection open,
5598  *         GNUNET_SYSERR to close it (signal serious error)
5599  */
5600 static int
5601 handle_mesh_connection_destroy (void *cls,
5602                                 const struct GNUNET_PeerIdentity *peer,
5603                                 const struct GNUNET_MessageHeader *message)
5604 {
5605   struct GNUNET_MESH_ConnectionDestroy *msg;
5606   struct MeshConnection *c;
5607   GNUNET_PEER_Id id;
5608   int fwd;
5609
5610   msg = (struct GNUNET_MESH_ConnectionDestroy *) message;
5611   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5612               "Got a CONNECTION DESTROY message from %s\n",
5613               GNUNET_i2s (peer));
5614   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5615               "  for connection %s\n",
5616               GNUNET_h2s (&msg->cid));
5617   c = connection_get (&msg->cid);
5618   if (NULL == c)
5619   {
5620     /* Probably already got the message from another path,
5621      * destroyed the tunnel and retransmitted to children.
5622      * Safe to ignore.
5623      */
5624     GNUNET_STATISTICS_update (stats, "# control on unknown tunnel",
5625                               1, GNUNET_NO);
5626     return GNUNET_OK;
5627   }
5628   id = GNUNET_PEER_search (peer);
5629   if (id == connection_get_prev_hop (c)->id)
5630     fwd = GNUNET_YES;
5631   else if (id == connection_get_next_hop (c)->id)
5632     fwd = GNUNET_NO;
5633   else
5634   {
5635     GNUNET_break_op (0);
5636     return GNUNET_OK;
5637   }
5638   send_prebuilt_message_connection (message, c, NULL, fwd);
5639   c->destroy = GNUNET_YES;
5640
5641   return GNUNET_OK;
5642 }
5643
5644
5645 /**
5646  * Handler for channel create messages.
5647  *
5648  * @param t Tunnel this channel is to be created in.
5649  * @param msg Message.
5650  * @param fwd Is this FWD traffic? GNUNET_YES : GNUNET_NO;
5651  */
5652 static void
5653 handle_channel_create (struct MeshTunnel2 *t,
5654                        struct GNUNET_MESH_ChannelCreate *msg,
5655                        int fwd)
5656 {
5657   MESH_ChannelNumber chid;
5658   struct MeshChannel *ch;
5659   struct MeshClient *c;
5660   uint32_t port;
5661
5662   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received Channel Create\n");
5663   /* Check message size */
5664   if (ntohs (msg->header.size) != sizeof (struct GNUNET_MESH_ChannelCreate))
5665   {
5666     GNUNET_break_op (0);
5667     return;
5668   }
5669
5670   /* Check if channel exists */
5671   chid = ntohl (msg->chid);
5672   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   chid %u\n", chid);
5673   ch = channel_get (t, chid);
5674   if (NULL != ch)
5675   {
5676     /* Probably a retransmission, safe to ignore */
5677     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   already exists...\n");
5678     if (NULL != ch->dest)
5679     {
5680       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   duplicate CC!!\n");
5681       channel_send_ack (ch, !fwd);
5682       return;
5683     }
5684   }
5685   else
5686   {
5687     /* Create channel */
5688     ch = channel_new (t, NULL, 0);
5689     ch->gid = chid;
5690     channel_set_options (ch, ntohl (msg->opt));
5691   }
5692
5693   /* Find a destination client */
5694   port = ntohl (msg->port);
5695   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   port %u\n", port);
5696   c = GNUNET_CONTAINER_multihashmap32_get (ports, port);
5697   if (NULL == c)
5698   {
5699     /* TODO send reject */
5700     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  no client has port registered\n");
5701     /* TODO free ch */
5702     return;
5703   }
5704
5705   channel_add_client (ch, c);
5706   if (GNUNET_YES == ch->reliable)
5707     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! Reliable\n");
5708
5709   send_local_channel_create (ch);
5710   channel_send_ack (ch, fwd);
5711   send_local_ack (ch, !fwd);
5712 }
5713
5714
5715 /**
5716  * Handler for channel ack messages.
5717  *
5718  * @param t Tunnel this channel is to be created in.
5719  * @param msg Message.
5720  * @param fwd Is this FWD traffic? GNUNET_YES : GNUNET_NO;
5721  */
5722 static void
5723 handle_channel_ack (struct MeshTunnel2 *t,
5724                     struct GNUNET_MESH_ChannelManage *msg,
5725                     int fwd)
5726 {
5727   MESH_ChannelNumber chid;
5728   struct MeshChannel *ch;
5729
5730   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received Channel ACK\n");
5731   /* Check message size */
5732   if (ntohs (msg->header.size) != sizeof (struct GNUNET_MESH_ChannelManage))
5733   {
5734     GNUNET_break_op (0);
5735     return;
5736   }
5737
5738   /* Check if channel exists */
5739   chid = ntohl (msg->chid);
5740   ch = channel_get (t, chid);
5741   if (NULL == ch)
5742   {
5743     GNUNET_break_op (0);
5744     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   channel %u unknown!!\n", chid);
5745     return;
5746   }
5747
5748   channel_confirm (ch, !fwd);
5749 }
5750
5751
5752 /**
5753  * Handler for channel destroy messages.
5754  *
5755  * @param t Tunnel this channel is to be destroyed of.
5756  * @param msg Message.
5757  * @param fwd Is this FWD traffic? GNUNET_YES : GNUNET_NO;
5758  */
5759 static void
5760 handle_channel_destroy (struct MeshTunnel2 *t,
5761                         struct GNUNET_MESH_ChannelManage *msg,
5762                         int fwd)
5763 {
5764   MESH_ChannelNumber chid;
5765   struct MeshChannel *ch;
5766
5767   /* Check message size */
5768   if (ntohs (msg->header.size) != sizeof (struct GNUNET_MESH_ChannelManage))
5769   {
5770     GNUNET_break_op (0);
5771     return;
5772   }
5773
5774   /* Check if channel exists */
5775   chid = ntohl (msg->chid);
5776   ch = channel_get (t, chid);
5777   if (NULL == ch)
5778   {
5779     /* Probably a retransmission, safe to ignore */
5780     return;
5781   }
5782
5783   send_local_channel_destroy (ch, fwd);
5784   channel_destroy (ch);
5785 }
5786
5787
5788 static void
5789 handle_decrypted (struct MeshTunnel2 *t,
5790                   const struct GNUNET_MessageHeader *msgh,
5791                   int fwd)
5792 {
5793   switch (ntohs (msgh->type))
5794   {
5795     case GNUNET_MESSAGE_TYPE_MESH_DATA:
5796       /* Don't send hop ACK, wait for client to ACK */
5797       handle_data (t, (struct GNUNET_MESH_Data *) msgh, fwd);
5798       break;
5799
5800     case GNUNET_MESSAGE_TYPE_MESH_DATA_ACK:
5801       handle_data_ack (t, (struct GNUNET_MESH_DataACK *) msgh, fwd);
5802       break;
5803
5804     case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_CREATE:
5805       handle_channel_create (t,
5806                              (struct GNUNET_MESH_ChannelCreate *) msgh,
5807                              fwd);
5808       break;
5809
5810     case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_ACK:
5811       handle_channel_ack (t,
5812                           (struct GNUNET_MESH_ChannelManage *) msgh,
5813                           fwd);
5814       break;
5815
5816     case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_DESTROY:
5817       handle_channel_destroy (t,
5818                               (struct GNUNET_MESH_ChannelManage *) msgh,
5819                               fwd);
5820       break;
5821
5822     default:
5823       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5824                   "end-to-end message not known (%u)\n",
5825                   ntohs (msgh->type));
5826   }
5827 }
5828
5829
5830 /**
5831  * Generic handler for mesh network encrypted traffic.
5832  *
5833  * @param peer Peer identity this notification is about.
5834  * @param message Encrypted message.
5835  * @param fwd Is this FWD traffic? GNUNET_YES : GNUNET_NO;
5836  *
5837  * @return GNUNET_OK to keep the connection open,
5838  *         GNUNET_SYSERR to close it (signal serious error)
5839  */
5840 static int
5841 handle_mesh_encrypted (const struct GNUNET_PeerIdentity *peer,
5842                        const struct GNUNET_MESH_Encrypted *msg,
5843                        int fwd)
5844 {
5845   struct MeshConnection *c;
5846   struct MeshTunnel2 *t;
5847   struct MeshPeer *neighbor;
5848   struct MeshFlowControl *fc;
5849   uint32_t pid;
5850   uint32_t ttl;
5851   uint16_t type;
5852   size_t size;
5853
5854   /* Check size */
5855   size = ntohs (msg->header.size);
5856   if (size <
5857       sizeof (struct GNUNET_MESH_Encrypted) +
5858       sizeof (struct GNUNET_MessageHeader))
5859   {
5860     GNUNET_break_op (0);
5861     return GNUNET_OK;
5862   }
5863   type = ntohs (msg->header.type);
5864   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "\n\n");
5865   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a %s message from %s\n",
5866               GNUNET_MESH_DEBUG_M2S (type), GNUNET_i2s (peer));
5867
5868   /* Check connection */
5869   c = connection_get (&msg->cid);
5870   if (NULL == c)
5871   {
5872     GNUNET_STATISTICS_update (stats, "# unknown connection", 1, GNUNET_NO);
5873     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "WARNING connection unknown\n");
5874     return GNUNET_OK;
5875   }
5876   t = c->t;
5877   fc = fwd ? &c->bck_fc : &c->fwd_fc;
5878
5879   /* Check if origin is as expected */
5880   neighbor = connection_get_hop (c, !fwd);
5881   if (peer_get (peer)->id != neighbor->id)
5882   {
5883     GNUNET_break_op (0);
5884     return GNUNET_OK;
5885   }
5886
5887   /* Check PID */
5888   pid = ntohl (msg->pid);
5889   if (GMC_is_pid_bigger (pid, fc->last_ack_sent))
5890   {
5891     GNUNET_STATISTICS_update (stats, "# unsolicited message", 1, GNUNET_NO);
5892     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5893                 "WARNING Received PID %u, (prev %u), ACK %u\n",
5894                 pid, fc->last_pid_recv, fc->last_ack_sent);
5895     return GNUNET_OK;
5896   }
5897   if (GNUNET_NO == GMC_is_pid_bigger (pid, fc->last_pid_recv))
5898   {
5899     GNUNET_STATISTICS_update (stats, "# duplicate PID", 1, GNUNET_NO);
5900     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5901                 " Pid %u not expected (%u+), dropping!\n",
5902                 pid, fc->last_pid_recv + 1);
5903     return GNUNET_OK;
5904   }
5905   if (MESH_CONNECTION_SENT == c->state)
5906     connection_change_state (c, MESH_CONNECTION_READY);
5907   connection_reset_timeout (c, fwd);
5908   fc->last_pid_recv = pid;
5909
5910   /* Is this message for us? */
5911   if (connection_is_terminal (c, fwd))
5912   {
5913     size_t dsize = size - sizeof (struct GNUNET_MESH_Encrypted);
5914     char cbuf[dsize];
5915     struct GNUNET_MessageHeader *msgh;
5916     unsigned int off;
5917
5918     /* TODO signature verification */
5919     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  message for us!\n");
5920     GNUNET_STATISTICS_update (stats, "# messages received", 1, GNUNET_NO);
5921
5922     fc->last_pid_recv = pid;
5923     tunnel_decrypt (t, cbuf, &msg[1], dsize, msg->iv, fwd);
5924     off = 0;
5925     while (off < dsize)
5926     {
5927       msgh = (struct GNUNET_MessageHeader *) &cbuf[off];
5928       handle_decrypted (t, msgh, fwd);
5929       off += ntohs (msgh->size);
5930     }
5931     send_ack (c, NULL, fwd);
5932     return GNUNET_OK;
5933   }
5934
5935   /* Message not for us: forward to next hop */
5936   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  not for us, retransmitting...\n");
5937   ttl = ntohl (msg->ttl);
5938   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   ttl: %u\n", ttl);
5939   if (ttl == 0)
5940   {
5941     GNUNET_STATISTICS_update (stats, "# TTL drops", 1, GNUNET_NO);
5942     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, " TTL is 0, DROPPING!\n");
5943     send_ack (c, NULL, fwd);
5944     return GNUNET_OK;
5945   }
5946   GNUNET_STATISTICS_update (stats, "# messages forwarded", 1, GNUNET_NO);
5947
5948   send_prebuilt_message_connection (&msg->header, c, NULL, fwd);
5949
5950   return GNUNET_OK;
5951 }
5952
5953
5954 /**
5955  * Core handler for mesh network traffic going orig->dest.
5956  *
5957  * @param cls Closure (unused).
5958  * @param message Message received.
5959  * @param peer Peer who sent the message.
5960  *
5961  * @return GNUNET_OK to keep the connection open,
5962  *         GNUNET_SYSERR to close it (signal serious error)
5963  */
5964 static int
5965 handle_mesh_fwd (void *cls, const struct GNUNET_PeerIdentity *peer,
5966                      const struct GNUNET_MessageHeader *message)
5967 {
5968   return handle_mesh_encrypted (peer,
5969                                 (struct GNUNET_MESH_Encrypted *)message,
5970                                 GNUNET_YES);
5971 }
5972
5973 /**
5974  * Core handler for mesh network traffic going dest->orig.
5975  *
5976  * @param cls Closure (unused).
5977  * @param message Message received.
5978  * @param peer Peer who sent the message.
5979  *
5980  * @return GNUNET_OK to keep the connection open,
5981  *         GNUNET_SYSERR to close it (signal serious error)
5982  */
5983 static int
5984 handle_mesh_bck (void *cls, const struct GNUNET_PeerIdentity *peer,
5985                      const struct GNUNET_MessageHeader *message)
5986 {
5987   return handle_mesh_encrypted (peer,
5988                                 (struct GNUNET_MESH_Encrypted *)message,
5989                                 GNUNET_NO);
5990 }
5991
5992
5993 /**
5994  * Core handler for mesh network traffic point-to-point acks.
5995  *
5996  * @param cls closure
5997  * @param message message
5998  * @param peer peer identity this notification is about
5999  *
6000  * @return GNUNET_OK to keep the connection open,
6001  *         GNUNET_SYSERR to close it (signal serious error)
6002  */
6003 static int
6004 handle_mesh_ack (void *cls, const struct GNUNET_PeerIdentity *peer,
6005                  const struct GNUNET_MessageHeader *message)
6006 {
6007   struct GNUNET_MESH_ACK *msg;
6008   struct MeshConnection *c;
6009   struct MeshFlowControl *fc;
6010   GNUNET_PEER_Id id;
6011   uint32_t ack;
6012
6013   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "\n\n");
6014   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got an ACK packet from %s!\n",
6015               GNUNET_i2s (peer));
6016   msg = (struct GNUNET_MESH_ACK *) message;
6017
6018   c = connection_get (&msg->cid);
6019
6020   if (NULL == c)
6021   {
6022     GNUNET_STATISTICS_update (stats, "# ack on unknown connection", 1,
6023                               GNUNET_NO);
6024     return GNUNET_OK;
6025   }
6026
6027   /* Is this a forward or backward ACK? */
6028   id = GNUNET_PEER_search (peer);
6029   if (connection_get_next_hop (c)->id == id)
6030   {
6031     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  FWD ACK\n");
6032     fc = &c->fwd_fc;
6033   }
6034   else if (connection_get_prev_hop (c)->id == id)
6035   {
6036     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  BCK ACK\n");
6037     fc = &c->bck_fc;
6038   }
6039   else
6040   {
6041     GNUNET_break_op (0);
6042     return GNUNET_OK;
6043   }
6044
6045   ack = ntohl (msg->ack);
6046   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  ACK %u\n", ack);
6047
6048   /* Cancel polling if the ACK is bigger than before. */
6049   if (GNUNET_SCHEDULER_NO_TASK != fc->poll_task &&
6050       GMC_is_pid_bigger (ack, fc->last_ack_recv))
6051   {
6052     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Cancel poll\n");
6053     GNUNET_SCHEDULER_cancel (fc->poll_task);
6054     fc->poll_task = GNUNET_SCHEDULER_NO_TASK;
6055     fc->poll_time = GNUNET_TIME_UNIT_SECONDS;
6056   }
6057
6058   fc->last_ack_recv = ack;
6059   connection_unlock_queue (c, fc == &c->fwd_fc);
6060
6061   return GNUNET_OK;
6062 }
6063
6064
6065 /**
6066  * Core handler for mesh network traffic point-to-point ack polls.
6067  *
6068  * @param cls closure
6069  * @param message message
6070  * @param peer peer identity this notification is about
6071  *
6072  * @return GNUNET_OK to keep the connection open,
6073  *         GNUNET_SYSERR to close it (signal serious error)
6074  */
6075 static int
6076 handle_mesh_poll (void *cls, const struct GNUNET_PeerIdentity *peer,
6077                   const struct GNUNET_MessageHeader *message)
6078 {
6079   struct GNUNET_MESH_Poll *msg;
6080   struct MeshConnection *c;
6081   struct MeshFlowControl *fc;
6082   GNUNET_PEER_Id id;
6083   uint32_t pid;
6084   int fwd;
6085
6086   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "\n\n");
6087   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a POLL packet from %s!\n",
6088               GNUNET_i2s (peer));
6089
6090   msg = (struct GNUNET_MESH_Poll *) message;
6091
6092   c = connection_get (&msg->cid);
6093
6094   if (NULL == c)
6095   {
6096     GNUNET_STATISTICS_update (stats, "# poll on unknown connection", 1,
6097                               GNUNET_NO);
6098     GNUNET_break_op (0);
6099     return GNUNET_OK;
6100   }
6101
6102   /* Is this a forward or backward ACK?
6103    * Note: a poll should never be needed in a loopback case,
6104    * since there is no possiblility of packet loss there, so
6105    * this way of discerining FWD/BCK should not be a problem.
6106    */
6107   id = GNUNET_PEER_search (peer);
6108   if (connection_get_next_hop (c)->id == id)
6109   {
6110     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  FWD ACK\n");
6111     fc = &c->fwd_fc;
6112   }
6113   else if (connection_get_prev_hop (c)->id == id)
6114   {
6115     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  BCK ACK\n");
6116     fc = &c->bck_fc;
6117   }
6118   else
6119   {
6120     GNUNET_break_op (0);
6121     return GNUNET_OK;
6122   }
6123
6124   pid = ntohl (msg->pid);
6125   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  PID %u, OLD %u\n",
6126               pid, fc->last_pid_recv);
6127   fc->last_pid_recv = pid;
6128   fwd = fc == &c->fwd_fc;
6129   send_ack (c, NULL, fwd);
6130
6131   return GNUNET_OK;
6132 }
6133
6134
6135 /**
6136  * Core handler for mesh keepalives.
6137  *
6138  * @param cls closure
6139  * @param message message
6140  * @param peer peer identity this notification is about
6141  * @return GNUNET_OK to keep the connection open,
6142  *         GNUNET_SYSERR to close it (signal serious error)
6143  *
6144  * TODO: Check who we got this from, to validate route.
6145  */
6146 static int
6147 handle_mesh_keepalive (void *cls, const struct GNUNET_PeerIdentity *peer,
6148                        const struct GNUNET_MessageHeader *message)
6149 {
6150   struct GNUNET_MESH_ConnectionKeepAlive *msg;
6151   struct MeshConnection *c;
6152   struct MeshPeer *neighbor;
6153   int fwd;
6154
6155   msg = (struct GNUNET_MESH_ConnectionKeepAlive *) message;
6156   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a keepalive packet from %s\n",
6157               GNUNET_i2s (peer));
6158
6159   c = connection_get (&msg->cid);
6160   if (NULL == c)
6161   {
6162     GNUNET_STATISTICS_update (stats, "# keepalive on unknown connection", 1,
6163                               GNUNET_NO);
6164     return GNUNET_OK;
6165   }
6166
6167   fwd = GNUNET_MESSAGE_TYPE_MESH_FWD_KEEPALIVE == ntohs (message->type) ? 
6168         GNUNET_YES : GNUNET_NO;
6169
6170   /* Check if origin is as expected */
6171   neighbor = connection_get_hop (c, fwd);
6172   if (peer_get (peer)->id != neighbor->id)
6173   {
6174     GNUNET_break_op (0);
6175     return GNUNET_OK;
6176   }
6177
6178   connection_change_state (c, MESH_CONNECTION_READY);
6179   connection_reset_timeout (c, fwd);
6180
6181   if (connection_is_terminal (c, fwd))
6182     return GNUNET_OK;
6183
6184   GNUNET_STATISTICS_update (stats, "# keepalives forwarded", 1, GNUNET_NO);
6185   send_prebuilt_message_connection (message, c, NULL, fwd);
6186
6187   return GNUNET_OK;
6188 }
6189
6190
6191
6192 /**
6193  * Functions to handle messages from core
6194  */
6195 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
6196   {&handle_mesh_connection_create, GNUNET_MESSAGE_TYPE_MESH_CONNECTION_CREATE,
6197     0},
6198   {&handle_mesh_connection_ack, GNUNET_MESSAGE_TYPE_MESH_CONNECTION_ACK,
6199     sizeof (struct GNUNET_MESH_ConnectionACK)},
6200   {&handle_mesh_connection_broken, GNUNET_MESSAGE_TYPE_MESH_CONNECTION_BROKEN,
6201     sizeof (struct GNUNET_MESH_ConnectionBroken)},
6202   {&handle_mesh_connection_destroy, GNUNET_MESSAGE_TYPE_MESH_CONNECTION_DESTROY,
6203     sizeof (struct GNUNET_MESH_ConnectionDestroy)},
6204   {&handle_mesh_keepalive, GNUNET_MESSAGE_TYPE_MESH_FWD_KEEPALIVE,
6205     sizeof (struct GNUNET_MESH_ConnectionKeepAlive)},
6206   {&handle_mesh_keepalive, GNUNET_MESSAGE_TYPE_MESH_BCK_KEEPALIVE,
6207     sizeof (struct GNUNET_MESH_ConnectionKeepAlive)},
6208   {&handle_mesh_ack, GNUNET_MESSAGE_TYPE_MESH_ACK,
6209     sizeof (struct GNUNET_MESH_ACK)},
6210   {&handle_mesh_poll, GNUNET_MESSAGE_TYPE_MESH_POLL,
6211     sizeof (struct GNUNET_MESH_Poll)},
6212   {&handle_mesh_fwd, GNUNET_MESSAGE_TYPE_MESH_FWD, 0},
6213   {&handle_mesh_bck, GNUNET_MESSAGE_TYPE_MESH_BCK, 0},
6214   {NULL, 0, 0}
6215 };
6216
6217
6218 /**
6219  * Function to process paths received for a new peer addition. The recorded
6220  * paths form the initial tunnel, which can be optimized later.
6221  * Called on each result obtained for the DHT search.
6222  *
6223  * @param cls closure
6224  * @param exp when will this value expire
6225  * @param key key of the result
6226  * @param get_path path of the get request
6227  * @param get_path_length lenght of get_path
6228  * @param put_path path of the put request
6229  * @param put_path_length length of the put_path
6230  * @param type type of the result
6231  * @param size number of bytes in data
6232  * @param data pointer to the result data
6233  */
6234 static void
6235 dht_get_id_handler (void *cls, struct GNUNET_TIME_Absolute exp,
6236                     const struct GNUNET_HashCode * key,
6237                     const struct GNUNET_PeerIdentity *get_path,
6238                     unsigned int get_path_length,
6239                     const struct GNUNET_PeerIdentity *put_path,
6240                     unsigned int put_path_length, enum GNUNET_BLOCK_Type type,
6241                     size_t size, const void *data)
6242 {
6243   struct MeshPeer *peer = cls;
6244   struct MeshPeerPath *p;
6245   struct MeshConnection *c;
6246   struct GNUNET_PeerIdentity pi;
6247   int i;
6248
6249   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got results from DHT!\n");
6250   GNUNET_PEER_resolve (peer->id, &pi);
6251   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  for %s\n", GNUNET_i2s (&pi));
6252
6253   p = path_build_from_dht (get_path, get_path_length,
6254                            put_path, put_path_length);
6255   path_add_to_peers (p, GNUNET_NO);
6256   path_destroy (p);
6257
6258   /* Count connections */
6259   for (c = peer->tunnel->connection_head, i = 0; NULL != c; c = c->next, i++);
6260
6261   /* If we already have 3 (or more (?!)) connections, it's enough */
6262   if (3 <= i)
6263     return;
6264
6265   if (peer->tunnel->state == MESH_TUNNEL_SEARCHING)
6266   {
6267     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " ... connect!\n");
6268     peer_connect (peer);
6269   }
6270   return;
6271 }
6272
6273
6274 /******************************************************************************/
6275 /*********************       MESH LOCAL HANDLES      **************************/
6276 /******************************************************************************/
6277
6278
6279 /**
6280  * Handler for client connection.
6281  *
6282  * @param cls Closure (unused).
6283  * @param client Client handler.
6284  */
6285 static void
6286 handle_local_client_connect (void *cls, struct GNUNET_SERVER_Client *client)
6287 {
6288   struct MeshClient *c;
6289
6290   if (NULL == client)
6291     return;
6292   c = GNUNET_malloc (sizeof (struct MeshClient));
6293   c->handle = client;
6294   c->id = next_client_id++; /* overflow not important: just for debug */
6295   GNUNET_SERVER_client_keep (client);
6296   GNUNET_SERVER_client_set_user_context (client, c);
6297   GNUNET_CONTAINER_DLL_insert (clients_head, clients_tail, c);
6298 }
6299
6300
6301 /**
6302  * Handler for client disconnection
6303  *
6304  * @param cls closure
6305  * @param client identification of the client; NULL
6306  *        for the last call when the server is destroyed
6307  */
6308 static void
6309 handle_local_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
6310 {
6311   struct MeshClient *c;
6312
6313   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "client disconnected: %p\n", client);
6314   if (client == NULL)
6315   {
6316     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   (SERVER DOWN)\n");
6317     return;
6318   }
6319
6320   c = client_get (client);
6321   if (NULL != c)
6322   {
6323     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "matching client found (%u, %p)\n",
6324                 c->id, c);
6325     GNUNET_SERVER_client_drop (c->handle);
6326     c->shutting_down = GNUNET_YES;
6327     if (NULL != c->own_channels)
6328     {
6329       GNUNET_CONTAINER_multihashmap32_iterate (c->own_channels,
6330                                                &channel_destroy_iterator, c);
6331       GNUNET_CONTAINER_multihashmap32_destroy (c->own_channels);
6332     }
6333
6334     if (NULL != c->incoming_channels)
6335     {
6336       GNUNET_CONTAINER_multihashmap32_iterate (c->incoming_channels,
6337                                                &channel_destroy_iterator, c);
6338       GNUNET_CONTAINER_multihashmap32_destroy (c->incoming_channels);
6339     }
6340
6341     if (NULL != c->ports)
6342     {
6343       GNUNET_CONTAINER_multihashmap32_iterate (c->ports,
6344                                                &client_release_ports, c);
6345       GNUNET_CONTAINER_multihashmap32_destroy (c->ports);
6346     }
6347     GNUNET_CONTAINER_DLL_remove (clients_head, clients_tail, c);
6348     GNUNET_STATISTICS_update (stats, "# clients", -1, GNUNET_NO);
6349     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  client free (%p)\n", c);
6350     GNUNET_free (c);
6351   }
6352   else
6353   {
6354     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, " context NULL!\n");
6355   }
6356   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "done!\n");
6357   return;
6358 }
6359
6360
6361 /**
6362  * Handler for new clients
6363  *
6364  * @param cls closure
6365  * @param client identification of the client
6366  * @param message the actual message, which includes messages the client wants
6367  */
6368 static void
6369 handle_local_new_client (void *cls, struct GNUNET_SERVER_Client *client,
6370                          const struct GNUNET_MessageHeader *message)
6371 {
6372   struct GNUNET_MESH_ClientConnect *cc_msg;
6373   struct MeshClient *c;
6374   unsigned int size;
6375   uint32_t *p;
6376   unsigned int i;
6377
6378   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new client connected %p\n", client);
6379
6380   /* Check data sanity */
6381   size = ntohs (message->size) - sizeof (struct GNUNET_MESH_ClientConnect);
6382   cc_msg = (struct GNUNET_MESH_ClientConnect *) message;
6383   if (0 != (size % sizeof (uint32_t)))
6384   {
6385     GNUNET_break (0);
6386     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6387     return;
6388   }
6389   size /= sizeof (uint32_t);
6390
6391   /* Initialize new client structure */
6392   c = GNUNET_SERVER_client_get_user_context (client, struct MeshClient);
6393   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  client id %u\n", c->id);
6394   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  client has %u ports\n", size);
6395   if (size > 0)
6396   {
6397     uint32_t u32;
6398
6399     p = (uint32_t *) &cc_msg[1];
6400     c->ports = GNUNET_CONTAINER_multihashmap32_create (size);
6401     for (i = 0; i < size; i++)
6402     {
6403       u32 = ntohl (p[i]);
6404       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "    port: %u\n", u32);
6405
6406       /* store in client's hashmap */
6407       GNUNET_CONTAINER_multihashmap32_put (c->ports, u32, c,
6408                                            GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
6409       /* store in global hashmap */
6410       /* FIXME only allow one client to have the port open,
6411        *       have a backup hashmap with waiting clients */
6412       GNUNET_CONTAINER_multihashmap32_put (ports, u32, c,
6413                                            GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
6414     }
6415   }
6416
6417   c->own_channels = GNUNET_CONTAINER_multihashmap32_create (32);
6418   c->incoming_channels = GNUNET_CONTAINER_multihashmap32_create (32);
6419   GNUNET_SERVER_notification_context_add (nc, client);
6420   GNUNET_STATISTICS_update (stats, "# clients", 1, GNUNET_NO);
6421
6422   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6423   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new client processed\n");
6424 }
6425
6426
6427 /**
6428  * Handler for requests of new tunnels
6429  *
6430  * @param cls Closure.
6431  * @param client Identification of the client.
6432  * @param message The actual message.
6433  */
6434 static void
6435 handle_local_channel_create (void *cls, struct GNUNET_SERVER_Client *client,
6436                             const struct GNUNET_MessageHeader *message)
6437 {
6438   struct GNUNET_MESH_ChannelMessage *msg;
6439   struct MeshPeer *peer;
6440   struct MeshTunnel2 *t;
6441   struct MeshChannel *ch;
6442   struct MeshClient *c;
6443   MESH_ChannelNumber chid;
6444
6445   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new channel requested\n");
6446
6447   /* Sanity check for client registration */
6448   if (NULL == (c = client_get (client)))
6449   {
6450     GNUNET_break (0);
6451     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6452     return;
6453   }
6454   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6455
6456   /* Message size sanity check */
6457   if (sizeof (struct GNUNET_MESH_ChannelMessage) != ntohs (message->size))
6458   {
6459     GNUNET_break (0);
6460     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6461     return;
6462   }
6463
6464   msg = (struct GNUNET_MESH_ChannelMessage *) message;
6465   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  towards %s:%u\n",
6466               GNUNET_i2s (&msg->peer), ntohl (msg->port));
6467   chid = ntohl (msg->channel_id);
6468
6469   /* Sanity check for duplicate channel IDs */
6470   if (NULL != channel_get_by_local_id (c, chid))
6471   {
6472     GNUNET_break (0);
6473     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6474     return;
6475   }
6476
6477   peer = peer_get (&msg->peer);
6478   if (NULL == peer->tunnel)
6479   {
6480     peer->tunnel = tunnel_new ();
6481     peer->tunnel->peer = peer;
6482   }
6483   t = peer->tunnel;
6484
6485   /* Create channel */
6486   ch = channel_new (t, c, chid);
6487   if (NULL == ch)
6488   {
6489     GNUNET_break (0);
6490     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6491     return;
6492   }
6493   ch->port = ntohl (msg->port);
6494   channel_set_options (ch, ntohl (msg->opt));
6495
6496   /* In unreliable channels, we'll use the DLL to buffer data for the root */
6497   ch->root_rel = GNUNET_new (struct MeshChannelReliability);
6498   ch->root_rel->ch = ch;
6499   ch->root_rel->expected_delay = MESH_RETRANSMIT_TIME;
6500
6501   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "CREATED CHANNEL %s[%x]:%u (%x)\n",
6502               peer2s (t->peer), ch->gid, ch->port, ch->lid_root);
6503   peer_connect (peer);
6504
6505   /* Send create channel */
6506   {
6507     struct GNUNET_MESH_ChannelCreate msgcc;
6508
6509     msgcc.header.size = htons (sizeof (msgcc));
6510     msgcc.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_CHANNEL_CREATE);
6511     msgcc.chid = htonl (ch->gid);
6512     msgcc.port = msg->port;
6513     msgcc.opt = msg->opt;
6514
6515     tunnel_queue_data (t, ch, &msgcc.header, GNUNET_YES);
6516   }
6517
6518   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6519   return;
6520 }
6521
6522
6523 /**
6524  * Handler for requests of deleting tunnels
6525  *
6526  * @param cls closure
6527  * @param client identification of the client
6528  * @param message the actual message
6529  */
6530 static void
6531 handle_local_channel_destroy (void *cls, struct GNUNET_SERVER_Client *client,
6532                              const struct GNUNET_MessageHeader *message)
6533 {
6534   struct GNUNET_MESH_ChannelMessage *msg;
6535   struct MeshClient *c;
6536   struct MeshChannel *ch;
6537   struct MeshTunnel2 *t;
6538   MESH_ChannelNumber chid;
6539
6540   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6541               "Got a DESTROY CHANNEL from client!\n");
6542
6543   /* Sanity check for client registration */
6544   if (NULL == (c = client_get (client)))
6545   {
6546     GNUNET_break (0);
6547     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6548     return;
6549   }
6550   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6551
6552   /* Message sanity check */
6553   if (sizeof (struct GNUNET_MESH_ChannelMessage) != ntohs (message->size))
6554   {
6555     GNUNET_break (0);
6556     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6557     return;
6558   }
6559
6560   msg = (struct GNUNET_MESH_ChannelMessage *) message;
6561
6562   /* Retrieve tunnel */
6563   chid = ntohl (msg->channel_id);
6564   ch = channel_get_by_local_id (c, chid);
6565   if (NULL == ch)
6566   {
6567     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "  channel %X not found\n", chid);
6568     GNUNET_break (0);
6569     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6570     return;
6571   }
6572
6573   /* Cleanup after the tunnel */
6574   client_delete_channel (c, ch);
6575   if (c == ch->dest && GNUNET_MESH_LOCAL_CHANNEL_ID_SERV <= chid)
6576   {
6577     ch->dest = NULL;
6578   }
6579   else if (c == ch->root && GNUNET_MESH_LOCAL_CHANNEL_ID_SERV > chid)
6580   {
6581     ch->root = NULL;
6582   }
6583   else 
6584   {
6585     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
6586                 "  channel %X client %p (%p, %p)\n",
6587                 chid, c, ch->root, ch->dest);
6588     GNUNET_break (0);
6589   }
6590
6591   t = ch->t;
6592   channel_destroy (ch);
6593   tunnel_destroy_if_empty (t);
6594
6595   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6596   return;
6597 }
6598
6599
6600 /**
6601  * Handler for client traffic
6602  *
6603  * @param cls closure
6604  * @param client identification of the client
6605  * @param message the actual message
6606  */
6607 static void
6608 handle_local_data (void *cls, struct GNUNET_SERVER_Client *client,
6609                    const struct GNUNET_MessageHeader *message)
6610 {
6611   struct GNUNET_MESH_LocalData *msg;
6612   struct MeshClient *c;
6613   struct MeshChannel *ch;
6614   struct MeshChannelReliability *rel;
6615   MESH_ChannelNumber chid;
6616   size_t size;
6617   int fwd;
6618
6619   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6620               "Got data from a client!\n");
6621
6622   /* Sanity check for client registration */
6623   if (NULL == (c = client_get (client)))
6624   {
6625     GNUNET_break (0);
6626     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6627     return;
6628   }
6629   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6630
6631   msg = (struct GNUNET_MESH_LocalData *) message;
6632
6633   /* Sanity check for message size */
6634   size = ntohs (message->size) - sizeof (struct GNUNET_MESH_LocalData);
6635   if (size < sizeof (struct GNUNET_MessageHeader))
6636   {
6637     GNUNET_break (0);
6638     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6639     return;
6640   }
6641
6642   /* Channel exists? */
6643   chid = ntohl (msg->id);
6644   fwd = chid < GNUNET_MESH_LOCAL_CHANNEL_ID_SERV;
6645   ch = channel_get_by_local_id (c, chid);
6646   if (NULL == ch)
6647   {
6648     GNUNET_break (0);
6649     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6650     return;
6651   }
6652
6653   /* Is the client in the channel? */
6654   if ( !( (fwd &&
6655            ch->root &&
6656            ch->root->handle == client)
6657          ||
6658           (!fwd &&
6659            ch->dest && 
6660            ch->dest->handle == client) ) )
6661   {
6662     GNUNET_break (0);
6663     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6664     return;
6665   }
6666
6667   rel = fwd ? ch->root_rel : ch->dest_rel;
6668   rel->client_ready = GNUNET_NO;
6669
6670   /* Ok, everything is correct, send the message. */
6671   {
6672     struct GNUNET_MESH_Data *payload;
6673     uint16_t p2p_size = sizeof(struct GNUNET_MESH_Data) + size;
6674     unsigned char cbuf[p2p_size];
6675
6676     payload = (struct GNUNET_MESH_Data *) cbuf;
6677     payload->mid = htonl (rel->mid_send);
6678     rel->mid_send++;
6679     memcpy (&payload[1], &msg[1], size);
6680     payload->header.size = htons (p2p_size);
6681     payload->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_DATA);
6682     payload->chid = htonl (ch->gid);
6683     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  sending on channel...\n");
6684     send_prebuilt_message_channel (&payload->header, ch, fwd);
6685
6686     if (GNUNET_YES == ch->reliable)
6687       channel_save_copy (ch, &payload->header, fwd);
6688   }
6689   if (tunnel_get_buffer (ch->t, fwd) > 0)
6690     send_local_ack (ch, fwd);
6691   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "receive done OK\n");
6692   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6693
6694   return;
6695 }
6696
6697
6698 /**
6699  * Handler for client's ACKs for payload traffic.
6700  *
6701  * @param cls Closure (unused).
6702  * @param client Identification of the client.
6703  * @param message The actual message.
6704  */
6705 static void
6706 handle_local_ack (void *cls, struct GNUNET_SERVER_Client *client,
6707                   const struct GNUNET_MessageHeader *message)
6708 {
6709   struct GNUNET_MESH_LocalAck *msg;
6710   struct MeshChannelReliability *rel;
6711   struct MeshChannel *ch;
6712   struct MeshClient *c;
6713   MESH_ChannelNumber chid;
6714   int fwd;
6715
6716   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a local ACK\n");
6717
6718   /* Sanity check for client registration */
6719   if (NULL == (c = client_get (client)))
6720   {
6721     GNUNET_break (0);
6722     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6723     return;
6724   }
6725   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6726
6727   msg = (struct GNUNET_MESH_LocalAck *) message;
6728
6729   /* Channel exists? */
6730   chid = ntohl (msg->channel_id);
6731   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on channel %X\n", chid);
6732   ch = channel_get_by_local_id (c, chid);
6733   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   -- ch %p\n", ch);
6734   if (NULL == ch)
6735   {
6736     GNUNET_break (0);
6737     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Channel %X unknown.\n", chid);
6738     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "  for client %u.\n", c->id);
6739     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6740     return;
6741   }
6742
6743   /* If client is root, the ACK is going FWD, therefore this is "BCK". */
6744   /* If client is dest, the ACK is going BCK, therefore this is "FWD" */
6745   fwd = chid >= GNUNET_MESH_LOCAL_CHANNEL_ID_SERV;
6746   rel = fwd ? ch->dest_rel : ch->root_rel;
6747
6748   rel->client_ready = GNUNET_YES;
6749   channel_send_client_buffered_data (ch, c, fwd);
6750   send_ack (NULL, ch, fwd);
6751
6752   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6753
6754   return;
6755 }
6756
6757
6758 /**
6759  * Iterator over all tunnels to send a monitoring client info about each tunnel.
6760  *
6761  * @param cls Closure (client handle).
6762  * @param key Key (hashed tunnel ID, unused).
6763  * @param value Tunnel info.
6764  *
6765  * @return GNUNET_YES, to keep iterating.
6766  */
6767 // static int
6768 // monitor_all_tunnels_iterator (void *cls,
6769 //                               const struct GNUNET_HashCode * key,
6770 //                               void *value)
6771 // {
6772 //   struct GNUNET_SERVER_Client *client = cls;
6773 //   struct MeshChannel *ch = value;
6774 //   struct GNUNET_MESH_LocalMonitor *msg;
6775 // 
6776 //   msg = GNUNET_malloc (sizeof(struct GNUNET_MESH_LocalMonitor));
6777 //   msg->channel_id = htonl (ch->gid);
6778 //   msg->header.size = htons (sizeof (struct GNUNET_MESH_LocalMonitor));
6779 //   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_INFO_TUNNELS);
6780 // 
6781 //   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
6782 //               "*  sending info about tunnel %s\n",
6783 //               GNUNET_i2s (&msg->owner));
6784 // 
6785 //   GNUNET_SERVER_notification_context_unicast (nc, client,
6786 //                                               &msg->header, GNUNET_NO);
6787 //   return GNUNET_YES;
6788 // }
6789
6790
6791 /**
6792  * Handler for client's MONITOR request.
6793  *
6794  * @param cls Closure (unused).
6795  * @param client Identification of the client.
6796  * @param message The actual message.
6797  */
6798 static void
6799 handle_local_get_tunnels (void *cls, struct GNUNET_SERVER_Client *client,
6800                           const struct GNUNET_MessageHeader *message)
6801 {
6802   struct MeshClient *c;
6803
6804   /* Sanity check for client registration */
6805   if (NULL == (c = client_get (client)))
6806   {
6807     GNUNET_break (0);
6808     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6809     return;
6810   }
6811
6812   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
6813               "Received get tunnels request from client %u\n",
6814               c->id);
6815 //   GNUNET_CONTAINER_multihashmap_iterate (tunnels,
6816 //                                          monitor_all_tunnels_iterator,
6817 //                                          client);
6818   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
6819               "Get tunnels request from client %u completed\n",
6820               c->id);
6821   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6822 }
6823
6824
6825 /**
6826  * Handler for client's MONITOR_TUNNEL request.
6827  *
6828  * @param cls Closure (unused).
6829  * @param client Identification of the client.
6830  * @param message The actual message.
6831  */
6832 static void
6833 handle_local_show_tunnel (void *cls, struct GNUNET_SERVER_Client *client,
6834                           const struct GNUNET_MessageHeader *message)
6835 {
6836   const struct GNUNET_MESH_LocalMonitor *msg;
6837   struct GNUNET_MESH_LocalMonitor *resp;
6838   struct MeshClient *c;
6839   struct MeshChannel *ch;
6840
6841   /* Sanity check for client registration */
6842   if (NULL == (c = client_get (client)))
6843   {
6844     GNUNET_break (0);
6845     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6846     return;
6847   }
6848
6849   msg = (struct GNUNET_MESH_LocalMonitor *) message;
6850   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
6851               "Received tunnel info request from client %u for tunnel %s[%X]\n",
6852               c->id,
6853               &msg->owner,
6854               ntohl (msg->channel_id));
6855 //   ch = channel_get (&msg->owner, ntohl (msg->channel_id));
6856   ch = NULL; // FIXME
6857   if (NULL == ch)
6858   {
6859     /* We don't know the tunnel */
6860     struct GNUNET_MESH_LocalMonitor warn;
6861
6862     warn = *msg;
6863     GNUNET_SERVER_notification_context_unicast (nc, client,
6864                                                 &warn.header,
6865                                                 GNUNET_NO);
6866     GNUNET_SERVER_receive_done (client, GNUNET_OK);
6867     return;
6868   }
6869
6870   /* Initialize context */
6871   resp = GNUNET_malloc (sizeof (struct GNUNET_MESH_LocalMonitor));
6872   *resp = *msg;
6873   resp->header.size = htons (sizeof (struct GNUNET_MESH_LocalMonitor));
6874   GNUNET_SERVER_notification_context_unicast (nc, c->handle,
6875                                               &resp->header, GNUNET_NO);
6876   GNUNET_free (resp);
6877
6878   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
6879               "Monitor tunnel request from client %u completed\n",
6880               c->id);
6881   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6882 }
6883
6884
6885 /**
6886  * Functions to handle messages from clients
6887  */
6888 static struct GNUNET_SERVER_MessageHandler client_handlers[] = {
6889   {&handle_local_new_client, NULL,
6890    GNUNET_MESSAGE_TYPE_MESH_LOCAL_CONNECT, 0},
6891   {&handle_local_channel_create, NULL,
6892    GNUNET_MESSAGE_TYPE_MESH_CHANNEL_CREATE,
6893    sizeof (struct GNUNET_MESH_ChannelMessage)},
6894   {&handle_local_channel_destroy, NULL,
6895    GNUNET_MESSAGE_TYPE_MESH_CHANNEL_DESTROY,
6896    sizeof (struct GNUNET_MESH_ChannelMessage)},
6897   {&handle_local_data, NULL,
6898    GNUNET_MESSAGE_TYPE_MESH_LOCAL_DATA, 0},
6899   {&handle_local_ack, NULL,
6900    GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK,
6901    sizeof (struct GNUNET_MESH_LocalAck)},
6902   {&handle_local_get_tunnels, NULL,
6903    GNUNET_MESSAGE_TYPE_MESH_LOCAL_INFO_TUNNELS,
6904    sizeof (struct GNUNET_MessageHeader)},
6905   {&handle_local_show_tunnel, NULL,
6906    GNUNET_MESSAGE_TYPE_MESH_LOCAL_INFO_TUNNEL,
6907      sizeof (struct GNUNET_MESH_LocalMonitor)},
6908   {NULL, NULL, 0, 0}
6909 };
6910
6911
6912 /**
6913  * Method called whenever a given peer connects.
6914  *
6915  * @param cls closure
6916  * @param peer peer identity this notification is about
6917  */
6918 static void
6919 core_connect (void *cls, const struct GNUNET_PeerIdentity *peer)
6920 {
6921   struct MeshPeer *pi;
6922   struct MeshPeerPath *path;
6923
6924   DEBUG_CONN ("Peer connected\n");
6925   DEBUG_CONN ("     %s\n", GNUNET_i2s (&my_full_id));
6926   pi = peer_get (peer);
6927   if (myid == pi->id)
6928   {
6929     DEBUG_CONN ("     (self)\n");
6930     path = path_new (1);
6931   }
6932   else
6933   {
6934     DEBUG_CONN ("     %s\n", GNUNET_i2s (peer));
6935     path = path_new (2);
6936     path->peers[1] = pi->id;
6937     GNUNET_PEER_change_rc (pi->id, 1);
6938     GNUNET_STATISTICS_update (stats, "# peers", 1, GNUNET_NO);
6939   }
6940   path->peers[0] = myid;
6941   GNUNET_PEER_change_rc (myid, 1);
6942   peer_add_path (pi, path, GNUNET_YES);
6943
6944   pi->connections = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_YES);
6945   return;
6946 }
6947
6948
6949 /**
6950  * Method called whenever a peer disconnects.
6951  *
6952  * @param cls closure
6953  * @param peer peer identity this notification is about
6954  */
6955 static void
6956 core_disconnect (void *cls, const struct GNUNET_PeerIdentity *peer)
6957 {
6958   struct MeshPeer *pi;
6959
6960   DEBUG_CONN ("Peer disconnected\n");
6961   pi = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
6962   if (NULL == pi)
6963   {
6964     GNUNET_break (0);
6965     return;
6966   }
6967
6968   GNUNET_CONTAINER_multihashmap_iterate (pi->connections,
6969                                          connection_broken,
6970                                          pi);
6971   GNUNET_CONTAINER_multihashmap_destroy (pi->connections);
6972   pi->connections = NULL;
6973   if (myid == pi->id)
6974   {
6975     DEBUG_CONN ("     (self)\n");
6976   }
6977   GNUNET_STATISTICS_update (stats, "# peers", -1, GNUNET_NO);
6978
6979   return;
6980 }
6981
6982
6983 /**
6984  * Install server (service) handlers and start listening to clients.
6985  */
6986 static void
6987 server_init (void)
6988 {
6989   GNUNET_SERVER_add_handlers (server_handle, client_handlers);
6990   GNUNET_SERVER_connect_notify (server_handle,
6991                                 &handle_local_client_connect, NULL);
6992   GNUNET_SERVER_disconnect_notify (server_handle,
6993                                    &handle_local_client_disconnect, NULL);
6994   nc = GNUNET_SERVER_notification_context_create (server_handle, 1);
6995
6996   clients_head = NULL;
6997   clients_tail = NULL;
6998   next_client_id = 0;
6999   GNUNET_SERVER_resume (server_handle);
7000 }
7001
7002
7003 /**
7004  * To be called on core init/fail.
7005  *
7006  * @param cls Closure (config)
7007  * @param identity the public identity of this peer
7008  */
7009 static void
7010 core_init (void *cls, 
7011            const struct GNUNET_PeerIdentity *identity)
7012 {
7013   const struct GNUNET_CONFIGURATION_Handle *c = cls;
7014   static int i = 0;
7015
7016   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Core init\n");
7017   if (0 != memcmp (identity, &my_full_id, sizeof (my_full_id)))
7018   {
7019     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _("Wrong CORE service\n"));
7020     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7021                 " core id %s\n",
7022                 GNUNET_i2s (identity));
7023     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7024                 " my id %s\n",
7025                 GNUNET_i2s (&my_full_id));
7026     GNUNET_CORE_disconnect (core_handle);
7027     core_handle = GNUNET_CORE_connect (c, /* Main configuration */
7028                                        NULL,      /* Closure passed to MESH functions */
7029                                        &core_init,        /* Call core_init once connected */
7030                                        &core_connect,     /* Handle connects */
7031                                        &core_disconnect,  /* remove peers on disconnects */
7032                                        NULL,      /* Don't notify about all incoming messages */
7033                                        GNUNET_NO, /* For header only in notification */
7034                                        NULL,      /* Don't notify about all outbound messages */
7035                                        GNUNET_NO, /* For header-only out notification */
7036                                        core_handlers);    /* Register these handlers */
7037     if (10 < i++)
7038       GNUNET_abort();
7039   }
7040   server_init ();
7041   return;
7042 }
7043
7044
7045 /******************************************************************************/
7046 /************************      MAIN FUNCTIONS      ****************************/
7047 /******************************************************************************/
7048
7049 /**
7050  * Iterator over tunnel hash map entries to destroy the tunnel during shutdown.
7051  *
7052  * @param cls closure
7053  * @param key current key code
7054  * @param value value in the hash map
7055  * @return GNUNET_YES if we should continue to iterate,
7056  *         GNUNET_NO if not.
7057  */
7058 static int
7059 shutdown_tunnel (void *cls, const struct GNUNET_HashCode * key, void *value)
7060 {
7061   struct MeshPeer *p = value;
7062   struct MeshTunnel2 *t = p->tunnel;
7063
7064   if (NULL != t)
7065     tunnel_destroy (t);
7066   return GNUNET_YES;
7067 }
7068
7069
7070 /**
7071  * Task run during shutdown.
7072  *
7073  * @param cls unused
7074  * @param tc unused
7075  */
7076 static void
7077 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
7078 {
7079   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shutting down\n");
7080
7081   if (core_handle != NULL)
7082   {
7083     GNUNET_CORE_disconnect (core_handle);
7084     core_handle = NULL;
7085   }
7086   GNUNET_CONTAINER_multihashmap_iterate (peers, &shutdown_tunnel, NULL);
7087   if (dht_handle != NULL)
7088   {
7089     GNUNET_DHT_disconnect (dht_handle);
7090     dht_handle = NULL;
7091   }
7092   if (nc != NULL)
7093   {
7094     GNUNET_SERVER_notification_context_destroy (nc);
7095     nc = NULL;
7096   }
7097   if (GNUNET_SCHEDULER_NO_TASK != announce_id_task)
7098   {
7099     GNUNET_SCHEDULER_cancel (announce_id_task);
7100     announce_id_task = GNUNET_SCHEDULER_NO_TASK;
7101   }
7102   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shut down\n");
7103 }
7104
7105
7106 /**
7107  * Process mesh requests.
7108  *
7109  * @param cls closure
7110  * @param server the initialized server
7111  * @param c configuration to use
7112  */
7113 static void
7114 run (void *cls, struct GNUNET_SERVER_Handle *server,
7115      const struct GNUNET_CONFIGURATION_Handle *c)
7116 {
7117   char *keyfile;
7118   struct GNUNET_CRYPTO_EccPrivateKey *pk;
7119
7120   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "starting to run\n");
7121   server_handle = server;
7122   GNUNET_SERVER_suspend (server_handle);
7123
7124   if (GNUNET_OK !=
7125       GNUNET_CONFIGURATION_get_value_filename (c, "PEER", "PRIVATE_KEY",
7126                                                &keyfile))
7127   {
7128     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7129                 _
7130                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
7131                 "mesh", "peer/privatekey");
7132     GNUNET_SCHEDULER_shutdown ();
7133     return;
7134   }
7135
7136   if (GNUNET_OK !=
7137       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "REFRESH_CONNECTION_TIME",
7138                                            &refresh_connection_time))
7139   {
7140     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7141                 _
7142                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
7143                 "mesh", "refresh path time");
7144     GNUNET_SCHEDULER_shutdown ();
7145     return;
7146   }
7147
7148   if (GNUNET_OK !=
7149       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "ID_ANNOUNCE_TIME",
7150                                            &id_announce_time))
7151   {
7152     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7153                 _
7154                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
7155                 "mesh", "id announce time");
7156     GNUNET_SCHEDULER_shutdown ();
7157     return;
7158   }
7159
7160   if (GNUNET_OK !=
7161       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "CONNECT_TIMEOUT",
7162                                            &connect_timeout))
7163   {
7164     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7165                 _
7166                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
7167                 "mesh", "connect timeout");
7168     GNUNET_SCHEDULER_shutdown ();
7169     return;
7170   }
7171
7172   if (GNUNET_OK !=
7173       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_MSGS_QUEUE",
7174                                              &max_msgs_queue))
7175   {
7176     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7177                 _
7178                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
7179                 "mesh", "max msgs queue");
7180     GNUNET_SCHEDULER_shutdown ();
7181     return;
7182   }
7183
7184   if (GNUNET_OK !=
7185       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_CONNECTIONS",
7186                                              &max_connections))
7187   {
7188     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7189                 _
7190                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
7191                 "mesh", "max tunnels");
7192     GNUNET_SCHEDULER_shutdown ();
7193     return;
7194   }
7195
7196   if (GNUNET_OK !=
7197       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DEFAULT_TTL",
7198                                              &default_ttl))
7199   {
7200     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
7201                 _
7202                 ("%s service is lacking key configuration settings (%s). Using default (%u).\n"),
7203                 "mesh", "default ttl", 64);
7204     default_ttl = 64;
7205   }
7206
7207   if (GNUNET_OK !=
7208       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_PEERS",
7209                                              &max_peers))
7210   {
7211     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
7212                 _("%s service is lacking key configuration settings (%s). Using default (%u).\n"),
7213                 "mesh", "max peers", 1000);
7214     max_peers = 1000;
7215   }
7216
7217   if (GNUNET_OK !=
7218       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DROP_PERCENT",
7219                                              &drop_percent))
7220   {
7221     drop_percent = 0;
7222   }
7223   else
7224   {
7225     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
7226                 "Mesh is running with drop mode enabled. "
7227                 "This is NOT a good idea! "
7228                 "Remove the DROP_PERCENT option from your configuration.\n");
7229   }
7230
7231   if (GNUNET_OK !=
7232       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DHT_REPLICATION_LEVEL",
7233                                              &dht_replication_level))
7234   {
7235     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
7236                 _
7237                 ("%s service is lacking key configuration settings (%s). Using default (%u).\n"),
7238                 "mesh", "dht replication level", 3);
7239     dht_replication_level = 3;
7240   }
7241
7242   connections = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_YES);
7243   peers = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
7244   ports = GNUNET_CONTAINER_multihashmap32_create (32);
7245
7246   dht_handle = GNUNET_DHT_connect (c, 64);
7247   if (NULL == dht_handle)
7248   {
7249     GNUNET_break (0);
7250   }
7251   stats = GNUNET_STATISTICS_create ("mesh", c);
7252
7253   /* Scheduled the task to clean up when shutdown is called */
7254   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
7255                                 NULL);
7256   pk = GNUNET_CRYPTO_ecc_key_create_from_file (keyfile);
7257   GNUNET_free (keyfile);
7258   GNUNET_assert (NULL != pk);
7259   my_private_key = pk;
7260   GNUNET_CRYPTO_ecc_key_get_public (my_private_key, &my_public_key);
7261   GNUNET_CRYPTO_hash (&my_public_key, sizeof (my_public_key),
7262                       &my_full_id.hashPubKey);
7263   myid = GNUNET_PEER_intern (&my_full_id);
7264   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
7265               "Mesh for peer [%s] starting\n",
7266               GNUNET_i2s(&my_full_id));
7267
7268   core_handle = GNUNET_CORE_connect (c, /* Main configuration */
7269                                      NULL,      /* Closure passed to MESH functions */
7270                                      &core_init,        /* Call core_init once connected */
7271                                      &core_connect,     /* Handle connects */
7272                                      &core_disconnect,  /* remove peers on disconnects */
7273                                      NULL,      /* Don't notify about all incoming messages */
7274                                      GNUNET_NO, /* For header only in notification */
7275                                      NULL,      /* Don't notify about all outbound messages */
7276                                      GNUNET_NO, /* For header-only out notification */
7277                                      core_handlers);    /* Register these handlers */
7278   if (NULL == core_handle)
7279   {
7280     GNUNET_break (0);
7281     GNUNET_SCHEDULER_shutdown ();
7282     return;
7283   }
7284   announce_id_task = GNUNET_SCHEDULER_add_now (&announce_id, cls);
7285   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Mesh service running\n");
7286 }
7287
7288
7289 /**
7290  * The main function for the mesh service.
7291  *
7292  * @param argc number of arguments from the command line
7293  * @param argv command line arguments
7294  * @return 0 ok, 1 on error
7295  */
7296 int
7297 main (int argc, char *const *argv)
7298 {
7299   int ret;
7300   int r;
7301
7302   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "main()\n");
7303   r = GNUNET_SERVICE_run (argc, argv, "mesh", GNUNET_SERVICE_OPTION_NONE, &run,
7304                           NULL);
7305   ret = (GNUNET_OK == r) ? 0 : 1;
7306   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "main() END\n");
7307
7308   INTERVAL_SHOW;
7309
7310   return ret;
7311 }