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