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