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