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