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