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