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