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