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