- send data directly if tunnel is already online (or local)
[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   if (MESH_TUNNEL_READY == t->state)
3092     tunnel_send_queued_data (t, fwd);
3093 }
3094
3095
3096 /**
3097  * Send all cached messages that we can, tunnel is online.
3098  *
3099  * @param t Tunnel that holds the messages.
3100  * @param fwd Is this fwd?
3101  */
3102 static void
3103 tunnel_send_queued_data (struct MeshTunnel2 *t, int fwd)
3104 {
3105   struct MeshTunnelQueue *tq;
3106   struct MeshTunnelQueue *next;
3107   unsigned int room;
3108
3109   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3110               "tunnel_send_queued_data on tunnel %s\n",
3111               peer2s (t->peer));
3112   room = tunnel_get_buffer (t, fwd);
3113   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  buffer space: %u\n", room);
3114   for (tq = t->tq_head; NULL != tq && room > 0; tq = next)
3115   {
3116     next = tq->next;
3117     room--;
3118     GNUNET_CONTAINER_DLL_remove (t->tq_head, t->tq_tail, tq);
3119     send_prebuilt_message_channel ((struct GNUNET_MessageHeader *) &tq[1],
3120                                    tq->ch, fwd);
3121
3122     GNUNET_free (tq);
3123   }
3124 }
3125
3126
3127 static void
3128 connection_change_state (struct MeshConnection* c,
3129                          enum MeshConnectionState state)
3130 {
3131   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3132               "Connection %s state was %s\n",
3133               GNUNET_h2s (&c->id), GNUNET_MESH_DEBUG_CS2S (c->state));
3134   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3135               "Connection %s state is now %s\n",
3136               GNUNET_h2s (&c->id), GNUNET_MESH_DEBUG_CS2S (state));
3137   c->state = state;
3138 }
3139
3140
3141 /**
3142  * Add a client to a channel, initializing all needed data structures.
3143  * 
3144  * @param ch Channel to which add the client.
3145  * @param c Client which to add to the channel.
3146  */
3147 static void
3148 channel_add_client (struct MeshChannel *ch, struct MeshClient *c)
3149 {
3150   struct MeshTunnel2 *t = ch->t;
3151
3152   if (NULL != ch->dest)
3153   {
3154     GNUNET_break (0);
3155     return;
3156   }
3157
3158   /* Assign local id as destination */
3159   while (NULL != channel_get_by_local_id (c, t->next_local_chid))
3160     t->next_local_chid = (t->next_local_chid + 1) | GNUNET_MESH_LOCAL_CHANNEL_ID_SERV;
3161   ch->lid_dest = t->next_local_chid++;
3162   t->next_local_chid = t->next_local_chid | GNUNET_MESH_LOCAL_CHANNEL_ID_SERV;
3163
3164   /* Store in client's hashmap */
3165   if (GNUNET_OK !=
3166       GNUNET_CONTAINER_multihashmap32_put (c->incoming_channels,
3167                                            ch->lid_dest, ch,
3168                                            GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
3169   {
3170     GNUNET_break (0);
3171     return;
3172   }
3173
3174   GNUNET_break (NULL == ch->dest_rel);
3175   ch->dest_rel = GNUNET_new (struct MeshChannelReliability);
3176   ch->dest_rel->ch = ch;
3177   ch->dest_rel->expected_delay = MESH_RETRANSMIT_TIME;
3178
3179   ch->dest = c;
3180 }
3181
3182
3183 static struct MeshConnection *
3184 tunnel_use_path (struct MeshTunnel2 *t, struct MeshPeerPath *p)
3185 {
3186   struct MeshConnection *c;
3187   struct GNUNET_HashCode cid;
3188   struct MeshPeer *peer;
3189   unsigned int own_pos;
3190
3191   if (NULL == t || NULL == p)
3192   {
3193     GNUNET_break (0);
3194     return NULL;
3195   }
3196
3197   GNUNET_CRYPTO_hash_create_random (GNUNET_CRYPTO_QUALITY_NONCE, &cid);
3198
3199   c = connection_new (&cid);
3200   c->t = t;
3201   GNUNET_CONTAINER_DLL_insert (t->connection_head, t->connection_tail, c);
3202   for (own_pos = 0; own_pos < p->length; own_pos++)
3203   {
3204     if (p->peers[own_pos] == myid)
3205       break;
3206   }
3207   if (own_pos > p->length - 1)
3208   {
3209     GNUNET_break (0);
3210     connection_destroy (c);
3211     return NULL;
3212   }
3213   c->own_pos = own_pos;
3214   c->path = p;
3215
3216   if (0 == own_pos)
3217   {
3218     c->fwd_maintenance_task =
3219         GNUNET_SCHEDULER_add_delayed (refresh_connection_time,
3220                                       &connection_fwd_keepalive, c);
3221   }
3222
3223   peer = connection_get_next_hop (c);
3224   if (NULL == peer->connections)
3225   {
3226     connection_destroy (c);
3227     return NULL;
3228   }
3229   GNUNET_CONTAINER_multihashmap_put (peer->connections, &c->id, c,
3230                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
3231   peer = connection_get_prev_hop (c);
3232   if (NULL == peer->connections)
3233   {
3234     connection_destroy (c);
3235     return NULL;
3236   }
3237   GNUNET_CONTAINER_multihashmap_put (peer->connections, &c->id, c,
3238                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
3239   return c;
3240 }
3241
3242
3243 /**
3244  * Notifies a tunnel that a connection has broken that affects at least
3245  * some of its peers. Sends a notification towards the root of the tree.
3246  * In case the peer is the owner of the tree, notifies the client that owns
3247  * the tunnel and tries to reconnect.
3248  * 
3249  * FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME 
3250  *
3251  * @param t Tunnel affected.
3252  * @param p1 Peer that got disconnected from p2.
3253  * @param p2 Peer that got disconnected from p1.
3254  *
3255  * @return Short ID of the peer disconnected (either p1 or p2).
3256  *         0 if the tunnel remained unaffected.
3257  */
3258 static GNUNET_PEER_Id
3259 tunnel_notify_connection_broken (struct MeshTunnel2* t,
3260                                  GNUNET_PEER_Id p1, GNUNET_PEER_Id p2)
3261 {
3262 //   if (myid != p1 && myid != p2) FIXME
3263 //   {
3264 //     return;
3265 //   }
3266 // 
3267 //   if (tree_get_predecessor (t->tree) != 0)
3268 //   {
3269 //     /* We are the peer still connected, notify owner of the disconnection. */
3270 //     struct GNUNET_MESH_PathBroken msg;
3271 //     struct GNUNET_PeerIdentity neighbor;
3272 // 
3273 //     msg.header.size = htons (sizeof (msg));
3274 //     msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_BROKEN);
3275 //     GNUNET_PEER_resolve (t->id.oid, &msg.oid);
3276 //     msg.tid = htonl (t->id.tid);
3277 //     msg.peer1 = my_full_id;
3278 //     GNUNET_PEER_resolve (pid, &msg.peer2);
3279 //     GNUNET_PEER_resolve (tree_get_predecessor (t->tree), &neighbor);
3280 //     send_prebuilt_message (&msg.header, &neighbor, t);
3281 //   }
3282   return 0;
3283 }
3284
3285
3286 /**
3287  * Send an end-to-end ACK message for the most recent in-sequence payload.
3288  *
3289  * If channel is not reliable, do nothing.
3290  *
3291  * @param ch Channel this is about.
3292  * @param fwd Is for FWD traffic? (ACK dest->owner)
3293  */
3294 static void
3295 channel_send_data_ack (struct MeshChannel *ch, int fwd)
3296 {
3297   struct GNUNET_MESH_DataACK msg;
3298   struct MeshChannelReliability *rel;
3299   struct MeshReliableMessage *copy;
3300   unsigned int delta;
3301   uint64_t mask;
3302   uint16_t type;
3303
3304   if (GNUNET_NO == ch->reliable)
3305   {
3306     return;
3307   }
3308   rel = fwd ? ch->dest_rel : ch->root_rel;
3309   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3310               "send_data_ack for %u\n",
3311               rel->mid_recv - 1);
3312
3313   type = GNUNET_MESSAGE_TYPE_MESH_DATA_ACK;
3314   msg.header.type = htons (type);
3315   msg.header.size = htons (sizeof (msg));
3316   msg.chid = htonl (ch->gid);
3317   msg.mid = htonl (rel->mid_recv - 1);
3318   msg.futures = 0;
3319   for (copy = rel->head_recv; NULL != copy; copy = copy->next)
3320   {
3321     if (copy->type != type)
3322       continue;
3323     delta = copy->mid - rel->mid_recv;
3324     if (63 < delta)
3325       break;
3326     mask = 0x1LL << delta;
3327     msg.futures |= mask;
3328     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3329                 " setting bit for %u (delta %u) (%llX) -> %llX\n",
3330                 copy->mid, delta, mask, msg.futures);
3331   }
3332   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " final futures %llX\n", msg.futures);
3333
3334   send_prebuilt_message_channel (&msg.header, ch, fwd);
3335   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "send_data_ack END\n");
3336 }
3337
3338
3339 /**
3340  * Send an ACK informing the predecessor about the available buffer space.
3341  *
3342  * Note that for fwd ack, the FWD mean forward *traffic* (root->dest),
3343  * the ACK itself goes "back" (dest->root).
3344  *
3345  * @param c Connection on which to send the ACK.
3346  * @param buffer How much space free to advertise?
3347  * @param fwd Is this FWD ACK? (Going dest->owner)
3348  */
3349 static void
3350 connection_send_ack (struct MeshConnection *c, unsigned int buffer, int fwd)
3351 {
3352   struct MeshFlowControl *next_fc;
3353   struct MeshFlowControl *prev_fc;
3354   struct GNUNET_MESH_ACK msg;
3355   uint32_t ack;
3356   int delta;
3357
3358   next_fc = fwd ? &c->fwd_fc : &c->bck_fc;
3359   prev_fc = fwd ? &c->bck_fc : &c->fwd_fc;
3360
3361   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3362               "connection send %s ack on %s\n",
3363               fwd ? "FWD" : "BCK", GNUNET_h2s (&c->id));
3364
3365   /* Check if we need to transmit the ACK */
3366   if (prev_fc->last_ack_sent - prev_fc->last_pid_recv > 3)
3367   {
3368     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Not sending ACK, buffer > 3\n");
3369     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3370                 "  last pid recv: %u, last ack sent: %u\n",
3371                 prev_fc->last_pid_recv, prev_fc->last_ack_sent);
3372     return;
3373   }
3374
3375   /* Ok, ACK might be necessary, what PID to ACK? */
3376   delta = next_fc->queue_max - next_fc->queue_n;
3377   ack = prev_fc->last_pid_recv + delta;
3378   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " ACK %u\n", ack);
3379   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3380               " last pid %u, last ack %u, qmax %u, q %u\n",
3381               prev_fc->last_pid_recv, prev_fc->last_ack_sent,
3382               next_fc->queue_max, next_fc->queue_n);
3383   if (ack == prev_fc->last_ack_sent)
3384   {
3385     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Not sending FWD ACK, not needed\n");
3386     return;
3387   }
3388
3389   prev_fc->last_ack_sent = ack;
3390
3391   /* Build ACK message and send on connection */
3392   msg.header.size = htons (sizeof (msg));
3393   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_ACK);
3394   msg.ack = htonl (ack);
3395   msg.cid = c->id;
3396
3397   send_prebuilt_message_connection (&msg.header, c, NULL, !fwd);
3398 }
3399
3400
3401 /**
3402  * Modify the mesh message TID from global to local and send to client.
3403  * 
3404  * @param ch Channel on which to send the message.
3405  * @param msg Message to modify and send.
3406  * @param c Client to send to.
3407  * @param tid Tunnel ID to use (c can be both owner and client).
3408  */
3409 static void
3410 channel_send_client_to_tid (struct MeshChannel *ch,
3411                              const struct GNUNET_MESH_Data *msg,
3412                              struct MeshClient *c, MESH_ChannelNumber id)
3413 {
3414   struct GNUNET_MESH_LocalData *copy;
3415   uint16_t size = ntohs (msg->header.size) - sizeof (struct GNUNET_MESH_Data);
3416   char cbuf[size + sizeof (struct GNUNET_MESH_LocalData)];
3417
3418   if (size < sizeof (struct GNUNET_MessageHeader))
3419   {
3420     GNUNET_break_op (0);
3421     return;
3422   }
3423   if (NULL == c)
3424   {
3425     GNUNET_break (0);
3426     return;
3427   }
3428   copy = (struct GNUNET_MESH_LocalData *) cbuf;
3429   memcpy (&copy[1], &msg[1], size);
3430   copy->header.size = htons (sizeof (struct GNUNET_MESH_LocalData) + size);
3431   copy->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_DATA);
3432   copy->id = htonl (id);
3433   GNUNET_SERVER_notification_context_unicast (nc, c->handle,
3434                                               &copy->header, GNUNET_NO);
3435 }
3436
3437
3438 /**
3439  * We have received a message out of order, or the client is not ready.
3440  * Buffer it until we receive an ACK from the client or the missing
3441  * message from the channel.
3442  *
3443  * @param msg Message to buffer (MUST be of type MESH_DATA).
3444  * @param rel Reliability data to the corresponding direction.
3445  */
3446 static void
3447 channel_rel_add_buffered_data (const struct GNUNET_MESH_Data *msg,
3448                                struct MeshChannelReliability *rel)
3449 {
3450   struct MeshReliableMessage *copy;
3451   struct MeshReliableMessage *prev;
3452   uint32_t mid;
3453   uint16_t size;
3454   
3455   size = ntohs (msg->header.size);
3456   mid = ntohl (msg->mid);
3457   
3458   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "add_buffered_data %u\n", mid);
3459   
3460   copy = GNUNET_malloc (sizeof (*copy) + size);
3461   copy->mid = mid;
3462   copy->rel = rel;
3463   memcpy (&copy[1], msg, size);
3464   
3465   rel->n_recv++;
3466   
3467   // FIXME do something better than O(n), although n < 64...
3468   // FIXME start from the end (most messages are the latest ones)
3469   for (prev = rel->head_recv; NULL != prev; prev = prev->next)
3470   {
3471     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " prev %u\n", prev->mid);
3472     if (GMC_is_pid_bigger (prev->mid, mid))
3473     {
3474       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " bingo!\n");
3475       GNUNET_CONTAINER_DLL_insert_before (rel->head_recv, rel->tail_recv,
3476                                           prev, copy);
3477       return;
3478     }
3479   }
3480     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " insert at tail!\n");
3481     GNUNET_CONTAINER_DLL_insert_tail (rel->head_recv, rel->tail_recv, copy);
3482     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "add_buffered_data END\n");
3483 }
3484
3485
3486 static void
3487 channel_send_client_data (struct MeshChannel *ch,
3488                           const struct GNUNET_MESH_Data *msg,
3489                           int fwd)
3490 {
3491   if (fwd)
3492   {
3493     if (ch->dest_rel->client_ready)
3494       channel_send_client_to_tid (ch, msg, ch->dest, ch->lid_dest);
3495     else
3496       channel_rel_add_buffered_data (msg, ch->dest_rel);
3497   }
3498   else
3499   {
3500     if (ch->root_rel->client_ready)
3501       channel_send_client_to_tid (ch, msg, ch->root, ch->lid_root);
3502     else
3503       channel_rel_add_buffered_data (msg, ch->root_rel);
3504   }
3505 }
3506
3507
3508 /**
3509  * Send a buffered message to the client, for in order delivery or
3510  * as result of client ACK.
3511  *
3512  * @param ch Channel on which to empty the message buffer.
3513  * @param c Client to send to.
3514  * @param rel Reliability structure to corresponding peer.
3515  *            If rel == bck_rel, this is FWD data.
3516  */
3517 static void
3518 channel_send_client_buffered_data (struct MeshChannel *ch,
3519                                    struct MeshClient *c,
3520                                    int fwd)
3521 {
3522   struct MeshReliableMessage *copy;
3523   struct MeshChannelReliability *rel;
3524
3525   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "send_buffered_data\n");
3526   rel = fwd ? ch->dest_rel : ch->root_rel;
3527   if (GNUNET_NO == rel->client_ready)
3528   {
3529     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "client not ready\n");
3530     return;
3531   }
3532
3533   copy = rel->head_recv;
3534   /* We never buffer channel management messages */
3535   if (NULL != copy)
3536   {
3537     if (copy->mid == rel->mid_recv || GNUNET_NO == ch->reliable)
3538     {
3539       struct GNUNET_MESH_Data *msg = (struct GNUNET_MESH_Data *) &copy[1];
3540
3541       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3542                   " have %u! now expecting %u\n",
3543                   copy->mid, rel->mid_recv + 1);
3544       channel_send_client_data (ch, msg, fwd);
3545       rel->n_recv--;
3546       rel->mid_recv++;
3547       GNUNET_CONTAINER_DLL_remove (rel->head_recv, rel->tail_recv, copy);
3548       GNUNET_free (copy);
3549     }
3550     else
3551     {
3552       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3553                   " reliable && don't have %u, next is %u\n",
3554                   rel->mid_recv,
3555                   copy->mid);
3556       return;
3557     }
3558   }
3559   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "send_buffered_data END\n");
3560 }
3561
3562
3563 /**
3564  * Destroy a reliable message after it has been acknowledged, either by
3565  * direct mid ACK or bitfield. Updates the appropriate data structures and
3566  * timers and frees all memory.
3567  * 
3568  * @param copy Message that is no longer needed: remote peer got it.
3569  */
3570 static void
3571 rel_message_free (struct MeshReliableMessage *copy)
3572 {
3573   struct MeshChannelReliability *rel;
3574   struct GNUNET_TIME_Relative time;
3575
3576   rel = copy->rel;
3577   time = GNUNET_TIME_absolute_get_duration (copy->timestamp);
3578   rel->expected_delay.rel_value_us *= 7;
3579   rel->expected_delay.rel_value_us += time.rel_value_us;
3580   rel->expected_delay.rel_value_us /= 8;
3581   rel->n_sent--;
3582   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! Freeing %u\n", copy->mid);
3583   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "    n_sent %u\n", rel->n_sent);
3584   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!!  took %s\n",
3585               GNUNET_STRINGS_relative_time_to_string (time, GNUNET_NO));
3586   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!!  new expected delay %s\n",
3587               GNUNET_STRINGS_relative_time_to_string (rel->expected_delay,
3588                                                       GNUNET_NO));
3589   rel->retry_timer = rel->expected_delay;
3590   GNUNET_CONTAINER_DLL_remove (rel->head_sent, rel->tail_sent, copy);
3591   GNUNET_free (copy);
3592 }
3593
3594
3595 /**
3596  * Destroy all reliable messages queued for a channel,
3597  * during a channel destruction.
3598  * Frees the reliability structure itself.
3599  *
3600  * @param rel Reliability data for a channel.
3601  */
3602 static void
3603 channel_rel_free_all (struct MeshChannelReliability *rel)
3604 {
3605   struct MeshReliableMessage *copy;
3606   struct MeshReliableMessage *next;
3607
3608   if (NULL == rel)
3609     return;
3610
3611   for (copy = rel->head_recv; NULL != copy; copy = next)
3612   {
3613     next = copy->next;
3614     GNUNET_CONTAINER_DLL_remove (rel->head_recv, rel->tail_recv, copy);
3615     GNUNET_free (copy);
3616   }
3617   for (copy = rel->head_sent; NULL != copy; copy = next)
3618   {
3619     next = copy->next;
3620     GNUNET_CONTAINER_DLL_remove (rel->head_sent, rel->tail_sent, copy);
3621     GNUNET_free (copy);
3622   }
3623   if (GNUNET_SCHEDULER_NO_TASK != rel->retry_task)
3624     GNUNET_SCHEDULER_cancel (rel->retry_task);
3625   GNUNET_free (rel);
3626 }
3627
3628
3629 /**
3630  * Mark future messages as ACK'd.
3631  *
3632  * @param rel Reliability data.
3633  * @param msg DataACK message with a bitfield of future ACK'd messages.
3634  */
3635 static void
3636 channel_rel_free_sent (struct MeshChannelReliability *rel,
3637                        const struct GNUNET_MESH_DataACK *msg)
3638 {
3639   struct MeshReliableMessage *copy;
3640   struct MeshReliableMessage *next;
3641   uint64_t bitfield;
3642   uint64_t mask;
3643   uint32_t mid;
3644   uint32_t target;
3645   unsigned int i;
3646
3647   bitfield = msg->futures;
3648   mid = ntohl (msg->mid);
3649   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3650               "free_sent_reliable %u %llX\n",
3651               mid, bitfield);
3652   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3653               " rel %p, head %p\n",
3654               rel, rel->head_sent);
3655   for (i = 0, copy = rel->head_sent;
3656        i < 64 && NULL != copy && 0 != bitfield;
3657        i++)
3658   {
3659     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3660                 " trying bit %u (mid %u)\n",
3661                 i, mid + i + 1);
3662     mask = 0x1LL << i;
3663     if (0 == (bitfield & mask))
3664      continue;
3665
3666     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " set!\n");
3667     /* Bit was set, clear the bit from the bitfield */
3668     bitfield &= ~mask;
3669
3670     /* The i-th bit was set. Do we have that copy? */
3671     /* Skip copies with mid < target */
3672     target = mid + i + 1;
3673     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " target %u\n", target);
3674     while (NULL != copy && GMC_is_pid_bigger (target, copy->mid))
3675      copy = copy->next;
3676
3677     /* Did we run out of copies? (previously freed, it's ok) */
3678     if (NULL == copy)
3679     {
3680      GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "run out of copies...\n");
3681      return;
3682     }
3683
3684     /* Did we overshoot the target? (previously freed, it's ok) */
3685     if (GMC_is_pid_bigger (copy->mid, target))
3686     {
3687      GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " next copy %u\n", copy->mid);
3688      continue;
3689     }
3690
3691     /* Now copy->mid == target, free it */
3692     next = copy->next;
3693     rel_message_free (copy);
3694     copy = next;
3695   }
3696   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "free_sent_reliable END\n");
3697 }
3698
3699
3700 /**
3701  * We haven't received an ACK after a certain time: restransmit the message.
3702  *
3703  * @param cls Closure (MeshReliableMessage with the message to restransmit)
3704  * @param tc TaskContext.
3705  */
3706 static void
3707 channel_retransmit_message (void *cls,
3708                             const struct GNUNET_SCHEDULER_TaskContext *tc)
3709 {
3710   struct MeshChannelReliability *rel = cls;
3711   struct MeshReliableMessage *copy;
3712   struct MeshPeerQueue *q;
3713   struct MeshChannel *ch;
3714   struct MeshConnection *c;
3715   struct GNUNET_MESH_Data *payload;
3716   struct MeshPeer *hop;
3717   int fwd;
3718
3719   rel->retry_task = GNUNET_SCHEDULER_NO_TASK;
3720   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
3721     return;
3722
3723   ch = rel->ch;
3724   copy = rel->head_sent;
3725   if (NULL == copy)
3726   {
3727     GNUNET_break (0);
3728     return;
3729   }
3730
3731   /* Search the message to be retransmitted in the outgoing queue.
3732    * Check only the queue for the connection that is going to be used,
3733    * if the message is stuck in some other connection's queue we shouldn't
3734    * act upon it:
3735    * - cancelling it and sending the new one doesn't guarantee it's delivery,
3736    *   the old connection could be temporary stalled or the queue happened to
3737    *   be long at time of insertion.
3738    * - not sending the new one could cause terrible delays the old connection
3739    *   is stalled.
3740    */
3741   payload = (struct GNUNET_MESH_Data *) &copy[1];
3742   fwd = (rel == ch->root_rel);
3743   c = tunnel_get_connection (ch->t, fwd);
3744   hop = connection_get_hop (c, fwd);
3745   for (q = hop->queue_head; NULL != q; q = q->next)
3746   {
3747     if (ntohs (payload->header.type) == q->type && ch == q->ch)
3748     {
3749       struct GNUNET_MESH_Data *queued_data = q->cls;
3750
3751       if (queued_data->mid == payload->mid)
3752         break;
3753     }
3754   }
3755
3756   /* Message not found in the queue that we are going to use. */
3757   if (NULL == q)
3758   {
3759     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! RETRANSMIT %u\n", copy->mid);
3760
3761     send_prebuilt_message_channel (&payload->header, ch, fwd);
3762     GNUNET_STATISTICS_update (stats, "# data retransmitted", 1, GNUNET_NO);
3763   }
3764   else
3765   {
3766     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! ALREADY IN QUEUE %u\n", copy->mid);
3767   }
3768
3769   rel->retry_timer = GNUNET_TIME_STD_BACKOFF (rel->retry_timer);
3770   rel->retry_task = GNUNET_SCHEDULER_add_delayed (rel->retry_timer,
3771                                                   &channel_retransmit_message,
3772                                                   cls);
3773 }
3774
3775
3776 /**
3777  * Send ACK on one or more connections due to buffer space to the client.
3778  *
3779  * Iterates all connections of the tunnel and sends ACKs appropriately.
3780  *
3781  * @param ch Channel which has some free buffer space.
3782  * @param fwd Is this in for FWD traffic? (ACK goes dest->root)
3783  */
3784 static void
3785 channel_send_connections_ack (struct MeshChannel *ch,
3786                               unsigned int buffer,
3787                               int fwd)
3788 {
3789   struct MeshTunnel2 *t = ch->t;
3790   struct MeshConnection *c;
3791   struct MeshFlowControl *fc;
3792   uint32_t allowed;
3793   uint32_t to_allow;
3794   uint32_t allow_per_connection;
3795   unsigned int cs;
3796
3797   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3798               "Channel send connection %s ack on %s:%X\n",
3799               fwd ? "FWD" : "BCK", peer2s (ch->t->peer), ch->gid);
3800
3801   /* Count connections, how many messages are already allowed */
3802   for (cs = 0, allowed = 0, c = t->connection_head; NULL != c; c = c->next)
3803   {
3804     fc = fwd ? &c->fwd_fc : &c->bck_fc;
3805     if (GMC_is_pid_bigger(fc->last_pid_recv, fc->last_ack_sent))
3806     {
3807       GNUNET_break (0);
3808       continue;
3809     }
3810     allowed += fc->last_ack_sent - fc->last_pid_recv;
3811     cs++;
3812   }
3813
3814   /* Make sure there is no overflow */
3815   if (allowed > buffer)
3816   {
3817     GNUNET_break (0);
3818     return;
3819   }
3820
3821   /* Authorize connections to send more data */
3822   to_allow = buffer - allowed;
3823
3824   for (c = t->connection_head; NULL != c && to_allow > 0; c = c->next)
3825   {
3826     allow_per_connection = to_allow/cs;
3827     to_allow -= allow_per_connection;
3828     cs--;
3829     fc = fwd ? &c->fwd_fc : &c->bck_fc;
3830     if (fc->last_ack_sent - fc->last_pid_recv > 64 / 3)
3831     {
3832       continue;
3833     }
3834     connection_send_ack (c, allow_per_connection, fwd);
3835   }
3836
3837   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3838                 "Channel send connection %s ack on %s:%X\n",
3839                 fwd ? "FWD" : "BCK", peer2s (ch->t->peer), ch->gid);
3840   GNUNET_break (to_allow == 0);
3841 }
3842
3843
3844 /**
3845  * Send an ACK on the appropriate connection/channel, depending on
3846  * the direction and the position of the peer.
3847  *
3848  * @param c Which connection to send the hop-by-hop ACK.
3849  * @param ch Channel, if any.
3850  * @param fwd Is this a fwd ACK? (will go dest->root)
3851  */
3852 static void
3853 send_ack (struct MeshConnection *c, struct MeshChannel *ch, int fwd)
3854 {
3855   unsigned int buffer;
3856
3857   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3858               "send ack %s on %p %p\n",
3859               fwd ? "FWD" : "BCK", c, ch);
3860   if (NULL == c || connection_is_terminal (c, fwd))
3861   {
3862     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  getting from all connections\n");
3863     buffer = tunnel_get_buffer (NULL == c ? ch->t : c->t, fwd);
3864   }
3865   else
3866   {
3867     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  getting from one connection\n");
3868     buffer = connection_get_buffer (c, fwd);
3869   }
3870   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  buffer available: %u\n", buffer);
3871
3872   if ( (NULL != ch && channel_is_terminal (ch, !fwd)) ||
3873        (NULL != c && connection_is_origin (c, fwd)) )
3874   {
3875     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  sending on channel...\n");
3876     if (0 < buffer)
3877     {
3878       GNUNET_assert (NULL != ch);
3879       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  really sending!\n");
3880       send_local_ack (ch, fwd);
3881     }
3882   }
3883   else if (NULL == c)
3884   {
3885     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  sending on all connections\n");
3886     GNUNET_assert (NULL != ch);
3887     channel_send_connections_ack (ch, buffer, fwd);
3888   }
3889   else 
3890   {
3891     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  sending on connection\n");
3892     connection_send_ack (c, buffer, fwd);
3893   }
3894 }
3895
3896
3897 /**
3898  * Channel was ACK'd by remote peer, mark as ready and cancel retransmission.
3899  *
3900  * @param ch Channel to mark as ready.
3901  * @param fwd Was the CREATE message sent fwd?
3902  */
3903 static void
3904 channel_confirm (struct MeshChannel *ch, int fwd)
3905 {
3906   struct MeshChannelReliability *rel;
3907   struct MeshReliableMessage *copy;
3908   struct MeshReliableMessage *next;
3909
3910   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3911               "  channel confirm %s %s:%X\n",
3912               fwd ? "FWD" : "BCK", peer2s (ch->t->peer), ch->gid);
3913   ch->state = MESH_CHANNEL_READY;
3914
3915   rel = fwd ? ch->root_rel : ch->dest_rel;
3916   for (copy = rel->head_sent; NULL != copy; copy = next)
3917   {
3918     struct GNUNET_MessageHeader *msg;
3919
3920     next = copy->next;
3921     msg = (struct GNUNET_MessageHeader *) &copy[1];
3922     if (ntohs (msg->type) == GNUNET_MESSAGE_TYPE_MESH_CHANNEL_CREATE)
3923     {
3924       rel_message_free (copy);
3925       /* TODO return? */
3926     }
3927   }
3928   send_ack (NULL, ch, fwd);
3929 }
3930
3931
3932 /**
3933  * Save a copy to retransmit in case it gets lost.
3934  *
3935  * Initializes all needed callbacks and timers.
3936  *
3937  * @param ch Channel this message goes on.
3938  * @param msg Message to copy.
3939  * @param fwd Is this fwd traffic?
3940  */
3941 static void
3942 channel_save_copy (struct MeshChannel *ch,
3943                    const struct GNUNET_MessageHeader *msg,
3944                    int fwd)
3945 {
3946   struct MeshChannelReliability *rel;
3947   struct MeshReliableMessage *copy;
3948   uint32_t mid;
3949   uint16_t type;
3950   uint16_t size;
3951
3952   rel = fwd ? ch->root_rel : ch->dest_rel;
3953   mid = rel->mid_send;
3954   type = ntohs (msg->type);
3955   size = ntohs (msg->size);
3956
3957   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! SAVE %u\n", mid);
3958   copy = GNUNET_malloc (sizeof (struct MeshReliableMessage) + size);
3959   copy->mid = mid;
3960   copy->timestamp = GNUNET_TIME_absolute_get ();
3961   copy->rel = rel;
3962   copy->type = type;
3963   memcpy (&copy[1], msg, size);
3964   rel->n_sent++;
3965   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " n_sent %u\n", rel->n_sent);
3966   GNUNET_CONTAINER_DLL_insert_tail (rel->head_sent, rel->tail_sent, copy);
3967   if (GNUNET_SCHEDULER_NO_TASK == rel->retry_task)
3968   {
3969     rel->retry_timer =
3970         GNUNET_TIME_relative_multiply (rel->expected_delay,
3971                                         MESH_RETRANSMIT_MARGIN);
3972     rel->retry_task =
3973         GNUNET_SCHEDULER_add_delayed (rel->retry_timer,
3974                                       &channel_retransmit_message,
3975                                       rel);
3976   }
3977 }
3978
3979
3980 /**
3981  * Send keepalive packets for a connection.
3982  *
3983  * @param c Connection to keep alive..
3984  * @param fwd Is this a FWD keepalive? (owner -> dest).
3985  */
3986 static void
3987 connection_keepalive (struct MeshConnection *c, int fwd)
3988 {
3989   struct GNUNET_MESH_ConnectionKeepAlive *msg;
3990   size_t size = sizeof (struct GNUNET_MESH_ConnectionKeepAlive);
3991   char cbuf[size];
3992   uint16_t type;
3993
3994   type = fwd ? GNUNET_MESSAGE_TYPE_MESH_FWD_KEEPALIVE :
3995                GNUNET_MESSAGE_TYPE_MESH_BCK_KEEPALIVE;
3996
3997   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3998               "sending %s keepalive for connection %s[%d]\n",
3999               fwd ? "FWD" : "BCK",
4000               peer2s (c->t->peer),
4001               c->id);
4002
4003   msg = (struct GNUNET_MESH_ConnectionKeepAlive *) cbuf;
4004   msg->header.size = htons (size);
4005   msg->header.type = htons (type);
4006   msg->cid = c->id;
4007
4008   send_prebuilt_message_connection (&msg->header, c, NULL, fwd);
4009 }
4010
4011
4012 /**
4013  * Send CONNECTION_{CREATE/ACK} packets for a connection.
4014  *
4015  * @param c Connection for which to send the message.
4016  * @param fwd If GNUNET_YES, send CREATE, otherwise send ACK.
4017  */
4018 static void
4019 connection_recreate (struct MeshConnection *c, int fwd)
4020 {
4021   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "sending connection recreate\n");
4022   if (fwd)
4023     send_connection_create (c);
4024   else
4025     send_connection_ack (c, GNUNET_NO);
4026 }
4027
4028
4029 /**
4030  * Generic connection timer management.
4031  * Depending on the role of the peer in the connection will send the
4032  * appropriate message (build or keepalive)
4033  *
4034  * @param c Conncetion to maintain.
4035  * @param fwd Is FWD?
4036  */
4037 static void
4038 connection_maintain (struct MeshConnection *c, int fwd)
4039 {
4040   if (MESH_TUNNEL_SEARCHING == c->t->state)
4041   {
4042     /* TODO DHT GET with RO_BART */
4043     return;
4044   }
4045   switch (c->state)
4046   {
4047     case MESH_CONNECTION_NEW:
4048       GNUNET_break (0);
4049     case MESH_CONNECTION_SENT:
4050       connection_recreate (c, fwd);
4051       break;
4052     case MESH_CONNECTION_READY:
4053       connection_keepalive (c, fwd);
4054       break;
4055     default:
4056       break;
4057   }
4058 }
4059
4060
4061 static void
4062 connection_fwd_keepalive (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
4063 {
4064   struct MeshConnection *c = cls;
4065
4066   c->fwd_maintenance_task = GNUNET_SCHEDULER_NO_TASK;
4067   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
4068     return;
4069
4070   connection_maintain (c, GNUNET_YES);
4071   c->fwd_maintenance_task = GNUNET_SCHEDULER_add_delayed (refresh_connection_time,
4072                                                           &connection_fwd_keepalive,
4073                                                           c);
4074 }
4075
4076
4077 static void
4078 connection_bck_keepalive (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
4079 {
4080   struct MeshConnection *c = cls;
4081
4082   c->bck_maintenance_task = GNUNET_SCHEDULER_NO_TASK;
4083   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
4084     return;
4085
4086   connection_maintain (c, GNUNET_NO);
4087   c->bck_maintenance_task = GNUNET_SCHEDULER_add_delayed (refresh_connection_time,
4088                                                           &connection_bck_keepalive,
4089                                                           c);
4090 }
4091
4092
4093 /**
4094  * Send a message to all peers in this connection that the connection
4095  * is no longer valid.
4096  *
4097  * If some peer should not receive the message, it should be zero'ed out
4098  * before calling this function.
4099  *
4100  * @param c The connection whose peers to notify.
4101  */
4102 static void
4103 connection_send_destroy (struct MeshConnection *c)
4104 {
4105   struct GNUNET_MESH_ConnectionDestroy msg;
4106
4107   msg.header.size = htons (sizeof (msg));
4108   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_TUNNEL_DESTROY);;
4109   msg.cid = c->id;
4110   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4111               "  sending connection destroy for connection %s[%X]\n",
4112               peer2s (c->t->peer),
4113               c->id);
4114
4115   if (GNUNET_NO == connection_is_terminal (c, GNUNET_YES))
4116     send_prebuilt_message_connection (&msg.header, c, NULL, GNUNET_YES);
4117   if (GNUNET_NO == connection_is_terminal (c, GNUNET_NO))
4118     send_prebuilt_message_connection (&msg.header, c, NULL, GNUNET_NO);
4119   c->destroy = GNUNET_YES;
4120 }
4121
4122
4123 /**
4124  * Confirm we got a channel create.
4125  *
4126  * @param ch The channel to confirm.
4127  * @param fwd Should we send the ACK fwd?
4128  */
4129 static void
4130 channel_send_ack (struct MeshChannel *ch, int fwd)
4131 {
4132   struct GNUNET_MESH_ChannelManage msg;
4133
4134   msg.header.size = htons (sizeof (msg));
4135   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_CHANNEL_ACK);
4136   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4137               "  sending channel %s ack for channel %s:%X\n",
4138               fwd ? "FWD" : "BCK", peer2s (ch->t->peer),
4139               ch->gid);
4140
4141   msg.chid = htonl (ch->gid);
4142   send_prebuilt_message_channel (&msg.header, ch, !fwd);
4143 }
4144
4145
4146 /**
4147  * Send a message to all clients (local and remote) of this channel
4148  * notifying that the channel is no longer valid.
4149  *
4150  * If some peer or client should not receive the message,
4151  * should be zero'ed out before calling this function.
4152  *
4153  * @param ch The channel whose clients to notify.
4154  */
4155 static void
4156 channel_send_destroy (struct MeshChannel *ch)
4157 {
4158   struct GNUNET_MESH_ChannelManage msg;
4159
4160   msg.header.size = htons (sizeof (msg));
4161   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_CHANNEL_DESTROY);
4162   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4163               "  sending channel destroy for channel %s:%X\n",
4164               peer2s (ch->t->peer),
4165               ch->gid);
4166
4167   if (channel_is_terminal (ch, GNUNET_NO))
4168   {
4169     if (NULL != ch->root && GNUNET_NO == ch->root->shutting_down)
4170     {
4171       msg.chid = htonl (ch->lid_root);
4172       send_local_channel_destroy (ch, GNUNET_NO);
4173     }
4174   }
4175   else
4176   {
4177     msg.chid = htonl (ch->gid);
4178     send_prebuilt_message_channel (&msg.header, ch, GNUNET_NO);
4179   }
4180
4181   if (channel_is_terminal (ch, GNUNET_YES))
4182   {
4183     if (NULL != ch->dest && GNUNET_NO == ch->dest->shutting_down)
4184     {
4185       msg.chid = htonl (ch->lid_dest);
4186       send_local_channel_destroy (ch, GNUNET_YES);
4187     }
4188   }
4189   else
4190   {
4191     msg.chid = htonl (ch->gid);
4192     send_prebuilt_message_channel (&msg.header, ch, GNUNET_YES);
4193   }
4194 }
4195
4196
4197 /**
4198  * Create a tunnel.
4199  */
4200 static struct MeshTunnel2 *
4201 tunnel_new (void)
4202 {
4203   struct MeshTunnel2 *t;
4204
4205   t = GNUNET_new (struct MeshTunnel2);
4206   t->next_chid = 0;
4207   t->next_local_chid = GNUNET_MESH_LOCAL_CHANNEL_ID_SERV;
4208 //   if (GNUNET_OK !=
4209 //       GNUNET_CONTAINER_multihashmap_put (tunnels, tid, t,
4210 //                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
4211 //   {
4212 //     GNUNET_break (0);
4213 //     tunnel_destroy (t);
4214 //     return NULL;
4215 //   }
4216
4217 //   char salt[] = "salt";
4218 //   GNUNET_CRYPTO_kdf (&t->e_key, sizeof (struct GNUNET_CRYPTO_AesSessionKey),
4219 //                      salt, sizeof (salt),
4220 //                      &t->e_key, sizeof (struct GNUNET_CRYPTO_AesSessionKey),
4221 //                      &my_full_id, sizeof (struct GNUNET_PeerIdentity),
4222 //                      GNUNET_PEER_resolve2 (t->peer->id), sizeof (struct GNUNET_PeerIdentity),
4223 //                      NULL);
4224 //   GNUNET_CRYPTO_kdf (&t->d_key, sizeof (struct GNUNET_CRYPTO_AesSessionKey),
4225 //                      salt, sizeof (salt),
4226 //                      &t->d_key, sizeof (struct GNUNET_CRYPTO_AesSessionKey),
4227 //                      GNUNET_PEER_resolve2 (t->peer->id), sizeof (struct GNUNET_PeerIdentity),
4228 //                      &my_full_id, sizeof (struct GNUNET_PeerIdentity),
4229 //                      NULL);
4230
4231   return t;
4232 }
4233
4234
4235 /**
4236  * Add a connection to a tunnel.
4237  *
4238  * @param t Tunnel.
4239  * @param c Connection.
4240  */
4241 static void
4242 tunnel_add_connection (struct MeshTunnel2 *t, struct MeshConnection *c)
4243 {
4244   struct MeshConnection *aux;
4245   c->t = t;
4246   for (aux = t->connection_head; aux != NULL; aux = aux->next)
4247     if (aux == c)
4248       return;
4249   GNUNET_CONTAINER_DLL_insert_tail (t->connection_head, t->connection_tail, c);
4250 }
4251
4252
4253 /**
4254  * Initialize a Flow Control structure to the initial state.
4255  * 
4256  * @param fc Flow Control structure to initialize.
4257  */
4258 static void
4259 fc_init (struct MeshFlowControl *fc)
4260 {
4261   fc->next_pid = 0;
4262   fc->last_pid_sent = (uint32_t) -1; /* Next (expected) = 0 */
4263   fc->last_pid_recv = (uint32_t) -1;
4264   fc->last_ack_sent = (uint32_t) 0;
4265   fc->last_ack_recv = (uint32_t) 0;
4266   fc->poll_task = GNUNET_SCHEDULER_NO_TASK;
4267   fc->poll_time = GNUNET_TIME_UNIT_SECONDS;
4268   fc->queue_n = 0;
4269   fc->queue_max = (max_msgs_queue / max_connections) + 1;
4270 }
4271
4272
4273 static struct MeshConnection *
4274 connection_new (const struct GNUNET_HashCode *cid)
4275 {
4276   struct MeshConnection *c;
4277
4278   c = GNUNET_new (struct MeshConnection);
4279   c->id = *cid;
4280   GNUNET_CONTAINER_multihashmap_put (connections, &c->id, c,
4281                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
4282   fc_init (&c->fwd_fc);
4283   fc_init (&c->bck_fc);
4284   c->fwd_fc.c = c;
4285   c->bck_fc.c = c;
4286
4287   return c;
4288 }
4289
4290
4291 /**
4292  * Find a connection.
4293  *
4294  * @param cid Connection ID.
4295  */
4296 static struct MeshConnection *
4297 connection_get (const struct GNUNET_HashCode *cid)
4298 {
4299   return GNUNET_CONTAINER_multihashmap_get (connections, cid);
4300 }
4301
4302
4303 static void
4304 connection_destroy (struct MeshConnection *c)
4305 {
4306   struct MeshPeer *peer;
4307
4308   if (NULL == c)
4309     return;
4310
4311   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "destroying connection %s[%X]\n",
4312               peer2s (c->t->peer),
4313               c->id);
4314
4315   /* Cancel all traffic */
4316   connection_cancel_queues (c, GNUNET_YES);
4317   connection_cancel_queues (c, GNUNET_NO);
4318
4319   /* Cancel maintainance task (keepalive/timeout) */
4320   if (GNUNET_SCHEDULER_NO_TASK != c->fwd_maintenance_task)
4321     GNUNET_SCHEDULER_cancel (c->fwd_maintenance_task);
4322   if (GNUNET_SCHEDULER_NO_TASK != c->bck_maintenance_task)
4323     GNUNET_SCHEDULER_cancel (c->bck_maintenance_task);
4324
4325   /* Deregister from neighbors */
4326   peer = connection_get_next_hop (c);
4327   if (NULL != peer && NULL != peer->connections)
4328     GNUNET_CONTAINER_multihashmap_remove (peer->connections, &c->id, c);
4329   peer = connection_get_prev_hop (c);
4330   if (NULL != peer && NULL != peer->connections)
4331     GNUNET_CONTAINER_multihashmap_remove (peer->connections, &c->id, c);
4332
4333   /* Delete */
4334   GNUNET_STATISTICS_update (stats, "# connections", -1, GNUNET_NO);
4335   GNUNET_CONTAINER_DLL_remove (c->t->connection_head, c->t->connection_tail, c);
4336   GNUNET_free (c);
4337 }
4338
4339
4340 static void
4341 tunnel_destroy (struct MeshTunnel2 *t)
4342 {
4343   struct MeshConnection *c;
4344   struct MeshConnection *next;
4345
4346   if (NULL == t)
4347     return;
4348
4349   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "destroying tunnel %s\n",
4350               peer2s (t->peer));
4351
4352 //   if (GNUNET_YES != GNUNET_CONTAINER_multihashmap_remove (tunnels, &t->id, t))
4353 //     GNUNET_break (0);
4354
4355   for (c = t->connection_head; NULL != c; c = next)
4356   {
4357     next = c->next;
4358     connection_destroy (c);
4359   }
4360
4361   GNUNET_STATISTICS_update (stats, "# tunnels", -1, GNUNET_NO);
4362
4363   GNUNET_free (t);
4364 }
4365
4366
4367 /**
4368  * Tunnel is empty: destroy it.
4369  *
4370  * Notifies all connections about the destruction.
4371  *
4372  * @param t Tunnel to destroy. 
4373  */
4374 static void
4375 tunnel_destroy_empty (struct MeshTunnel2 *t)
4376 {
4377   struct MeshConnection *c;
4378
4379   for (c = t->connection_head; NULL != c; c = c->next)
4380   {
4381     if (GNUNET_NO == c->destroy)
4382       connection_send_destroy (c);
4383   }
4384
4385   if (0 == t->pending_messages)
4386     tunnel_destroy (t);
4387   else
4388     t->destroy = GNUNET_YES;
4389 }
4390
4391
4392 /**
4393  * Destroy tunnel if empty (no more channels).
4394  *
4395  * @param t Tunnel to destroy if empty.
4396  */
4397 static void
4398 tunnel_destroy_if_empty (struct MeshTunnel2 *t)
4399 {
4400   if (NULL != t->channel_head)
4401     return;
4402
4403   tunnel_destroy_empty (t);
4404 }
4405
4406
4407 /**
4408  * Destroy a channel and free all resources.
4409  * 
4410  * @param ch Channel to destroy.
4411  */
4412 static void
4413 channel_destroy (struct MeshChannel *ch)
4414 {
4415   struct MeshClient *c;
4416
4417   if (NULL == ch)
4418     return;
4419
4420   c = ch->root;
4421   if (NULL != c)
4422   {
4423     if (GNUNET_YES != GNUNET_CONTAINER_multihashmap32_remove (c->own_channels,
4424                                                               ch->lid_root, ch))
4425     {
4426       GNUNET_break (0);
4427     }
4428   }
4429
4430   c = ch->dest;
4431   if (NULL != c)
4432   {
4433     if (GNUNET_YES !=
4434         GNUNET_CONTAINER_multihashmap32_remove (c->incoming_channels,
4435                                                 ch->lid_dest, ch))
4436     {
4437       GNUNET_break (0);
4438     }
4439   }
4440
4441   channel_rel_free_all (ch->root_rel);
4442   channel_rel_free_all (ch->dest_rel);
4443
4444   GNUNET_CONTAINER_DLL_remove (ch->t->channel_head, ch->t->channel_tail, ch);
4445   GNUNET_STATISTICS_update (stats, "# channels", -1, GNUNET_NO);
4446
4447   GNUNET_free (ch);
4448 }
4449
4450 /**
4451  * Create a new channel.
4452  *
4453  * @param t Tunnel this channel is in.
4454  * @param owner Client that owns the channel, NULL for foreign channels.
4455  * @param lid_root Local ID for root client.
4456  *
4457  * @return A new initialized channel. NULL on error.
4458  */
4459 static struct MeshChannel *
4460 channel_new (struct MeshTunnel2 *t,
4461              struct MeshClient *owner, MESH_ChannelNumber lid_root)
4462 {
4463   struct MeshChannel *ch;
4464
4465   ch = GNUNET_new (struct MeshChannel);
4466   ch->root = owner;
4467   ch->lid_root = lid_root;
4468   ch->t = t;
4469
4470   GNUNET_STATISTICS_update (stats, "# channels", 1, GNUNET_NO);
4471
4472   if (NULL != owner)
4473   {
4474     while (NULL != channel_get (t, t->next_chid))
4475     {
4476       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Channel %u exists (%p)...\n",
4477                   t->next_chid, channel_get (t, t->next_chid));
4478       t->next_chid = (t->next_chid + 1) & ~GNUNET_MESH_LOCAL_CHANNEL_ID_CLI;
4479     }
4480     ch->gid = t->next_chid;
4481     t->next_chid = (t->next_chid + 1) & ~GNUNET_MESH_LOCAL_CHANNEL_ID_CLI;
4482
4483     if (GNUNET_OK !=
4484         GNUNET_CONTAINER_multihashmap32_put (owner->own_channels, lid_root, ch,
4485                                              GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
4486     {
4487       GNUNET_break (0);
4488       channel_destroy (ch);
4489       GNUNET_SERVER_receive_done (owner->handle, GNUNET_SYSERR);
4490       return NULL;
4491     }
4492   }
4493   GNUNET_CONTAINER_DLL_insert (t->channel_head, t->channel_tail, ch);
4494
4495   return ch;
4496 }
4497
4498
4499 /**
4500  * Set options in a channel, extracted from a bit flag field
4501  * 
4502  * @param ch Channel to set options to.
4503  * @param options Bit array in host byte order.
4504  */
4505 static void
4506 channel_set_options (struct MeshChannel *ch, uint32_t options)
4507 {
4508   ch->nobuffer = (options & GNUNET_MESH_OPTION_NOBUFFER) != 0 ?
4509                  GNUNET_YES : GNUNET_NO;
4510   ch->reliable = (options & GNUNET_MESH_OPTION_RELIABLE) != 0 ?
4511                  GNUNET_YES : GNUNET_NO;
4512 }
4513
4514
4515 /**
4516  * Iterator for deleting each channel whose client endpoint disconnected.
4517  *
4518  * @param cls Closure (client that has disconnected).
4519  * @param key The local channel id (used to access the hashmap).
4520  * @param value The value stored at the key (channel to destroy).
4521  *
4522  * @return GNUNET_OK, keep iterating.
4523  */
4524 static int
4525 channel_destroy_iterator (void *cls,
4526                           uint32_t key,
4527                           void *value)
4528 {
4529   struct MeshChannel *ch = value;
4530   struct MeshClient *c = cls;
4531   struct MeshTunnel2 *t;
4532
4533   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4534               " Channel %X (%X / %X) destroy, due to client %u shutdown.\n",
4535               ch->gid, ch->lid_root, ch->lid_dest, c->id);
4536
4537   if (c == ch->dest)
4538   {
4539     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Client %u is destination.\n", c->id);
4540   }
4541   if (c == ch->root)
4542   {
4543     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Client %u is owner.\n", c->id);
4544   }
4545
4546   t = ch->t;
4547   channel_send_destroy (ch);
4548   channel_destroy (ch);
4549   tunnel_destroy_if_empty (t);
4550
4551   return GNUNET_OK;
4552 }
4553
4554
4555 /**
4556  * Remove client's ports from the global hashmap on disconnect.
4557  *
4558  * @param cls Closure (unused).
4559  * @param key Port.
4560  * @param value Client structure.
4561  *
4562  * @return GNUNET_OK, keep iterating.
4563  */
4564 static int
4565 client_release_ports (void *cls,
4566                       uint32_t key,
4567                       void *value)
4568 {
4569   int res;
4570
4571   res = GNUNET_CONTAINER_multihashmap32_remove (ports, key, value);
4572   if (GNUNET_YES != res)
4573   {
4574     GNUNET_break (0);
4575     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4576                 "Port %u by client %p was not registered.\n",
4577                 key, value);
4578   }
4579   return GNUNET_OK;
4580 }
4581
4582
4583 /**
4584  * Timeout function due to lack of keepalive/traffic from the owner.
4585  * Destroys connection if called.
4586  *
4587  * @param cls Closure (connection to destroy).
4588  * @param tc TaskContext.
4589  */
4590 static void
4591 connection_fwd_timeout (void *cls,
4592                         const struct GNUNET_SCHEDULER_TaskContext *tc)
4593 {
4594   struct MeshConnection *c = cls;
4595
4596   c->fwd_maintenance_task = GNUNET_SCHEDULER_NO_TASK;
4597   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
4598     return;
4599   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4600               "Connection %s[%X] FWD timed out. Destroying.\n",
4601               peer2s (c->t->peer),
4602               c->id);
4603
4604   if (connection_is_origin (c, GNUNET_YES)) /* If local, leave. */
4605     return;
4606
4607   connection_destroy (c);
4608 }
4609
4610
4611 /**
4612  * Timeout function due to lack of keepalive/traffic from the destination.
4613  * Destroys connection if called.
4614  *
4615  * @param cls Closure (connection to destroy).
4616  * @param tc TaskContext
4617  */
4618 static void
4619 connection_bck_timeout (void *cls,
4620                         const struct GNUNET_SCHEDULER_TaskContext *tc)
4621 {
4622   struct MeshConnection *c = cls;
4623
4624   c->bck_maintenance_task = GNUNET_SCHEDULER_NO_TASK;
4625   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
4626     return;
4627
4628   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4629               "Connection %s[%X] FWD timed out. Destroying.\n",
4630               peer2s (c->t->peer),
4631               c->id);
4632
4633   if (connection_is_origin (c, GNUNET_NO)) /* If local, leave. */
4634     return;
4635
4636   connection_destroy (c);
4637 }
4638
4639
4640 /**
4641  * Resets the connection timeout task, some other message has done the
4642  * task's job.
4643  * - For the first peer on the direction this means to send
4644  *   a keepalive or a path confirmation message (either create or ACK).
4645  * - For all other peers, this means to destroy the connection,
4646  *   due to lack of activity.
4647  * Starts the tiemout if no timeout was running (connection just created).
4648  *
4649  * @param c Connection whose timeout to reset.
4650  * @param fwd Is this forward?
4651  *
4652  * TODO use heap to improve efficiency of scheduler.
4653  */
4654 static void
4655 connection_reset_timeout (struct MeshConnection *c, int fwd)
4656 {
4657   GNUNET_SCHEDULER_TaskIdentifier *ti;
4658   GNUNET_SCHEDULER_Task f;
4659
4660   ti = fwd ? &c->fwd_maintenance_task : &c->bck_maintenance_task;
4661
4662   if (GNUNET_SCHEDULER_NO_TASK != *ti)
4663     GNUNET_SCHEDULER_cancel (*ti);
4664
4665   if (connection_is_origin (c, fwd)) /* Endpoint */
4666   {
4667     f  = fwd ? &connection_fwd_keepalive : &connection_bck_keepalive;
4668     *ti = GNUNET_SCHEDULER_add_delayed (refresh_connection_time, f, c);
4669   }
4670   else /* Relay */
4671   {
4672     struct GNUNET_TIME_Relative delay;
4673
4674     delay = GNUNET_TIME_relative_multiply (refresh_connection_time, 4);
4675     f  = fwd ? &connection_fwd_timeout : &connection_bck_timeout;
4676     *ti = GNUNET_SCHEDULER_add_delayed (delay, f, c);
4677   }
4678 }
4679
4680
4681 /**
4682  * Iterator to notify all connections of a broken link. Mark connections
4683  * to destroy after all traffic has been sent.
4684  *
4685  * @param cls Closure (peer disconnected).
4686  * @param key Current key code (tid).
4687  * @param value Value in the hash map (connection).
4688  *
4689  * @return GNUNET_YES if we should continue to iterate,
4690  *         GNUNET_NO if not.
4691  */
4692 static int
4693 connection_broken (void *cls,
4694                    const struct GNUNET_HashCode *key,
4695                    void *value)
4696 {
4697   struct MeshPeer *peer = cls;
4698   struct MeshConnection *c = value;
4699   struct GNUNET_MESH_ConnectionBroken msg;
4700   int fwd;
4701
4702   fwd = peer == connection_get_prev_hop (c);
4703
4704   connection_cancel_queues (c, !fwd);
4705   if (connection_is_terminal (c, fwd))
4706   {
4707     /* Local shutdown, no one to notify about this. */
4708     connection_destroy (c);
4709     return GNUNET_YES;
4710   }
4711
4712   msg.header.size = htons (sizeof (struct GNUNET_MESH_ConnectionBroken));
4713   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_CONNECTION_BROKEN);
4714   msg.cid = c->id;
4715   msg.peer1 = my_full_id;
4716   msg.peer2 = *GNUNET_PEER_resolve2 (peer->id);
4717   send_prebuilt_message_connection (&msg.header, c, NULL, fwd);
4718   c->destroy = GNUNET_YES;
4719
4720   return GNUNET_YES;
4721 }
4722
4723 /******************************************************************************/
4724 /****************      MESH NETWORK HANDLER HELPERS     ***********************/
4725 /******************************************************************************/
4726
4727 /**
4728  * Free a transmission that was already queued with all resources
4729  * associated to the request.
4730  *
4731  * @param queue Queue handler to cancel.
4732  * @param clear_cls Is it necessary to free associated cls?
4733  */
4734 static void
4735 queue_destroy (struct MeshPeerQueue *queue, int clear_cls)
4736 {
4737   struct MeshPeer *peer;
4738   struct MeshFlowControl *fc;
4739   int fwd;
4740
4741   fwd = queue->fwd;
4742   peer = queue->peer;
4743   GNUNET_assert (NULL != queue->c);
4744   fc = fwd ? &queue->c->fwd_fc : &queue->c->bck_fc;
4745
4746   if (GNUNET_YES == clear_cls)
4747   {
4748     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   queue destroy type %s\n",
4749                 GNUNET_MESH_DEBUG_M2S (queue->type));
4750     switch (queue->type)
4751     {
4752       case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_DESTROY:
4753       case GNUNET_MESSAGE_TYPE_MESH_TUNNEL_DESTROY:
4754         GNUNET_log (GNUNET_ERROR_TYPE_INFO, "destroying a DESTROY message\n");
4755         GNUNET_break (GNUNET_YES == queue->c->destroy);
4756         /* fall through */
4757       case GNUNET_MESSAGE_TYPE_MESH_FWD:
4758       case GNUNET_MESSAGE_TYPE_MESH_BCK:
4759       case GNUNET_MESSAGE_TYPE_MESH_ACK:
4760       case GNUNET_MESSAGE_TYPE_MESH_POLL:
4761       case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_ACK:
4762       case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_CREATE:
4763       case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_BROKEN:
4764         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   prebuilt message\n");;
4765         GNUNET_free_non_null (queue->cls);
4766         break;
4767
4768       default:
4769         GNUNET_break (0);
4770         GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "   type %s unknown!\n",
4771                     GNUNET_MESH_DEBUG_M2S (queue->type));
4772     }
4773
4774   }
4775   GNUNET_CONTAINER_DLL_remove (peer->queue_head, peer->queue_tail, queue);
4776
4777   if (queue->type != GNUNET_MESSAGE_TYPE_MESH_ACK &&
4778       queue->type != GNUNET_MESSAGE_TYPE_MESH_POLL)
4779   {
4780     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Q_N- %p %u\n", fc, fc->queue_n);
4781     fc->queue_n--;
4782     peer->queue_n--;
4783   }
4784   if (NULL != queue->c)
4785   {
4786     queue->c->pending_messages--;
4787     if (NULL != queue->c->t)
4788     {
4789       queue->c->t->pending_messages--;
4790     }
4791   }
4792
4793   GNUNET_free (queue);
4794 }
4795
4796
4797 static size_t
4798 queue_send (void *cls, size_t size, void *buf)
4799 {
4800   struct MeshPeer *peer = cls;
4801   struct MeshFlowControl *fc;
4802   struct MeshConnection *c;
4803   struct GNUNET_MessageHeader *msg;
4804   struct MeshPeerQueue *queue;
4805   struct MeshTunnel2 *t;
4806   struct MeshChannel *ch;
4807   const struct GNUNET_PeerIdentity *dst_id;
4808   size_t data_size;
4809   uint32_t pid;
4810   uint16_t type;
4811   int fwd;
4812
4813   peer->core_transmit = NULL;
4814   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* Queue send (max %u)\n", size);
4815
4816   if (NULL == buf || 0 == size)
4817   {
4818     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* Buffer size 0.\n");
4819     return 0;
4820   }
4821
4822   /* Initialize */
4823   queue = peer_get_first_message (peer);
4824   if (NULL == queue)
4825   {
4826     GNUNET_break (0); /* Core tmt_rdy should've been canceled */
4827     return 0;
4828   }
4829   c = queue->c;
4830   fwd = queue->fwd;
4831   fc = fwd ? &c->fwd_fc : &c->bck_fc;
4832
4833   dst_id = GNUNET_PEER_resolve2 (peer->id);
4834   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*   towards %s\n", GNUNET_i2s (dst_id));
4835   /* Check if buffer size is enough for the message */
4836   if (queue->size > size)
4837   {
4838       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*   not enough room, reissue\n");
4839       peer->core_transmit =
4840           GNUNET_CORE_notify_transmit_ready (core_handle,
4841                                              GNUNET_NO,
4842                                              0,
4843                                              GNUNET_TIME_UNIT_FOREVER_REL,
4844                                              dst_id,
4845                                              queue->size,
4846                                              &queue_send,
4847                                              peer);
4848       return 0;
4849   }
4850   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*   size %u ok\n", queue->size);
4851
4852   t = (NULL != c) ? c->t : NULL;
4853   type = 0;
4854
4855   /* Fill buf */
4856   switch (queue->type)
4857   {
4858     case GNUNET_MESSAGE_TYPE_MESH_TUNNEL_DESTROY:
4859     case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_DESTROY:
4860     case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_BROKEN:
4861     case GNUNET_MESSAGE_TYPE_MESH_FWD:
4862     case GNUNET_MESSAGE_TYPE_MESH_BCK:
4863     case GNUNET_MESSAGE_TYPE_MESH_ACK:
4864     case GNUNET_MESSAGE_TYPE_MESH_POLL:
4865       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4866                   "*   raw: %s\n",
4867                   GNUNET_MESH_DEBUG_M2S (queue->type));
4868       data_size = send_core_data_raw (queue->cls, size, buf);
4869       msg = (struct GNUNET_MessageHeader *) buf;
4870       type = ntohs (msg->type);
4871       break;
4872     case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_CREATE:
4873       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*   path create\n");
4874       if (connection_is_origin (c, GNUNET_YES))
4875         data_size = send_core_connection_create (queue->c, size, buf);
4876       else
4877         data_size = send_core_data_raw (queue->cls, size, buf);
4878       break;
4879     case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_ACK:
4880       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*   path ack\n");
4881       if (connection_is_origin (c, GNUNET_NO) ||
4882           connection_is_origin (c, GNUNET_YES))
4883         data_size = send_core_connection_ack (queue->c, size, buf);
4884       else
4885         data_size = send_core_data_raw (queue->cls, size, buf);
4886       break;
4887     case GNUNET_MESSAGE_TYPE_MESH_DATA:
4888     case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_CREATE:
4889     case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_DESTROY:
4890       /* This should be encapsulted */
4891       GNUNET_break (0);
4892       data_size = 0;
4893       break;
4894     default:
4895       GNUNET_break (0);
4896       GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "*   type unknown: %u\n",
4897                   queue->type);
4898       data_size = 0;
4899   }
4900
4901   if (0 < drop_percent &&
4902       GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, 101) < drop_percent)
4903   {
4904     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4905                 "Dropping message of type %s\n",
4906                 GNUNET_MESH_DEBUG_M2S (queue->type));
4907     data_size = 0;
4908   }
4909
4910   /* Free queue, but cls was freed by send_core_* */
4911   ch = queue->ch;
4912   queue_destroy (queue, GNUNET_NO);
4913
4914   /* Send ACK if needed, after accounting for sent ID in fc->queue_n */
4915   switch (type)
4916   {
4917     case GNUNET_MESSAGE_TYPE_MESH_FWD:
4918     case GNUNET_MESSAGE_TYPE_MESH_BCK:
4919       pid = ntohl ( ((struct GNUNET_MESH_Encrypted *) buf)->pid );
4920       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*   accounting pid %u\n", pid);
4921       fc->last_pid_sent = pid;
4922       send_ack (c, ch, fwd);
4923       break;
4924     default:
4925       break;
4926   }
4927
4928   /* If more data in queue, send next */
4929   queue = peer_get_first_message (peer);
4930   if (NULL != queue)
4931   {
4932     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*   more data!\n");
4933     if (NULL == peer->core_transmit) {
4934       peer->core_transmit =
4935           GNUNET_CORE_notify_transmit_ready(core_handle,
4936                                             0,
4937                                             0,
4938                                             GNUNET_TIME_UNIT_FOREVER_REL,
4939                                             dst_id,
4940                                             queue->size,
4941                                             &queue_send,
4942                                             peer);
4943     }
4944     else
4945     {
4946       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4947                   "*   tmt rdy called somewhere else\n");
4948     }
4949     if (GNUNET_SCHEDULER_NO_TASK == fc->poll_task)
4950     {
4951       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*   starting poll timeout\n");
4952       fc->poll_task =
4953           GNUNET_SCHEDULER_add_delayed (fc->poll_time, &connection_poll, fc);
4954     }
4955   }
4956   else
4957   {
4958     if (GNUNET_SCHEDULER_NO_TASK != fc->poll_task)
4959     {
4960       GNUNET_SCHEDULER_cancel (fc->poll_task);
4961       fc->poll_task = GNUNET_SCHEDULER_NO_TASK;
4962     }
4963   }
4964   if (NULL != c)
4965   {
4966     c->pending_messages--;
4967     if (GNUNET_YES == c->destroy && 0 == c->pending_messages)
4968     {
4969       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*  destroying connection!\n");
4970       connection_destroy (c);
4971     }
4972   }
4973
4974   if (NULL != t)
4975   {
4976     t->pending_messages--;
4977     if (GNUNET_YES == t->destroy && 0 == t->pending_messages)
4978     {
4979 //       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*  destroying tunnel!\n");
4980       tunnel_destroy (t);
4981     }
4982   }
4983   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*  Return %d\n", data_size);
4984   return data_size;
4985 }
4986
4987
4988 static void
4989 queue_add (void *cls, uint16_t type, size_t size,
4990            struct MeshConnection *c,
4991            struct MeshChannel *ch,
4992            int fwd)
4993 {
4994   struct MeshPeerQueue *queue;
4995   struct MeshFlowControl *fc;
4996   struct MeshPeer *peer;
4997   int priority;
4998   int call_core;
4999
5000   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5001               "queue add %s %s (%u) on c %p, ch %p\n",
5002               fwd ? "FWD" : "BCK",  GNUNET_MESH_DEBUG_M2S (type), size, c, ch);
5003   GNUNET_assert (NULL != c);
5004
5005   fc   = fwd ? &c->fwd_fc : &c->bck_fc;
5006   peer = fwd ? connection_get_next_hop (c) : connection_get_prev_hop (c);
5007
5008   if (NULL == fc)
5009   {
5010     GNUNET_break (0);
5011     return;
5012   }
5013   
5014   if (NULL == peer->connections)
5015   {
5016     /* We are not connected to this peer, ignore request. */
5017     GNUNET_break_op (0);
5018     return;
5019   }
5020
5021   priority = 0;
5022
5023   if (GNUNET_MESSAGE_TYPE_MESH_POLL == type ||
5024       GNUNET_MESSAGE_TYPE_MESH_ACK == type)
5025   {
5026     priority = 100;
5027   }
5028
5029   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "priority %d\n", priority);
5030   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "fc %p\n", fc);
5031   if (fc->queue_n >= fc->queue_max && 0 == priority)
5032   {
5033     GNUNET_STATISTICS_update (stats, "# messages dropped (buffer full)",
5034                               1, GNUNET_NO);
5035     GNUNET_break (0);
5036     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5037                 "queue full: %u/%u\n",
5038                 fc->queue_n, fc->queue_max);
5039     return; /* Drop this message */
5040   }
5041
5042   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "last pid %u\n", fc->last_pid_sent);
5043   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "     ack %u\n", fc->last_ack_recv);
5044   if (GMC_is_pid_bigger (fc->last_pid_sent + 1, fc->last_ack_recv))
5045   {
5046     call_core = GNUNET_NO;
5047     if (GNUNET_SCHEDULER_NO_TASK == fc->poll_task &&
5048         GNUNET_MESSAGE_TYPE_MESH_POLL != type)
5049     {
5050       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5051                   "no buffer space (%u > %u): starting poll\n",
5052                   fc->last_pid_sent + 1, fc->last_ack_recv);
5053       fc->poll_task = GNUNET_SCHEDULER_add_delayed (fc->poll_time,
5054                                                     &connection_poll,
5055                                                     fc);
5056     }
5057   }
5058   else
5059     call_core = GNUNET_YES;
5060   queue = GNUNET_malloc (sizeof (struct MeshPeerQueue));
5061   queue->cls = cls;
5062   queue->type = type;
5063   queue->size = size;
5064   queue->peer = peer;
5065   queue->c = c;
5066   queue->ch = ch;
5067   queue->fwd = fwd;
5068   if (100 <= priority)
5069   {
5070     struct MeshPeerQueue *copy;
5071     struct MeshPeerQueue *next;
5072
5073     for (copy = peer->queue_head; NULL != copy; copy = next)
5074     {
5075       next = copy->next;
5076       if (copy->type == type && copy->c == c && copy->fwd == fwd)
5077       {
5078         /* Example: also a FWD ACK for connection XYZ */
5079         queue_destroy (copy, GNUNET_YES);
5080       }
5081     }
5082     GNUNET_CONTAINER_DLL_insert (peer->queue_head, peer->queue_tail, queue);
5083   }
5084   else
5085   {
5086     GNUNET_CONTAINER_DLL_insert_tail (peer->queue_head, peer->queue_tail, queue);
5087     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Q_N+ %p %u\n", fc, fc->queue_n);
5088     fc->queue_n++;
5089     peer->queue_n++;
5090   }
5091
5092   if (NULL == peer->core_transmit && GNUNET_YES == call_core)
5093   {
5094     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5095                 "calling core tmt rdy towards %s for %u bytes\n",
5096                 peer2s (peer), size);
5097     peer->core_transmit =
5098         GNUNET_CORE_notify_transmit_ready (core_handle,
5099                                            0,
5100                                            0,
5101                                            GNUNET_TIME_UNIT_FOREVER_REL,
5102                                            GNUNET_PEER_resolve2 (peer->id),
5103                                            size,
5104                                            &queue_send,
5105                                            peer);
5106   }
5107   else
5108   {
5109     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5110                 "core tmt rdy towards %s already called\n",
5111                 peer2s (peer));
5112
5113   }
5114   c->pending_messages++;
5115   if (NULL != c->t)
5116     c->t->pending_messages++;
5117 }
5118
5119
5120 /******************************************************************************/
5121 /********************      MESH NETWORK HANDLERS     **************************/
5122 /******************************************************************************/
5123
5124
5125 /**
5126  * Generic handler for mesh network payload traffic.
5127  *
5128  * @param t Tunnel on which we got this message.
5129  * @param message Unencryted data message.
5130  * @param fwd Is this FWD traffic? GNUNET_YES : GNUNET_NO;
5131  */
5132 static void
5133 handle_data (struct MeshTunnel2 *t, const struct GNUNET_MESH_Data *msg, int fwd)
5134 {
5135   struct MeshChannelReliability *rel;
5136   struct MeshChannel *ch;
5137   struct MeshClient *c;
5138   uint32_t mid;
5139   uint16_t type;
5140   size_t size;
5141
5142   /* Check size */
5143   size = ntohs (msg->header.size);
5144   if (size <
5145       sizeof (struct GNUNET_MESH_Data) +
5146       sizeof (struct GNUNET_MessageHeader))
5147   {
5148     GNUNET_break (0);
5149     return;
5150   }
5151   type = ntohs (msg->header.type);
5152   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a %s message\n",
5153               GNUNET_MESH_DEBUG_M2S (type));
5154   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " payload of type %s\n",
5155               GNUNET_MESH_DEBUG_M2S (ntohs (msg[1].header.type)));
5156
5157   /* Check channel */
5158   ch = channel_get (t, ntohl (msg->chid));
5159   if (NULL == ch)
5160   {
5161     GNUNET_STATISTICS_update (stats, "# data on unknown channel", 1, GNUNET_NO);
5162     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
5163                 ntohl (msg->chid));
5164     return;
5165   }
5166
5167   /*  Initialize FWD/BCK data */
5168   c        = fwd ? ch->dest     : ch->root;
5169   rel      = fwd ? ch->dest_rel : ch->root_rel;
5170
5171   if (NULL == c)
5172   {
5173     GNUNET_break (0);
5174     return;
5175   }
5176
5177   tunnel_change_state (t, MESH_TUNNEL_READY);
5178
5179   GNUNET_STATISTICS_update (stats, "# data received", 1, GNUNET_NO);
5180
5181   mid = ntohl (msg->mid);
5182   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " mid %u\n", mid);
5183
5184   if (GNUNET_NO == ch->reliable ||
5185       ( !GMC_is_pid_bigger (rel->mid_recv, mid) &&
5186         GMC_is_pid_bigger (rel->mid_recv + 64, mid) ) )
5187   {
5188     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! RECV %u\n", mid);
5189     if (GNUNET_YES == ch->reliable)
5190     {
5191       /* Is this the exact next expected messasge? */
5192       if (mid == rel->mid_recv)
5193       {
5194         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "as expected\n");
5195         rel->mid_recv++;
5196         channel_send_client_data (ch, msg, fwd);
5197       }
5198       else
5199       {
5200         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "save for later\n");
5201         channel_rel_add_buffered_data (msg, rel);
5202       }
5203     }
5204     else
5205     {
5206       /* Tunnel is unreliable: send to clients directly */
5207       /* FIXME: accept Out Of Order traffic */
5208       rel->mid_recv = mid + 1;
5209       channel_send_client_data (ch, msg, fwd);
5210     }
5211   }
5212   else
5213   {
5214     GNUNET_break_op (0);
5215     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5216                 " MID %u not expected (%u - %u), dropping!\n",
5217                 mid, rel->mid_recv, rel->mid_recv + 64);
5218   }
5219
5220   channel_send_data_ack (ch, fwd);
5221 }
5222
5223 /**
5224  * Handler for mesh network traffic end-to-end ACKs.
5225  *
5226  * @param t Tunnel on which we got this message.
5227  * @param message Data message.
5228  * @param fwd Is this a fwd ACK? (dest->orig)
5229  */
5230 static void
5231 handle_data_ack (struct MeshTunnel2 *t,
5232                  const struct GNUNET_MESH_DataACK *msg, int fwd)
5233 {
5234   struct MeshChannelReliability *rel;
5235   struct MeshReliableMessage *copy;
5236   struct MeshReliableMessage *next;
5237   struct MeshChannel *ch;
5238   uint32_t ack;
5239   uint16_t type;
5240   int work;
5241
5242   type = ntohs (msg->header.type);
5243   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a %s message!\n",
5244               GNUNET_MESH_DEBUG_M2S (type));
5245   ch = channel_get (t, ntohl (msg->chid));
5246   if (NULL == ch)
5247   {
5248     GNUNET_STATISTICS_update (stats, "# ack on unknown channel", 1, GNUNET_NO);
5249     return;
5250   }
5251   ack = ntohl (msg->mid);
5252   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! %s ACK %u\n",
5253               (GNUNET_YES == fwd) ? "FWD" : "BCK", ack);
5254
5255   if (GNUNET_YES == fwd)
5256   {
5257     rel = ch->root_rel;
5258   }
5259   else
5260   {
5261     rel = ch->dest_rel;
5262   }
5263   if (NULL == rel)
5264   {
5265     GNUNET_break (0);
5266     return;
5267   }
5268
5269   for (work = GNUNET_NO, copy = rel->head_sent; copy != NULL; copy = next)
5270   {
5271     if (GMC_is_pid_bigger (copy->mid, ack))
5272     {
5273       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!!  head %u, out!\n", copy->mid);
5274       channel_rel_free_sent (rel, msg);
5275       break;
5276     }
5277     work = GNUNET_YES;
5278     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!!  id %u\n", copy->mid);
5279     next = copy->next;
5280     rel_message_free (copy);
5281   }
5282   /* ACK client if needed */
5283 //   channel_send_ack (t, type, GNUNET_MESSAGE_TYPE_MESH_UNICAST_ACK == type);
5284
5285   /* If some message was free'd, update the retransmission delay*/
5286   if (GNUNET_YES == work)
5287   {
5288     if (GNUNET_SCHEDULER_NO_TASK != rel->retry_task)
5289     {
5290       GNUNET_SCHEDULER_cancel (rel->retry_task);
5291       if (NULL == rel->head_sent)
5292       {
5293         rel->retry_task = GNUNET_SCHEDULER_NO_TASK;
5294       }
5295       else
5296       {
5297         struct GNUNET_TIME_Absolute new_target;
5298         struct GNUNET_TIME_Relative delay;
5299
5300         delay = GNUNET_TIME_relative_multiply (rel->retry_timer,
5301                                                MESH_RETRANSMIT_MARGIN);
5302         new_target = GNUNET_TIME_absolute_add (rel->head_sent->timestamp,
5303                                                delay);
5304         delay = GNUNET_TIME_absolute_get_remaining (new_target);
5305         rel->retry_task =
5306             GNUNET_SCHEDULER_add_delayed (delay,
5307                                           &channel_retransmit_message,
5308                                           rel);
5309       }
5310     }
5311     else
5312       GNUNET_break (0);
5313   }
5314 }
5315
5316
5317 /**
5318  * Core handler for connection creation.
5319  *
5320  * @param cls Closure (unused).
5321  * @param peer Sender (neighbor).
5322  * @param message Message.
5323  *
5324  * @return GNUNET_OK to keep the connection open,
5325  *         GNUNET_SYSERR to close it (signal serious error)
5326  */
5327 static int
5328 handle_mesh_connection_create (void *cls,
5329                                const struct GNUNET_PeerIdentity *peer,
5330                                const struct GNUNET_MessageHeader *message)
5331 {
5332   struct GNUNET_MESH_ConnectionCreate *msg;
5333   struct GNUNET_PeerIdentity *id;
5334   struct GNUNET_HashCode *cid;
5335   struct MeshPeerPath *path;
5336   struct MeshPeer *dest_peer;
5337   struct MeshPeer *orig_peer;
5338   struct MeshConnection *c;
5339   unsigned int own_pos;
5340   uint16_t size;
5341   uint16_t i;
5342
5343   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "\n\n");
5344   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received a connection create msg\n");
5345
5346   /* Check size */
5347   size = ntohs (message->size);
5348   if (size < sizeof (struct GNUNET_MESH_ConnectionCreate))
5349   {
5350     GNUNET_break_op (0);
5351     return GNUNET_OK;
5352   }
5353
5354   /* Calculate hops */
5355   size -= sizeof (struct GNUNET_MESH_ConnectionCreate);
5356   if (size % sizeof (struct GNUNET_PeerIdentity))
5357   {
5358     GNUNET_break_op (0);
5359     return GNUNET_OK;
5360   }
5361   size /= sizeof (struct GNUNET_PeerIdentity);
5362   if (1 > size)
5363   {
5364     GNUNET_break_op (0);
5365     return GNUNET_OK;
5366   }
5367   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "    path has %u hops.\n", size);
5368
5369   /* Get parameters */
5370   msg = (struct GNUNET_MESH_ConnectionCreate *) message;
5371   cid = &msg->cid;
5372   id = (struct GNUNET_PeerIdentity *) &msg[1];
5373   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5374               "    connection %s (%s).\n",
5375               GNUNET_h2s (cid), GNUNET_i2s (id));
5376
5377   /* Create connection */
5378   c = connection_get (cid);
5379   if (NULL == c)
5380   {
5381     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Creating connection\n");
5382     c = connection_new (cid);
5383     if (NULL == c)
5384       return GNUNET_OK;
5385     connection_reset_timeout (c, GNUNET_YES);
5386
5387     /* Create path */
5388     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Creating path...\n");
5389     path = path_new (size);
5390     own_pos = 0;
5391     for (i = 0; i < size; i++)
5392     {
5393       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  ... adding %s\n",
5394                   GNUNET_i2s (&id[i]));
5395       path->peers[i] = GNUNET_PEER_intern (&id[i]);
5396       if (path->peers[i] == myid)
5397         own_pos = i;
5398     }
5399     if (own_pos == 0 && path->peers[own_pos] != myid)
5400     {
5401       /* create path: self not found in path through self */
5402       GNUNET_break_op (0);
5403       path_destroy (path);
5404       connection_destroy (c);
5405       return GNUNET_OK;
5406     }
5407     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Own position: %u\n", own_pos);
5408     path_add_to_peers (path, GNUNET_NO);
5409     c->path = path_duplicate (path);
5410     c->own_pos = own_pos;
5411   }
5412   else
5413   {
5414     path = NULL;
5415   }
5416   if (MESH_CONNECTION_NEW == c->state)
5417     connection_change_state (c, MESH_CONNECTION_SENT);
5418
5419   /* Remember peers */
5420   dest_peer = peer_get (&id[size - 1]);
5421   orig_peer = peer_get (&id[0]);
5422
5423   /* Is it a connection to us? */
5424   if (c->own_pos == size - 1)
5425   {
5426     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  It's for us!\n");
5427     peer_add_path_to_origin (orig_peer, path, GNUNET_YES);
5428
5429     if (NULL == orig_peer->tunnel)
5430     {
5431       orig_peer->tunnel = tunnel_new ();
5432       orig_peer->tunnel->peer = orig_peer;
5433     }
5434     tunnel_add_connection (orig_peer->tunnel, c);
5435     if (MESH_TUNNEL_NEW == c->t->state)
5436       tunnel_change_state (c->t,  MESH_TUNNEL_WAITING);
5437
5438     send_connection_ack (c, GNUNET_NO);
5439     if (MESH_CONNECTION_SENT == c->state)
5440       connection_change_state (c, MESH_CONNECTION_ACK);
5441
5442     /* Keep tunnel alive in direction dest->owner*/
5443     connection_reset_timeout (c, GNUNET_NO);
5444   }
5445   else
5446   {
5447     /* It's for somebody else! Retransmit. */
5448     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Retransmitting.\n");
5449     peer_add_path (dest_peer, path_duplicate (path), GNUNET_NO);
5450     peer_add_path_to_origin (orig_peer, path, GNUNET_NO);
5451     send_prebuilt_message_connection (message, c, NULL, GNUNET_YES);
5452   }
5453   return GNUNET_OK;
5454 }
5455
5456
5457 /**
5458  * Core handler for path ACKs
5459  *
5460  * @param cls closure
5461  * @param message message
5462  * @param peer peer identity this notification is about
5463  *
5464  * @return GNUNET_OK to keep the connection open,
5465  *         GNUNET_SYSERR to close it (signal serious error)
5466  */
5467 static int
5468 handle_mesh_connection_ack (void *cls, const struct GNUNET_PeerIdentity *peer,
5469                             const struct GNUNET_MessageHeader *message)
5470 {
5471   struct GNUNET_MESH_ConnectionACK *msg;
5472   struct MeshConnection *c;
5473   struct MeshPeerPath *p;
5474   struct MeshPeer *pi;
5475   int fwd;
5476
5477   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "\n\n");
5478   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received a connection ACK msg\n");
5479   msg = (struct GNUNET_MESH_ConnectionACK *) message;
5480   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on connection %s\n",
5481               GNUNET_h2s (&msg->cid));
5482   c = connection_get (&msg->cid);
5483   if (NULL == c)
5484   {
5485     GNUNET_STATISTICS_update (stats, "# control on unknown connection",
5486                               1, GNUNET_NO);
5487     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  don't know the connection!\n");
5488     return GNUNET_OK;
5489   }
5490
5491
5492   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  via peer %s\n",
5493               GNUNET_i2s (peer));
5494   pi = peer_get (peer);
5495   if (connection_get_next_hop (c) == pi)
5496   {
5497     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  SYNACK\n");
5498     fwd = GNUNET_NO;
5499     if (MESH_CONNECTION_SENT == c->state)
5500       connection_change_state (c, MESH_CONNECTION_ACK);
5501   }
5502   else if (connection_get_prev_hop (c) == pi)
5503   {
5504     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  ACK\n");
5505     fwd = GNUNET_YES;
5506     connection_change_state (c, MESH_CONNECTION_READY);
5507   }
5508   else
5509   {
5510     GNUNET_break_op (0);
5511     return GNUNET_OK;
5512   }
5513   connection_reset_timeout (c, fwd);
5514
5515   /* Add path to peers? */
5516   p = c->path;
5517   if (NULL != p)
5518   {
5519     path_add_to_peers (p, GNUNET_YES);
5520   }
5521   else
5522   {
5523     GNUNET_break (0);
5524   }
5525
5526   /* Message for us as creator? */
5527   if (connection_is_origin (c, GNUNET_YES))
5528   {
5529     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Connection (SYN)ACK for us!\n");
5530     connection_change_state (c, MESH_CONNECTION_READY);
5531     if (MESH_TUNNEL_READY != c->t->state)
5532       tunnel_change_state (c->t, MESH_TUNNEL_READY);
5533     send_connection_ack (c, GNUNET_YES);
5534     tunnel_send_queued_data (c->t, GNUNET_YES);
5535     if (3 <= tunnel_count_connections (c->t) && NULL != c->t->peer->dhtget)
5536     {
5537       GNUNET_DHT_get_stop (c->t->peer->dhtget);
5538       c->t->peer->dhtget = NULL;
5539     }
5540     return GNUNET_OK;
5541   }
5542
5543   /* Message for us as destination? */
5544   if (connection_is_terminal (c, GNUNET_YES))
5545   {
5546     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Connection ACK for us!\n");
5547     if (MESH_TUNNEL_READY != c->t->state)
5548       tunnel_change_state (c->t, MESH_TUNNEL_READY);
5549     connection_change_state (c, MESH_CONNECTION_READY);
5550     tunnel_send_queued_data (c->t, GNUNET_NO);
5551     return GNUNET_OK;
5552   }
5553
5554   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  not for us, retransmitting...\n");
5555   send_prebuilt_message_connection (message, c, NULL, fwd);
5556   return GNUNET_OK;
5557 }
5558
5559
5560 /**
5561  * Core handler for notifications of broken paths
5562  *
5563  * @param cls Closure (unused).
5564  * @param peer Peer identity of sending neighbor.
5565  * @param message Message.
5566  *
5567  * @return GNUNET_OK to keep the connection open,
5568  *         GNUNET_SYSERR to close it (signal serious error)
5569  */
5570 static int
5571 handle_mesh_connection_broken (void *cls, const struct GNUNET_PeerIdentity *peer,
5572                                const struct GNUNET_MessageHeader *message)
5573 {
5574   struct GNUNET_MESH_ConnectionBroken *msg;
5575   struct MeshConnection *c;
5576
5577   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5578               "Received a CONNECTION BROKEN msg from %s\n", GNUNET_i2s (peer));
5579   msg = (struct GNUNET_MESH_ConnectionBroken *) message;
5580   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  regarding %s\n",
5581               GNUNET_i2s (&msg->peer1));
5582   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  regarding %s\n",
5583               GNUNET_i2s (&msg->peer2));
5584   c = connection_get (&msg->cid);
5585   if (NULL == c)
5586   {
5587     GNUNET_break_op (0);
5588     return GNUNET_OK;
5589   }
5590   tunnel_notify_connection_broken (c->t, GNUNET_PEER_search (&msg->peer1),
5591                                    GNUNET_PEER_search (&msg->peer2));
5592   return GNUNET_OK;
5593
5594 }
5595
5596
5597 /**
5598  * Core handler for tunnel destruction
5599  *
5600  * @param cls Closure (unused).
5601  * @param peer Peer identity of sending neighbor.
5602  * @param message Message.
5603  *
5604  * @return GNUNET_OK to keep the connection open,
5605  *         GNUNET_SYSERR to close it (signal serious error)
5606  */
5607 static int
5608 handle_mesh_connection_destroy (void *cls,
5609                                 const struct GNUNET_PeerIdentity *peer,
5610                                 const struct GNUNET_MessageHeader *message)
5611 {
5612   struct GNUNET_MESH_ConnectionDestroy *msg;
5613   struct MeshConnection *c;
5614   GNUNET_PEER_Id id;
5615   int fwd;
5616
5617   msg = (struct GNUNET_MESH_ConnectionDestroy *) message;
5618   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5619               "Got a CONNECTION DESTROY message from %s\n",
5620               GNUNET_i2s (peer));
5621   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5622               "  for connection %s\n",
5623               GNUNET_h2s (&msg->cid));
5624   c = connection_get (&msg->cid);
5625   if (NULL == c)
5626   {
5627     /* Probably already got the message from another path,
5628      * destroyed the tunnel and retransmitted to children.
5629      * Safe to ignore.
5630      */
5631     GNUNET_STATISTICS_update (stats, "# control on unknown tunnel",
5632                               1, GNUNET_NO);
5633     return GNUNET_OK;
5634   }
5635   id = GNUNET_PEER_search (peer);
5636   if (id == connection_get_prev_hop (c)->id)
5637     fwd = GNUNET_YES;
5638   else if (id == connection_get_next_hop (c)->id)
5639     fwd = GNUNET_NO;
5640   else
5641   {
5642     GNUNET_break_op (0);
5643     return GNUNET_OK;
5644   }
5645   send_prebuilt_message_connection (message, c, NULL, fwd);
5646   c->destroy = GNUNET_YES;
5647
5648   return GNUNET_OK;
5649 }
5650
5651
5652 /**
5653  * Handler for channel create messages.
5654  *
5655  * @param t Tunnel this channel is to be created in.
5656  * @param msg Message.
5657  * @param fwd Is this FWD traffic? GNUNET_YES : GNUNET_NO;
5658  */
5659 static void
5660 handle_channel_create (struct MeshTunnel2 *t,
5661                        struct GNUNET_MESH_ChannelCreate *msg,
5662                        int fwd)
5663 {
5664   MESH_ChannelNumber chid;
5665   struct MeshChannel *ch;
5666   struct MeshClient *c;
5667   uint32_t port;
5668
5669   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received Channel Create\n");
5670   /* Check message size */
5671   if (ntohs (msg->header.size) != sizeof (struct GNUNET_MESH_ChannelCreate))
5672   {
5673     GNUNET_break_op (0);
5674     return;
5675   }
5676
5677   /* Check if channel exists */
5678   chid = ntohl (msg->chid);
5679   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   chid %u\n", chid);
5680   ch = channel_get (t, chid);
5681   if (NULL != ch)
5682   {
5683     /* Probably a retransmission, safe to ignore */
5684     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   already exists...\n");
5685     if (NULL != ch->dest)
5686     {
5687       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   duplicate CC!!\n");
5688       channel_send_ack (ch, !fwd);
5689       return;
5690     }
5691   }
5692   else
5693   {
5694     /* Create channel */
5695     ch = channel_new (t, NULL, 0);
5696     ch->gid = chid;
5697     channel_set_options (ch, ntohl (msg->opt));
5698   }
5699
5700   /* Find a destination client */
5701   port = ntohl (msg->port);
5702   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   port %u\n", port);
5703   c = GNUNET_CONTAINER_multihashmap32_get (ports, port);
5704   if (NULL == c)
5705   {
5706     /* TODO send reject */
5707     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  no client has port registered\n");
5708     /* TODO free ch */
5709     return;
5710   }
5711
5712   channel_add_client (ch, c);
5713   if (GNUNET_YES == ch->reliable)
5714     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! Reliable\n");
5715
5716   send_local_channel_create (ch);
5717   channel_send_ack (ch, fwd);
5718   send_local_ack (ch, !fwd);
5719 }
5720
5721
5722 /**
5723  * Handler for channel ack messages.
5724  *
5725  * @param t Tunnel this channel is to be created in.
5726  * @param msg Message.
5727  * @param fwd Is this FWD traffic? GNUNET_YES : GNUNET_NO;
5728  */
5729 static void
5730 handle_channel_ack (struct MeshTunnel2 *t,
5731                     struct GNUNET_MESH_ChannelManage *msg,
5732                     int fwd)
5733 {
5734   MESH_ChannelNumber chid;
5735   struct MeshChannel *ch;
5736
5737   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received Channel ACK\n");
5738   /* Check message size */
5739   if (ntohs (msg->header.size) != sizeof (struct GNUNET_MESH_ChannelManage))
5740   {
5741     GNUNET_break_op (0);
5742     return;
5743   }
5744
5745   /* Check if channel exists */
5746   chid = ntohl (msg->chid);
5747   ch = channel_get (t, chid);
5748   if (NULL == ch)
5749   {
5750     GNUNET_break_op (0);
5751     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   channel %u unknown!!\n", chid);
5752     return;
5753   }
5754
5755   channel_confirm (ch, !fwd);
5756 }
5757
5758
5759 /**
5760  * Handler for channel destroy messages.
5761  *
5762  * @param t Tunnel this channel is to be destroyed of.
5763  * @param msg Message.
5764  * @param fwd Is this FWD traffic? GNUNET_YES : GNUNET_NO;
5765  */
5766 static void
5767 handle_channel_destroy (struct MeshTunnel2 *t,
5768                         struct GNUNET_MESH_ChannelManage *msg,
5769                         int fwd)
5770 {
5771   MESH_ChannelNumber chid;
5772   struct MeshChannel *ch;
5773
5774   /* Check message size */
5775   if (ntohs (msg->header.size) != sizeof (struct GNUNET_MESH_ChannelManage))
5776   {
5777     GNUNET_break_op (0);
5778     return;
5779   }
5780
5781   /* Check if channel exists */
5782   chid = ntohl (msg->chid);
5783   ch = channel_get (t, chid);
5784   if (NULL == ch)
5785   {
5786     /* Probably a retransmission, safe to ignore */
5787     return;
5788   }
5789
5790   send_local_channel_destroy (ch, fwd);
5791   channel_destroy (ch);
5792 }
5793
5794
5795 static void
5796 handle_decrypted (struct MeshTunnel2 *t,
5797                   const struct GNUNET_MessageHeader *msgh,
5798                   int fwd)
5799 {
5800   switch (ntohs (msgh->type))
5801   {
5802     case GNUNET_MESSAGE_TYPE_MESH_DATA:
5803       /* Don't send hop ACK, wait for client to ACK */
5804       handle_data (t, (struct GNUNET_MESH_Data *) msgh, fwd);
5805       break;
5806
5807     case GNUNET_MESSAGE_TYPE_MESH_DATA_ACK:
5808       handle_data_ack (t, (struct GNUNET_MESH_DataACK *) msgh, fwd);
5809       break;
5810
5811     case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_CREATE:
5812       handle_channel_create (t,
5813                              (struct GNUNET_MESH_ChannelCreate *) msgh,
5814                              fwd);
5815       break;
5816
5817     case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_ACK:
5818       handle_channel_ack (t,
5819                           (struct GNUNET_MESH_ChannelManage *) msgh,
5820                           fwd);
5821       break;
5822
5823     case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_DESTROY:
5824       handle_channel_destroy (t,
5825                               (struct GNUNET_MESH_ChannelManage *) msgh,
5826                               fwd);
5827       break;
5828
5829     default:
5830       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5831                   "end-to-end message not known (%u)\n",
5832                   ntohs (msgh->type));
5833   }
5834 }
5835
5836
5837 /**
5838  * Generic handler for mesh network encrypted traffic.
5839  *
5840  * @param peer Peer identity this notification is about.
5841  * @param message Encrypted message.
5842  * @param fwd Is this FWD traffic? GNUNET_YES : GNUNET_NO;
5843  *
5844  * @return GNUNET_OK to keep the connection open,
5845  *         GNUNET_SYSERR to close it (signal serious error)
5846  */
5847 static int
5848 handle_mesh_encrypted (const struct GNUNET_PeerIdentity *peer,
5849                        const struct GNUNET_MESH_Encrypted *msg,
5850                        int fwd)
5851 {
5852   struct MeshConnection *c;
5853   struct MeshTunnel2 *t;
5854   struct MeshPeer *neighbor;
5855   struct MeshFlowControl *fc;
5856   uint32_t pid;
5857   uint32_t ttl;
5858   uint16_t type;
5859   size_t size;
5860
5861   /* Check size */
5862   size = ntohs (msg->header.size);
5863   if (size <
5864       sizeof (struct GNUNET_MESH_Encrypted) +
5865       sizeof (struct GNUNET_MessageHeader))
5866   {
5867     GNUNET_break_op (0);
5868     return GNUNET_OK;
5869   }
5870   type = ntohs (msg->header.type);
5871   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "\n\n");
5872   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a %s message from %s\n",
5873               GNUNET_MESH_DEBUG_M2S (type), GNUNET_i2s (peer));
5874
5875   /* Check connection */
5876   c = connection_get (&msg->cid);
5877   if (NULL == c)
5878   {
5879     GNUNET_STATISTICS_update (stats, "# unknown connection", 1, GNUNET_NO);
5880     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "WARNING connection unknown\n");
5881     return GNUNET_OK;
5882   }
5883   t = c->t;
5884   fc = fwd ? &c->bck_fc : &c->fwd_fc;
5885
5886   /* Check if origin is as expected */
5887   neighbor = connection_get_hop (c, !fwd);
5888   if (peer_get (peer)->id != neighbor->id)
5889   {
5890     GNUNET_break_op (0);
5891     return GNUNET_OK;
5892   }
5893
5894   /* Check PID */
5895   pid = ntohl (msg->pid);
5896   if (GMC_is_pid_bigger (pid, fc->last_ack_sent))
5897   {
5898     GNUNET_STATISTICS_update (stats, "# unsolicited message", 1, GNUNET_NO);
5899     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5900                 "WARNING Received PID %u, (prev %u), ACK %u\n",
5901                 pid, fc->last_pid_recv, fc->last_ack_sent);
5902     return GNUNET_OK;
5903   }
5904   if (GNUNET_NO == GMC_is_pid_bigger (pid, fc->last_pid_recv))
5905   {
5906     GNUNET_STATISTICS_update (stats, "# duplicate PID", 1, GNUNET_NO);
5907     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5908                 " Pid %u not expected (%u+), dropping!\n",
5909                 pid, fc->last_pid_recv + 1);
5910     return GNUNET_OK;
5911   }
5912   if (MESH_CONNECTION_SENT == c->state)
5913     connection_change_state (c, MESH_CONNECTION_READY);
5914   connection_reset_timeout (c, fwd);
5915   fc->last_pid_recv = pid;
5916
5917   /* Is this message for us? */
5918   if (connection_is_terminal (c, fwd))
5919   {
5920     size_t dsize = size - sizeof (struct GNUNET_MESH_Encrypted);
5921     char cbuf[dsize];
5922     struct GNUNET_MessageHeader *msgh;
5923     unsigned int off;
5924
5925     /* TODO signature verification */
5926     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  message for us!\n");
5927     GNUNET_STATISTICS_update (stats, "# messages received", 1, GNUNET_NO);
5928
5929     fc->last_pid_recv = pid;
5930     tunnel_decrypt (t, cbuf, &msg[1], dsize, msg->iv, fwd);
5931     off = 0;
5932     while (off < dsize)
5933     {
5934       msgh = (struct GNUNET_MessageHeader *) &cbuf[off];
5935       handle_decrypted (t, msgh, fwd);
5936       off += ntohs (msgh->size);
5937     }
5938     send_ack (c, NULL, fwd);
5939     return GNUNET_OK;
5940   }
5941
5942   /* Message not for us: forward to next hop */
5943   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  not for us, retransmitting...\n");
5944   ttl = ntohl (msg->ttl);
5945   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   ttl: %u\n", ttl);
5946   if (ttl == 0)
5947   {
5948     GNUNET_STATISTICS_update (stats, "# TTL drops", 1, GNUNET_NO);
5949     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, " TTL is 0, DROPPING!\n");
5950     send_ack (c, NULL, fwd);
5951     return GNUNET_OK;
5952   }
5953   GNUNET_STATISTICS_update (stats, "# messages forwarded", 1, GNUNET_NO);
5954
5955   send_prebuilt_message_connection (&msg->header, c, NULL, fwd);
5956
5957   return GNUNET_OK;
5958 }
5959
5960
5961 /**
5962  * Core handler for mesh network traffic going orig->dest.
5963  *
5964  * @param cls Closure (unused).
5965  * @param message Message received.
5966  * @param peer Peer who sent the message.
5967  *
5968  * @return GNUNET_OK to keep the connection open,
5969  *         GNUNET_SYSERR to close it (signal serious error)
5970  */
5971 static int
5972 handle_mesh_fwd (void *cls, const struct GNUNET_PeerIdentity *peer,
5973                      const struct GNUNET_MessageHeader *message)
5974 {
5975   return handle_mesh_encrypted (peer,
5976                                 (struct GNUNET_MESH_Encrypted *)message,
5977                                 GNUNET_YES);
5978 }
5979
5980 /**
5981  * Core handler for mesh network traffic going dest->orig.
5982  *
5983  * @param cls Closure (unused).
5984  * @param message Message received.
5985  * @param peer Peer who sent the message.
5986  *
5987  * @return GNUNET_OK to keep the connection open,
5988  *         GNUNET_SYSERR to close it (signal serious error)
5989  */
5990 static int
5991 handle_mesh_bck (void *cls, const struct GNUNET_PeerIdentity *peer,
5992                      const struct GNUNET_MessageHeader *message)
5993 {
5994   return handle_mesh_encrypted (peer,
5995                                 (struct GNUNET_MESH_Encrypted *)message,
5996                                 GNUNET_NO);
5997 }
5998
5999
6000 /**
6001  * Core handler for mesh network traffic point-to-point acks.
6002  *
6003  * @param cls closure
6004  * @param message message
6005  * @param peer peer identity this notification is about
6006  *
6007  * @return GNUNET_OK to keep the connection open,
6008  *         GNUNET_SYSERR to close it (signal serious error)
6009  */
6010 static int
6011 handle_mesh_ack (void *cls, const struct GNUNET_PeerIdentity *peer,
6012                  const struct GNUNET_MessageHeader *message)
6013 {
6014   struct GNUNET_MESH_ACK *msg;
6015   struct MeshConnection *c;
6016   struct MeshFlowControl *fc;
6017   GNUNET_PEER_Id id;
6018   uint32_t ack;
6019   int fwd;
6020
6021   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "\n\n");
6022   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got an ACK packet from %s!\n",
6023               GNUNET_i2s (peer));
6024   msg = (struct GNUNET_MESH_ACK *) message;
6025
6026   c = connection_get (&msg->cid);
6027
6028   if (NULL == c)
6029   {
6030     GNUNET_STATISTICS_update (stats, "# ack on unknown connection", 1,
6031                               GNUNET_NO);
6032     return GNUNET_OK;
6033   }
6034
6035   /* Is this a forward or backward ACK? */
6036   id = GNUNET_PEER_search (peer);
6037   if (connection_get_next_hop (c)->id == id)
6038   {
6039     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  FWD ACK\n");
6040     fc = &c->fwd_fc;
6041     fwd = GNUNET_YES;
6042   }
6043   else if (connection_get_prev_hop (c)->id == id)
6044   {
6045     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  BCK ACK\n");
6046     fc = &c->bck_fc;
6047     fwd = GNUNET_NO;
6048   }
6049   else
6050   {
6051     GNUNET_break_op (0);
6052     return GNUNET_OK;
6053   }
6054
6055   ack = ntohl (msg->ack);
6056   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  ACK %u (was %u)\n",
6057               ack, fc->last_ack_recv);
6058   if (GMC_is_pid_bigger (ack, fc->last_ack_recv))
6059     fc->last_ack_recv = ack;
6060
6061   /* Cancel polling if the ACK is big enough. */
6062   if (GNUNET_SCHEDULER_NO_TASK != fc->poll_task &&
6063       GMC_is_pid_bigger (fc->last_ack_recv, fc->last_pid_sent))
6064   {
6065     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Cancel poll\n");
6066     GNUNET_SCHEDULER_cancel (fc->poll_task);
6067     fc->poll_task = GNUNET_SCHEDULER_NO_TASK;
6068     fc->poll_time = GNUNET_TIME_UNIT_SECONDS;
6069   }
6070
6071   connection_unlock_queue (c, fwd);
6072
6073   return GNUNET_OK;
6074 }
6075
6076
6077 /**
6078  * Core handler for mesh network traffic point-to-point ack polls.
6079  *
6080  * @param cls closure
6081  * @param message message
6082  * @param peer peer identity this notification is about
6083  *
6084  * @return GNUNET_OK to keep the connection open,
6085  *         GNUNET_SYSERR to close it (signal serious error)
6086  */
6087 static int
6088 handle_mesh_poll (void *cls, const struct GNUNET_PeerIdentity *peer,
6089                   const struct GNUNET_MessageHeader *message)
6090 {
6091   struct GNUNET_MESH_Poll *msg;
6092   struct MeshConnection *c;
6093   struct MeshFlowControl *fc;
6094   GNUNET_PEER_Id id;
6095   uint32_t pid;
6096   int fwd;
6097
6098   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "\n\n");
6099   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a POLL packet from %s!\n",
6100               GNUNET_i2s (peer));
6101
6102   msg = (struct GNUNET_MESH_Poll *) message;
6103
6104   c = connection_get (&msg->cid);
6105
6106   if (NULL == c)
6107   {
6108     GNUNET_STATISTICS_update (stats, "# poll on unknown connection", 1,
6109                               GNUNET_NO);
6110     GNUNET_break_op (0);
6111     return GNUNET_OK;
6112   }
6113
6114   /* Is this a forward or backward ACK?
6115    * Note: a poll should never be needed in a loopback case,
6116    * since there is no possiblility of packet loss there, so
6117    * this way of discerining FWD/BCK should not be a problem.
6118    */
6119   id = GNUNET_PEER_search (peer);
6120   if (connection_get_next_hop (c)->id == id)
6121   {
6122     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  FWD ACK\n");
6123     fc = &c->fwd_fc;
6124   }
6125   else if (connection_get_prev_hop (c)->id == id)
6126   {
6127     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  BCK ACK\n");
6128     fc = &c->bck_fc;
6129   }
6130   else
6131   {
6132     GNUNET_break_op (0);
6133     return GNUNET_OK;
6134   }
6135
6136   pid = ntohl (msg->pid);
6137   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  PID %u, OLD %u\n",
6138               pid, fc->last_pid_recv);
6139   fc->last_pid_recv = pid;
6140   fwd = fc == &c->fwd_fc;
6141   send_ack (c, NULL, fwd);
6142
6143   return GNUNET_OK;
6144 }
6145
6146
6147 /**
6148  * Core handler for mesh keepalives.
6149  *
6150  * @param cls closure
6151  * @param message message
6152  * @param peer peer identity this notification is about
6153  * @return GNUNET_OK to keep the connection open,
6154  *         GNUNET_SYSERR to close it (signal serious error)
6155  *
6156  * TODO: Check who we got this from, to validate route.
6157  */
6158 static int
6159 handle_mesh_keepalive (void *cls, const struct GNUNET_PeerIdentity *peer,
6160                        const struct GNUNET_MessageHeader *message)
6161 {
6162   struct GNUNET_MESH_ConnectionKeepAlive *msg;
6163   struct MeshConnection *c;
6164   struct MeshPeer *neighbor;
6165   int fwd;
6166
6167   msg = (struct GNUNET_MESH_ConnectionKeepAlive *) message;
6168   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a keepalive packet from %s\n",
6169               GNUNET_i2s (peer));
6170
6171   c = connection_get (&msg->cid);
6172   if (NULL == c)
6173   {
6174     GNUNET_STATISTICS_update (stats, "# keepalive on unknown connection", 1,
6175                               GNUNET_NO);
6176     return GNUNET_OK;
6177   }
6178
6179   fwd = GNUNET_MESSAGE_TYPE_MESH_FWD_KEEPALIVE == ntohs (message->type) ? 
6180         GNUNET_YES : GNUNET_NO;
6181
6182   /* Check if origin is as expected */
6183   neighbor = connection_get_hop (c, fwd);
6184   if (peer_get (peer)->id != neighbor->id)
6185   {
6186     GNUNET_break_op (0);
6187     return GNUNET_OK;
6188   }
6189
6190   connection_change_state (c, MESH_CONNECTION_READY);
6191   connection_reset_timeout (c, fwd);
6192
6193   if (connection_is_terminal (c, fwd))
6194     return GNUNET_OK;
6195
6196   GNUNET_STATISTICS_update (stats, "# keepalives forwarded", 1, GNUNET_NO);
6197   send_prebuilt_message_connection (message, c, NULL, fwd);
6198
6199   return GNUNET_OK;
6200 }
6201
6202
6203
6204 /**
6205  * Functions to handle messages from core
6206  */
6207 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
6208   {&handle_mesh_connection_create, GNUNET_MESSAGE_TYPE_MESH_CONNECTION_CREATE,
6209     0},
6210   {&handle_mesh_connection_ack, GNUNET_MESSAGE_TYPE_MESH_CONNECTION_ACK,
6211     sizeof (struct GNUNET_MESH_ConnectionACK)},
6212   {&handle_mesh_connection_broken, GNUNET_MESSAGE_TYPE_MESH_CONNECTION_BROKEN,
6213     sizeof (struct GNUNET_MESH_ConnectionBroken)},
6214   {&handle_mesh_connection_destroy, GNUNET_MESSAGE_TYPE_MESH_CONNECTION_DESTROY,
6215     sizeof (struct GNUNET_MESH_ConnectionDestroy)},
6216   {&handle_mesh_keepalive, GNUNET_MESSAGE_TYPE_MESH_FWD_KEEPALIVE,
6217     sizeof (struct GNUNET_MESH_ConnectionKeepAlive)},
6218   {&handle_mesh_keepalive, GNUNET_MESSAGE_TYPE_MESH_BCK_KEEPALIVE,
6219     sizeof (struct GNUNET_MESH_ConnectionKeepAlive)},
6220   {&handle_mesh_ack, GNUNET_MESSAGE_TYPE_MESH_ACK,
6221     sizeof (struct GNUNET_MESH_ACK)},
6222   {&handle_mesh_poll, GNUNET_MESSAGE_TYPE_MESH_POLL,
6223     sizeof (struct GNUNET_MESH_Poll)},
6224   {&handle_mesh_fwd, GNUNET_MESSAGE_TYPE_MESH_FWD, 0},
6225   {&handle_mesh_bck, GNUNET_MESSAGE_TYPE_MESH_BCK, 0},
6226   {NULL, 0, 0}
6227 };
6228
6229
6230 /**
6231  * Function to process paths received for a new peer addition. The recorded
6232  * paths form the initial tunnel, which can be optimized later.
6233  * Called on each result obtained for the DHT search.
6234  *
6235  * @param cls closure
6236  * @param exp when will this value expire
6237  * @param key key of the result
6238  * @param get_path path of the get request
6239  * @param get_path_length lenght of get_path
6240  * @param put_path path of the put request
6241  * @param put_path_length length of the put_path
6242  * @param type type of the result
6243  * @param size number of bytes in data
6244  * @param data pointer to the result data
6245  */
6246 static void
6247 dht_get_id_handler (void *cls, struct GNUNET_TIME_Absolute exp,
6248                     const struct GNUNET_HashCode * key,
6249                     const struct GNUNET_PeerIdentity *get_path,
6250                     unsigned int get_path_length,
6251                     const struct GNUNET_PeerIdentity *put_path,
6252                     unsigned int put_path_length, enum GNUNET_BLOCK_Type type,
6253                     size_t size, const void *data)
6254 {
6255   struct MeshPeer *peer = cls;
6256   struct MeshPeerPath *p;
6257   struct MeshConnection *c;
6258   struct GNUNET_PeerIdentity pi;
6259   int i;
6260
6261   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got results from DHT!\n");
6262   GNUNET_PEER_resolve (peer->id, &pi);
6263   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  for %s\n", GNUNET_i2s (&pi));
6264
6265   p = path_build_from_dht (get_path, get_path_length,
6266                            put_path, put_path_length);
6267   path_add_to_peers (p, GNUNET_NO);
6268   path_destroy (p);
6269
6270   /* Count connections */
6271   for (c = peer->tunnel->connection_head, i = 0; NULL != c; c = c->next, i++);
6272
6273   /* If we already have 3 (or more (?!)) connections, it's enough */
6274   if (3 <= i)
6275     return;
6276
6277   if (peer->tunnel->state == MESH_TUNNEL_SEARCHING)
6278   {
6279     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " ... connect!\n");
6280     peer_connect (peer);
6281   }
6282   return;
6283 }
6284
6285
6286 /******************************************************************************/
6287 /*********************       MESH LOCAL HANDLES      **************************/
6288 /******************************************************************************/
6289
6290
6291 /**
6292  * Handler for client connection.
6293  *
6294  * @param cls Closure (unused).
6295  * @param client Client handler.
6296  */
6297 static void
6298 handle_local_client_connect (void *cls, struct GNUNET_SERVER_Client *client)
6299 {
6300   struct MeshClient *c;
6301
6302   if (NULL == client)
6303     return;
6304   c = GNUNET_malloc (sizeof (struct MeshClient));
6305   c->handle = client;
6306   c->id = next_client_id++; /* overflow not important: just for debug */
6307   GNUNET_SERVER_client_keep (client);
6308   GNUNET_SERVER_client_set_user_context (client, c);
6309   GNUNET_CONTAINER_DLL_insert (clients_head, clients_tail, c);
6310 }
6311
6312
6313 /**
6314  * Handler for client disconnection
6315  *
6316  * @param cls closure
6317  * @param client identification of the client; NULL
6318  *        for the last call when the server is destroyed
6319  */
6320 static void
6321 handle_local_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
6322 {
6323   struct MeshClient *c;
6324
6325   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "client disconnected: %p\n", client);
6326   if (client == NULL)
6327   {
6328     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   (SERVER DOWN)\n");
6329     return;
6330   }
6331
6332   c = client_get (client);
6333   if (NULL != c)
6334   {
6335     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "matching client found (%u, %p)\n",
6336                 c->id, c);
6337     GNUNET_SERVER_client_drop (c->handle);
6338     c->shutting_down = GNUNET_YES;
6339     if (NULL != c->own_channels)
6340     {
6341       GNUNET_CONTAINER_multihashmap32_iterate (c->own_channels,
6342                                                &channel_destroy_iterator, c);
6343       GNUNET_CONTAINER_multihashmap32_destroy (c->own_channels);
6344     }
6345
6346     if (NULL != c->incoming_channels)
6347     {
6348       GNUNET_CONTAINER_multihashmap32_iterate (c->incoming_channels,
6349                                                &channel_destroy_iterator, c);
6350       GNUNET_CONTAINER_multihashmap32_destroy (c->incoming_channels);
6351     }
6352
6353     if (NULL != c->ports)
6354     {
6355       GNUNET_CONTAINER_multihashmap32_iterate (c->ports,
6356                                                &client_release_ports, c);
6357       GNUNET_CONTAINER_multihashmap32_destroy (c->ports);
6358     }
6359     GNUNET_CONTAINER_DLL_remove (clients_head, clients_tail, c);
6360     GNUNET_STATISTICS_update (stats, "# clients", -1, GNUNET_NO);
6361     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  client free (%p)\n", c);
6362     GNUNET_free (c);
6363   }
6364   else
6365   {
6366     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, " context NULL!\n");
6367   }
6368   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "done!\n");
6369   return;
6370 }
6371
6372
6373 /**
6374  * Handler for new clients
6375  *
6376  * @param cls closure
6377  * @param client identification of the client
6378  * @param message the actual message, which includes messages the client wants
6379  */
6380 static void
6381 handle_local_new_client (void *cls, struct GNUNET_SERVER_Client *client,
6382                          const struct GNUNET_MessageHeader *message)
6383 {
6384   struct GNUNET_MESH_ClientConnect *cc_msg;
6385   struct MeshClient *c;
6386   unsigned int size;
6387   uint32_t *p;
6388   unsigned int i;
6389
6390   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new client connected %p\n", client);
6391
6392   /* Check data sanity */
6393   size = ntohs (message->size) - sizeof (struct GNUNET_MESH_ClientConnect);
6394   cc_msg = (struct GNUNET_MESH_ClientConnect *) message;
6395   if (0 != (size % sizeof (uint32_t)))
6396   {
6397     GNUNET_break (0);
6398     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6399     return;
6400   }
6401   size /= sizeof (uint32_t);
6402
6403   /* Initialize new client structure */
6404   c = GNUNET_SERVER_client_get_user_context (client, struct MeshClient);
6405   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  client id %u\n", c->id);
6406   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  client has %u ports\n", size);
6407   if (size > 0)
6408   {
6409     uint32_t u32;
6410
6411     p = (uint32_t *) &cc_msg[1];
6412     c->ports = GNUNET_CONTAINER_multihashmap32_create (size);
6413     for (i = 0; i < size; i++)
6414     {
6415       u32 = ntohl (p[i]);
6416       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "    port: %u\n", u32);
6417
6418       /* store in client's hashmap */
6419       GNUNET_CONTAINER_multihashmap32_put (c->ports, u32, c,
6420                                            GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
6421       /* store in global hashmap */
6422       /* FIXME only allow one client to have the port open,
6423        *       have a backup hashmap with waiting clients */
6424       GNUNET_CONTAINER_multihashmap32_put (ports, u32, c,
6425                                            GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
6426     }
6427   }
6428
6429   c->own_channels = GNUNET_CONTAINER_multihashmap32_create (32);
6430   c->incoming_channels = GNUNET_CONTAINER_multihashmap32_create (32);
6431   GNUNET_SERVER_notification_context_add (nc, client);
6432   GNUNET_STATISTICS_update (stats, "# clients", 1, GNUNET_NO);
6433
6434   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6435   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new client processed\n");
6436 }
6437
6438
6439 /**
6440  * Handler for requests of new tunnels
6441  *
6442  * @param cls Closure.
6443  * @param client Identification of the client.
6444  * @param message The actual message.
6445  */
6446 static void
6447 handle_local_channel_create (void *cls, struct GNUNET_SERVER_Client *client,
6448                             const struct GNUNET_MessageHeader *message)
6449 {
6450   struct GNUNET_MESH_ChannelMessage *msg;
6451   struct MeshPeer *peer;
6452   struct MeshTunnel2 *t;
6453   struct MeshChannel *ch;
6454   struct MeshClient *c;
6455   MESH_ChannelNumber chid;
6456
6457   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new channel requested\n");
6458
6459   /* Sanity check for client registration */
6460   if (NULL == (c = client_get (client)))
6461   {
6462     GNUNET_break (0);
6463     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6464     return;
6465   }
6466   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6467
6468   /* Message size sanity check */
6469   if (sizeof (struct GNUNET_MESH_ChannelMessage) != ntohs (message->size))
6470   {
6471     GNUNET_break (0);
6472     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6473     return;
6474   }
6475
6476   msg = (struct GNUNET_MESH_ChannelMessage *) message;
6477   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  towards %s:%u\n",
6478               GNUNET_i2s (&msg->peer), ntohl (msg->port));
6479   chid = ntohl (msg->channel_id);
6480
6481   /* Sanity check for duplicate channel IDs */
6482   if (NULL != channel_get_by_local_id (c, chid))
6483   {
6484     GNUNET_break (0);
6485     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6486     return;
6487   }
6488
6489   peer = peer_get (&msg->peer);
6490   if (NULL == peer->tunnel)
6491   {
6492     peer->tunnel = tunnel_new ();
6493     peer->tunnel->peer = peer;
6494   }
6495   t = peer->tunnel;
6496
6497   /* Create channel */
6498   ch = channel_new (t, c, chid);
6499   if (NULL == ch)
6500   {
6501     GNUNET_break (0);
6502     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6503     return;
6504   }
6505   ch->port = ntohl (msg->port);
6506   channel_set_options (ch, ntohl (msg->opt));
6507
6508   /* In unreliable channels, we'll use the DLL to buffer data for the root */
6509   ch->root_rel = GNUNET_new (struct MeshChannelReliability);
6510   ch->root_rel->ch = ch;
6511   ch->root_rel->expected_delay = MESH_RETRANSMIT_TIME;
6512
6513   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "CREATED CHANNEL %s[%x]:%u (%x)\n",
6514               peer2s (t->peer), ch->gid, ch->port, ch->lid_root);
6515   peer_connect (peer);
6516
6517   /* Send create channel */
6518   {
6519     struct GNUNET_MESH_ChannelCreate msgcc;
6520
6521     msgcc.header.size = htons (sizeof (msgcc));
6522     msgcc.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_CHANNEL_CREATE);
6523     msgcc.chid = htonl (ch->gid);
6524     msgcc.port = msg->port;
6525     msgcc.opt = msg->opt;
6526
6527     tunnel_queue_data (t, ch, &msgcc.header, GNUNET_YES);
6528   }
6529
6530   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6531   return;
6532 }
6533
6534
6535 /**
6536  * Handler for requests of deleting tunnels
6537  *
6538  * @param cls closure
6539  * @param client identification of the client
6540  * @param message the actual message
6541  */
6542 static void
6543 handle_local_channel_destroy (void *cls, struct GNUNET_SERVER_Client *client,
6544                              const struct GNUNET_MessageHeader *message)
6545 {
6546   struct GNUNET_MESH_ChannelMessage *msg;
6547   struct MeshClient *c;
6548   struct MeshChannel *ch;
6549   struct MeshTunnel2 *t;
6550   MESH_ChannelNumber chid;
6551
6552   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6553               "Got a DESTROY CHANNEL from client!\n");
6554
6555   /* Sanity check for client registration */
6556   if (NULL == (c = client_get (client)))
6557   {
6558     GNUNET_break (0);
6559     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6560     return;
6561   }
6562   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6563
6564   /* Message sanity check */
6565   if (sizeof (struct GNUNET_MESH_ChannelMessage) != ntohs (message->size))
6566   {
6567     GNUNET_break (0);
6568     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6569     return;
6570   }
6571
6572   msg = (struct GNUNET_MESH_ChannelMessage *) message;
6573
6574   /* Retrieve tunnel */
6575   chid = ntohl (msg->channel_id);
6576   ch = channel_get_by_local_id (c, chid);
6577   if (NULL == ch)
6578   {
6579     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "  channel %X not found\n", chid);
6580     GNUNET_break (0);
6581     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6582     return;
6583   }
6584
6585   /* Cleanup after the tunnel */
6586   client_delete_channel (c, ch);
6587   if (c == ch->dest && GNUNET_MESH_LOCAL_CHANNEL_ID_SERV <= chid)
6588   {
6589     ch->dest = NULL;
6590   }
6591   else if (c == ch->root && GNUNET_MESH_LOCAL_CHANNEL_ID_SERV > chid)
6592   {
6593     ch->root = NULL;
6594   }
6595   else 
6596   {
6597     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
6598                 "  channel %X client %p (%p, %p)\n",
6599                 chid, c, ch->root, ch->dest);
6600     GNUNET_break (0);
6601   }
6602
6603   t = ch->t;
6604   channel_destroy (ch);
6605   tunnel_destroy_if_empty (t);
6606
6607   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6608   return;
6609 }
6610
6611
6612 /**
6613  * Handler for client traffic
6614  *
6615  * @param cls closure
6616  * @param client identification of the client
6617  * @param message the actual message
6618  */
6619 static void
6620 handle_local_data (void *cls, struct GNUNET_SERVER_Client *client,
6621                    const struct GNUNET_MessageHeader *message)
6622 {
6623   struct GNUNET_MESH_LocalData *msg;
6624   struct MeshClient *c;
6625   struct MeshChannel *ch;
6626   struct MeshChannelReliability *rel;
6627   MESH_ChannelNumber chid;
6628   size_t size;
6629   int fwd;
6630
6631   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6632               "Got data from a client!\n");
6633
6634   /* Sanity check for client registration */
6635   if (NULL == (c = client_get (client)))
6636   {
6637     GNUNET_break (0);
6638     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6639     return;
6640   }
6641   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6642
6643   msg = (struct GNUNET_MESH_LocalData *) message;
6644
6645   /* Sanity check for message size */
6646   size = ntohs (message->size) - sizeof (struct GNUNET_MESH_LocalData);
6647   if (size < sizeof (struct GNUNET_MessageHeader))
6648   {
6649     GNUNET_break (0);
6650     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6651     return;
6652   }
6653
6654   /* Channel exists? */
6655   chid = ntohl (msg->id);
6656   fwd = chid < GNUNET_MESH_LOCAL_CHANNEL_ID_SERV;
6657   ch = channel_get_by_local_id (c, chid);
6658   if (NULL == ch)
6659   {
6660     GNUNET_break (0);
6661     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6662     return;
6663   }
6664
6665   /* Is the client in the channel? */
6666   if ( !( (fwd &&
6667            ch->root &&
6668            ch->root->handle == client)
6669          ||
6670           (!fwd &&
6671            ch->dest && 
6672            ch->dest->handle == client) ) )
6673   {
6674     GNUNET_break (0);
6675     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6676     return;
6677   }
6678
6679   rel = fwd ? ch->root_rel : ch->dest_rel;
6680   rel->client_ready = GNUNET_NO;
6681
6682   /* Ok, everything is correct, send the message. */
6683   {
6684     struct GNUNET_MESH_Data *payload;
6685     uint16_t p2p_size = sizeof(struct GNUNET_MESH_Data) + size;
6686     unsigned char cbuf[p2p_size];
6687
6688     payload = (struct GNUNET_MESH_Data *) cbuf;
6689     payload->mid = htonl (rel->mid_send);
6690     rel->mid_send++;
6691     memcpy (&payload[1], &msg[1], size);
6692     payload->header.size = htons (p2p_size);
6693     payload->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_DATA);
6694     payload->chid = htonl (ch->gid);
6695     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  sending on channel...\n");
6696     send_prebuilt_message_channel (&payload->header, ch, fwd);
6697
6698     if (GNUNET_YES == ch->reliable)
6699       channel_save_copy (ch, &payload->header, fwd);
6700   }
6701   if (tunnel_get_buffer (ch->t, fwd) > 0)
6702     send_local_ack (ch, fwd);
6703   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "receive done OK\n");
6704   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6705
6706   return;
6707 }
6708
6709
6710 /**
6711  * Handler for client's ACKs for payload traffic.
6712  *
6713  * @param cls Closure (unused).
6714  * @param client Identification of the client.
6715  * @param message The actual message.
6716  */
6717 static void
6718 handle_local_ack (void *cls, struct GNUNET_SERVER_Client *client,
6719                   const struct GNUNET_MessageHeader *message)
6720 {
6721   struct GNUNET_MESH_LocalAck *msg;
6722   struct MeshChannelReliability *rel;
6723   struct MeshChannel *ch;
6724   struct MeshClient *c;
6725   MESH_ChannelNumber chid;
6726   int fwd;
6727
6728   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a local ACK\n");
6729
6730   /* Sanity check for client registration */
6731   if (NULL == (c = client_get (client)))
6732   {
6733     GNUNET_break (0);
6734     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6735     return;
6736   }
6737   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6738
6739   msg = (struct GNUNET_MESH_LocalAck *) message;
6740
6741   /* Channel exists? */
6742   chid = ntohl (msg->channel_id);
6743   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on channel %X\n", chid);
6744   ch = channel_get_by_local_id (c, chid);
6745   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   -- ch %p\n", ch);
6746   if (NULL == ch)
6747   {
6748     GNUNET_break (0);
6749     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Channel %X unknown.\n", chid);
6750     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "  for client %u.\n", c->id);
6751     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6752     return;
6753   }
6754
6755   /* If client is root, the ACK is going FWD, therefore this is "BCK". */
6756   /* If client is dest, the ACK is going BCK, therefore this is "FWD" */
6757   fwd = chid >= GNUNET_MESH_LOCAL_CHANNEL_ID_SERV;
6758   rel = fwd ? ch->dest_rel : ch->root_rel;
6759
6760   rel->client_ready = GNUNET_YES;
6761   channel_send_client_buffered_data (ch, c, fwd);
6762   send_ack (NULL, ch, fwd);
6763
6764   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6765
6766   return;
6767 }
6768
6769
6770 /**
6771  * Iterator over all tunnels to send a monitoring client info about each tunnel.
6772  *
6773  * @param cls Closure (client handle).
6774  * @param key Key (hashed tunnel ID, unused).
6775  * @param value Tunnel info.
6776  *
6777  * @return GNUNET_YES, to keep iterating.
6778  */
6779 // static int
6780 // monitor_all_tunnels_iterator (void *cls,
6781 //                               const struct GNUNET_HashCode * key,
6782 //                               void *value)
6783 // {
6784 //   struct GNUNET_SERVER_Client *client = cls;
6785 //   struct MeshChannel *ch = value;
6786 //   struct GNUNET_MESH_LocalMonitor *msg;
6787 // 
6788 //   msg = GNUNET_malloc (sizeof(struct GNUNET_MESH_LocalMonitor));
6789 //   msg->channel_id = htonl (ch->gid);
6790 //   msg->header.size = htons (sizeof (struct GNUNET_MESH_LocalMonitor));
6791 //   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_INFO_TUNNELS);
6792 // 
6793 //   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
6794 //               "*  sending info about tunnel %s\n",
6795 //               GNUNET_i2s (&msg->owner));
6796 // 
6797 //   GNUNET_SERVER_notification_context_unicast (nc, client,
6798 //                                               &msg->header, GNUNET_NO);
6799 //   return GNUNET_YES;
6800 // }
6801
6802
6803 /**
6804  * Handler for client's MONITOR request.
6805  *
6806  * @param cls Closure (unused).
6807  * @param client Identification of the client.
6808  * @param message The actual message.
6809  */
6810 static void
6811 handle_local_get_tunnels (void *cls, struct GNUNET_SERVER_Client *client,
6812                           const struct GNUNET_MessageHeader *message)
6813 {
6814   struct MeshClient *c;
6815
6816   /* Sanity check for client registration */
6817   if (NULL == (c = client_get (client)))
6818   {
6819     GNUNET_break (0);
6820     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6821     return;
6822   }
6823
6824   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
6825               "Received get tunnels request from client %u\n",
6826               c->id);
6827 //   GNUNET_CONTAINER_multihashmap_iterate (tunnels,
6828 //                                          monitor_all_tunnels_iterator,
6829 //                                          client);
6830   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
6831               "Get tunnels request from client %u completed\n",
6832               c->id);
6833   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6834 }
6835
6836
6837 /**
6838  * Handler for client's MONITOR_TUNNEL request.
6839  *
6840  * @param cls Closure (unused).
6841  * @param client Identification of the client.
6842  * @param message The actual message.
6843  */
6844 static void
6845 handle_local_show_tunnel (void *cls, struct GNUNET_SERVER_Client *client,
6846                           const struct GNUNET_MessageHeader *message)
6847 {
6848   const struct GNUNET_MESH_LocalMonitor *msg;
6849   struct GNUNET_MESH_LocalMonitor *resp;
6850   struct MeshClient *c;
6851   struct MeshChannel *ch;
6852
6853   /* Sanity check for client registration */
6854   if (NULL == (c = client_get (client)))
6855   {
6856     GNUNET_break (0);
6857     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6858     return;
6859   }
6860
6861   msg = (struct GNUNET_MESH_LocalMonitor *) message;
6862   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
6863               "Received tunnel info request from client %u for tunnel %s[%X]\n",
6864               c->id,
6865               &msg->owner,
6866               ntohl (msg->channel_id));
6867 //   ch = channel_get (&msg->owner, ntohl (msg->channel_id));
6868   ch = NULL; // FIXME
6869   if (NULL == ch)
6870   {
6871     /* We don't know the tunnel */
6872     struct GNUNET_MESH_LocalMonitor warn;
6873
6874     warn = *msg;
6875     GNUNET_SERVER_notification_context_unicast (nc, client,
6876                                                 &warn.header,
6877                                                 GNUNET_NO);
6878     GNUNET_SERVER_receive_done (client, GNUNET_OK);
6879     return;
6880   }
6881
6882   /* Initialize context */
6883   resp = GNUNET_malloc (sizeof (struct GNUNET_MESH_LocalMonitor));
6884   *resp = *msg;
6885   resp->header.size = htons (sizeof (struct GNUNET_MESH_LocalMonitor));
6886   GNUNET_SERVER_notification_context_unicast (nc, c->handle,
6887                                               &resp->header, GNUNET_NO);
6888   GNUNET_free (resp);
6889
6890   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
6891               "Monitor tunnel request from client %u completed\n",
6892               c->id);
6893   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6894 }
6895
6896
6897 /**
6898  * Functions to handle messages from clients
6899  */
6900 static struct GNUNET_SERVER_MessageHandler client_handlers[] = {
6901   {&handle_local_new_client, NULL,
6902    GNUNET_MESSAGE_TYPE_MESH_LOCAL_CONNECT, 0},
6903   {&handle_local_channel_create, NULL,
6904    GNUNET_MESSAGE_TYPE_MESH_CHANNEL_CREATE,
6905    sizeof (struct GNUNET_MESH_ChannelMessage)},
6906   {&handle_local_channel_destroy, NULL,
6907    GNUNET_MESSAGE_TYPE_MESH_CHANNEL_DESTROY,
6908    sizeof (struct GNUNET_MESH_ChannelMessage)},
6909   {&handle_local_data, NULL,
6910    GNUNET_MESSAGE_TYPE_MESH_LOCAL_DATA, 0},
6911   {&handle_local_ack, NULL,
6912    GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK,
6913    sizeof (struct GNUNET_MESH_LocalAck)},
6914   {&handle_local_get_tunnels, NULL,
6915    GNUNET_MESSAGE_TYPE_MESH_LOCAL_INFO_TUNNELS,
6916    sizeof (struct GNUNET_MessageHeader)},
6917   {&handle_local_show_tunnel, NULL,
6918    GNUNET_MESSAGE_TYPE_MESH_LOCAL_INFO_TUNNEL,
6919      sizeof (struct GNUNET_MESH_LocalMonitor)},
6920   {NULL, NULL, 0, 0}
6921 };
6922
6923
6924 /**
6925  * Method called whenever a given peer connects.
6926  *
6927  * @param cls closure
6928  * @param peer peer identity this notification is about
6929  */
6930 static void
6931 core_connect (void *cls, const struct GNUNET_PeerIdentity *peer)
6932 {
6933   struct MeshPeer *pi;
6934   struct MeshPeerPath *path;
6935
6936   DEBUG_CONN ("Peer connected\n");
6937   DEBUG_CONN ("     %s\n", GNUNET_i2s (&my_full_id));
6938   pi = peer_get (peer);
6939   if (myid == pi->id)
6940   {
6941     DEBUG_CONN ("     (self)\n");
6942     path = path_new (1);
6943   }
6944   else
6945   {
6946     DEBUG_CONN ("     %s\n", GNUNET_i2s (peer));
6947     path = path_new (2);
6948     path->peers[1] = pi->id;
6949     GNUNET_PEER_change_rc (pi->id, 1);
6950     GNUNET_STATISTICS_update (stats, "# peers", 1, GNUNET_NO);
6951   }
6952   path->peers[0] = myid;
6953   GNUNET_PEER_change_rc (myid, 1);
6954   peer_add_path (pi, path, GNUNET_YES);
6955
6956   pi->connections = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_YES);
6957   return;
6958 }
6959
6960
6961 /**
6962  * Method called whenever a peer disconnects.
6963  *
6964  * @param cls closure
6965  * @param peer peer identity this notification is about
6966  */
6967 static void
6968 core_disconnect (void *cls, const struct GNUNET_PeerIdentity *peer)
6969 {
6970   struct MeshPeer *pi;
6971
6972   DEBUG_CONN ("Peer disconnected\n");
6973   pi = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
6974   if (NULL == pi)
6975   {
6976     GNUNET_break (0);
6977     return;
6978   }
6979
6980   GNUNET_CONTAINER_multihashmap_iterate (pi->connections,
6981                                          connection_broken,
6982                                          pi);
6983   GNUNET_CONTAINER_multihashmap_destroy (pi->connections);
6984   pi->connections = NULL;
6985   if (myid == pi->id)
6986   {
6987     DEBUG_CONN ("     (self)\n");
6988   }
6989   GNUNET_STATISTICS_update (stats, "# peers", -1, GNUNET_NO);
6990
6991   return;
6992 }
6993
6994
6995 /**
6996  * Install server (service) handlers and start listening to clients.
6997  */
6998 static void
6999 server_init (void)
7000 {
7001   GNUNET_SERVER_add_handlers (server_handle, client_handlers);
7002   GNUNET_SERVER_connect_notify (server_handle,
7003                                 &handle_local_client_connect, NULL);
7004   GNUNET_SERVER_disconnect_notify (server_handle,
7005                                    &handle_local_client_disconnect, NULL);
7006   nc = GNUNET_SERVER_notification_context_create (server_handle, 1);
7007
7008   clients_head = NULL;
7009   clients_tail = NULL;
7010   next_client_id = 0;
7011   GNUNET_SERVER_resume (server_handle);
7012 }
7013
7014
7015 /**
7016  * To be called on core init/fail.
7017  *
7018  * @param cls Closure (config)
7019  * @param identity the public identity of this peer
7020  */
7021 static void
7022 core_init (void *cls, 
7023            const struct GNUNET_PeerIdentity *identity)
7024 {
7025   const struct GNUNET_CONFIGURATION_Handle *c = cls;
7026   static int i = 0;
7027
7028   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Core init\n");
7029   if (0 != memcmp (identity, &my_full_id, sizeof (my_full_id)))
7030   {
7031     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _("Wrong CORE service\n"));
7032     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7033                 " core id %s\n",
7034                 GNUNET_i2s (identity));
7035     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7036                 " my id %s\n",
7037                 GNUNET_i2s (&my_full_id));
7038     GNUNET_CORE_disconnect (core_handle);
7039     core_handle = GNUNET_CORE_connect (c, /* Main configuration */
7040                                        NULL,      /* Closure passed to MESH functions */
7041                                        &core_init,        /* Call core_init once connected */
7042                                        &core_connect,     /* Handle connects */
7043                                        &core_disconnect,  /* remove peers on disconnects */
7044                                        NULL,      /* Don't notify about all incoming messages */
7045                                        GNUNET_NO, /* For header only in notification */
7046                                        NULL,      /* Don't notify about all outbound messages */
7047                                        GNUNET_NO, /* For header-only out notification */
7048                                        core_handlers);    /* Register these handlers */
7049     if (10 < i++)
7050       GNUNET_abort();
7051   }
7052   server_init ();
7053   return;
7054 }
7055
7056
7057 /******************************************************************************/
7058 /************************      MAIN FUNCTIONS      ****************************/
7059 /******************************************************************************/
7060
7061 /**
7062  * Iterator over tunnel hash map entries to destroy the tunnel during shutdown.
7063  *
7064  * @param cls closure
7065  * @param key current key code
7066  * @param value value in the hash map
7067  * @return GNUNET_YES if we should continue to iterate,
7068  *         GNUNET_NO if not.
7069  */
7070 static int
7071 shutdown_tunnel (void *cls, const struct GNUNET_HashCode * key, void *value)
7072 {
7073   struct MeshPeer *p = value;
7074   struct MeshTunnel2 *t = p->tunnel;
7075
7076   if (NULL != t)
7077     tunnel_destroy (t);
7078   return GNUNET_YES;
7079 }
7080
7081
7082 /**
7083  * Task run during shutdown.
7084  *
7085  * @param cls unused
7086  * @param tc unused
7087  */
7088 static void
7089 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
7090 {
7091   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shutting down\n");
7092
7093   if (core_handle != NULL)
7094   {
7095     GNUNET_CORE_disconnect (core_handle);
7096     core_handle = NULL;
7097   }
7098   GNUNET_CONTAINER_multihashmap_iterate (peers, &shutdown_tunnel, NULL);
7099   if (dht_handle != NULL)
7100   {
7101     GNUNET_DHT_disconnect (dht_handle);
7102     dht_handle = NULL;
7103   }
7104   if (nc != NULL)
7105   {
7106     GNUNET_SERVER_notification_context_destroy (nc);
7107     nc = NULL;
7108   }
7109   if (GNUNET_SCHEDULER_NO_TASK != announce_id_task)
7110   {
7111     GNUNET_SCHEDULER_cancel (announce_id_task);
7112     announce_id_task = GNUNET_SCHEDULER_NO_TASK;
7113   }
7114   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shut down\n");
7115 }
7116
7117
7118 /**
7119  * Process mesh requests.
7120  *
7121  * @param cls closure
7122  * @param server the initialized server
7123  * @param c configuration to use
7124  */
7125 static void
7126 run (void *cls, struct GNUNET_SERVER_Handle *server,
7127      const struct GNUNET_CONFIGURATION_Handle *c)
7128 {
7129   char *keyfile;
7130   struct GNUNET_CRYPTO_EccPrivateKey *pk;
7131
7132   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "starting to run\n");
7133   server_handle = server;
7134   GNUNET_SERVER_suspend (server_handle);
7135
7136   if (GNUNET_OK !=
7137       GNUNET_CONFIGURATION_get_value_filename (c, "PEER", "PRIVATE_KEY",
7138                                                &keyfile))
7139   {
7140     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7141                 _
7142                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
7143                 "mesh", "peer/privatekey");
7144     GNUNET_SCHEDULER_shutdown ();
7145     return;
7146   }
7147
7148   if (GNUNET_OK !=
7149       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "REFRESH_CONNECTION_TIME",
7150                                            &refresh_connection_time))
7151   {
7152     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7153                 _
7154                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
7155                 "mesh", "refresh path time");
7156     GNUNET_SCHEDULER_shutdown ();
7157     return;
7158   }
7159
7160   if (GNUNET_OK !=
7161       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "ID_ANNOUNCE_TIME",
7162                                            &id_announce_time))
7163   {
7164     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7165                 _
7166                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
7167                 "mesh", "id announce time");
7168     GNUNET_SCHEDULER_shutdown ();
7169     return;
7170   }
7171
7172   if (GNUNET_OK !=
7173       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "CONNECT_TIMEOUT",
7174                                            &connect_timeout))
7175   {
7176     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7177                 _
7178                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
7179                 "mesh", "connect timeout");
7180     GNUNET_SCHEDULER_shutdown ();
7181     return;
7182   }
7183
7184   if (GNUNET_OK !=
7185       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_MSGS_QUEUE",
7186                                              &max_msgs_queue))
7187   {
7188     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7189                 _
7190                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
7191                 "mesh", "max msgs queue");
7192     GNUNET_SCHEDULER_shutdown ();
7193     return;
7194   }
7195
7196   if (GNUNET_OK !=
7197       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_CONNECTIONS",
7198                                              &max_connections))
7199   {
7200     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7201                 _
7202                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
7203                 "mesh", "max tunnels");
7204     GNUNET_SCHEDULER_shutdown ();
7205     return;
7206   }
7207
7208   if (GNUNET_OK !=
7209       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DEFAULT_TTL",
7210                                              &default_ttl))
7211   {
7212     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
7213                 _
7214                 ("%s service is lacking key configuration settings (%s). Using default (%u).\n"),
7215                 "mesh", "default ttl", 64);
7216     default_ttl = 64;
7217   }
7218
7219   if (GNUNET_OK !=
7220       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_PEERS",
7221                                              &max_peers))
7222   {
7223     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
7224                 _("%s service is lacking key configuration settings (%s). Using default (%u).\n"),
7225                 "mesh", "max peers", 1000);
7226     max_peers = 1000;
7227   }
7228
7229   if (GNUNET_OK !=
7230       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DROP_PERCENT",
7231                                              &drop_percent))
7232   {
7233     drop_percent = 0;
7234   }
7235   else
7236   {
7237     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
7238                 "Mesh is running with drop mode enabled. "
7239                 "This is NOT a good idea! "
7240                 "Remove the DROP_PERCENT option from your configuration.\n");
7241   }
7242
7243   if (GNUNET_OK !=
7244       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DHT_REPLICATION_LEVEL",
7245                                              &dht_replication_level))
7246   {
7247     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
7248                 _
7249                 ("%s service is lacking key configuration settings (%s). Using default (%u).\n"),
7250                 "mesh", "dht replication level", 3);
7251     dht_replication_level = 3;
7252   }
7253
7254   connections = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_YES);
7255   peers = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
7256   ports = GNUNET_CONTAINER_multihashmap32_create (32);
7257
7258   dht_handle = GNUNET_DHT_connect (c, 64);
7259   if (NULL == dht_handle)
7260   {
7261     GNUNET_break (0);
7262   }
7263   stats = GNUNET_STATISTICS_create ("mesh", c);
7264
7265   /* Scheduled the task to clean up when shutdown is called */
7266   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
7267                                 NULL);
7268   pk = GNUNET_CRYPTO_ecc_key_create_from_file (keyfile);
7269   GNUNET_free (keyfile);
7270   GNUNET_assert (NULL != pk);
7271   my_private_key = pk;
7272   GNUNET_CRYPTO_ecc_key_get_public (my_private_key, &my_public_key);
7273   GNUNET_CRYPTO_hash (&my_public_key, sizeof (my_public_key),
7274                       &my_full_id.hashPubKey);
7275   myid = GNUNET_PEER_intern (&my_full_id);
7276   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
7277               "Mesh for peer [%s] starting\n",
7278               GNUNET_i2s(&my_full_id));
7279
7280   core_handle = GNUNET_CORE_connect (c, /* Main configuration */
7281                                      NULL,      /* Closure passed to MESH functions */
7282                                      &core_init,        /* Call core_init once connected */
7283                                      &core_connect,     /* Handle connects */
7284                                      &core_disconnect,  /* remove peers on disconnects */
7285                                      NULL,      /* Don't notify about all incoming messages */
7286                                      GNUNET_NO, /* For header only in notification */
7287                                      NULL,      /* Don't notify about all outbound messages */
7288                                      GNUNET_NO, /* For header-only out notification */
7289                                      core_handlers);    /* Register these handlers */
7290   if (NULL == core_handle)
7291   {
7292     GNUNET_break (0);
7293     GNUNET_SCHEDULER_shutdown ();
7294     return;
7295   }
7296   announce_id_task = GNUNET_SCHEDULER_add_now (&announce_id, cls);
7297   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Mesh service running\n");
7298 }
7299
7300
7301 /**
7302  * The main function for the mesh service.
7303  *
7304  * @param argc number of arguments from the command line
7305  * @param argv command line arguments
7306  * @return 0 ok, 1 on error
7307  */
7308 int
7309 main (int argc, char *const *argv)
7310 {
7311   int ret;
7312   int r;
7313
7314   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "main()\n");
7315   r = GNUNET_SERVICE_run (argc, argv, "mesh", GNUNET_SERVICE_OPTION_NONE, &run,
7316                           NULL);
7317   ret = (GNUNET_OK == r) ? 0 : 1;
7318   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "main() END\n");
7319
7320   INTERVAL_SHOW;
7321
7322   return ret;
7323 }