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