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