- fix
[oweals/gnunet.git] / src / mesh / gnunet-service-mesh-enc.c
1 /*
2      This file is part of GNUnet.
3      (C) 2001-2013 Christian Grothoff (and other contributing authors)
4
5      GNUnet is free software; you can redistribute it and/or modify
6      it under the terms of the GNU General Public License as published
7      by the Free Software Foundation; either version 3, or (at your
8      option) any later version.
9
10      GNUnet is distributed in the hope that it will be useful, but
11      WITHOUT ANY WARRANTY; without even the implied warranty of
12      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13      General Public License for more details.
14
15      You should have received a copy of the GNU General Public License
16      along with GNUnet; see the file COPYING.  If not, write to the
17      Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18      Boston, MA 02111-1307, USA.
19 */
20
21 /**
22  * @file mesh/gnunet-service-mesh-enc.c
23  * @brief GNUnet MESH service with encryption
24  * @author Bartlomiej Polot
25  *
26  *  FIXME in progress:
27  * - when sending in-order buffered data, wait for client ACKs
28  * - add signatures
29  * - add encryption
30  * - set connection IDs independently from tunnel, tunnel has no ID
31  *
32  * TODO:
33  * - relay corking down to core
34  * - set ttl relative to path length
35  * TODO END
36  * 
37  * Dictionary:
38  * - peer: other mesh instance. If there is direct connection it's a neighbor.
39  * - tunnel: encrypted connection to a peer, neighbor or not.
40  * - channel: connection between two clients, on the same or different peers.
41  *            have properties like reliability.
42  * - path: series of directly connected peer from one peer to another.
43  * - connection: path which is being used in a tunnel.
44  */
45
46 #include "platform.h"
47 #include "gnunet_crypto_lib.h"
48 #include "mesh_enc.h"
49 #include "mesh_protocol_enc.h"
50 #include "mesh_path.h"
51 #include "block_mesh.h"
52 #include "gnunet_dht_service.h"
53 #include "gnunet_statistics_service.h"
54
55 #define MESH_BLOOM_SIZE         128
56
57 #define MESH_DEBUG_DHT          GNUNET_NO
58 #define MESH_DEBUG_CONNECTION   GNUNET_YES
59 #define MESH_DEBUG_TIMING       __LINUX__ && GNUNET_NO
60
61 #define MESH_MAX_POLL_TIME      GNUNET_TIME_relative_multiply (\
62                                   GNUNET_TIME_UNIT_MINUTES,\
63                                   10)
64 #define MESH_RETRANSMIT_TIME    GNUNET_TIME_UNIT_SECONDS
65 #define MESH_RETRANSMIT_MARGIN  4
66
67 #if MESH_DEBUG_CONNECTION
68 #define DEBUG_CONN(...) GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, __VA_ARGS__)
69 #else
70 #define DEBUG_CONN(...)
71 #endif
72
73 #if MESH_DEBUG_DHT
74 #define DEBUG_DHT(...) GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, __VA_ARGS__)
75 #else
76 #define DEBUG_DHT(...)
77 #endif
78
79 #if MESH_DEBUG_TIMING
80 #include <time.h>
81 double __sum;
82 uint64_t __count;
83 struct timespec __mesh_start;
84 struct timespec __mesh_end;
85 #define INTERVAL_START clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &(__mesh_start))
86 #define INTERVAL_END \
87 do {\
88   clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &(__mesh_end));\
89   double __diff = __mesh_end.tv_nsec - __mesh_start.tv_nsec;\
90   if (__diff < 0) __diff += 1000000000;\
91   __sum += __diff;\
92   __count++;\
93 } while (0)
94 #define INTERVAL_SHOW \
95 if (0 < __count)\
96   GNUNET_log (GNUNET_ERROR_TYPE_INFO, "AVG process time: %f ns\n", __sum/__count)
97 #else
98 #define INTERVAL_START
99 #define INTERVAL_END
100 #define INTERVAL_SHOW
101 #endif
102
103 /**
104  * All the states a tunnel can be in.
105  */
106 enum MeshTunnelState
107 {
108     /**
109      * Uninitialized status, should never appear in operation.
110      */
111   MESH_TUNNEL_NEW,
112
113     /**
114      * Path to the peer not known yet
115      */
116   MESH_TUNNEL_SEARCHING,
117
118     /**
119      * Request sent, not yet answered.
120      */
121   MESH_TUNNEL_WAITING,
122
123     /**
124      * Peer connected and ready to accept data
125      */
126   MESH_TUNNEL_READY,
127
128     /**
129      * Peer connected previosly but not responding
130      */
131   MESH_TUNNEL_RECONNECTING
132 };
133
134
135 /**
136  * All the states a connection can be in.
137  */
138 enum MeshConnectionState
139 {
140   /**
141    * Uninitialized status, should never appear in operation.
142    */
143   MESH_CONNECTION_NEW,
144
145   /**
146    * Connection create message sent, waiting for ACK.
147    */
148   MESH_CONNECTION_SENT,
149
150   /**
151    * Connection ACK sent, waiting for ACK.
152    */
153   MESH_CONNECTION_ACK,
154
155   /**
156    * Connection confirmed, ready to carry traffic.
157    */
158   MESH_CONNECTION_READY,
159 };
160
161
162 /**
163  * All the states a connection can be in.
164  */
165 enum MeshChannelState
166 {
167   /**
168    * Uninitialized status, should never appear in operation.
169    */
170   MESH_CHANNEL_NEW,
171
172   /**
173    * Connection create message sent, waiting for ACK.
174    */
175   MESH_CHANNEL_SENT,
176
177   /**
178    * Connection confirmed, ready to carry traffic..
179    */
180   MESH_CHANNEL_READY,
181 };
182
183
184 /******************************************************************************/
185 /************************      DATA STRUCTURES     ****************************/
186 /******************************************************************************/
187
188 /** FWD declaration */
189 struct MeshClient;
190 struct MeshPeer;
191 struct MeshTunnel2;
192 struct MeshConnection;
193 struct MeshChannel;
194 struct MeshChannelReliability;
195
196
197 /**
198  * Struct containing info about a queued transmission to this peer
199  */
200 struct MeshPeerQueue
201 {
202     /**
203       * DLL next
204       */
205   struct MeshPeerQueue *next;
206
207     /**
208       * DLL previous
209       */
210   struct MeshPeerQueue *prev;
211
212     /**
213      * Peer this transmission is directed to.
214      */
215   struct MeshPeer *peer;
216
217     /**
218      * Connection this message belongs to.
219      */
220   struct MeshConnection *c;
221
222     /**
223      * Is FWD in c?
224      */
225   int fwd;
226
227     /**
228      * Channel this message belongs to, if known.
229      */
230   struct MeshChannel *ch;
231
232     /**
233      * Pointer to info stucture used as cls.
234      */
235   void *cls;
236
237     /**
238      * Type of message
239      */
240   uint16_t type;
241
242     /**
243      * Size of the message
244      */
245   size_t size;
246 };
247
248
249 /**
250  * Struct to encapsulate all the Flow Control information to a peer to which
251  * we are directly connected (on a core level).
252  */
253 struct MeshFlowControl
254 {
255   /**
256    * Connection this controls.
257    */
258   struct MeshConnection *c;
259
260   /**
261    * How many messages are in the queue on this connection.
262    */
263   unsigned int queue_n;
264
265   /**
266    * How many messages do we accept in the queue.
267    */
268   unsigned int queue_max;
269
270   /**
271    * Next ID to use.
272    */
273   uint32_t next_pid;
274
275   /**
276    * ID of the last packet sent towards the peer.
277    */
278   uint32_t last_pid_sent;
279
280   /**
281    * ID of the last packet received from the peer.
282    */
283   uint32_t last_pid_recv;
284
285   /**
286    * Last ACK sent to the peer (peer can't send more than this PID).
287    */
288   uint32_t last_ack_sent;
289
290   /**
291    * Last ACK sent towards the origin (for traffic towards leaf node).
292    */
293   uint32_t last_ack_recv;
294
295   /**
296    * Task to poll the peer in case of a lost ACK causes stall.
297    */
298   GNUNET_SCHEDULER_TaskIdentifier poll_task;
299
300   /**
301    * How frequently to poll for ACKs.
302    */
303   struct GNUNET_TIME_Relative poll_time;
304 };
305
306
307 /**
308  * Struct containing all information regarding a given peer
309  */
310 struct MeshPeer
311 {
312     /**
313      * ID of the peer
314      */
315   GNUNET_PEER_Id id;
316
317     /**
318      * Last time we heard from this peer
319      */
320   struct GNUNET_TIME_Absolute last_contact;
321
322     /**
323      * Paths to reach the peer, ordered by ascending hop count
324      */
325   struct MeshPeerPath *path_head;
326
327     /**
328      * Paths to reach the peer, ordered by ascending hop count
329      */
330   struct MeshPeerPath *path_tail;
331
332     /**
333      * Handle to stop the DHT search for paths to this peer
334      */
335   struct GNUNET_DHT_GetHandle *dhtget;
336
337     /**
338      * Tunnel to this peer, if any.
339      */
340   struct MeshTunnel2 *tunnel;
341
342     /**
343      * Connections that go through this peer, indexed by tid;
344      */
345   struct GNUNET_CONTAINER_MultiHashMap *connections;
346
347     /**
348      * Handle for queued transmissions
349      */
350   struct GNUNET_CORE_TransmitHandle *core_transmit;
351
352   /**
353    * Transmission queue to core DLL head
354    */
355   struct MeshPeerQueue *queue_head;
356   
357   /**
358    * Transmission queue to core DLL tail
359    */
360   struct MeshPeerQueue *queue_tail;
361
362   /**
363    * How many messages are in the queue to this peer.
364    */
365   unsigned int queue_n;
366 };
367
368
369 /**
370  * Info needed to retry a message in case it gets lost.
371  */
372 struct MeshReliableMessage
373 {
374     /**
375      * Double linked list, FIFO style
376      */
377   struct MeshReliableMessage    *next;
378   struct MeshReliableMessage    *prev;
379
380     /**
381      * Type of message (payload, channel management).
382      */
383   int16_t type;
384
385     /**
386      * Tunnel Reliability queue this message is in.
387      */
388   struct MeshChannelReliability  *rel;
389
390     /**
391      * ID of the message (ACK needed to free)
392      */
393   uint32_t                      mid;
394
395     /**
396      * When was this message issued (to calculate ACK delay)
397      */
398   struct GNUNET_TIME_Absolute   timestamp;
399
400   /* struct GNUNET_MESH_Data with payload */
401 };
402
403
404 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 (NULL != t &&
1833       (MESH_TUNNEL_SEARCHING == t->state || MESH_TUNNEL_NEW == t->state))
1834     tunnel_change_state (t, MESH_TUNNEL_WAITING);
1835   if (MESH_CONNECTION_NEW == connection->state)
1836     connection_change_state (connection, MESH_CONNECTION_SENT);
1837 }
1838
1839
1840 /**
1841  * Sends a CONNECTION ACK message in reponse to a received CONNECTION_CREATE
1842  * directed to us.
1843  *
1844  * @param connection Connection to confirm.
1845  * @param fwd Is this a fwd ACK? (First is bck (SYNACK), second is fwd (ACK))
1846  */
1847 static void
1848 send_connection_ack (struct MeshConnection *connection, int fwd) 
1849 {
1850   struct MeshTunnel2 *t;
1851
1852   t = connection->t;
1853   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Send connection ack\n");
1854   queue_add (NULL,
1855              GNUNET_MESSAGE_TYPE_MESH_CONNECTION_ACK,
1856              sizeof (struct GNUNET_MESH_ConnectionACK),
1857              connection,
1858              NULL,
1859              fwd);
1860   if (MESH_TUNNEL_NEW == t->state)
1861     tunnel_change_state (t, MESH_TUNNEL_WAITING);
1862 }
1863
1864
1865 /**
1866  * Build a hop-by-hop ACK message and queue it to send for the given connection.
1867  * 
1868  * @param c Which connection to send the hop-by-hop ACK.
1869  * @param ack Value of the ACK.
1870  * @param fwd Is this fwd?
1871  */
1872 static void
1873 send_ack (struct MeshConnection *c, uint32_t ack, int fwd)
1874 {
1875   struct GNUNET_MESH_ACK msg;
1876
1877   msg.header.size = htons (sizeof (msg));
1878   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_ACK);
1879   msg.ack = htonl (ack);
1880   msg.cid = c->id;
1881
1882   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1883               "connection send %s ack %u on %s\n",
1884               fwd ? "FWD" : "BCK", ack, GNUNET_h2s (&c->id));
1885
1886   send_prebuilt_message_connection (&msg.header, c, NULL, fwd);
1887 }
1888
1889
1890 /**
1891   * Core callback to write a pre-constructed data packet to core buffer
1892   *
1893   * @param cls Closure (MeshTransmissionDescriptor with data in "data" member).
1894   * @param size Number of bytes available in buf.
1895   * @param buf Where the to write the message.
1896   *
1897   * @return number of bytes written to buf
1898   */
1899 static size_t
1900 send_core_data_raw (void *cls, size_t size, void *buf)
1901 {
1902   struct GNUNET_MessageHeader *msg = cls;
1903   size_t total_size;
1904
1905   GNUNET_assert (NULL != msg);
1906   total_size = ntohs (msg->size);
1907
1908   if (total_size > size)
1909   {
1910     GNUNET_break (0);
1911     return 0;
1912   }
1913   memcpy (buf, msg, total_size);
1914   GNUNET_free (cls);
1915   return total_size;
1916 }
1917
1918
1919 /**
1920  * Function to send a create connection message to a peer.
1921  *
1922  * @param c Connection to create.
1923  * @param size number of bytes available in buf
1924  * @param buf where the callee should write the message
1925  * @return number of bytes written to buf
1926  */
1927 static size_t
1928 send_core_connection_create (struct MeshConnection *c, size_t size, void *buf)
1929 {
1930   struct GNUNET_MESH_ConnectionCreate *msg;
1931   struct GNUNET_PeerIdentity *peer_ptr;
1932   struct MeshPeerPath *p = c->path;
1933   size_t size_needed;
1934   int i;
1935
1936   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending CONNECTION CREATE...\n");
1937   size_needed =
1938       sizeof (struct GNUNET_MESH_ConnectionCreate) +
1939       p->length * sizeof (struct GNUNET_PeerIdentity);
1940
1941   if (size < size_needed || NULL == buf)
1942   {
1943     GNUNET_break (0);
1944     return 0;
1945   }
1946   msg = (struct GNUNET_MESH_ConnectionCreate *) buf;
1947   msg->header.size = htons (size_needed);
1948   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_CONNECTION_CREATE);
1949   msg->cid = c->id;
1950
1951   peer_ptr = (struct GNUNET_PeerIdentity *) &msg[1];
1952   for (i = 0; i < p->length; i++)
1953   {
1954     GNUNET_PEER_resolve (p->peers[i], peer_ptr++);
1955   }
1956
1957   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1958               "CONNECTION CREATE (%u bytes long) sent!\n", size_needed);
1959   return size_needed;
1960 }
1961
1962
1963 /**
1964  * Creates a path ack message in buf and frees all unused resources.
1965  *
1966  * @param c Connection to send an ACK on.
1967  * @param size number of bytes available in buf
1968  * @param buf where the callee should write the message
1969  *
1970  * @return number of bytes written to buf
1971  */
1972 static size_t
1973 send_core_connection_ack (struct MeshConnection *c, size_t size, void *buf)
1974 {
1975   struct GNUNET_MESH_ConnectionACK *msg = buf;
1976   struct MeshTunnel2 *t = c->t;
1977
1978   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending CONNECTION ACK...\n");
1979   GNUNET_assert (NULL != t);
1980   if (sizeof (struct GNUNET_MESH_ConnectionACK) > size)
1981   {
1982     GNUNET_break (0);
1983     return 0;
1984   }
1985   msg->header.size = htons (sizeof (struct GNUNET_MESH_ConnectionACK));
1986   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_CONNECTION_ACK);
1987   msg->cid = c->id;
1988
1989   /* TODO add signature */
1990
1991   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "CONNECTION ACK sent!\n");
1992   return sizeof (struct GNUNET_MESH_ConnectionACK);
1993 }
1994
1995
1996 /**
1997  * Destroy the peer_info and free any allocated resources linked to it
1998  *
1999  * @param peer The peer_info to destroy.
2000  *
2001  * @return GNUNET_OK on success
2002  */
2003 static int
2004 peer_destroy (struct MeshPeer *peer)
2005 {
2006   struct GNUNET_PeerIdentity id;
2007   struct MeshPeerPath *p;
2008   struct MeshPeerPath *nextp;
2009
2010   GNUNET_PEER_resolve (peer->id, &id);
2011   GNUNET_PEER_change_rc (peer->id, -1);
2012
2013   if (GNUNET_YES !=
2014       GNUNET_CONTAINER_multihashmap_remove (peers, &id.hashPubKey, peer))
2015   {
2016     GNUNET_break (0);
2017     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2018                 "removing peer %s, not in hashmap\n", GNUNET_i2s (&id));
2019   }
2020   if (NULL != peer->dhtget)
2021   {
2022     GNUNET_DHT_get_stop (peer->dhtget);
2023   }
2024   p = peer->path_head;
2025   while (NULL != p)
2026   {
2027     nextp = p->next;
2028     GNUNET_CONTAINER_DLL_remove (peer->path_head, peer->path_tail, p);
2029     path_destroy (p);
2030     p = nextp;
2031   }
2032   tunnel_destroy_empty (peer->tunnel);
2033   GNUNET_free (peer);
2034   return GNUNET_OK;
2035 }
2036
2037
2038 /**
2039  * Returns if peer is used (has a tunnel, is neighbor).
2040  *
2041  * @peer Peer to check.
2042  *
2043  * @return GNUNET_YES if peer is in use.
2044  */
2045 static int
2046 peer_is_used (struct MeshPeer *peer)
2047 {
2048   struct MeshPeerPath *p;
2049
2050   if (NULL != peer->tunnel)
2051     return GNUNET_YES;
2052
2053   for (p = peer->path_head; NULL != p; p = p->next)
2054   {
2055     if (p->length < 3)
2056       return GNUNET_YES;
2057   }
2058   return GNUNET_NO;
2059 }
2060
2061 /**
2062  * Iterator over all the peers to get the oldest timestamp.
2063  *
2064  * @param cls Closure (unsued).
2065  * @param key ID of the peer.
2066  * @param value Peer_Info of the peer.
2067  */
2068 static int
2069 peer_get_oldest (void *cls,
2070                  const struct GNUNET_HashCode *key,
2071                  void *value)
2072 {
2073   struct MeshPeer *p = value;
2074   struct GNUNET_TIME_Absolute *abs = cls;
2075
2076   /* Don't count active peers */
2077   if (GNUNET_YES == peer_is_used (p))
2078     return GNUNET_YES;
2079
2080   if (abs->abs_value_us < p->last_contact.abs_value_us)
2081     abs->abs_value_us = p->last_contact.abs_value_us;
2082
2083   return GNUNET_YES;
2084 }
2085
2086
2087 /**
2088  * Iterator over all the peers to remove the oldest entry.
2089  *
2090  * @param cls Closure (unsued).
2091  * @param key ID of the peer.
2092  * @param value Peer_Info of the peer.
2093  */
2094 static int
2095 peer_timeout (void *cls,
2096               const struct GNUNET_HashCode *key,
2097               void *value)
2098 {
2099   struct MeshPeer *p = value;
2100   struct GNUNET_TIME_Absolute *abs = cls;
2101
2102   if (p->last_contact.abs_value_us == abs->abs_value_us &&
2103       GNUNET_NO == peer_is_used (p))
2104   {
2105     peer_destroy (p);
2106     return GNUNET_NO;
2107   }
2108   return GNUNET_YES;
2109 }
2110
2111
2112 /**
2113  * Delete oldest unused peer.
2114  */
2115 static void
2116 peer_delete_oldest (void)
2117 {
2118   struct GNUNET_TIME_Absolute abs;
2119
2120   abs = GNUNET_TIME_UNIT_FOREVER_ABS;
2121
2122   GNUNET_CONTAINER_multihashmap_iterate (peers,
2123                                          &peer_get_oldest,
2124                                          &abs);
2125   GNUNET_CONTAINER_multihashmap_iterate (peers,
2126                                          &peer_timeout,
2127                                          &abs);
2128 }
2129
2130
2131 /**
2132  * Retrieve the MeshPeer stucture associated with the peer, create one
2133  * and insert it in the appropriate structures if the peer is not known yet.
2134  *
2135  * @param peer Full identity of the peer.
2136  *
2137  * @return Existing or newly created peer info.
2138  */
2139 static struct MeshPeer *
2140 peer_get (const struct GNUNET_PeerIdentity *peer_id)
2141 {
2142   struct MeshPeer *peer;
2143
2144   peer = GNUNET_CONTAINER_multihashmap_get (peers, &peer_id->hashPubKey);
2145   if (NULL == peer)
2146   {
2147     peer = GNUNET_new (struct MeshPeer);
2148     if (GNUNET_CONTAINER_multihashmap_size (peers) > max_peers)
2149     {
2150       peer_delete_oldest ();
2151     }
2152     GNUNET_CONTAINER_multihashmap_put (peers, &peer_id->hashPubKey, peer,
2153                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
2154     peer->id = GNUNET_PEER_intern (peer_id);
2155   }
2156   peer->last_contact = GNUNET_TIME_absolute_get();
2157
2158   return peer;
2159 }
2160
2161
2162 /**
2163  * Retrieve the MeshPeer stucture associated with the peer, create one
2164  * and insert it in the appropriate structures if the peer is not known yet.
2165  *
2166  * @param peer Short identity of the peer.
2167  *
2168  * @return Existing or newly created peer info.
2169  */
2170 static struct MeshPeer *
2171 peer_get_short (const GNUNET_PEER_Id peer)
2172 {
2173   return peer_get (GNUNET_PEER_resolve2 (peer));
2174 }
2175
2176
2177 /**
2178  * Get a cost of a path for a peer considering existing tunnel connections.
2179  *
2180  * @param peer Peer towards which the path is considered.
2181  * @param path Candidate path.
2182  *
2183  * @return Cost of the path (path length + number of overlapping nodes)
2184  */
2185 static unsigned int
2186 peer_get_path_cost (const struct MeshPeer *peer,
2187                     const struct MeshPeerPath *path)
2188 {
2189   struct MeshConnection *c;
2190   unsigned int overlap;
2191   unsigned int i;
2192   unsigned int j;
2193
2194   if (NULL == path)
2195     return 0;
2196
2197   overlap = 0;
2198   GNUNET_assert (NULL != peer->tunnel);
2199
2200   for (i = 0; i < path->length; i++)
2201   {
2202     for (c = peer->tunnel->connection_head; NULL != c; c = c->next)
2203     {
2204       for (j = 0; j < c->path->length; j++)
2205       {
2206         if (path->peers[i] == c->path->peers[j])
2207         {
2208           overlap++;
2209           break;
2210         }
2211       }
2212     }
2213   }
2214   return (path->length + overlap) * (path->score * -1);
2215 }
2216
2217
2218 /**
2219  * Choose the best path towards a peer considering the tunnel properties.
2220  *
2221  * @param peer The destination peer.
2222  *
2223  * @return Best current known path towards the peer, if any.
2224  */
2225 static struct MeshPeerPath *
2226 peer_get_best_path (const struct MeshPeer *peer)
2227 {
2228   struct MeshPeerPath *best_p;
2229   struct MeshPeerPath *p;
2230   struct MeshConnection *c;
2231   unsigned int best_cost;
2232   unsigned int cost;
2233
2234   best_cost = UINT_MAX;
2235   best_p = NULL;
2236   for (p = peer->path_head; NULL != p; p = p->next)
2237   {
2238     for (c = peer->tunnel->connection_head; NULL != c; c = c->next)
2239       if (c->path == p)
2240         break;
2241     if (NULL != c)
2242       continue; /* If path is in use in a connection, skip it. */
2243
2244     if ((cost = peer_get_path_cost (peer, p)) < best_cost)
2245     {
2246       best_cost = cost;
2247       best_p = p;
2248     }
2249   }
2250   return best_p;
2251 }
2252
2253 static int
2254 queue_is_sendable (struct MeshPeerQueue *q)
2255 {
2256   struct MeshFlowControl *fc;
2257
2258   /* Is PID-independent? */
2259   switch (q->type)
2260   {
2261     case GNUNET_MESSAGE_TYPE_MESH_ACK:
2262     case GNUNET_MESSAGE_TYPE_MESH_POLL:
2263       return GNUNET_YES;
2264   }
2265
2266   /* Is PID allowed? */
2267   fc = q->fwd ? &q->c->fwd_fc : &q->c->bck_fc;
2268   if (GMC_is_pid_bigger (fc->last_ack_recv, fc->last_pid_sent))
2269     return GNUNET_YES;
2270
2271   return GNUNET_NO;
2272 }
2273
2274
2275 /**
2276  * Get first sendable message.
2277  *
2278  * @param peer The destination peer.
2279  *
2280  * @return Best current known path towards the peer, if any.
2281  */
2282 static struct MeshPeerQueue *
2283 peer_get_first_message (const struct MeshPeer *peer)
2284 {
2285   struct MeshPeerQueue *q;
2286
2287   for (q = peer->queue_head; NULL != q; q = q->next)
2288   {
2289     if (queue_is_sendable (q))
2290       return q;
2291   }
2292
2293   return NULL;
2294 }
2295
2296
2297 /**
2298  * Try to establish a new connection to this peer in the given tunnel.
2299  * If the peer doesn't have any path to it yet, try to get one.
2300  * If the peer already has some path, send a CREATE CONNECTION towards it.
2301  *
2302  * @param peer PeerInfo of the peer.
2303  */
2304 static void
2305 peer_connect (struct MeshPeer *peer)
2306 {
2307   struct MeshTunnel2 *t;
2308   struct MeshPeerPath *p;
2309   struct MeshConnection *c;
2310
2311   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2312               "peer_connect towards %s\n",
2313               peer2s (peer));
2314   t = peer->tunnel;
2315   if (NULL != peer->path_head)
2316   {
2317     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "path exists\n");
2318     p = peer_get_best_path (peer);
2319     if (NULL != p)
2320     {
2321       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  %u hops\n", p->length);
2322       c = tunnel_use_path (t, p);
2323       send_connection_create (c);
2324     }
2325   }
2326   else if (NULL == peer->dhtget)
2327   {
2328     const struct GNUNET_PeerIdentity *id;
2329
2330     id = GNUNET_PEER_resolve2 (peer->id);
2331     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2332                 "  Starting DHT GET for peer %s\n", peer2s (peer));
2333     peer->dhtget = GNUNET_DHT_get_start (dht_handle,    /* handle */
2334                                          GNUNET_BLOCK_TYPE_MESH_PEER, /* type */
2335                                          &id->hashPubKey,     /* key to search */
2336                                          dht_replication_level, /* replication level */
2337                                          GNUNET_DHT_RO_RECORD_ROUTE |
2338                                          GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE,
2339                                          NULL,       /* xquery */
2340                                          0,     /* xquery bits */
2341                                          &dht_get_id_handler, peer);
2342     if (MESH_TUNNEL_NEW == t->state)
2343       tunnel_change_state (t, MESH_TUNNEL_SEARCHING);
2344   }
2345   else
2346   {
2347     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2348                 "There is no path but the DHT GET is already started.\n");
2349   }
2350 }
2351
2352
2353 /**
2354  * Get the first transmittable message for a connection.
2355  *
2356  * @param c Connection.
2357  * @param fwd Is this FWD?
2358  *
2359  * @return First transmittable message.
2360  */
2361 static struct MeshPeerQueue *
2362 connection_get_first_message (struct MeshConnection *c, int fwd)
2363 {
2364   struct MeshPeerQueue *q;
2365   struct MeshPeer *p;
2366
2367   p = connection_get_hop (c, fwd);
2368
2369   for (q = p->queue_head; NULL != q; q = q->next)
2370   {
2371     if (q->c != c)
2372       continue;
2373     if (queue_is_sendable (q))
2374       return q;
2375   }
2376
2377   return NULL;
2378 }
2379
2380
2381 /**
2382  * Is this peer the first one on the connection?
2383  *
2384  * @param c Connection.
2385  * @param fwd Is this about fwd traffic?
2386  *
2387  * @return GNUNET_YES if origin, GNUNET_NO if relay/terminal.
2388  */
2389 static int
2390 connection_is_origin (struct MeshConnection *c, int fwd)
2391 {
2392   if (!fwd && c->own_pos == c->path->length - 1)
2393     return GNUNET_YES;
2394   if (fwd && c->own_pos == 0)
2395     return GNUNET_YES;
2396   return GNUNET_NO;
2397 }
2398
2399
2400 /**
2401  * Is this peer the last one on the connection?
2402  *
2403  * @param c Connection.
2404  * @param fwd Is this about fwd traffic?
2405  *            Note that the ROOT is the terminal for BCK traffic!
2406  *
2407  * @return GNUNET_YES if terminal, GNUNET_NO if relay/origin.
2408  */
2409 static int
2410 connection_is_terminal (struct MeshConnection *c, int fwd)
2411 {
2412   if (fwd && c->own_pos == c->path->length - 1)
2413     return GNUNET_YES;
2414   if (!fwd && c->own_pos == 0)
2415     return GNUNET_YES;
2416   return GNUNET_NO;
2417 }
2418
2419
2420 /**
2421  * @brief Re-initiate traffic on this connection if necessary.
2422  *
2423  * Check if there is traffic queued towards this peer
2424  * and the core transmit handle is NULL (traffic was stalled).
2425  * If so, call core tmt rdy.
2426  *
2427  * @param c Connection on which initiate traffic.
2428  * @param fwd Is this about fwd traffic?
2429  */
2430 static void
2431 connection_unlock_queue (struct MeshConnection *c, int fwd)
2432 {
2433   struct MeshPeer *peer;
2434   struct MeshPeerQueue *q;
2435   size_t size;
2436
2437   peer = connection_get_hop (c, fwd);
2438
2439   if (NULL != peer->core_transmit)
2440     return; /* Already unlocked */
2441
2442   q = connection_get_first_message (c, fwd);
2443   if (NULL == q)
2444     return; /* Nothing to transmit */
2445
2446   size = q->size;
2447   peer->core_transmit =
2448       GNUNET_CORE_notify_transmit_ready (core_handle,
2449                                          GNUNET_NO,
2450                                          0,
2451                                          GNUNET_TIME_UNIT_FOREVER_REL,
2452                                          GNUNET_PEER_resolve2 (peer->id),
2453                                          size,
2454                                          &queue_send,
2455                                          peer);
2456 }
2457
2458
2459 /**
2460  * Cancel all transmissions that belong to a certain connection.
2461  *
2462  * @param c Connection which to cancel.
2463  * @param fwd Cancel fwd traffic?
2464  */
2465 static void
2466 connection_cancel_queues (struct MeshConnection *c, int fwd)
2467 {
2468   struct MeshPeerQueue *q;
2469   struct MeshPeerQueue *next;
2470   struct MeshFlowControl *fc;
2471   struct MeshPeer *peer;
2472
2473   if (NULL == c)
2474   {
2475     GNUNET_break (0);
2476     return;
2477   }
2478   fc = fwd ? &c->fwd_fc : &c->bck_fc;
2479   peer = connection_get_hop (c, fwd);
2480
2481   for (q = peer->queue_head; NULL != q; q = next)
2482   {
2483     next = q->next;
2484     if (q->c == c)
2485     {
2486       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2487                   "connection_cancel_queue %s\n",
2488                   GNUNET_MESH_DEBUG_M2S (q->type));
2489       queue_destroy (q, GNUNET_YES);
2490     }
2491   }
2492   if (NULL == peer->queue_head)
2493   {
2494     if (NULL != peer->core_transmit)
2495     {
2496       GNUNET_CORE_notify_transmit_ready_cancel (peer->core_transmit);
2497       peer->core_transmit = NULL;
2498     }
2499     if (GNUNET_SCHEDULER_NO_TASK != fc->poll_task)
2500     {
2501       GNUNET_SCHEDULER_cancel (fc->poll_task);
2502       fc->poll_task = GNUNET_SCHEDULER_NO_TASK;
2503     }
2504   }
2505 }
2506
2507
2508 /**
2509  * Remove all paths that rely on a direct connection between p1 and p2
2510  * from the peer itself and notify all tunnels about it.
2511  *
2512  * @param peer PeerInfo of affected peer.
2513  * @param p1 GNUNET_PEER_Id of one peer.
2514  * @param p2 GNUNET_PEER_Id of another peer that was connected to the first and
2515  *           no longer is.
2516  *
2517  * TODO: optimize (see below)
2518  */
2519 static void
2520 peer_remove_path (struct MeshPeer *peer, GNUNET_PEER_Id p1,
2521                   GNUNET_PEER_Id p2)
2522 {
2523   struct MeshPeerPath *p;
2524   struct MeshPeerPath *next;
2525   struct MeshPeer *peer_d;
2526   GNUNET_PEER_Id d;
2527   unsigned int destroyed;
2528   unsigned int i;
2529
2530   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "peer_info_remove_path\n");
2531   destroyed = 0;
2532   for (p = peer->path_head; NULL != p; p = next)
2533   {
2534     next = p->next;
2535     for (i = 0; i < (p->length - 1); i++)
2536     {
2537       if ((p->peers[i] == p1 && p->peers[i + 1] == p2) ||
2538           (p->peers[i] == p2 && p->peers[i + 1] == p1))
2539       {
2540         GNUNET_CONTAINER_DLL_remove (peer->path_head, peer->path_tail, p);
2541         path_destroy (p);
2542         destroyed++;
2543         break;
2544       }
2545     }
2546   }
2547   if (0 == destroyed)
2548     return;
2549
2550
2551   d = tunnel_notify_connection_broken (peer->tunnel, p1, p2);
2552
2553   peer_d = peer_get_short (d); // FIXME
2554   next = peer_get_best_path (peer_d);
2555   tunnel_use_path (peer->tunnel, next);
2556   peer_connect (peer_d);
2557
2558   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "peer_info_remove_path END\n");
2559 }
2560
2561
2562 /**
2563  * Add the path to the peer and update the path used to reach it in case this
2564  * is the shortest.
2565  *
2566  * @param peer_info Destination peer to add the path to.
2567  * @param path New path to add. Last peer must be the peer in arg 1.
2568  *             Path will be either used of freed if already known.
2569  * @param trusted Do we trust that this path is real?
2570  */
2571 void
2572 peer_add_path (struct MeshPeer *peer_info, struct MeshPeerPath *path,
2573                     int trusted)
2574 {
2575   struct MeshPeerPath *aux;
2576   unsigned int l;
2577   unsigned int l2;
2578
2579   if ((NULL == peer_info) || (NULL == path))
2580   {
2581     GNUNET_break (0);
2582     path_destroy (path);
2583     return;
2584   }
2585   if (path->peers[path->length - 1] != peer_info->id)
2586   {
2587     GNUNET_break (0);
2588     path_destroy (path);
2589     return;
2590   }
2591   if (2 >= path->length && GNUNET_NO == trusted)
2592   {
2593     /* Only allow CORE to tell us about direct paths */
2594     path_destroy (path);
2595     return;
2596   }
2597   for (l = 1; l < path->length; l++)
2598   {
2599     if (path->peers[l] == myid)
2600     {
2601       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shortening path by %u\n", l);
2602       for (l2 = 0; l2 < path->length - l; l2++)
2603       {
2604         path->peers[l2] = path->peers[l + l2];
2605       }
2606       path->length -= l;
2607       l = 1;
2608       path->peers =
2609           GNUNET_realloc (path->peers, path->length * sizeof (GNUNET_PEER_Id));
2610     }
2611   }
2612
2613   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "adding path [%u] to peer %s\n",
2614               path->length, peer2s (peer_info));
2615
2616   l = path_get_length (path);
2617   if (0 == l)
2618   {
2619     path_destroy (path);
2620     return;
2621   }
2622
2623   GNUNET_assert (peer_info->id == path->peers[path->length - 1]);
2624   for (aux = peer_info->path_head; aux != NULL; aux = aux->next)
2625   {
2626     l2 = path_get_length (aux);
2627     if (l2 > l)
2628     {
2629       GNUNET_CONTAINER_DLL_insert_before (peer_info->path_head,
2630                                           peer_info->path_tail, aux, path);
2631       return;
2632     }
2633     else
2634     {
2635       if (l2 == l && memcmp (path->peers, aux->peers, l) == 0)
2636       {
2637         path_destroy (path);
2638         return;
2639       }
2640     }
2641   }
2642   GNUNET_CONTAINER_DLL_insert_tail (peer_info->path_head, peer_info->path_tail,
2643                                     path);
2644   return;
2645 }
2646
2647
2648 /**
2649  * Add the path to the origin peer and update the path used to reach it in case
2650  * this is the shortest.
2651  * The path is given in peer_info -> destination, therefore we turn the path
2652  * upside down first.
2653  *
2654  * @param peer_info Peer to add the path to, being the origin of the path.
2655  * @param path New path to add after being inversed.
2656  *             Path will be either used or freed.
2657  * @param trusted Do we trust that this path is real?
2658  */
2659 static void
2660 peer_add_path_to_origin (struct MeshPeer *peer_info,
2661                          struct MeshPeerPath *path, int trusted)
2662 {
2663   path_invert (path);
2664   peer_add_path (peer_info, path, trusted);
2665 }
2666
2667
2668
2669 /**
2670  * Function called if a connection has been stalled for a while,
2671  * possibly due to a missed ACK. Poll the neighbor about its ACK status.
2672  *
2673  * @param cls Closure (poll ctx).
2674  * @param tc TaskContext.
2675  */
2676 static void
2677 connection_poll (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2678 {
2679   struct MeshFlowControl *fc = cls;
2680   struct GNUNET_MESH_Poll msg;
2681   struct MeshConnection *c;
2682
2683   fc->poll_task = GNUNET_SCHEDULER_NO_TASK;
2684   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
2685   {
2686     return;
2687   }
2688
2689   c = fc->c;
2690   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " *** Polling!\n");
2691   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " *** connection %s[%X]\n", 
2692               peer2s (c->t->peer), c->id);
2693
2694   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_POLL);
2695   msg.header.size = htons (sizeof (msg));
2696   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " *** pid (%u)!\n", fc->last_pid_sent);
2697   send_prebuilt_message_connection (&msg.header, c, NULL, fc == &c->fwd_fc);
2698   fc->poll_time = GNUNET_TIME_STD_BACKOFF (fc->poll_time);
2699   fc->poll_task = GNUNET_SCHEDULER_add_delayed (fc->poll_time,
2700                                                 &connection_poll, fc);
2701 }
2702
2703
2704 /**
2705  * Build a PeerPath from the paths returned from the DHT, reversing the paths
2706  * to obtain a local peer -> destination path and interning the peer ids.
2707  *
2708  * @return Newly allocated and created path
2709  */
2710 static struct MeshPeerPath *
2711 path_build_from_dht (const struct GNUNET_PeerIdentity *get_path,
2712                      unsigned int get_path_length,
2713                      const struct GNUNET_PeerIdentity *put_path,
2714                      unsigned int put_path_length)
2715 {
2716   struct MeshPeerPath *p;
2717   GNUNET_PEER_Id id;
2718   int i;
2719
2720   p = path_new (1);
2721   p->peers[0] = myid;
2722   GNUNET_PEER_change_rc (myid, 1);
2723   i = get_path_length;
2724   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   GET has %d hops.\n", i);
2725   for (i--; i >= 0; i--)
2726   {
2727     id = GNUNET_PEER_intern (&get_path[i]);
2728     if (p->length > 0 && id == p->peers[p->length - 1])
2729     {
2730       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   Optimizing 1 hop out.\n");
2731       GNUNET_PEER_change_rc (id, -1);
2732     }
2733     else
2734     {
2735       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   Adding from GET: %s.\n",
2736                   GNUNET_i2s (&get_path[i]));
2737       p->length++;
2738       p->peers = GNUNET_realloc (p->peers, sizeof (GNUNET_PEER_Id) * p->length);
2739       p->peers[p->length - 1] = id;
2740     }
2741   }
2742   i = put_path_length;
2743   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   PUT has %d hops.\n", i);
2744   for (i--; i >= 0; i--)
2745   {
2746     id = GNUNET_PEER_intern (&put_path[i]);
2747     if (id == myid)
2748     {
2749       /* PUT path went through us, so discard the path up until now and start
2750        * from here to get a much shorter (and loop-free) path.
2751        */
2752       path_destroy (p);
2753       p = path_new (0);
2754     }
2755     if (p->length > 0 && id == p->peers[p->length - 1])
2756     {
2757       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   Optimizing 1 hop out.\n");
2758       GNUNET_PEER_change_rc (id, -1);
2759     }
2760     else
2761     {
2762       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   Adding from PUT: %s.\n",
2763                   GNUNET_i2s (&put_path[i]));
2764       p->length++;
2765       p->peers = GNUNET_realloc (p->peers, sizeof (GNUNET_PEER_Id) * p->length);
2766       p->peers[p->length - 1] = id;
2767     }
2768   }
2769 #if MESH_DEBUG
2770   if (get_path_length > 0)
2771     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   (first of GET: %s)\n",
2772                 GNUNET_i2s (&get_path[0]));
2773   if (put_path_length > 0)
2774     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   (first of PUT: %s)\n",
2775                 GNUNET_i2s (&put_path[0]));
2776   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   In total: %d hops\n",
2777               p->length);
2778   for (i = 0; i < p->length; i++)
2779   {
2780     struct GNUNET_PeerIdentity peer_id;
2781
2782     GNUNET_PEER_resolve (p->peers[i], &peer_id);
2783     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "       %u: %s\n", p->peers[i],
2784                 GNUNET_i2s (&peer_id));
2785   }
2786 #endif
2787   return p;
2788 }
2789
2790
2791 /**
2792  * Adds a path to the peer_infos of all the peers in the path
2793  *
2794  * @param p Path to process.
2795  * @param confirmed Whether we know if the path works or not.
2796  */
2797 static void
2798 path_add_to_peers (struct MeshPeerPath *p, int confirmed)
2799 {
2800   unsigned int i;
2801
2802   /* TODO: invert and add */
2803   for (i = 0; i < p->length && p->peers[i] != myid; i++) /* skip'em */ ;
2804   for (i++; i < p->length; i++)
2805   {
2806     struct MeshPeer *aux;
2807     struct MeshPeerPath *copy;
2808
2809     aux = peer_get_short (p->peers[i]);
2810     copy = path_duplicate (p);
2811     copy->length = i + 1;
2812     peer_add_path (aux, copy, p->length < 3 ? GNUNET_NO : confirmed);
2813   }
2814 }
2815
2816
2817 /**
2818  * Search for a channel among the channels for a client
2819  *
2820  * @param c the client whose channels to search in
2821  * @param chid the local id of the channel
2822  *
2823  * @return channel handler, NULL if doesn't exist
2824  */
2825 static struct MeshChannel *
2826 channel_get_by_local_id (struct MeshClient *c, MESH_ChannelNumber chid)
2827 {
2828   if (0 == (chid & GNUNET_MESH_LOCAL_CHANNEL_ID_CLI))
2829   {
2830     GNUNET_break_op (0);
2831     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "CHID %X not a local chid\n", chid);
2832     return NULL;
2833   }
2834   if (chid >= GNUNET_MESH_LOCAL_CHANNEL_ID_SERV)
2835     return GNUNET_CONTAINER_multihashmap32_get (c->incoming_channels, chid);
2836   return GNUNET_CONTAINER_multihashmap32_get (c->own_channels, chid);
2837 }
2838
2839 /**
2840  * Search for a tunnel by global ID using full PeerIdentities.
2841  *
2842  * @param t Tunnel containing the channel.
2843  * @param chid Public channel number.
2844  *
2845  * @return channel handler, NULL if doesn't exist
2846  */
2847 static struct MeshChannel *
2848 channel_get (struct MeshTunnel2 *t, MESH_ChannelNumber chid)
2849 {
2850   struct MeshChannel *ch;
2851
2852   if (NULL == t)
2853     return NULL;
2854
2855   for (ch = t->channel_head; NULL != ch; ch = ch->next)
2856   {
2857     if (ch->gid == chid)
2858       break;
2859   }
2860
2861   return ch;
2862 }
2863
2864
2865 /**
2866  * Change the tunnel state.
2867  *
2868  * @param t Tunnel whose state to change.
2869  * @param state New state.
2870  */
2871 static void
2872 tunnel_change_state (struct MeshTunnel2* t, enum MeshTunnelState state)
2873 {
2874   if (NULL == t)
2875     return;
2876   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2877               "Tunnel %s state was %s\n",
2878               peer2s (t->peer),
2879               GNUNET_MESH_DEBUG_TS2S (t->state));
2880   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2881               "Tunnel %s state is now %s\n",
2882               peer2s (t->peer),
2883               GNUNET_MESH_DEBUG_TS2S (state));
2884   t->state = state;
2885 }
2886
2887
2888 /**
2889  * Cache a message to be sent once tunnel is online.
2890  *
2891  * @param t Tunnel to hold the message.
2892  * @param ch Channel the message is about.
2893  * @param msg Message itself (copy will be made).
2894  * @param fwd Is this fwd?
2895  */
2896 static void
2897 tunnel_queue_data (struct MeshTunnel2 *t,
2898                    struct MeshChannel *ch,
2899                    struct GNUNET_MessageHeader *msg,
2900                    int fwd)
2901 {
2902   struct MeshTunnelQueue *tq;
2903   uint16_t size = ntohs (msg->size);
2904
2905   tq = GNUNET_malloc (sizeof (struct MeshTunnelQueue) + size);
2906
2907   tq->ch = ch;
2908   memcpy (&tq[1], msg, size);
2909   GNUNET_CONTAINER_DLL_insert_tail (t->tq_head, t->tq_tail, tq);
2910 }
2911
2912
2913 /**
2914  * Send all cached messages that we can, tunnel is online.
2915  *
2916  * @param t Tunnel that holds the messages.
2917  * @param fwd Is this fwd?
2918  */
2919 static void
2920 tunnel_send_queued_data (struct MeshTunnel2 *t, int fwd)
2921 {
2922   struct MeshTunnelQueue *tq;
2923   struct MeshTunnelQueue *next;
2924   unsigned int room;
2925
2926   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2927               "tunnel_send_queued_data on tunnel %s\n",
2928               peer2s (t->peer));
2929   room = tunnel_get_buffer (t, fwd);
2930   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  buffer space: %u\n", room);
2931   for (tq = t->tq_head; NULL != tq && room > 0; tq = next)
2932   {
2933     next = tq->next;
2934     room--;
2935     GNUNET_CONTAINER_DLL_remove (t->tq_head, t->tq_tail, tq);
2936     send_prebuilt_message_channel ((struct GNUNET_MessageHeader *) &tq[1],
2937                                    tq->ch, fwd);
2938
2939     GNUNET_free (tq);
2940   }
2941 }
2942
2943
2944 static void
2945 connection_change_state (struct MeshConnection* c,
2946                          enum MeshConnectionState state)
2947 {
2948   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2949               "Connection %s state was %s\n",
2950               GNUNET_h2s (&c->id), GNUNET_MESH_DEBUG_CS2S (c->state));
2951   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2952               "Connection %s state is now %s\n",
2953               GNUNET_h2s (&c->id), GNUNET_MESH_DEBUG_CS2S (state));
2954   c->state = state;
2955 }
2956
2957
2958 /**
2959  * Add a client to a channel, initializing all needed data structures.
2960  * 
2961  * @param ch Channel to which add the client.
2962  * @param c Client which to add to the channel.
2963  */
2964 static void
2965 channel_add_client (struct MeshChannel *ch, struct MeshClient *c)
2966 {
2967   struct MeshTunnel2 *t = ch->t;
2968
2969   if (NULL != ch->dest)
2970   {
2971     GNUNET_break(0);
2972     return;
2973   }
2974
2975   /* Assign local id as destination */
2976   while (NULL != channel_get_by_local_id (c, t->next_local_chid))
2977     t->next_local_chid = (t->next_local_chid + 1) | GNUNET_MESH_LOCAL_CHANNEL_ID_SERV;
2978   ch->lid_dest = t->next_local_chid++;
2979   t->next_local_chid = t->next_local_chid | GNUNET_MESH_LOCAL_CHANNEL_ID_SERV;
2980
2981   /* Store in client's hashmap */
2982   if (GNUNET_OK !=
2983       GNUNET_CONTAINER_multihashmap32_put (c->incoming_channels,
2984                                            ch->lid_dest, ch,
2985                                            GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
2986   {
2987     GNUNET_break (0);
2988     return;
2989   }
2990   ch->dest = c;
2991 }
2992
2993
2994 static struct MeshConnection *
2995 tunnel_use_path (struct MeshTunnel2 *t, struct MeshPeerPath *p)
2996 {
2997   struct MeshConnection *c;
2998   struct GNUNET_HashCode cid;
2999   struct MeshPeer *peer;
3000   unsigned int own_pos;
3001
3002   GNUNET_CRYPTO_hash_create_random (GNUNET_CRYPTO_QUALITY_NONCE, &cid);
3003
3004   c = connection_new (&cid);
3005   c->t = t;
3006   for (own_pos = 0; own_pos < p->length; own_pos++)
3007   {
3008     if (p->peers[own_pos] == myid)
3009       break;
3010   }
3011   if (own_pos > p->length - 1)
3012   {
3013     GNUNET_break (0);
3014     connection_destroy (c);
3015     return NULL;
3016   }
3017   c->own_pos = own_pos;
3018   c->path = p;
3019
3020   if (0 == own_pos)
3021   {
3022     c->fwd_maintenance_task =
3023         GNUNET_SCHEDULER_add_delayed (refresh_connection_time,
3024                                       &connection_fwd_keepalive, c);
3025   }
3026
3027   peer = connection_get_next_hop (c);
3028   GNUNET_CONTAINER_multihashmap_put (peer->connections, &c->id, c,
3029                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
3030   peer = connection_get_prev_hop (c);
3031   GNUNET_CONTAINER_multihashmap_put (peer->connections, &c->id, c,
3032                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
3033   return c;
3034 }
3035
3036
3037 /**
3038  * Notifies a tunnel that a connection has broken that affects at least
3039  * some of its peers. Sends a notification towards the root of the tree.
3040  * In case the peer is the owner of the tree, notifies the client that owns
3041  * the tunnel and tries to reconnect.
3042  * 
3043  * FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME 
3044  *
3045  * @param t Tunnel affected.
3046  * @param p1 Peer that got disconnected from p2.
3047  * @param p2 Peer that got disconnected from p1.
3048  *
3049  * @return Short ID of the peer disconnected (either p1 or p2).
3050  *         0 if the tunnel remained unaffected.
3051  */
3052 static GNUNET_PEER_Id
3053 tunnel_notify_connection_broken (struct MeshTunnel2* t,
3054                                  GNUNET_PEER_Id p1, GNUNET_PEER_Id p2)
3055 {
3056 //   if (myid != p1 && myid != p2) FIXME
3057 //   {
3058 //     return;
3059 //   }
3060 // 
3061 //   if (tree_get_predecessor (t->tree) != 0)
3062 //   {
3063 //     /* We are the peer still connected, notify owner of the disconnection. */
3064 //     struct GNUNET_MESH_PathBroken msg;
3065 //     struct GNUNET_PeerIdentity neighbor;
3066 // 
3067 //     msg.header.size = htons (sizeof (msg));
3068 //     msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_BROKEN);
3069 //     GNUNET_PEER_resolve (t->id.oid, &msg.oid);
3070 //     msg.tid = htonl (t->id.tid);
3071 //     msg.peer1 = my_full_id;
3072 //     GNUNET_PEER_resolve (pid, &msg.peer2);
3073 //     GNUNET_PEER_resolve (tree_get_predecessor (t->tree), &neighbor);
3074 //     send_prebuilt_message (&msg.header, &neighbor, t);
3075 //   }
3076   return 0;
3077 }
3078
3079
3080 /**
3081  * Send an end-to-end FWD ACK message for the most recent in-sequence payload.
3082  *
3083  * @param ch Channel this is about.
3084  * @param fwd Is for FWD traffic? (ACK dest->owner)
3085  */
3086 static void
3087 channel_send_data_ack (struct MeshChannel *ch, int fwd)
3088 {
3089   struct GNUNET_MESH_DataACK msg;
3090   struct MeshChannelReliability *rel;
3091   struct MeshReliableMessage *copy;
3092   unsigned int delta;
3093   uint64_t mask;
3094   uint32_t *mid;
3095   uint16_t type;
3096
3097   if (GNUNET_NO == ch->reliable)
3098   {
3099     GNUNET_break (0);
3100     return;
3101   }
3102   rel = fwd ? ch->bck_rel       : ch->fwd_rel;
3103   mid = fwd ? &ch->mid_recv_fwd : &ch->mid_recv_bck;
3104   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3105               "send_data_ack for %u\n",
3106               *mid - 1);
3107
3108   type = GNUNET_MESSAGE_TYPE_MESH_DATA_ACK;
3109   msg.header.type = htons (type);
3110   msg.header.size = htons (sizeof (msg));
3111   msg.chid = htonl (ch->gid);
3112   msg.mid = htonl (*mid - 1);
3113   msg.futures = 0;
3114   for (copy = rel->head_recv; NULL != copy; copy = copy->next)
3115   {
3116     if (copy->type != type)
3117       continue;
3118     delta = copy->mid - *mid;
3119     if (63 < delta)
3120       break;
3121     mask = 0x1LL << delta;
3122     msg.futures |= mask;
3123     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3124                 " setting bit for %u (delta %u) (%llX) -> %llX\n",
3125                 copy->mid, delta, mask, msg.futures);
3126   }
3127   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " final futures %llX\n", msg.futures);
3128
3129   send_prebuilt_message_channel (&msg.header, ch, fwd);
3130   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "send_data_ack END\n");
3131 }
3132
3133
3134 /**
3135  * Send an ACK informing the predecessor about the available buffer space.
3136  *
3137  * Note that for fwd ack, the FWD mean forward *traffic* (root->dest),
3138  * the ACK itself goes "back" (dest->root).
3139  *
3140  * @param c Connection on which to send the ACK.
3141  * @param fwd Is this FWD ACK? (Going dest->owner)
3142  */
3143 static void
3144 connection_send_ack (struct MeshConnection *c, int fwd)
3145 {
3146   struct MeshFlowControl *next_fc;
3147   struct MeshFlowControl *prev_fc;
3148   uint32_t ack;
3149   int delta;
3150
3151   next_fc = fwd ? &c->fwd_fc : &c->bck_fc;
3152   prev_fc = fwd ? &c->bck_fc : &c->fwd_fc;
3153
3154   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3155               "connection send %s ack on %s\n",
3156               fwd ? "FWD" : "BCK", GNUNET_h2s (&c->id));
3157
3158   /* Check if we need to transmit the ACK */
3159   if (prev_fc->last_ack_sent - prev_fc->last_pid_recv > 3)
3160   {
3161     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Not sending ACK, buffer > 3\n");
3162     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3163                 "  last pid recv: %u, last ack sent: %u\n",
3164                 prev_fc->last_pid_recv, prev_fc->last_ack_sent);
3165     return;
3166   }
3167
3168   /* Ok, ACK might be necessary, what PID to ACK? */
3169   delta = next_fc->queue_max - next_fc->queue_n;
3170   ack = prev_fc->last_pid_recv + delta;
3171   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " ACK %u\n", ack);
3172   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3173               " last pid %u, last ack %u, qmax %u, q %u\n",
3174               prev_fc->last_pid_recv, prev_fc->last_ack_sent,
3175               next_fc->queue_max, next_fc->queue_n);
3176   if (ack == prev_fc->last_ack_sent)
3177   {
3178     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Not sending FWD ACK, not needed\n");
3179     return;
3180   }
3181
3182   prev_fc->last_ack_sent = ack;
3183   send_ack (c, ack, fwd);
3184 }
3185
3186
3187 /**
3188  * Modify the mesh message TID from global to local and send to client.
3189  * 
3190  * @param ch Channel on which to send the message.
3191  * @param msg Message to modify and send.
3192  * @param c Client to send to.
3193  * @param tid Tunnel ID to use (c can be both owner and client).
3194  */
3195 static void
3196 channel_send_client_to_tid (struct MeshChannel *ch,
3197                              const struct GNUNET_MESH_Data *msg,
3198                              struct MeshClient *c, MESH_ChannelNumber id)
3199 {
3200   struct GNUNET_MESH_LocalData *copy;
3201   uint16_t size = ntohs (msg->header.size) - sizeof (struct GNUNET_MESH_Data);
3202   char cbuf[size + sizeof (struct GNUNET_MESH_LocalData)];
3203
3204   if (size < sizeof (struct GNUNET_MessageHeader))
3205   {
3206     GNUNET_break_op (0);
3207     return;
3208   }
3209   if (NULL == c)
3210   {
3211     GNUNET_break (0);
3212     return;
3213   }
3214   copy = (struct GNUNET_MESH_LocalData *) cbuf;
3215   memcpy (&copy[1], &msg[1], size);
3216   copy->header.size = htons (sizeof (struct GNUNET_MESH_LocalData) + size);
3217   copy->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_DATA);
3218   copy->id = htonl (id);
3219   GNUNET_SERVER_notification_context_unicast (nc, c->handle,
3220                                               &copy->header, GNUNET_NO);
3221 }
3222
3223 /**
3224  * Modify the data message ID from global to local and send to client.
3225  * 
3226  * @param ch Channel on which to send the message.
3227  * @param msg Message to modify and send.
3228  * @param fwd Forward?
3229  */
3230 static void
3231 channel_send_client_data (struct MeshChannel *ch,
3232                           const struct GNUNET_MESH_Data *msg,
3233                           int fwd)
3234 {
3235   if (fwd)
3236     channel_send_client_to_tid (ch, msg, ch->dest, ch->lid_dest);
3237   else
3238     channel_send_client_to_tid (ch, msg, ch->root, ch->lid_root);
3239 }
3240
3241
3242 /**
3243  * Send a buffered message to the client, for in order delivery or
3244  * as result of client ACK.
3245  *
3246  * @param ch Channel on which to empty the message buffer.
3247  * @param c Client to send to.
3248  * @param rel Reliability structure to corresponding peer.
3249  *            If rel == bck_rel, this is FWD data.
3250  */
3251 static void
3252 channel_send_client_buffered_data (struct MeshChannel *ch,
3253                                    struct MeshClient *c,
3254                                    struct MeshChannelReliability *rel)
3255 {
3256   struct MeshReliableMessage *copy;
3257   uint32_t *mid;
3258
3259   if (GNUNET_NO == rel->client_ready)
3260   {
3261     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "client not ready\n");
3262     return;
3263   }
3264
3265   mid = rel == ch->bck_rel ? &ch->mid_recv_fwd : &ch->mid_recv_bck;
3266
3267   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "send_buffered_data\n");
3268   copy = rel->head_recv;
3269   /* We never buffer channel management messages */
3270   if (NULL != copy)
3271   {
3272     if (copy->mid == *mid || GNUNET_NO == ch->reliable)
3273     {
3274       struct GNUNET_MESH_Data *msg = (struct GNUNET_MESH_Data *) &copy[1];
3275
3276       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3277                   " have %u! now expecting %u\n",
3278                   copy->mid, *mid + 1);
3279       channel_send_client_data (ch, msg, (rel == ch->bck_rel));
3280       rel->n_recv--;
3281       *mid = *mid + 1;
3282       GNUNET_CONTAINER_DLL_remove (rel->head_recv, rel->tail_recv, copy);
3283       GNUNET_free (copy);
3284     }
3285     else
3286     {
3287       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3288                   " reliable && don't have %u, next is %u\n",
3289                   *mid,
3290                   copy->mid);
3291       return;
3292     }
3293   }
3294   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "send_buffered_data END\n");
3295 }
3296
3297
3298 /**
3299  * We have received a message out of order, or the client is not ready.
3300  * Buffer it until we receive an ACK from the client or the missing
3301  * message from the channel.
3302  *
3303  * @param msg Message to buffer (MUST be of type MESH_DATA).
3304  * @param rel Reliability data to the corresponding direction.
3305  */
3306 static void
3307 channel_rel_add_buffered_data (const struct GNUNET_MESH_Data *msg,
3308                                struct MeshChannelReliability *rel)
3309 {
3310   struct MeshReliableMessage *copy;
3311   struct MeshReliableMessage *prev;
3312   uint32_t mid;
3313   uint16_t size;
3314
3315   size = ntohs (msg->header.size);
3316   mid = ntohl (msg->mid);
3317
3318   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "add_buffered_data %u\n", mid);
3319
3320   copy = GNUNET_malloc (sizeof (*copy) + size);
3321   copy->mid = mid;
3322   copy->rel = rel;
3323   memcpy (&copy[1], msg, size);
3324
3325   rel->n_recv++;
3326
3327   // FIXME do something better than O(n), although n < 64...
3328   // FIXME start from the end (most messages are the latest ones)
3329   for (prev = rel->head_recv; NULL != prev; prev = prev->next)
3330   {
3331     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " prev %u\n", prev->mid);
3332     if (GMC_is_pid_bigger (prev->mid, mid))
3333     {
3334       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " bingo!\n");
3335       GNUNET_CONTAINER_DLL_insert_before (rel->head_recv, rel->tail_recv,
3336                                           prev, copy);
3337       return;
3338     }
3339   }
3340   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " insert at tail!\n");
3341   GNUNET_CONTAINER_DLL_insert_tail (rel->head_recv, rel->tail_recv, copy);
3342   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "add_buffered_data END\n");
3343 }
3344
3345
3346 /**
3347  * Destroy a reliable message after it has been acknowledged, either by
3348  * direct mid ACK or bitfield. Updates the appropriate data structures and
3349  * timers and frees all memory.
3350  * 
3351  * @param copy Message that is no longer needed: remote peer got it.
3352  */
3353 static void
3354 rel_message_free (struct MeshReliableMessage *copy)
3355 {
3356   struct MeshChannelReliability *rel;
3357   struct GNUNET_TIME_Relative time;
3358
3359   rel = copy->rel;
3360   time = GNUNET_TIME_absolute_get_duration (copy->timestamp);
3361   rel->expected_delay.rel_value_us *= 7;
3362   rel->expected_delay.rel_value_us += time.rel_value_us;
3363   rel->expected_delay.rel_value_us /= 8;
3364   rel->n_sent--;
3365   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! Freeing %u\n", copy->mid);
3366   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "    n_sent %u\n", rel->n_sent);
3367   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!!  took %s\n",
3368               GNUNET_STRINGS_relative_time_to_string (time, GNUNET_NO));
3369   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!!  new expected delay %s\n",
3370               GNUNET_STRINGS_relative_time_to_string (rel->expected_delay,
3371                                                       GNUNET_NO));
3372   rel->retry_timer = rel->expected_delay;
3373   GNUNET_CONTAINER_DLL_remove (rel->head_sent, rel->tail_sent, copy);
3374   GNUNET_free (copy);
3375 }
3376
3377
3378 /**
3379  * Destroy all reliable messages queued for a channel,
3380  * during a channel destruction.
3381  * Frees the reliability structure itself.
3382  *
3383  * @param rel Reliability data for a channel.
3384  */
3385 static void
3386 channel_rel_free_all (struct MeshChannelReliability *rel)
3387 {
3388   struct MeshReliableMessage *copy;
3389   struct MeshReliableMessage *next;
3390
3391   if (NULL == rel)
3392     return;
3393
3394   for (copy = rel->head_recv; NULL != copy; copy = next)
3395   {
3396     next = copy->next;
3397     GNUNET_CONTAINER_DLL_remove (rel->head_recv, rel->tail_recv, copy);
3398     GNUNET_free (copy);
3399   }
3400   for (copy = rel->head_sent; NULL != copy; copy = next)
3401   {
3402     next = copy->next;
3403     GNUNET_CONTAINER_DLL_remove (rel->head_sent, rel->tail_sent, copy);
3404     GNUNET_free (copy);
3405   }
3406   if (GNUNET_SCHEDULER_NO_TASK != rel->retry_task)
3407     GNUNET_SCHEDULER_cancel (rel->retry_task);
3408   GNUNET_free (rel);
3409 }
3410
3411
3412 /**
3413  * Mark future messages as ACK'd.
3414  *
3415  * @param rel Reliability data.
3416  * @param msg DataACK message with a bitfield of future ACK'd messages.
3417  */
3418 static void
3419 channel_rel_free_sent (struct MeshChannelReliability *rel,
3420                        const struct GNUNET_MESH_DataACK *msg)
3421 {
3422   struct MeshReliableMessage *copy;
3423   struct MeshReliableMessage *next;
3424   uint64_t bitfield;
3425   uint64_t mask;
3426   uint32_t mid;
3427   uint32_t target;
3428   unsigned int i;
3429
3430   bitfield = msg->futures;
3431   mid = ntohl (msg->mid);
3432   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3433               "free_sent_reliable %u %llX\n",
3434               mid, bitfield);
3435   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3436               " rel %p, head %p\n",
3437               rel, rel->head_sent);
3438   for (i = 0, copy = rel->head_sent;
3439        i < 64 && NULL != copy && 0 != bitfield;
3440        i++)
3441   {
3442     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3443                 " trying bit %u (mid %u)\n",
3444                 i, mid + i + 1);
3445     mask = 0x1LL << i;
3446     if (0 == (bitfield & mask))
3447      continue;
3448
3449     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " set!\n");
3450     /* Bit was set, clear the bit from the bitfield */
3451     bitfield &= ~mask;
3452
3453     /* The i-th bit was set. Do we have that copy? */
3454     /* Skip copies with mid < target */
3455     target = mid + i + 1;
3456     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " target %u\n", target);
3457     while (NULL != copy && GMC_is_pid_bigger (target, copy->mid))
3458      copy = copy->next;
3459
3460     /* Did we run out of copies? (previously freed, it's ok) */
3461     if (NULL == copy)
3462     {
3463      GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "run out of copies...\n");
3464      return;
3465     }
3466
3467     /* Did we overshoot the target? (previously freed, it's ok) */
3468     if (GMC_is_pid_bigger (copy->mid, target))
3469     {
3470      GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " next copy %u\n", copy->mid);
3471      continue;
3472     }
3473
3474     /* Now copy->mid == target, free it */
3475     next = copy->next;
3476     rel_message_free (copy);
3477     copy = next;
3478   }
3479   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "free_sent_reliable END\n");
3480 }
3481
3482
3483 /**
3484  * We haven't received an ACK after a certain time: restransmit the message.
3485  *
3486  * @param cls Closure (MeshReliableMessage with the message to restransmit)
3487  * @param tc TaskContext.
3488  */
3489 static void
3490 channel_retransmit_message (void *cls,
3491                             const struct GNUNET_SCHEDULER_TaskContext *tc)
3492 {
3493   struct MeshChannelReliability *rel = cls;
3494   struct MeshReliableMessage *copy;
3495   struct MeshPeerQueue *q;
3496   struct MeshChannel *ch;
3497   struct MeshConnection *c;
3498   struct GNUNET_MESH_Data *payload;
3499   struct MeshPeer *hop;
3500   int fwd;
3501
3502   rel->retry_task = GNUNET_SCHEDULER_NO_TASK;
3503   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
3504     return;
3505
3506   ch = rel->ch;
3507   copy = rel->head_sent;
3508   if (NULL == copy)
3509   {
3510     GNUNET_break (0);
3511     return;
3512   }
3513
3514   /* Search the message to be retransmitted in the outgoing queue.
3515    * Check only the queue for the connection that is going to be used,
3516    * if the message is stuck in some other connection's queue we shouldn't
3517    * act upon it:
3518    * - cancelling it and sending the new one doesn't guarantee it's delivery,
3519    *   the old connection could be temporary stalled or the queue happened to
3520    *   be long at time of insertion.
3521    * - not sending the new one could cause terrible delays the old connection
3522    *   is stalled.
3523    */
3524   payload = (struct GNUNET_MESH_Data *) &copy[1];
3525   fwd = (rel == ch->fwd_rel);
3526   c = tunnel_get_connection (ch->t, fwd);
3527   hop = connection_get_hop (c, fwd);
3528   for (q = hop->queue_head; NULL != q; q = q->next)
3529   {
3530     if (ntohs (payload->header.type) == q->type && ch == q->ch)
3531     {
3532       struct GNUNET_MESH_Data *queued_data = q->cls;
3533
3534       if (queued_data->mid == payload->mid)
3535         break;
3536     }
3537   }
3538
3539   /* Message not found in the queue that we are going to use. */
3540   if (NULL == q)
3541   {
3542     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! RETRANSMIT %u\n", copy->mid);
3543
3544     send_prebuilt_message_channel (&payload->header, ch, ch->fwd_rel == rel);
3545     GNUNET_STATISTICS_update (stats, "# data retransmitted", 1, GNUNET_NO);
3546   }
3547   else
3548   {
3549     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! ALREADY IN QUEUE %u\n", copy->mid);
3550   }
3551
3552   rel->retry_timer = GNUNET_TIME_STD_BACKOFF (rel->retry_timer);
3553   rel->retry_task = GNUNET_SCHEDULER_add_delayed (rel->retry_timer,
3554                                                   &channel_retransmit_message,
3555                                                   cls);
3556 }
3557
3558
3559 /**
3560  * Send an ACK to a client if needed.
3561  *
3562  * @param ch Channel this is regarding.
3563  * @param fwd Is this about fwd traffic? (ACk goes the opposite direction).
3564  */
3565 static void
3566 channel_send_client_ack (struct MeshChannel *ch, int fwd)
3567 {
3568   struct MeshClient *c;
3569   int blocked;
3570
3571   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3572               "Channel send client %s ack on %s:%X\n",
3573               fwd ? "FWD" : "BCK", peer2s (ch->t->peer), ch->gid);
3574
3575   /* Check for buffer space */
3576   if (0 >= tunnel_get_buffer (ch->t, fwd))
3577     return;
3578
3579   /* Client to receive the ACK (fwd indicates traffic to be ACK'd) */
3580   c = fwd ? ch->root : ch->dest;
3581
3582   blocked = fwd ? ch->blocked_fwd : ch->blocked_bck;
3583   if (GNUNET_YES == blocked)
3584     send_local_ack (ch, c, fwd);
3585   else
3586     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Client not blocked\n");
3587 }
3588
3589
3590 /**
3591  * Send ACK on one or more connections due to buffer space to the client.
3592  *
3593  * @param ch Channel which has some free buffer space.
3594  * @param buffer Buffer space.
3595  * @param fwd Is this in the FWD direction?
3596  */
3597 static void
3598 channel_send_connection_ack (struct MeshChannel *ch, uint32_t buffer, int fwd)
3599 {
3600   struct MeshTunnel2 *t = ch->t;
3601   struct MeshConnection *c;
3602   struct MeshFlowControl *fc;
3603   uint32_t allowed;
3604   uint32_t to_allow;
3605   unsigned int cs;
3606
3607   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3608               "Channel send connection %s ack on %s:%X\n",
3609               fwd ? "FWD" : "BCK", peer2s (ch->t->peer), ch->gid);
3610
3611   /* Count connections, how many messages are already allowed */
3612   for (cs = 0, allowed = 0, c = t->connection_head; NULL != c; c = c->next)
3613   {
3614     fc = fwd ? &c->fwd_fc : &c->bck_fc;
3615     if (GMC_is_pid_bigger(fc->last_pid_recv, fc->last_ack_sent))
3616     {
3617       GNUNET_break (0);
3618       continue;
3619     }
3620     allowed += fc->last_ack_sent - fc->last_pid_recv;
3621     cs++;
3622   }
3623
3624   /* Make sure there is no overflow */
3625   if (allowed > buffer)
3626   {
3627     GNUNET_break (0);
3628     return;
3629   }
3630
3631   /* Authorize connections to send more data */
3632   to_allow = buffer - allowed;
3633   for (c = t->connection_head; NULL != c && to_allow > 0; c = c->next)
3634   {
3635     fc = fwd ? &c->fwd_fc : &c->bck_fc;
3636     if (fc->last_ack_sent - fc->last_pid_recv > 64 / 3)
3637     {
3638       continue;
3639     }
3640     send_ack (c, fc->last_ack_sent + 1, fwd);
3641     to_allow--;
3642   }
3643
3644   GNUNET_break (to_allow == 0);
3645 }
3646
3647
3648 /**
3649  * Channel was ACK'd by remote peer, mark as ready and cancel retransmission.
3650  *
3651  * @param ch Channel to mark as ready.
3652  * @param fwd Was the CREATE message sent fwd?
3653  */
3654 static void
3655 channel_confirm (struct MeshChannel *ch, int fwd)
3656 {
3657   struct MeshChannelReliability *rel;
3658   struct MeshReliableMessage *copy;
3659   struct MeshReliableMessage *next;
3660
3661   ch->state = MESH_CHANNEL_READY;
3662
3663   rel = fwd ? ch->fwd_rel : ch->bck_rel;
3664   for (copy = rel->head_sent; NULL != copy; copy = next)
3665   {
3666     struct GNUNET_MessageHeader *msg;
3667
3668     next = copy->next;
3669     msg = (struct GNUNET_MessageHeader *) &copy[1];
3670     if (ntohs (msg->type) == GNUNET_MESSAGE_TYPE_MESH_CHANNEL_CREATE)
3671     {
3672       rel_message_free (copy);
3673       /* TODO return? */
3674     }
3675   }
3676 }
3677
3678
3679 /**
3680  * Save a copy to retransmit in case it gets lost.
3681  *
3682  * Initializes all needed callbacks and timers.
3683  *
3684  * @param ch Channel this message goes on.
3685  * @param msg Message to copy.
3686  * @param fwd Is this fwd traffic?
3687  */
3688 static void
3689 channel_save_copy (struct MeshChannel *ch,
3690                    const struct GNUNET_MessageHeader *msg,
3691                    int fwd)
3692 {
3693   struct MeshChannelReliability *rel;
3694   struct MeshReliableMessage *copy;
3695   uint32_t mid;
3696   uint16_t type;
3697   uint16_t size;
3698
3699   rel = fwd ? ch->fwd_rel       : ch->bck_rel;
3700   mid = fwd ? ch->mid_send_fwd  : ch->mid_send_bck;
3701   type = ntohs (msg->type);
3702   size = ntohs (msg->size);
3703
3704   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! SAVE %u\n", mid);
3705   copy = GNUNET_malloc (sizeof (struct MeshReliableMessage) + size);
3706   copy->mid = mid;
3707   copy->timestamp = GNUNET_TIME_absolute_get ();
3708   copy->rel = rel;
3709   copy->type = type;
3710   memcpy (&copy[1], msg, size);
3711   rel->n_sent++;
3712   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " n_sent %u\n", rel->n_sent);
3713   GNUNET_CONTAINER_DLL_insert_tail (rel->head_sent, rel->tail_sent, copy);
3714   if (GNUNET_SCHEDULER_NO_TASK == rel->retry_task)
3715   {
3716     rel->retry_timer =
3717         GNUNET_TIME_relative_multiply (rel->expected_delay,
3718                                         MESH_RETRANSMIT_MARGIN);
3719     rel->retry_task =
3720         GNUNET_SCHEDULER_add_delayed (rel->retry_timer,
3721                                       &channel_retransmit_message,
3722                                       rel);
3723   }
3724 }
3725
3726
3727 /**
3728  * Send keepalive packets for a connection.
3729  *
3730  * @param c Connection to keep alive..
3731  * @param fwd Is this a FWD keepalive? (owner -> dest).
3732  */
3733 static void
3734 connection_keepalive (struct MeshConnection *c, int fwd)
3735 {
3736   struct GNUNET_MESH_ConnectionKeepAlive *msg;
3737   size_t size = sizeof (struct GNUNET_MESH_ConnectionKeepAlive);
3738   char cbuf[size];
3739   uint16_t type;
3740
3741   type = fwd ? GNUNET_MESSAGE_TYPE_MESH_FWD_KEEPALIVE :
3742                GNUNET_MESSAGE_TYPE_MESH_BCK_KEEPALIVE;
3743
3744   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3745               "sending %s keepalive for connection %s[%d]\n",
3746               fwd ? "FWD" : "BCK",
3747               peer2s (c->t->peer),
3748               c->id);
3749
3750   msg = (struct GNUNET_MESH_ConnectionKeepAlive *) cbuf;
3751   msg->header.size = htons (size);
3752   msg->header.type = htons (type);
3753   msg->cid = c->id;
3754
3755   send_prebuilt_message_connection (&msg->header, c, NULL, fwd);
3756 }
3757
3758
3759 /**
3760  * Send CONNECTION_{CREATE/ACK} packets for a connection.
3761  *
3762  * @param c Connection for which to send the message.
3763  * @param fwd If GNUNET_YES, send CREATE, otherwise send ACK.
3764  */
3765 static void
3766 connection_recreate (struct MeshConnection *c, int fwd)
3767 {
3768   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "sending connection recreate\n");
3769   if (fwd)
3770     send_connection_create (c);
3771   else
3772     send_connection_ack (c, GNUNET_NO);
3773 }
3774
3775
3776 /**
3777  * Generic connection timer management.
3778  * Depending on the role of the peer in the connection will send the
3779  * appropriate message (build or keepalive)
3780  *
3781  * @param c Conncetion to maintain.
3782  * @param fwd Is FWD?
3783  */
3784 static void
3785 connection_maintain (struct MeshConnection *c, int fwd)
3786 {
3787   if (MESH_TUNNEL_SEARCHING == c->t->state)
3788   {
3789     /* TODO DHT GET with RO_BART */
3790     return;
3791   }
3792   switch (c->state)
3793   {
3794     case MESH_CONNECTION_NEW:
3795       GNUNET_break (0);
3796     case MESH_CONNECTION_SENT:
3797       connection_recreate (c, fwd);
3798       break;
3799     case MESH_CONNECTION_READY:
3800       connection_keepalive (c, fwd);
3801       break;
3802     default:
3803       break;
3804   }
3805 }
3806
3807
3808 static void
3809 connection_fwd_keepalive (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3810 {
3811   struct MeshConnection *c = cls;
3812
3813   c->fwd_maintenance_task = GNUNET_SCHEDULER_NO_TASK;
3814   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
3815     return;
3816
3817   connection_maintain (c, GNUNET_YES);
3818   c->fwd_maintenance_task = GNUNET_SCHEDULER_add_delayed (refresh_connection_time,
3819                                                           &connection_fwd_keepalive,
3820                                                           c);
3821 }
3822
3823
3824 static void
3825 connection_bck_keepalive (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3826 {
3827   struct MeshConnection *c = cls;
3828
3829   c->bck_maintenance_task = GNUNET_SCHEDULER_NO_TASK;
3830   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
3831     return;
3832
3833   connection_maintain (c, GNUNET_NO);
3834   c->bck_maintenance_task = GNUNET_SCHEDULER_add_delayed (refresh_connection_time,
3835                                                           &connection_bck_keepalive,
3836                                                           c);
3837 }
3838
3839
3840 /**
3841  * Send a message to all peers in this connection that the connection
3842  * is no longer valid.
3843  *
3844  * If some peer should not receive the message, it should be zero'ed out
3845  * before calling this function.
3846  *
3847  * @param c The connection whose peers to notify.
3848  */
3849 static void
3850 connection_send_destroy (struct MeshConnection *c)
3851 {
3852   struct GNUNET_MESH_ConnectionDestroy msg;
3853
3854   msg.header.size = htons (sizeof (msg));
3855   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_TUNNEL_DESTROY);;
3856   msg.cid = c->id;
3857   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3858               "  sending connection destroy for connection %s[%X]\n",
3859               peer2s (c->t->peer),
3860               c->id);
3861
3862   send_prebuilt_message_connection (&msg.header, c, NULL, GNUNET_YES);
3863   send_prebuilt_message_connection (&msg.header, c, NULL, GNUNET_NO);
3864   c->destroy = GNUNET_YES;
3865 }
3866
3867
3868 /**
3869  * Confirm we got a channel create.
3870  *
3871  * @param ch The channel to confirm.
3872  * @param fwd Should we send the ACK fwd?
3873  */
3874 static void
3875 channel_send_ack (struct MeshChannel *ch, int fwd)
3876 {
3877   struct GNUNET_MESH_ChannelManage msg;
3878
3879   msg.header.size = htons (sizeof (msg));
3880   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_CHANNEL_ACK);
3881   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3882               "  sending channel ack for channel %s:%X\n",
3883               peer2s (ch->t->peer),
3884               ch->gid);
3885
3886   msg.chid = htonl (ch->gid);
3887   send_prebuilt_message_channel (&msg.header, ch, fwd);
3888 }
3889
3890
3891 /**
3892  * Send a message to all clients (local and remote) of this channel
3893  * notifying that the channel is no longer valid.
3894  *
3895  * If some peer or client should not receive the message,
3896  * should be zero'ed out before calling this function.
3897  *
3898  * @param ch The channel whose clients to notify.
3899  */
3900 static void
3901 channel_send_destroy (struct MeshChannel *ch)
3902 {
3903   struct GNUNET_MESH_ChannelManage msg;
3904
3905   msg.header.size = htons (sizeof (msg));
3906   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_CHANNEL_DESTROY);
3907   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3908               "  sending channel destroy for channel %s:%X\n",
3909               peer2s (ch->t->peer),
3910               ch->gid);
3911
3912   if (NULL != ch->root)
3913   {
3914     msg.chid = htonl (ch->lid_root);
3915     send_local_channel_destroy (ch, GNUNET_NO);
3916   }
3917   else
3918   {
3919     msg.chid = htonl (ch->gid);
3920     send_prebuilt_message_channel (&msg.header, ch, GNUNET_NO);
3921   }
3922
3923   if (NULL != ch->dest)
3924   {
3925     msg.chid = htonl (ch->lid_dest);
3926     send_local_channel_destroy (ch, GNUNET_YES);
3927   }
3928   else
3929   {
3930     msg.chid = htonl (ch->gid);
3931     send_prebuilt_message_channel (&msg.header, ch, GNUNET_YES);
3932   }
3933 }
3934
3935
3936 /**
3937  * Create a tunnel.
3938  */
3939 static struct MeshTunnel2 *
3940 tunnel_new (void)
3941 {
3942   struct MeshTunnel2 *t;
3943
3944   t = GNUNET_new (struct MeshTunnel2);
3945   t->next_chid = 0;
3946   t->next_local_chid = GNUNET_MESH_LOCAL_CHANNEL_ID_SERV;
3947 //   if (GNUNET_OK !=
3948 //       GNUNET_CONTAINER_multihashmap_put (tunnels, tid, t,
3949 //                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
3950 //   {
3951 //     GNUNET_break (0);
3952 //     tunnel_destroy (t);
3953 //     return NULL;
3954 //   }
3955
3956 //   char salt[] = "salt";
3957 //   GNUNET_CRYPTO_kdf (&t->e_key, sizeof (struct GNUNET_CRYPTO_AesSessionKey),
3958 //                      salt, sizeof (salt),
3959 //                      &t->e_key, sizeof (struct GNUNET_CRYPTO_AesSessionKey),
3960 //                      &my_full_id, sizeof (struct GNUNET_PeerIdentity),
3961 //                      GNUNET_PEER_resolve2 (t->peer->id), sizeof (struct GNUNET_PeerIdentity),
3962 //                      NULL);
3963 //   GNUNET_CRYPTO_kdf (&t->d_key, sizeof (struct GNUNET_CRYPTO_AesSessionKey),
3964 //                      salt, sizeof (salt),
3965 //                      &t->d_key, sizeof (struct GNUNET_CRYPTO_AesSessionKey),
3966 //                      GNUNET_PEER_resolve2 (t->peer->id), sizeof (struct GNUNET_PeerIdentity),
3967 //                      &my_full_id, sizeof (struct GNUNET_PeerIdentity),
3968 //                      NULL);
3969
3970   return t;
3971 }
3972
3973
3974 /**
3975  * Add a connection to a tunnel.
3976  *
3977  * @param t Tunnel.
3978  * @param c Connection.
3979  */
3980 static void
3981 tunnel_add_connection (struct MeshTunnel2 *t, struct MeshConnection *c)
3982 {
3983   c->t = t;
3984   GNUNET_CONTAINER_DLL_insert_tail (t->connection_head, t->connection_tail, c);
3985 }
3986
3987
3988 /**
3989  * Initialize a Flow Control structure to the initial state.
3990  * 
3991  * @param fc Flow Control structure to initialize.
3992  */
3993 static void
3994 fc_init (struct MeshFlowControl *fc)
3995 {
3996   fc->next_pid = 0;
3997   fc->last_pid_sent = (uint32_t) -1; /* Next (expected) = 0 */
3998   fc->last_pid_recv = (uint32_t) -1;
3999   fc->last_ack_sent = (uint32_t) 0;
4000   fc->last_ack_recv = (uint32_t) 0;
4001   fc->poll_task = GNUNET_SCHEDULER_NO_TASK;
4002   fc->poll_time = GNUNET_TIME_UNIT_SECONDS;
4003   fc->queue_n = 0;
4004   fc->queue_max = (max_msgs_queue / max_connections) + 1;
4005 }
4006
4007
4008 static struct MeshConnection *
4009 connection_new (const struct GNUNET_HashCode *cid)
4010 {
4011   struct MeshConnection *c;
4012
4013   c = GNUNET_new (struct MeshConnection);
4014   c->id = *cid;
4015   GNUNET_CONTAINER_multihashmap_put (connections, &c->id, c,
4016                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
4017   fc_init (&c->fwd_fc);
4018   fc_init (&c->bck_fc);
4019   c->fwd_fc.c = c;
4020   c->bck_fc.c = c;
4021
4022   return c;
4023 }
4024
4025
4026 /**
4027  * Find a connection.
4028  *
4029  * @param cid Connection ID.
4030  */
4031 static struct MeshConnection *
4032 connection_get (const struct GNUNET_HashCode *cid)
4033 {
4034   return GNUNET_CONTAINER_multihashmap_get (connections, cid);
4035 }
4036
4037
4038 static void
4039 connection_destroy (struct MeshConnection *c)
4040 {
4041   struct MeshPeer *peer;
4042
4043   if (NULL == c)
4044     return;
4045
4046   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "destroying connection %s[%X]\n",
4047               peer2s (c->t->peer),
4048               c->id);
4049
4050   /* Cancel all traffic */
4051   connection_cancel_queues (c, GNUNET_YES);
4052   connection_cancel_queues (c, GNUNET_NO);
4053
4054   /* Cancel maintainance task (keepalive/timeout) */
4055   if (GNUNET_SCHEDULER_NO_TASK != c->fwd_maintenance_task)
4056     GNUNET_SCHEDULER_cancel (c->fwd_maintenance_task);
4057   if (GNUNET_SCHEDULER_NO_TASK != c->bck_maintenance_task)
4058     GNUNET_SCHEDULER_cancel (c->bck_maintenance_task);
4059
4060   /* Deregister from neighbors */
4061   peer = connection_get_next_hop (c);
4062   if (NULL != peer)
4063     GNUNET_CONTAINER_multihashmap_remove (peer->connections, &c->id, c);
4064   peer = connection_get_prev_hop (c);
4065   if (NULL != peer)
4066     GNUNET_CONTAINER_multihashmap_remove (peer->connections, &c->id, c);
4067
4068   /* Delete */
4069   GNUNET_STATISTICS_update (stats, "# connections", -1, GNUNET_NO);
4070   GNUNET_CONTAINER_DLL_remove (c->t->connection_head, c->t->connection_tail, c);
4071   GNUNET_free (c);
4072 }
4073
4074
4075 static void
4076 tunnel_destroy (struct MeshTunnel2 *t)
4077 {
4078   struct MeshConnection *c;
4079   struct MeshConnection *next;
4080
4081   if (NULL == t)
4082     return;
4083
4084   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "destroying tunnel %s\n",
4085               peer2s (t->peer));
4086
4087 //   if (GNUNET_YES != GNUNET_CONTAINER_multihashmap_remove (tunnels, &t->id, t))
4088 //     GNUNET_break (0);
4089
4090   for (c = t->connection_head; NULL != c; c = next)
4091   {
4092     next = c->next;
4093     connection_destroy (c);
4094   }
4095
4096   GNUNET_STATISTICS_update (stats, "# tunnels", -1, GNUNET_NO);
4097
4098   GNUNET_free (t);
4099 }
4100
4101
4102 /**
4103  * Tunnel is empty: destroy it.
4104  *
4105  * Notifies all connections about the destruction.
4106  *
4107  * @param t Tunnel to destroy. 
4108  */
4109 static void
4110 tunnel_destroy_empty (struct MeshTunnel2 *t)
4111 {
4112   struct MeshConnection *c;
4113
4114   for (c = t->connection_head; NULL != c; c = c->next)
4115   {
4116     if (GNUNET_NO == c->destroy)
4117       connection_send_destroy (c);
4118   }
4119
4120   if (0 == t->pending_messages)
4121     tunnel_destroy (t);
4122   else
4123     t->destroy = GNUNET_YES;
4124 }
4125
4126
4127 /**
4128  * Destroy tunnel if empty (no more channels).
4129  *
4130  * @param t Tunnel to destroy if empty.
4131  */
4132 static void
4133 tunnel_destroy_if_empty (struct MeshTunnel2 *t)
4134 {
4135   if (NULL != t->channel_head)
4136     return;
4137
4138   tunnel_destroy_empty (t);
4139 }
4140
4141
4142 /**
4143  * Destroy a channel and free all resources.
4144  * 
4145  * @param ch Channel to destroy.
4146  */
4147 static void
4148 channel_destroy (struct MeshChannel *ch)
4149 {
4150   struct MeshClient *c;
4151
4152   if (NULL == ch)
4153     return;
4154
4155   c = ch->root;
4156   if (NULL != c)
4157   {
4158     if (GNUNET_YES != GNUNET_CONTAINER_multihashmap32_remove (c->own_channels,
4159                                                               ch->lid_root, ch))
4160     {
4161       GNUNET_break (0);
4162     }
4163   }
4164
4165   c = ch->dest;
4166   if (NULL != c)
4167   {
4168     if (GNUNET_YES !=
4169         GNUNET_CONTAINER_multihashmap32_remove (c->incoming_channels,
4170                                                 ch->lid_dest, ch))
4171     {
4172       GNUNET_break (0);
4173     }
4174   }
4175
4176   channel_rel_free_all (ch->fwd_rel);
4177   channel_rel_free_all (ch->bck_rel);
4178
4179   GNUNET_CONTAINER_DLL_remove (ch->t->channel_head, ch->t->channel_tail, ch);
4180   GNUNET_STATISTICS_update (stats, "# channels", -1, GNUNET_NO);
4181
4182   GNUNET_free (ch);
4183 }
4184
4185 /**
4186  * Create a new channel.
4187  *
4188  * @param t Tunnel this channel is in.
4189  * @param owner Client that owns the channel, NULL for foreign channels.
4190  * @param lid_root Local ID for root client.
4191  *
4192  * @return A new initialized channel. NULL on error.
4193  */
4194 static struct MeshChannel *
4195 channel_new (struct MeshTunnel2 *t,
4196              struct MeshClient *owner, MESH_ChannelNumber lid_root)
4197 {
4198   struct MeshChannel *ch;
4199
4200   ch = GNUNET_new (struct MeshChannel);
4201   ch->root = owner;
4202   ch->lid_root = lid_root;
4203   ch->t = t;
4204   ch->blocked_fwd = GNUNET_YES;
4205   ch->blocked_bck = GNUNET_YES;
4206
4207   GNUNET_CONTAINER_DLL_insert (t->channel_head, t->channel_tail, ch);
4208
4209   GNUNET_STATISTICS_update (stats, "# channels", 1, GNUNET_NO);
4210
4211   if (NULL != owner)
4212   {
4213     while (NULL != channel_get (t, t->next_chid))
4214       t->next_chid = (t->next_chid + 1) & ~GNUNET_MESH_LOCAL_CHANNEL_ID_CLI;
4215     ch->gid = t->next_chid;
4216     t->next_chid = (t->next_chid + 1) & ~GNUNET_MESH_LOCAL_CHANNEL_ID_CLI;
4217
4218     if(GNUNET_OK !=
4219        GNUNET_CONTAINER_multihashmap32_put (owner->own_channels, lid_root, ch,
4220                                            GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
4221     {
4222       GNUNET_break (0);
4223       channel_destroy (ch);
4224       GNUNET_SERVER_receive_done (owner->handle, GNUNET_SYSERR);
4225       return NULL;
4226     }
4227   }
4228
4229   return ch;
4230 }
4231
4232
4233 /**
4234  * Set options in a channel, extracted from a bit flag field
4235  * 
4236  * @param ch Channel to set options to.
4237  * @param options Bit array in host byte order.
4238  */
4239 static void
4240 channel_set_options (struct MeshChannel *ch, uint32_t options)
4241 {
4242   ch->nobuffer = (options & GNUNET_MESH_OPTION_NOBUFFER) != 0 ?
4243                  GNUNET_YES : GNUNET_NO;
4244   ch->reliable = (options & GNUNET_MESH_OPTION_RELIABLE) != 0 ?
4245                  GNUNET_YES : GNUNET_NO;
4246 }
4247
4248
4249 /**
4250  * Iterator for deleting each channel whose client endpoint disconnected.
4251  *
4252  * @param cls Closure (client that has disconnected).
4253  * @param key The local channel id (used to access the hashmap).
4254  * @param value The value stored at the key (channel to destroy).
4255  *
4256  * @return GNUNET_OK, keep iterating.
4257  */
4258 static int
4259 channel_destroy_iterator (void *cls,
4260                           uint32_t key,
4261                           void *value)
4262 {
4263   struct MeshChannel *ch = value;
4264   struct MeshClient *c = cls;
4265   struct MeshTunnel2 *t;
4266
4267   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4268               " Channel %X (%X / %X) destroy, due to client %u shutdown.\n",
4269               ch->gid, ch->lid_root, ch->lid_dest, c->id);
4270
4271   if (c == ch->dest)
4272   {
4273     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Client %u is destination.\n", c->id);
4274     ch->dest = NULL;
4275   }
4276   if (c == ch->root)
4277   {
4278     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Client %u is owner.\n", c->id);
4279     ch->root = NULL;
4280   }
4281
4282   t = ch->t;
4283   channel_send_destroy (ch);
4284   channel_destroy (ch);
4285   tunnel_destroy_if_empty (t);
4286
4287   return GNUNET_OK;
4288 }
4289
4290
4291 /**
4292  * Remove client's ports from the global hashmap on disconnect.
4293  *
4294  * @param cls Closure (unused).
4295  * @param key Port.
4296  * @param value Client structure.
4297  *
4298  * @return GNUNET_OK, keep iterating.
4299  */
4300 static int
4301 client_release_ports (void *cls,
4302                       uint32_t key,
4303                       void *value)
4304 {
4305   int res;
4306
4307   res = GNUNET_CONTAINER_multihashmap32_remove (ports, key, value);
4308   if (GNUNET_YES != res)
4309   {
4310     GNUNET_break (0);
4311     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4312                 "Port %u by client %p was not registered.\n",
4313                 key, value);
4314   }
4315   return GNUNET_OK;
4316 }
4317
4318
4319 /**
4320  * Timeout function due to lack of keepalive/traffic from the owner.
4321  * Destroys connection if called.
4322  *
4323  * @param cls Closure (connection to destroy).
4324  * @param tc TaskContext.
4325  */
4326 static void
4327 connection_fwd_timeout (void *cls,
4328                         const struct GNUNET_SCHEDULER_TaskContext *tc)
4329 {
4330   struct MeshConnection *c = cls;
4331
4332   c->fwd_maintenance_task = GNUNET_SCHEDULER_NO_TASK;
4333   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
4334     return;
4335   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4336               "Connection %s[%X] FWD timed out. Destroying.\n",
4337               peer2s (c->t->peer),
4338               c->id);
4339
4340   if (connection_is_origin (c, GNUNET_YES)) /* If local, leave. */
4341     return;
4342
4343   connection_destroy (c);
4344 }
4345
4346
4347 /**
4348  * Timeout function due to lack of keepalive/traffic from the destination.
4349  * Destroys connection if called.
4350  *
4351  * @param cls Closure (connection to destroy).
4352  * @param tc TaskContext
4353  */
4354 static void
4355 connection_bck_timeout (void *cls,
4356                         const struct GNUNET_SCHEDULER_TaskContext *tc)
4357 {
4358   struct MeshConnection *c = cls;
4359
4360   c->bck_maintenance_task = GNUNET_SCHEDULER_NO_TASK;
4361   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
4362     return;
4363
4364   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4365               "Connection %s[%X] FWD timed out. Destroying.\n",
4366               peer2s (c->t->peer),
4367               c->id);
4368
4369   if (connection_is_origin (c, GNUNET_NO)) /* If local, leave. */
4370     return;
4371
4372   connection_destroy (c);
4373 }
4374
4375
4376 /**
4377  * Resets the connection timeout task, some other message has done the
4378  * task's job.
4379  * - For the first peer on the direction this means to send
4380  *   a keepalive or a path confirmation message (either create or ACK).
4381  * - For all other peers, this means to destroy the connection,
4382  *   due to lack of activity.
4383  * Starts the tiemout if no timeout was running (connection just created).
4384  *
4385  * @param c Connection whose timeout to reset.
4386  * @param fwd Is this forward?
4387  *
4388  * TODO use heap to improve efficiency of scheduler.
4389  */
4390 static void
4391 connection_reset_timeout (struct MeshConnection *c, int fwd)
4392 {
4393   GNUNET_SCHEDULER_TaskIdentifier *ti;
4394   GNUNET_SCHEDULER_Task f;
4395
4396   ti = fwd ? &c->fwd_maintenance_task : &c->bck_maintenance_task;
4397
4398   if (GNUNET_SCHEDULER_NO_TASK != *ti)
4399     GNUNET_SCHEDULER_cancel (*ti);
4400
4401   if (connection_is_origin (c, fwd)) /* Endpoint */
4402   {
4403     f  = fwd ? &connection_fwd_keepalive : &connection_bck_keepalive;
4404     *ti = GNUNET_SCHEDULER_add_delayed (refresh_connection_time, f, c);
4405   }
4406   else /* Relay */
4407   {
4408     struct GNUNET_TIME_Relative delay;
4409
4410     delay = GNUNET_TIME_relative_multiply (refresh_connection_time, 4);
4411     f  = fwd ? &connection_fwd_timeout : &connection_bck_timeout;
4412     *ti = GNUNET_SCHEDULER_add_delayed (delay, f, c);
4413   }
4414 }
4415
4416
4417 /**
4418  * Iterator to notify all connections of a broken link. Mark connections
4419  * to destroy after all traffic has been sent.
4420  *
4421  * @param cls Closure (peer disconnected).
4422  * @param key Current key code (tid).
4423  * @param value Value in the hash map (connection).
4424  *
4425  * @return GNUNET_YES if we should continue to iterate,
4426  *         GNUNET_NO if not.
4427  */
4428 static int
4429 connection_broken (void *cls,
4430                    const struct GNUNET_HashCode *key,
4431                    void *value)
4432 {
4433   struct MeshPeer *peer = cls;
4434   struct MeshConnection *c = value;
4435   struct GNUNET_MESH_ConnectionBroken msg;
4436   int fwd;
4437
4438   fwd = peer == connection_get_prev_hop (c);
4439   connection_cancel_queues (c, !fwd);
4440
4441   msg.header.size = htons (sizeof (struct GNUNET_MESH_ConnectionBroken));
4442   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_CONNECTION_BROKEN);
4443   msg.cid = c->id;
4444   msg.peer1 = my_full_id;
4445   msg.peer2 = *GNUNET_PEER_resolve2 (peer->id);
4446   send_prebuilt_message_connection (&msg.header, c, NULL, fwd);
4447   c->destroy = GNUNET_YES;
4448
4449   return GNUNET_YES;
4450 }
4451
4452 /******************************************************************************/
4453 /****************      MESH NETWORK HANDLER HELPERS     ***********************/
4454 /******************************************************************************/
4455
4456 /**
4457  * Free a transmission that was already queued with all resources
4458  * associated to the request.
4459  *
4460  * @param queue Queue handler to cancel.
4461  * @param clear_cls Is it necessary to free associated cls?
4462  */
4463 static void
4464 queue_destroy (struct MeshPeerQueue *queue, int clear_cls)
4465 {
4466   struct MeshPeer *peer;
4467   struct MeshFlowControl *fc;
4468   int fwd;
4469
4470   fwd = queue->fwd;
4471   peer = queue->peer;
4472   GNUNET_assert (NULL != queue->c);
4473   fc = fwd ? &queue->c->fwd_fc : &queue->c->bck_fc;
4474
4475   if (GNUNET_YES == clear_cls)
4476   {
4477     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   queue destroy type %s\n",
4478                 GNUNET_MESH_DEBUG_M2S (queue->type));
4479     switch (queue->type)
4480     {
4481       case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_DESTROY:
4482       case GNUNET_MESSAGE_TYPE_MESH_TUNNEL_DESTROY:
4483         GNUNET_log (GNUNET_ERROR_TYPE_INFO, "destroying a DESTROY message\n");
4484         GNUNET_break (GNUNET_YES == queue->c->destroy);
4485         /* fall through */
4486       case GNUNET_MESSAGE_TYPE_MESH_FWD:
4487       case GNUNET_MESSAGE_TYPE_MESH_BCK:
4488       case GNUNET_MESSAGE_TYPE_MESH_ACK:
4489       case GNUNET_MESSAGE_TYPE_MESH_POLL:
4490       case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_ACK:
4491       case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_CREATE:
4492         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   prebuilt message\n");;
4493         GNUNET_free_non_null (queue->cls);
4494         break;
4495
4496       default:
4497         GNUNET_break (0);
4498         GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "   type %s unknown!\n",
4499                     GNUNET_MESH_DEBUG_M2S (queue->type));
4500     }
4501
4502   }
4503   GNUNET_CONTAINER_DLL_remove (peer->queue_head, peer->queue_tail, queue);
4504
4505   fc->queue_n--;
4506   peer->queue_n--;
4507   if (NULL != queue->c)
4508   {
4509     queue->c->pending_messages--;
4510     if (NULL != queue->c->t)
4511     {
4512       queue->c->t->pending_messages--;
4513     }
4514   }
4515
4516   GNUNET_free (queue);
4517 }
4518
4519
4520 static size_t
4521 queue_send (void *cls, size_t size, void *buf)
4522 {
4523   struct MeshPeer *peer = cls;
4524   struct MeshFlowControl *fc;
4525   struct MeshConnection *c;
4526   struct GNUNET_MessageHeader *msg;
4527   struct MeshPeerQueue *queue;
4528   struct MeshTunnel2 *t;
4529   const struct GNUNET_PeerIdentity *dst_id;
4530   size_t data_size;
4531   uint32_t pid;
4532   uint16_t type;
4533   int fwd;
4534
4535   peer->core_transmit = NULL;
4536   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* Queue send\n");
4537
4538   if (NULL == buf || 0 == size)
4539   {
4540     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* Buffer size 0.\n");
4541     return 0;
4542   }
4543
4544   /* Initialize */
4545   queue = peer_get_first_message (peer);
4546   if (NULL == queue)
4547   {
4548     GNUNET_break (0); /* Core tmt_rdy should've been canceled */
4549     return 0;
4550   }
4551   c = queue->c;
4552   fwd = queue->fwd;
4553   fc = fwd ? &c->fwd_fc : &c->bck_fc;
4554
4555
4556   dst_id = GNUNET_PEER_resolve2 (peer->id);
4557   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*   towards %s\n", GNUNET_i2s (dst_id));
4558   /* Check if buffer size is enough for the message */
4559   if (queue->size > size)
4560   {
4561       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*   not enough room, reissue\n");
4562       peer->core_transmit =
4563           GNUNET_CORE_notify_transmit_ready (core_handle,
4564                                              GNUNET_NO,
4565                                              0,
4566                                              GNUNET_TIME_UNIT_FOREVER_REL,
4567                                              dst_id,
4568                                              queue->size,
4569                                              &queue_send,
4570                                              peer);
4571       return 0;
4572   }
4573   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*   size ok\n");
4574
4575   t = (NULL != c) ? c->t : NULL;
4576   type = 0;
4577
4578   /* Fill buf */
4579   switch (queue->type)
4580   {
4581     case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_DESTROY:
4582     case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_BROKEN:
4583     case GNUNET_MESSAGE_TYPE_MESH_FWD:
4584     case GNUNET_MESSAGE_TYPE_MESH_BCK:
4585     case GNUNET_MESSAGE_TYPE_MESH_ACK:
4586     case GNUNET_MESSAGE_TYPE_MESH_POLL:
4587       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4588                   "*   raw: %s\n",
4589                   GNUNET_MESH_DEBUG_M2S (queue->type));
4590       data_size = send_core_data_raw (queue->cls, size, buf);
4591       msg = (struct GNUNET_MessageHeader *) buf;
4592       type = ntohs (msg->type);
4593       break;
4594     case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_CREATE:
4595       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*   path create\n");
4596       if (connection_is_origin (c, GNUNET_YES))
4597         data_size = send_core_connection_create (queue->c, size, buf);
4598       else
4599         data_size = send_core_data_raw (queue->cls, size, buf);
4600       break;
4601     case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_ACK:
4602       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*   path ack\n");
4603       if (connection_is_origin (c, GNUNET_NO))
4604         data_size = send_core_connection_ack (queue->c, size, buf);
4605       else
4606         data_size = send_core_data_raw (queue->cls, size, buf);
4607       break;
4608     case GNUNET_MESSAGE_TYPE_MESH_DATA:
4609     case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_CREATE:
4610     case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_DESTROY:
4611       /* This should be encapsulted */
4612       GNUNET_break (0);
4613       break;
4614     default:
4615       GNUNET_break (0);
4616       GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "*   type unknown: %u\n",
4617                   queue->type);
4618       data_size = 0;
4619   }
4620
4621   if (0 < drop_percent &&
4622       GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, 101) < drop_percent)
4623   {
4624     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4625                 "Dropping message of type %s\n",
4626                 GNUNET_MESH_DEBUG_M2S (queue->type));
4627     data_size = 0;
4628   }
4629
4630   /* Send ACK if needed, after accounting for sent ID in fc->queue_n */
4631   switch (type)
4632   {
4633     case GNUNET_MESSAGE_TYPE_MESH_FWD:
4634     case GNUNET_MESSAGE_TYPE_MESH_BCK:
4635       pid = ntohl ( ((struct GNUNET_MESH_Encrypted *) buf)->pid );
4636       fc->last_pid_sent = pid;
4637       if (NULL != queue->ch)
4638         channel_send_client_ack (queue->ch, fwd);
4639       else
4640         connection_send_ack (c, fwd);
4641       break;
4642     default:
4643       break;
4644   }
4645
4646   /* Free queue, but cls was freed by send_core_* */
4647   queue_destroy (queue, GNUNET_NO);
4648
4649   /* If more data in queue, send next */
4650   queue = peer_get_first_message (peer);
4651   if (NULL != queue)
4652   {
4653     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*   more data!\n");
4654     if (NULL == peer->core_transmit) {
4655       peer->core_transmit =
4656           GNUNET_CORE_notify_transmit_ready(core_handle,
4657                                             0,
4658                                             0,
4659                                             GNUNET_TIME_UNIT_FOREVER_REL,
4660                                             dst_id,
4661                                             queue->size,
4662                                             &queue_send,
4663                                             peer);
4664     }
4665     else
4666     {
4667       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4668                   "*   tmt rdy called somewhere else\n");
4669     }
4670     if (GNUNET_SCHEDULER_NO_TASK == fc->poll_task)
4671     {
4672       GNUNET_log (GNUNET_ERROR_TYPE_INFO, "*   %s starting poll timeout\n");
4673       fc->poll_task =
4674           GNUNET_SCHEDULER_add_delayed (fc->poll_time, &connection_poll, fc);
4675     }
4676   }
4677   else
4678   {
4679     if (GNUNET_SCHEDULER_NO_TASK != fc->poll_task)
4680     {
4681       GNUNET_SCHEDULER_cancel (fc->poll_task);
4682       fc->poll_task = GNUNET_SCHEDULER_NO_TASK;
4683     }
4684   }
4685   if (NULL != c)
4686   {
4687     c->pending_messages--;
4688     if (GNUNET_YES == c->destroy && 0 == c->pending_messages)
4689     {
4690       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*  destroying connection!\n");
4691       connection_destroy (c);
4692     }
4693   }
4694
4695   if (NULL != t)
4696   {
4697     t->pending_messages--;
4698     if (GNUNET_YES == t->destroy && 0 == t->pending_messages)
4699     {
4700       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*  destroying tunnel!\n");
4701       tunnel_destroy (t);
4702     }
4703   }
4704   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*  Return %d\n", data_size);
4705   return data_size;
4706 }
4707
4708
4709 static void
4710 queue_add (void *cls, uint16_t type, size_t size,
4711            struct MeshConnection *c,
4712            struct MeshChannel *ch,
4713            int fwd)
4714 {
4715   struct MeshPeerQueue *queue;
4716   struct MeshFlowControl *fc;
4717   struct MeshPeer *peer;
4718   int priority;
4719
4720   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4721               "queue add %s %s (%u) on c %p, ch %p\n",
4722               fwd ? "FWD" : "BCK",  GNUNET_MESH_DEBUG_M2S (type), size, c, ch);
4723   GNUNET_assert (NULL != c);
4724
4725   fc   = fwd ? &c->fwd_fc : &c->bck_fc;
4726   peer = fwd ? connection_get_next_hop (c) : connection_get_prev_hop (c);
4727
4728   if (NULL == fc)
4729   {
4730     GNUNET_break (0);
4731     return;
4732   }
4733
4734   priority = 0;
4735
4736   if (GNUNET_MESSAGE_TYPE_MESH_POLL == type ||
4737       GNUNET_MESSAGE_TYPE_MESH_ACK == type)
4738     priority = 100;
4739
4740   if (NULL != ch &&
4741       ( (NULL != ch->root && GNUNET_MESSAGE_TYPE_MESH_FWD == type) ||
4742         (NULL != ch->dest && GNUNET_MESSAGE_TYPE_MESH_BCK == type) ))
4743     priority = 50;
4744
4745   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "priority %d\n", priority);
4746   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "fc %p\n", fc);
4747   if (fc->queue_n >= fc->queue_max && 0 == priority)
4748   {
4749     GNUNET_STATISTICS_update (stats, "# messages dropped (buffer full)",
4750                               1, GNUNET_NO);
4751     GNUNET_break (0);
4752     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4753                 "queue full: %u/%u\n",
4754                 fc->queue_n, fc->queue_max);
4755     return; /* Drop this message */
4756   }
4757
4758   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "pid %u\n", fc->last_pid_sent);
4759   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "ack %u\n", fc->last_ack_recv);
4760   if (GMC_is_pid_bigger (fc->last_pid_sent + 1, fc->last_ack_recv) &&
4761       GNUNET_SCHEDULER_NO_TASK == fc->poll_task)
4762   {
4763     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4764                 "no buffer space (%u > %u): starting poll\n",
4765                 fc->last_pid_sent + 1, fc->last_ack_recv);
4766     fc->poll_task = GNUNET_SCHEDULER_add_delayed (fc->poll_time,
4767                                                   &connection_poll,
4768                                                   fc);
4769   }
4770   queue = GNUNET_malloc (sizeof (struct MeshPeerQueue));
4771   queue->cls = cls;
4772   queue->type = type;
4773   queue->size = size;
4774   queue->peer = peer;
4775   queue->c = c;
4776   queue->ch = ch;
4777   queue->fwd = fwd;
4778   if (100 <= priority)
4779     GNUNET_CONTAINER_DLL_insert (peer->queue_head, peer->queue_tail, queue);
4780   else
4781     GNUNET_CONTAINER_DLL_insert_tail (peer->queue_head, peer->queue_tail, queue);
4782
4783   if (NULL == peer->core_transmit)
4784   {
4785     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4786                 "calling core tmt rdy towards %s\n",
4787                 peer2s (peer));
4788     peer->core_transmit =
4789         GNUNET_CORE_notify_transmit_ready (core_handle,
4790                                            0,
4791                                            0,
4792                                            GNUNET_TIME_UNIT_FOREVER_REL,
4793                                            GNUNET_PEER_resolve2 (peer->id),
4794                                            size,
4795                                            &queue_send,
4796                                            peer);
4797   }
4798   else
4799   {
4800     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4801                 "core tmt rdy towards %s already called\n",
4802                 peer2s (peer));
4803
4804   }
4805   c->pending_messages++;
4806   c->t->pending_messages++;
4807   fc->queue_n++;
4808   peer->queue_n++;
4809 }
4810
4811
4812 /******************************************************************************/
4813 /********************      MESH NETWORK HANDLERS     **************************/
4814 /******************************************************************************/
4815
4816
4817 /**
4818  * Generic handler for mesh network payload traffic.
4819  *
4820  * @param t Tunnel on which we got this message.
4821  * @param message Unencryted data message.
4822  * @param fwd Is this FWD traffic? GNUNET_YES : GNUNET_NO;
4823  *
4824  * @return GNUNET_OK to keep the connection open,
4825  *         GNUNET_SYSERR to close it (signal serious error)
4826  */
4827 static int
4828 handle_data (struct MeshTunnel2 *t, const struct GNUNET_MESH_Data *msg, int fwd)
4829 {
4830   struct MeshChannelReliability *rel;
4831   struct MeshChannel *ch;
4832   struct MeshClient *c;
4833   uint32_t mid;
4834   uint32_t *mid_recv;
4835   uint16_t type;
4836   size_t size;
4837
4838   /* Check size */
4839   size = ntohs (msg->header.size);
4840   if (size <
4841       sizeof (struct GNUNET_MESH_Data) +
4842       sizeof (struct GNUNET_MessageHeader))
4843   {
4844     GNUNET_break (0);
4845     return GNUNET_OK;
4846   }
4847   type = ntohs (msg->header.type);
4848   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a %s message\n",
4849               GNUNET_MESH_DEBUG_M2S (type));
4850   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " payload of type %s\n",
4851               GNUNET_MESH_DEBUG_M2S (ntohs (msg[1].header.type)));
4852
4853   /* Check channel */
4854   ch = channel_get (t, ntohl (msg->chid));
4855   if (NULL == ch)
4856   {
4857     GNUNET_STATISTICS_update (stats, "# data on unknown channel", 1, GNUNET_NO);
4858     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel unknown\n");
4859     return GNUNET_OK;
4860   }
4861
4862   /*  Initialize FWD/BCK data */
4863   c        = fwd ? ch->dest          : ch->root;
4864   rel      = fwd ? ch->bck_rel       : ch->fwd_rel;
4865   mid_recv = fwd ? &ch->mid_recv_fwd : &ch->mid_recv_bck;
4866
4867   if (NULL == c)
4868   {
4869     GNUNET_break (0);
4870     return GNUNET_OK;
4871   }
4872
4873   tunnel_change_state (t, MESH_TUNNEL_READY);
4874
4875   GNUNET_STATISTICS_update (stats, "# data received", 1, GNUNET_NO);
4876
4877   mid = ntohl (msg->mid);
4878   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " mid %u\n", mid);
4879
4880   if (GNUNET_NO == ch->reliable ||
4881       ( !GMC_is_pid_bigger (*mid_recv, mid) &&
4882         GMC_is_pid_bigger (*mid_recv + 64, mid) ) )
4883   {
4884     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! RECV %u\n", mid);
4885     if (GNUNET_YES == ch->reliable)
4886     {
4887       /* Is this the exact next expected messasge? */
4888       if (mid == *mid_recv)
4889       {
4890         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "as expected\n");
4891         *mid_recv = *mid_recv + 1;
4892         channel_send_client_data (ch, msg, fwd);
4893         channel_send_client_buffered_data (ch, c, rel);
4894       }
4895       else
4896       {
4897         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "save for later\n");
4898         channel_rel_add_buffered_data (msg, rel);
4899       }
4900     }
4901     else /* Tunnel unreliable, send to clients directly */
4902     {
4903       channel_send_client_data (ch, msg, fwd);
4904     }
4905   }
4906   else
4907   {
4908     GNUNET_break_op (0);
4909     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4910                 " MID %u not expected (%u - %u), dropping!\n",
4911                 mid, *mid_recv, *mid_recv + 64);
4912   }
4913
4914   channel_send_data_ack (ch, fwd);
4915   return GNUNET_OK;
4916 }
4917
4918 /**
4919  * Handler for mesh network traffic end-to-end ACKs.
4920  *
4921  * @param t Tunnel on which we got this message.
4922  * @param message Data message.
4923  * @param fwd Is this a fwd ACK? (dest->orig)
4924  *
4925  * @return GNUNET_OK to keep the connection open,
4926  *         GNUNET_SYSERR to close it (signal serious error)
4927  */
4928 static int
4929 handle_data_ack (struct MeshTunnel2 *t,
4930                  const struct GNUNET_MESH_DataACK *msg, int fwd)
4931 {
4932   struct MeshChannelReliability *rel;
4933   struct MeshReliableMessage *copy;
4934   struct MeshReliableMessage *next;
4935   struct MeshChannel *ch;
4936   uint32_t ack;
4937   uint16_t type;
4938   int work;
4939
4940   type = ntohs (msg->header.type);
4941   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a %s message!\n",
4942               GNUNET_MESH_DEBUG_M2S (type));
4943   ch = channel_get (t, ntohl (msg->chid));
4944   if (NULL == ch)
4945   {
4946     GNUNET_STATISTICS_update (stats, "# ack on unknown channel", 1, GNUNET_NO);
4947     return GNUNET_OK;
4948   }
4949   ack = ntohl (msg->mid);
4950   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! %s ACK %u\n",
4951               (GNUNET_YES == fwd) ? "FWD" : "BCK", ack);
4952
4953   if (GNUNET_YES == fwd)
4954   {
4955     rel = ch->fwd_rel;
4956   }
4957   else
4958   {
4959     rel = ch->bck_rel;
4960   }
4961   if (NULL == rel)
4962   {
4963     return GNUNET_OK;
4964   }
4965
4966   for (work = GNUNET_NO, copy = rel->head_sent; copy != NULL; copy = next)
4967   {
4968     if (GMC_is_pid_bigger (copy->mid, ack))
4969     {
4970       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!!  head %u, out!\n", copy->mid);
4971       channel_rel_free_sent (rel, msg);
4972       break;
4973     }
4974     work = GNUNET_YES;
4975     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!!  id %u\n", copy->mid);
4976     next = copy->next;
4977     rel_message_free (copy);
4978   }
4979   /* ACK client if needed */
4980 //   channel_send_ack (t, type, GNUNET_MESSAGE_TYPE_MESH_UNICAST_ACK == type);
4981
4982   /* If some message was free'd, update the retransmission delay*/
4983   if (GNUNET_YES == work)
4984   {
4985     if (GNUNET_SCHEDULER_NO_TASK != rel->retry_task)
4986     {
4987       GNUNET_SCHEDULER_cancel (rel->retry_task);
4988       if (NULL == rel->head_sent)
4989       {
4990         rel->retry_task = GNUNET_SCHEDULER_NO_TASK;
4991       }
4992       else
4993       {
4994         struct GNUNET_TIME_Absolute new_target;
4995         struct GNUNET_TIME_Relative delay;
4996
4997         delay = GNUNET_TIME_relative_multiply (rel->retry_timer,
4998                                                MESH_RETRANSMIT_MARGIN);
4999         new_target = GNUNET_TIME_absolute_add (rel->head_sent->timestamp,
5000                                                delay);
5001         delay = GNUNET_TIME_absolute_get_remaining (new_target);
5002         rel->retry_task =
5003             GNUNET_SCHEDULER_add_delayed (delay,
5004                                           &channel_retransmit_message,
5005                                           rel);
5006       }
5007     }
5008     else
5009       GNUNET_break (0);
5010   }
5011   return GNUNET_OK;
5012 }
5013
5014
5015 /**
5016  * Core handler for connection creation.
5017  *
5018  * @param cls Closure (unused).
5019  * @param peer Sender (neighbor).
5020  * @param message Message.
5021  *
5022  * @return GNUNET_OK to keep the connection open,
5023  *         GNUNET_SYSERR to close it (signal serious error)
5024  */
5025 static int
5026 handle_mesh_connection_create (void *cls,
5027                                const struct GNUNET_PeerIdentity *peer,
5028                                const struct GNUNET_MessageHeader *message)
5029 {
5030   struct GNUNET_MESH_ConnectionCreate *msg;
5031   struct GNUNET_PeerIdentity *id;
5032   struct GNUNET_HashCode *cid;
5033   struct MeshPeerPath *path;
5034   struct MeshPeer *dest_peer;
5035   struct MeshPeer *orig_peer;
5036   struct MeshConnection *c;
5037   unsigned int own_pos;
5038   uint16_t size;
5039   uint16_t i;
5040
5041   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received a connection create msg\n");
5042
5043   /* Check size */
5044   size = ntohs (message->size);
5045   if (size < sizeof (struct GNUNET_MESH_ConnectionCreate))
5046   {
5047     GNUNET_break_op (0);
5048     return GNUNET_OK;
5049   }
5050
5051   /* Calculate hops */
5052   size -= sizeof (struct GNUNET_MESH_ConnectionCreate);
5053   if (size % sizeof (struct GNUNET_PeerIdentity))
5054   {
5055     GNUNET_break_op (0);
5056     return GNUNET_OK;
5057   }
5058   size /= sizeof (struct GNUNET_PeerIdentity);
5059   if (1 > size)
5060   {
5061     GNUNET_break_op (0);
5062     return GNUNET_OK;
5063   }
5064   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "    path has %u hops.\n", size);
5065
5066   /* Get parameters */
5067   msg = (struct GNUNET_MESH_ConnectionCreate *) message;
5068   cid = &msg->cid;
5069   id = (struct GNUNET_PeerIdentity *) &msg[1];
5070   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5071               "    connection %s (%s).\n",
5072               GNUNET_h2s (cid), GNUNET_i2s (id));
5073
5074   /* Create connection */
5075   c = connection_get (cid);
5076   if (NULL == c)
5077   {
5078     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Creating connection\n");
5079     c = connection_new (cid);
5080     if (NULL == c)
5081       return GNUNET_OK;
5082   }
5083   connection_reset_timeout (c, GNUNET_YES);
5084   tunnel_change_state (c->t,  MESH_TUNNEL_WAITING);
5085
5086   /* Remember peers */
5087   dest_peer = peer_get (&id[size - 1]);
5088   orig_peer = peer_get (&id[0]);
5089
5090   /* Create path */
5091   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Creating path...\n");
5092   path = path_new (size);
5093   own_pos = 0;
5094   for (i = 0; i < size; i++)
5095   {
5096     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  ... adding %s\n",
5097                 GNUNET_i2s (&id[i]));
5098     path->peers[i] = GNUNET_PEER_intern (&id[i]);
5099     if (path->peers[i] == myid)
5100       own_pos = i;
5101   }
5102   if (own_pos == 0 && path->peers[own_pos] != myid)
5103   {
5104     /* create path: self not found in path through self */
5105     GNUNET_break_op (0);
5106     path_destroy (path);
5107     connection_destroy (c);
5108     return GNUNET_OK;
5109   }
5110   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Own position: %u\n", own_pos);
5111   path_add_to_peers (path, GNUNET_NO);
5112   c->path = path_duplicate (path);
5113   c->own_pos = own_pos;
5114
5115   /* Is it a connection to us? */
5116   if (own_pos == size - 1)
5117   {
5118     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  It's for us!\n");
5119     peer_add_path_to_origin (orig_peer, path, GNUNET_YES);
5120
5121     if (NULL == orig_peer->tunnel)
5122       orig_peer->tunnel = tunnel_new ();
5123     tunnel_add_connection (orig_peer->tunnel, c);
5124
5125     send_connection_ack (c, GNUNET_NO);
5126
5127     /* Keep tunnel alive in direction dest->owner*/
5128     connection_reset_timeout (c, GNUNET_NO); 
5129   }
5130   else
5131   {
5132     /* It's for somebody else! Retransmit. */
5133     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Retransmitting.\n");
5134     peer_add_path (dest_peer, path_duplicate (path), GNUNET_NO);
5135     peer_add_path_to_origin (orig_peer, path, GNUNET_NO);
5136     send_prebuilt_message_connection (message, c, NULL, GNUNET_YES);
5137   }
5138   return GNUNET_OK;
5139 }
5140
5141
5142 /**
5143  * Core handler for path ACKs
5144  *
5145  * @param cls closure
5146  * @param message message
5147  * @param peer peer identity this notification is about
5148  *
5149  * @return GNUNET_OK to keep the connection open,
5150  *         GNUNET_SYSERR to close it (signal serious error)
5151  */
5152 static int
5153 handle_mesh_connection_ack (void *cls, const struct GNUNET_PeerIdentity *peer,
5154                             const struct GNUNET_MessageHeader *message)
5155 {
5156   struct GNUNET_MESH_ConnectionACK *msg;
5157   struct MeshPeerPath *p;
5158   struct MeshConnection *c;
5159
5160   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received a connection ACK msg\n");
5161   msg = (struct GNUNET_MESH_ConnectionACK *) message;
5162   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on connection %s\n",
5163               GNUNET_h2s (&msg->cid));
5164   c = connection_get (&msg->cid);
5165   if (NULL == c)
5166   {
5167     GNUNET_STATISTICS_update (stats, "# control on unknown connection",
5168                               1, GNUNET_NO);
5169     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  don't know the connection!\n");
5170     return GNUNET_OK;
5171   }
5172
5173   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  via peer %s\n",
5174               GNUNET_i2s (peer));
5175
5176   /* Add path to peers? */
5177   p = c->path;
5178   if (NULL != p)
5179   {
5180     path_add_to_peers (p, GNUNET_YES);
5181   }
5182   else
5183   {
5184     GNUNET_break (0);
5185   }
5186   connection_change_state (c, MESH_CONNECTION_READY);
5187   connection_reset_timeout (c, GNUNET_NO);
5188   if (MESH_TUNNEL_READY != c->t->state)
5189     tunnel_change_state (c->t, MESH_TUNNEL_READY);
5190   tunnel_send_queued_data (c->t, GNUNET_YES);
5191
5192   /* Message for us? */
5193   if (connection_is_terminal (c, GNUNET_NO))
5194   {
5195     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  It's for us!\n");
5196     if (3 <= tunnel_count_connections (c->t) && NULL != c->t->peer->dhtget)
5197     {
5198       GNUNET_DHT_get_stop (c->t->peer->dhtget);
5199       c->t->peer->dhtget = NULL;
5200     }
5201     //connection_send_ack (c, GNUNET_NO); /* FIXME */
5202     return GNUNET_OK;
5203   }
5204
5205   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  not for us, retransmitting...\n");
5206   send_prebuilt_message_connection (message, c, NULL, GNUNET_NO);
5207   return GNUNET_OK;
5208 }
5209
5210
5211 /**
5212  * Core handler for notifications of broken paths
5213  *
5214  * @param cls Closure (unused).
5215  * @param peer Peer identity of sending neighbor.
5216  * @param message Message.
5217  *
5218  * @return GNUNET_OK to keep the connection open,
5219  *         GNUNET_SYSERR to close it (signal serious error)
5220  */
5221 static int
5222 handle_mesh_connection_broken (void *cls, const struct GNUNET_PeerIdentity *peer,
5223                                const struct GNUNET_MessageHeader *message)
5224 {
5225   struct GNUNET_MESH_ConnectionBroken *msg;
5226   struct MeshConnection *c;
5227
5228   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5229               "Received a CONNECTION BROKEN msg from %s\n", GNUNET_i2s (peer));
5230   msg = (struct GNUNET_MESH_ConnectionBroken *) message;
5231   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  regarding %s\n",
5232               GNUNET_i2s (&msg->peer1));
5233   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  regarding %s\n",
5234               GNUNET_i2s (&msg->peer2));
5235   c = connection_get (&msg->cid);
5236   if (NULL == c)
5237   {
5238     GNUNET_break_op (0);
5239     return GNUNET_OK;
5240   }
5241   tunnel_notify_connection_broken (c->t, GNUNET_PEER_search (&msg->peer1),
5242                                    GNUNET_PEER_search (&msg->peer2));
5243   return GNUNET_OK;
5244
5245 }
5246
5247
5248 /**
5249  * Core handler for tunnel destruction
5250  *
5251  * @param cls Closure (unused).
5252  * @param peer Peer identity of sending neighbor.
5253  * @param message Message.
5254  *
5255  * @return GNUNET_OK to keep the connection open,
5256  *         GNUNET_SYSERR to close it (signal serious error)
5257  */
5258 static int
5259 handle_mesh_connection_destroy (void *cls,
5260                                 const struct GNUNET_PeerIdentity *peer,
5261                                 const struct GNUNET_MessageHeader *message)
5262 {
5263   struct GNUNET_MESH_ConnectionDestroy *msg;
5264   struct MeshConnection *c;
5265   GNUNET_PEER_Id id;
5266   int fwd;
5267
5268   msg = (struct GNUNET_MESH_ConnectionDestroy *) message;
5269   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5270               "Got a CONNECTION DESTROY message from %s\n",
5271               GNUNET_i2s (peer));
5272   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5273               "  for connection %s\n",
5274               GNUNET_h2s (&msg->cid));
5275   c = connection_get (&msg->cid);
5276   if (NULL == c)
5277   {
5278     /* Probably already got the message from another path,
5279      * destroyed the tunnel and retransmitted to children.
5280      * Safe to ignore.
5281      */
5282     GNUNET_STATISTICS_update (stats, "# control on unknown tunnel",
5283                               1, GNUNET_NO);
5284     return GNUNET_OK;
5285   }
5286   id = GNUNET_PEER_search (peer);
5287   if (id == connection_get_prev_hop (c)->id)
5288     fwd = GNUNET_YES;
5289   else if (id == connection_get_next_hop (c)->id)
5290     fwd = GNUNET_NO;
5291   else
5292   {
5293     GNUNET_break_op (0);
5294     return GNUNET_OK;
5295   }
5296   send_prebuilt_message_connection (message, c, NULL, fwd);
5297   c->destroy = GNUNET_YES;
5298
5299   return GNUNET_OK;
5300 }
5301
5302
5303 /**
5304  * Handler for channel create messages.
5305  *
5306  * @param t Tunnel this channel is to be created in.
5307  * @param msg Message.
5308  * @param fwd Is this FWD traffic? GNUNET_YES : GNUNET_NO;
5309  *
5310  * @return GNUNET_OK to keep the connection open,
5311  *         GNUNET_SYSERR to close it (signal serious error)
5312  */
5313 static int
5314 handle_channel_create (struct MeshTunnel2 *t,
5315                        struct GNUNET_MESH_ChannelCreate *msg,
5316                        int fwd)
5317 {
5318   MESH_ChannelNumber chid;
5319   struct MeshChannel *ch;
5320   struct MeshClient *c;
5321   uint32_t port;
5322
5323   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received Channel Create\n");
5324   /* Check message size */
5325   if (ntohs (msg->header.size) != sizeof (struct GNUNET_MESH_ChannelCreate))
5326   {
5327     GNUNET_break_op (0);
5328     return GNUNET_OK;
5329   }
5330
5331   /* Check if channel exists */
5332   chid = ntohl (msg->chid);
5333   ch = channel_get (t, chid);
5334   if (NULL != ch)
5335   {
5336     /* Probably a retransmission, safe to ignore */
5337     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   already exists...\n");
5338   }
5339   else
5340   {
5341     /* Create channel */
5342     ch = channel_new (t, NULL, 0);
5343     channel_set_options (ch, ntohl (msg->opt));
5344   }
5345
5346   /* Find a destination client */
5347   port = ntohl (msg->port);
5348   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   port %u\n", port);
5349   c = GNUNET_CONTAINER_multihashmap32_get (ports, port);
5350   if (NULL == c)
5351   {
5352     /* TODO send reject */
5353     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  no client has port registered\n");
5354     return GNUNET_OK;
5355   }
5356
5357   channel_add_client (ch, c);
5358   if (GNUNET_YES == ch->reliable)
5359   {
5360     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! Reliable\n");
5361     ch->bck_rel = GNUNET_malloc (sizeof (struct MeshChannelReliability));
5362     ch->bck_rel->ch = ch;
5363     ch->bck_rel->expected_delay = MESH_RETRANSMIT_TIME;
5364   }
5365
5366   send_local_channel_create (ch);
5367   channel_send_ack (ch, !fwd);
5368
5369   return GNUNET_OK;
5370 }
5371
5372
5373 /**
5374  * Handler for channel ack messages.
5375  *
5376  * @param t Tunnel this channel is to be created in.
5377  * @param msg Message.
5378  * @param fwd Is this FWD traffic? GNUNET_YES : GNUNET_NO;
5379  *
5380  * @return GNUNET_OK to keep the connection open,
5381  *         GNUNET_SYSERR to close it (signal serious error)
5382  */
5383 static int
5384 handle_channel_ack (struct MeshTunnel2 *t,
5385                     struct GNUNET_MESH_ChannelManage *msg,
5386                     int fwd)
5387 {
5388   MESH_ChannelNumber chid;
5389   struct MeshChannel *ch;
5390
5391   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received Channel ACK\n");
5392   /* Check message size */
5393   if (ntohs (msg->header.size) != sizeof (struct GNUNET_MESH_ChannelManage))
5394   {
5395     GNUNET_break_op (0);
5396     return GNUNET_OK;
5397   }
5398
5399   /* Check if channel exists */
5400   chid = ntohl (msg->chid);
5401   ch = channel_get (t, chid);
5402   if (NULL == ch)
5403   {
5404     GNUNET_break_op (0);
5405     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   channel %u unknown!!\n", chid);
5406     return GNUNET_OK;
5407   }
5408
5409   channel_confirm (ch, !fwd);
5410   return GNUNET_OK;
5411 }
5412
5413
5414 /**
5415  * Handler for channel destroy messages.
5416  *
5417  * @param t Tunnel this channel is to be destroyed of.
5418  * @param msg Message.
5419  * @param fwd Is this FWD traffic? GNUNET_YES : GNUNET_NO;
5420  *
5421  * @return GNUNET_OK to keep the connection open,
5422  *         GNUNET_SYSERR to close it (signal serious error)
5423  */
5424 static int
5425 handle_channel_destroy (struct MeshTunnel2 *t,
5426                         struct GNUNET_MESH_ChannelManage *msg,
5427                         int fwd)
5428 {
5429   MESH_ChannelNumber chid;
5430   struct MeshChannel *ch;
5431
5432   /* Check message size */
5433   if (ntohs (msg->header.size) != sizeof (struct GNUNET_MESH_ChannelManage))
5434   {
5435     GNUNET_break_op (0);
5436     return GNUNET_OK;
5437   }
5438
5439   /* Check if channel exists */
5440   chid = ntohl (msg->chid);
5441   ch = channel_get (t, chid);
5442   if (NULL == ch)
5443   {
5444     /* Probably a retransmission, safe to ignore */
5445     return GNUNET_OK;
5446   }
5447
5448   send_local_channel_destroy (ch, fwd);
5449   channel_destroy (ch);
5450
5451   return GNUNET_OK;
5452 }
5453
5454
5455 /**
5456  * Generic handler for mesh network encrypted traffic.
5457  *
5458  * @param peer Peer identity this notification is about.
5459  * @param message Encrypted message.
5460  * @param fwd Is this FWD traffic? GNUNET_YES : GNUNET_NO;
5461  *
5462  * @return GNUNET_OK to keep the connection open,
5463  *         GNUNET_SYSERR to close it (signal serious error)
5464  */
5465 static int
5466 handle_mesh_encrypted (const struct GNUNET_PeerIdentity *peer,
5467                        const struct GNUNET_MESH_Encrypted *msg,
5468                        int fwd)
5469 {
5470   struct MeshConnection *c;
5471   struct MeshTunnel2 *t;
5472   struct MeshPeer *neighbor;
5473   struct MeshFlowControl *fc;
5474   uint32_t pid;
5475   uint32_t ttl;
5476   uint16_t type;
5477   size_t size;
5478
5479   /* Check size */
5480   size = ntohs (msg->header.size);
5481   if (size <
5482       sizeof (struct GNUNET_MESH_Encrypted) +
5483       sizeof (struct GNUNET_MessageHeader))
5484   {
5485     GNUNET_break (0);
5486     return GNUNET_OK;
5487   }
5488   type = ntohs (msg->header.type);
5489   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a %s message from %s\n",
5490               GNUNET_MESH_DEBUG_M2S (type), GNUNET_i2s (peer));
5491
5492   /* Check connection */
5493   c = connection_get (&msg->cid);
5494   if (NULL == c)
5495   {
5496     GNUNET_STATISTICS_update (stats, "# unknown connection", 1, GNUNET_NO);
5497     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "WARNING connection unknown\n");
5498     return GNUNET_OK;
5499   }
5500   t = c->t;
5501   fc = fwd ? &c->fwd_fc : &c->bck_fc;
5502
5503   /* Check if origin is as expected */
5504   neighbor = connection_get_hop (c, fwd);
5505   if (peer_get (peer)->id != neighbor->id)
5506   {
5507     GNUNET_break_op (0);
5508     return GNUNET_OK;
5509   }
5510
5511   /* Check PID */
5512   pid = ntohl (msg->pid);
5513   if (GMC_is_pid_bigger (pid, fc->last_ack_sent))
5514   {
5515     GNUNET_STATISTICS_update (stats, "# unsolicited message", 1, GNUNET_NO);
5516     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5517                 "WARNING Received PID %u, (prev %u), ACK %u\n",
5518                 pid, fc->last_pid_recv, fc->last_ack_sent);
5519     return GNUNET_OK;
5520   }
5521   if (GNUNET_NO == GMC_is_pid_bigger (pid, fc->last_pid_recv))
5522   {
5523     GNUNET_STATISTICS_update (stats, "# duplicate PID", 1, GNUNET_NO);
5524     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5525                 " Pid %u not expected (%u+), dropping!\n",
5526                 pid, fc->last_pid_recv + 1);
5527     return GNUNET_OK;
5528   }
5529   if (MESH_CONNECTION_SENT == c->state)
5530     connection_change_state (c, MESH_CONNECTION_READY);
5531   connection_reset_timeout (c, fwd);
5532   fc->last_pid_recv = pid;
5533
5534   /* Is this message for us? */
5535   if (connection_is_terminal (c, fwd))
5536   {
5537     size_t dsize = size - sizeof (struct GNUNET_MESH_Encrypted);
5538     char cbuf[dsize];
5539     struct GNUNET_MessageHeader *msgh;
5540     int r;
5541
5542     /* TODO signature verification */
5543     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  it's for us!\n");
5544     GNUNET_STATISTICS_update (stats, "# messages received", 1, GNUNET_NO);
5545
5546     fc->last_pid_recv = pid;
5547     tunnel_decrypt (t, cbuf, &msg[1], dsize, msg->iv, fwd);
5548     msgh = (struct GNUNET_MessageHeader *) cbuf;
5549     switch (ntohs (msgh->type))
5550     {
5551       case GNUNET_MESSAGE_TYPE_MESH_DATA_ACK:
5552         r = handle_data_ack (t, (struct GNUNET_MESH_DataACK *) msgh, fwd);
5553         break;
5554
5555       case GNUNET_MESSAGE_TYPE_MESH_DATA:
5556         r = handle_data (t, (struct GNUNET_MESH_Data *) msgh, fwd);
5557         break;
5558
5559       case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_CREATE:
5560         r = handle_channel_create (t,
5561                                    (struct GNUNET_MESH_ChannelCreate *) msgh,
5562                                    fwd);
5563         break;
5564
5565       case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_ACK:
5566         r = handle_channel_ack (t,
5567                                 (struct GNUNET_MESH_ChannelManage *) msgh,
5568                                 fwd);
5569         break;
5570
5571       case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_DESTROY:
5572         r = handle_channel_destroy (t,
5573                                     (struct GNUNET_MESH_ChannelManage *) msgh,
5574                                     fwd);
5575         break;
5576
5577       default:
5578         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5579                     "end-to-end message not known (%u)\n",
5580                     ntohs (msgh->type));
5581         r = GNUNET_OK;
5582     }
5583
5584     connection_send_ack (c, fwd);
5585     return r;
5586   }
5587
5588   /* Message not for us: forward to next hop */
5589   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  not for us, retransmitting...\n");
5590   ttl = ntohl (msg->ttl);
5591   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   ttl: %u\n", ttl);
5592   if (ttl == 0)
5593   {
5594     GNUNET_STATISTICS_update (stats, "# TTL drops", 1, GNUNET_NO);
5595     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, " TTL is 0, DROPPING!\n");
5596     connection_send_ack (c, fwd);
5597     return GNUNET_OK;
5598   }
5599   GNUNET_STATISTICS_update (stats, "# messages forwarded", 1, GNUNET_NO);
5600
5601   send_prebuilt_message_connection (&msg->header, c, NULL, fwd);
5602
5603   return GNUNET_OK;
5604 }
5605
5606
5607 /**
5608  * Core handler for mesh network traffic going orig->dest.
5609  *
5610  * @param cls Closure (unused).
5611  * @param message Message received.
5612  * @param peer Peer who sent the message.
5613  *
5614  * @return GNUNET_OK to keep the connection open,
5615  *         GNUNET_SYSERR to close it (signal serious error)
5616  */
5617 static int
5618 handle_mesh_fwd (void *cls, const struct GNUNET_PeerIdentity *peer,
5619                      const struct GNUNET_MessageHeader *message)
5620 {
5621   return handle_mesh_encrypted (peer,
5622                                 (struct GNUNET_MESH_Encrypted *)message,
5623                                 GNUNET_YES);
5624 }
5625
5626 /**
5627  * Core handler for mesh network traffic going dest->orig.
5628  *
5629  * @param cls Closure (unused).
5630  * @param message Message received.
5631  * @param peer Peer who sent the message.
5632  *
5633  * @return GNUNET_OK to keep the connection open,
5634  *         GNUNET_SYSERR to close it (signal serious error)
5635  */
5636 static int
5637 handle_mesh_bck (void *cls, const struct GNUNET_PeerIdentity *peer,
5638                      const struct GNUNET_MessageHeader *message)
5639 {
5640   return handle_mesh_encrypted (peer,
5641                                 (struct GNUNET_MESH_Encrypted *)message,
5642                                 GNUNET_NO);
5643 }
5644
5645
5646 /**
5647  * Core handler for mesh network traffic point-to-point acks.
5648  *
5649  * @param cls closure
5650  * @param message message
5651  * @param peer peer identity this notification is about
5652  *
5653  * @return GNUNET_OK to keep the connection open,
5654  *         GNUNET_SYSERR to close it (signal serious error)
5655  */
5656 static int
5657 handle_mesh_ack (void *cls, const struct GNUNET_PeerIdentity *peer,
5658                  const struct GNUNET_MessageHeader *message)
5659 {
5660   struct GNUNET_MESH_ACK *msg;
5661   struct MeshConnection *c;
5662   struct MeshFlowControl *fc;
5663   GNUNET_PEER_Id id;
5664   uint32_t ack;
5665
5666   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got an ACK packet from %s!\n",
5667               GNUNET_i2s (peer));
5668   msg = (struct GNUNET_MESH_ACK *) message;
5669
5670   c = connection_get (&msg->cid);
5671
5672   if (NULL == c)
5673   {
5674     GNUNET_STATISTICS_update (stats, "# ack on unknown connection", 1,
5675                               GNUNET_NO);
5676     return GNUNET_OK;
5677   }
5678
5679   ack = ntohl (msg->ack);
5680   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  ACK %u\n", ack);
5681
5682   /* Is this a forward or backward ACK? */
5683   id = GNUNET_PEER_search (peer);
5684   if (connection_get_next_hop (c)->id == id)
5685   {
5686     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  FWD ACK\n");
5687     fc = &c->fwd_fc;
5688   }
5689   else if (connection_get_prev_hop (c)->id == id)
5690   {
5691     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  BCK ACK\n");
5692     fc = &c->bck_fc;
5693   }
5694   else
5695   {
5696     GNUNET_break_op (0);
5697     return GNUNET_OK;
5698   }
5699
5700   /* Cancel polling if the ACK is bigger than before. */
5701   if (GNUNET_SCHEDULER_NO_TASK != fc->poll_task &&
5702       GMC_is_pid_bigger (ack, fc->last_ack_recv))
5703   {
5704     GNUNET_SCHEDULER_cancel (fc->poll_task);
5705     fc->poll_task = GNUNET_SCHEDULER_NO_TASK;
5706     fc->poll_time = GNUNET_TIME_UNIT_SECONDS;
5707   }
5708
5709   fc->last_ack_recv = ack;
5710   connection_unlock_queue (c, fc == &c->fwd_fc);
5711
5712   return GNUNET_OK;
5713 }
5714
5715
5716 /**
5717  * Core handler for mesh network traffic point-to-point ack polls.
5718  *
5719  * @param cls closure
5720  * @param message message
5721  * @param peer peer identity this notification is about
5722  *
5723  * @return GNUNET_OK to keep the connection open,
5724  *         GNUNET_SYSERR to close it (signal serious error)
5725  */
5726 static int
5727 handle_mesh_poll (void *cls, const struct GNUNET_PeerIdentity *peer,
5728                   const struct GNUNET_MessageHeader *message)
5729 {
5730   struct GNUNET_MESH_Poll *msg;
5731   struct MeshConnection *c;
5732   struct MeshFlowControl *fc;
5733   GNUNET_PEER_Id id;
5734   uint32_t pid;
5735
5736   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a POLL packet from %s!\n",
5737               GNUNET_i2s (peer));
5738
5739   msg = (struct GNUNET_MESH_Poll *) message;
5740
5741   c = connection_get (&msg->cid);
5742
5743   if (NULL == c)
5744   {
5745     GNUNET_STATISTICS_update (stats, "# poll on unknown connection", 1,
5746                               GNUNET_NO);
5747     GNUNET_break_op (0);
5748     return GNUNET_OK;
5749   }
5750
5751   /* Is this a forward or backward ACK? */
5752   id = GNUNET_PEER_search (peer);
5753   if (connection_get_next_hop (c)->id == id)
5754   {
5755     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  FWD ACK\n");
5756     fc = &c->fwd_fc;
5757   }
5758   else if (connection_get_prev_hop (c)->id == id)
5759   {
5760     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  BCK ACK\n");
5761     fc = &c->bck_fc;
5762   }
5763   else
5764   {
5765     GNUNET_break_op (0);
5766     return GNUNET_OK;
5767   }
5768
5769   pid = ntohl (msg->pid);
5770   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  PID %u, OLD %u\n",
5771               pid, fc->last_pid_recv);
5772   fc->last_pid_recv = pid;
5773   connection_send_ack (c, fc == &c->fwd_fc);
5774
5775   return GNUNET_OK;
5776 }
5777
5778
5779 /**
5780  * Core handler for mesh keepalives.
5781  *
5782  * @param cls closure
5783  * @param message message
5784  * @param peer peer identity this notification is about
5785  * @return GNUNET_OK to keep the connection open,
5786  *         GNUNET_SYSERR to close it (signal serious error)
5787  *
5788  * TODO: Check who we got this from, to validate route.
5789  */
5790 static int
5791 handle_mesh_keepalive (void *cls, const struct GNUNET_PeerIdentity *peer,
5792                        const struct GNUNET_MessageHeader *message)
5793 {
5794   struct GNUNET_MESH_ConnectionKeepAlive *msg;
5795   struct MeshConnection *c;
5796   struct MeshPeer *neighbor;
5797   int fwd;
5798
5799   msg = (struct GNUNET_MESH_ConnectionKeepAlive *) message;
5800   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a keepalive packet from %s\n",
5801               GNUNET_i2s (peer));
5802
5803   c = connection_get (&msg->cid);
5804   if (NULL == c)
5805   {
5806     GNUNET_STATISTICS_update (stats, "# keepalive on unknown connection", 1,
5807                               GNUNET_NO);
5808     return GNUNET_OK;
5809   }
5810
5811   fwd = GNUNET_MESSAGE_TYPE_MESH_FWD_KEEPALIVE == ntohs (message->type) ? 
5812         GNUNET_YES : GNUNET_NO;
5813
5814   /* Check if origin is as expected */
5815   neighbor = connection_get_hop (c, fwd);
5816   if (peer_get (peer)->id != neighbor->id)
5817   {
5818     GNUNET_break_op (0);
5819     return GNUNET_OK;
5820   }
5821
5822   connection_change_state (c, MESH_CONNECTION_READY);
5823   connection_reset_timeout (c, fwd);
5824
5825   if (connection_is_terminal (c, fwd))
5826     return GNUNET_OK;
5827
5828   GNUNET_STATISTICS_update (stats, "# keepalives forwarded", 1, GNUNET_NO);
5829   send_prebuilt_message_connection (message, c, NULL, fwd);
5830
5831   return GNUNET_OK;
5832 }
5833
5834
5835
5836 /**
5837  * Functions to handle messages from core
5838  */
5839 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
5840   {&handle_mesh_connection_create, GNUNET_MESSAGE_TYPE_MESH_CONNECTION_CREATE,
5841     0},
5842   {&handle_mesh_connection_ack, GNUNET_MESSAGE_TYPE_MESH_CONNECTION_ACK,
5843     sizeof (struct GNUNET_MESH_ConnectionACK)},
5844   {&handle_mesh_connection_broken, GNUNET_MESSAGE_TYPE_MESH_CONNECTION_BROKEN,
5845     sizeof (struct GNUNET_MESH_ConnectionBroken)},
5846   {&handle_mesh_connection_destroy, GNUNET_MESSAGE_TYPE_MESH_CONNECTION_DESTROY,
5847     sizeof (struct GNUNET_MESH_ConnectionDestroy)},
5848   {&handle_mesh_keepalive, GNUNET_MESSAGE_TYPE_MESH_FWD_KEEPALIVE,
5849     sizeof (struct GNUNET_MESH_ConnectionKeepAlive)},
5850   {&handle_mesh_keepalive, GNUNET_MESSAGE_TYPE_MESH_BCK_KEEPALIVE,
5851     sizeof (struct GNUNET_MESH_ConnectionKeepAlive)},
5852   {&handle_mesh_ack, GNUNET_MESSAGE_TYPE_MESH_ACK,
5853     sizeof (struct GNUNET_MESH_ACK)},
5854   {&handle_mesh_poll, GNUNET_MESSAGE_TYPE_MESH_POLL,
5855     sizeof (struct GNUNET_MESH_Poll)},
5856   {&handle_mesh_fwd, GNUNET_MESSAGE_TYPE_MESH_FWD, 0},
5857   {&handle_mesh_bck, GNUNET_MESSAGE_TYPE_MESH_BCK, 0},
5858   {NULL, 0, 0}
5859 };
5860
5861
5862 /**
5863  * Function to process paths received for a new peer addition. The recorded
5864  * paths form the initial tunnel, which can be optimized later.
5865  * Called on each result obtained for the DHT search.
5866  *
5867  * @param cls closure
5868  * @param exp when will this value expire
5869  * @param key key of the result
5870  * @param get_path path of the get request
5871  * @param get_path_length lenght of get_path
5872  * @param put_path path of the put request
5873  * @param put_path_length length of the put_path
5874  * @param type type of the result
5875  * @param size number of bytes in data
5876  * @param data pointer to the result data
5877  */
5878 static void
5879 dht_get_id_handler (void *cls, struct GNUNET_TIME_Absolute exp,
5880                     const struct GNUNET_HashCode * key,
5881                     const struct GNUNET_PeerIdentity *get_path,
5882                     unsigned int get_path_length,
5883                     const struct GNUNET_PeerIdentity *put_path,
5884                     unsigned int put_path_length, enum GNUNET_BLOCK_Type type,
5885                     size_t size, const void *data)
5886 {
5887   struct MeshPeer *peer = cls;
5888   struct MeshPeerPath *p;
5889   struct MeshConnection *c;
5890   struct GNUNET_PeerIdentity pi;
5891   int i;
5892
5893   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got results from DHT!\n");
5894   GNUNET_PEER_resolve (peer->id, &pi);
5895   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  for %s\n", GNUNET_i2s (&pi));
5896
5897   p = path_build_from_dht (get_path, get_path_length,
5898                            put_path, put_path_length);
5899   path_add_to_peers (p, GNUNET_NO);
5900   path_destroy (p);
5901
5902   /* Count connections */
5903   for (c = peer->tunnel->connection_head, i = 0; NULL != c; c = c->next, i++);
5904
5905   /* If we already have 3 (or more (?!)) connections, it's enough */
5906   if (3 <= i)
5907     return;
5908
5909   if (peer->tunnel->state == MESH_TUNNEL_SEARCHING)
5910   {
5911     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " ... connect!\n");
5912     peer_connect (peer);
5913   }
5914   return;
5915 }
5916
5917
5918 /******************************************************************************/
5919 /*********************       MESH LOCAL HANDLES      **************************/
5920 /******************************************************************************/
5921
5922
5923 /**
5924  * Handler for client connection.
5925  *
5926  * @param cls Closure (unused).
5927  * @param client Client handler.
5928  */
5929 static void
5930 handle_local_client_connect (void *cls, struct GNUNET_SERVER_Client *client)
5931 {
5932   struct MeshClient *c;
5933
5934   if (NULL == client)
5935     return;
5936   c = GNUNET_malloc (sizeof (struct MeshClient));
5937   c->handle = client;
5938   c->id = next_client_id++; /* overflow not important: just for debug */
5939   GNUNET_SERVER_client_keep (client);
5940   GNUNET_SERVER_client_set_user_context (client, c);
5941   GNUNET_CONTAINER_DLL_insert (clients_head, clients_tail, c);
5942 }
5943
5944
5945 /**
5946  * Handler for client disconnection
5947  *
5948  * @param cls closure
5949  * @param client identification of the client; NULL
5950  *        for the last call when the server is destroyed
5951  */
5952 static void
5953 handle_local_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
5954 {
5955   struct MeshClient *c;
5956
5957   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "client disconnected: %p\n", client);
5958   if (client == NULL)
5959   {
5960     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   (SERVER DOWN)\n");
5961     return;
5962   }
5963
5964   c = client_get (client);
5965   if (NULL != c)
5966   {
5967     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "matching client found (%u, %p)\n",
5968                 c->id, c);
5969     GNUNET_SERVER_client_drop (c->handle);
5970     c->shutting_down = GNUNET_YES;
5971     if (NULL != c->own_channels)
5972     {
5973       GNUNET_CONTAINER_multihashmap32_iterate (c->own_channels,
5974                                                &channel_destroy_iterator, c);
5975       GNUNET_CONTAINER_multihashmap32_destroy (c->own_channels);
5976     }
5977
5978     if (NULL != c->incoming_channels)
5979     {
5980       GNUNET_CONTAINER_multihashmap32_iterate (c->incoming_channels,
5981                                                &channel_destroy_iterator, c);
5982       GNUNET_CONTAINER_multihashmap32_destroy (c->incoming_channels);
5983     }
5984
5985     if (NULL != c->ports)
5986     {
5987       GNUNET_CONTAINER_multihashmap32_iterate (c->ports,
5988                                                &client_release_ports, c);
5989       GNUNET_CONTAINER_multihashmap32_destroy (c->ports);
5990     }
5991     GNUNET_CONTAINER_DLL_remove (clients_head, clients_tail, c);
5992     GNUNET_STATISTICS_update (stats, "# clients", -1, GNUNET_NO);
5993     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  client free (%p)\n", c);
5994     GNUNET_free (c);
5995   }
5996   else
5997   {
5998     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, " context NULL!\n");
5999   }
6000   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "done!\n");
6001   return;
6002 }
6003
6004
6005 /**
6006  * Handler for new clients
6007  *
6008  * @param cls closure
6009  * @param client identification of the client
6010  * @param message the actual message, which includes messages the client wants
6011  */
6012 static void
6013 handle_local_new_client (void *cls, struct GNUNET_SERVER_Client *client,
6014                          const struct GNUNET_MessageHeader *message)
6015 {
6016   struct GNUNET_MESH_ClientConnect *cc_msg;
6017   struct MeshClient *c;
6018   unsigned int size;
6019   uint32_t *p;
6020   unsigned int i;
6021
6022   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new client connected %p\n", client);
6023
6024   /* Check data sanity */
6025   size = ntohs (message->size) - sizeof (struct GNUNET_MESH_ClientConnect);
6026   cc_msg = (struct GNUNET_MESH_ClientConnect *) message;
6027   if (0 != (size % sizeof (uint32_t)))
6028   {
6029     GNUNET_break (0);
6030     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6031     return;
6032   }
6033   size /= sizeof (uint32_t);
6034
6035   /* Initialize new client structure */
6036   c = GNUNET_SERVER_client_get_user_context (client, struct MeshClient);
6037   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  client id %u\n", c->id);
6038   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  client has %u ports\n", size);
6039   if (size > 0)
6040   {
6041     uint32_t u32;
6042
6043     p = (uint32_t *) &cc_msg[1];
6044     c->ports = GNUNET_CONTAINER_multihashmap32_create (size);
6045     for (i = 0; i < size; i++)
6046     {
6047       u32 = ntohl (p[i]);
6048       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "    port: %u\n", u32);
6049
6050       /* store in client's hashmap */
6051       GNUNET_CONTAINER_multihashmap32_put (c->ports, u32, c,
6052                                            GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
6053       /* store in global hashmap */
6054       /* FIXME only allow one client to have the port open,
6055        *       have a backup hashmap with waiting clients */
6056       GNUNET_CONTAINER_multihashmap32_put (ports, u32, c,
6057                                            GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
6058     }
6059   }
6060
6061   c->own_channels = GNUNET_CONTAINER_multihashmap32_create (32);
6062   c->incoming_channels = GNUNET_CONTAINER_multihashmap32_create (32);
6063   GNUNET_SERVER_notification_context_add (nc, client);
6064   GNUNET_STATISTICS_update (stats, "# clients", 1, GNUNET_NO);
6065
6066   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6067   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new client processed\n");
6068 }
6069
6070
6071 /**
6072  * Handler for requests of new tunnels
6073  *
6074  * @param cls Closure.
6075  * @param client Identification of the client.
6076  * @param message The actual message.
6077  */
6078 static void
6079 handle_local_channel_create (void *cls, struct GNUNET_SERVER_Client *client,
6080                             const struct GNUNET_MessageHeader *message)
6081 {
6082   struct GNUNET_MESH_ChannelMessage *msg;
6083   struct MeshPeer *peer;
6084   struct MeshTunnel2 *t;
6085   struct MeshChannel *ch;
6086   struct MeshClient *c;
6087   MESH_ChannelNumber chid;
6088
6089   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new channel requested\n");
6090
6091   /* Sanity check for client registration */
6092   if (NULL == (c = client_get (client)))
6093   {
6094     GNUNET_break (0);
6095     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6096     return;
6097   }
6098   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6099
6100   /* Message size sanity check */
6101   if (sizeof (struct GNUNET_MESH_ChannelMessage) != ntohs (message->size))
6102   {
6103     GNUNET_break (0);
6104     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6105     return;
6106   }
6107
6108   msg = (struct GNUNET_MESH_ChannelMessage *) message;
6109   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  towards %s:%u\n",
6110               GNUNET_i2s (&msg->peer), ntohl (msg->port));
6111   chid = ntohl (msg->channel_id);
6112
6113   /* Sanity check for duplicate channel IDs */
6114   if (NULL != channel_get_by_local_id (c, chid))
6115   {
6116     GNUNET_break (0);
6117     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6118     return;
6119   }
6120
6121   peer = peer_get (&msg->peer);
6122   if (NULL == peer->tunnel)
6123   {
6124     peer->tunnel = tunnel_new ();
6125     peer->tunnel->peer = peer;
6126   }
6127   t = peer->tunnel;
6128
6129   /* Create channel */
6130   ch = channel_new (t, c, chid);
6131   if (NULL == ch)
6132   {
6133     GNUNET_break (0);
6134     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6135     return;
6136   }
6137   ch->port = ntohl (msg->port);
6138   channel_set_options (ch, ntohl (msg->opt));
6139
6140   /* In unreliable channels, we'll use the DLL to buffer data for the root */
6141   ch->fwd_rel = GNUNET_malloc (sizeof (struct MeshChannelReliability));
6142   ch->fwd_rel->ch = ch;
6143   ch->fwd_rel->expected_delay = MESH_RETRANSMIT_TIME;
6144
6145   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "CREATED CHANNEL %s[%x]:%u (%x)\n",
6146               peer2s (t->peer), ch->gid, ch->port, ch->lid_root);
6147   peer_connect (peer);
6148
6149   /* Send create channel */
6150   {
6151     struct GNUNET_MESH_ChannelCreate msgcc;
6152
6153     msgcc.header.size = htons (sizeof (msgcc));
6154     msgcc.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_CHANNEL_CREATE);
6155     msgcc.chid = htonl (ch->gid);
6156     msgcc.port = msg->port;
6157     msgcc.opt = msg->opt;
6158
6159     tunnel_queue_data (t, ch, &msgcc.header, GNUNET_YES);
6160   }
6161
6162   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6163   return;
6164 }
6165
6166
6167 /**
6168  * Handler for requests of deleting tunnels
6169  *
6170  * @param cls closure
6171  * @param client identification of the client
6172  * @param message the actual message
6173  */
6174 static void
6175 handle_local_channel_destroy (void *cls, struct GNUNET_SERVER_Client *client,
6176                              const struct GNUNET_MessageHeader *message)
6177 {
6178   struct GNUNET_MESH_ChannelMessage *msg;
6179   struct MeshClient *c;
6180   struct MeshChannel *ch;
6181   struct MeshTunnel2 *t;
6182   MESH_ChannelNumber chid;
6183
6184   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6185               "Got a DESTROY CHANNEL from client!\n");
6186
6187   /* Sanity check for client registration */
6188   if (NULL == (c = client_get (client)))
6189   {
6190     GNUNET_break (0);
6191     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6192     return;
6193   }
6194   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6195
6196   /* Message sanity check */
6197   if (sizeof (struct GNUNET_MESH_ChannelMessage) != ntohs (message->size))
6198   {
6199     GNUNET_break (0);
6200     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6201     return;
6202   }
6203
6204   msg = (struct GNUNET_MESH_ChannelMessage *) message;
6205
6206   /* Retrieve tunnel */
6207   chid = ntohl (msg->channel_id);
6208   ch = channel_get_by_local_id (c, chid);
6209   if (NULL == ch)
6210   {
6211     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "  channel %X not found\n", chid);
6212     GNUNET_break (0);
6213     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6214     return;
6215   }
6216
6217   /* Cleanup after the tunnel */
6218   client_delete_channel (c, ch);
6219   if (c == ch->dest && GNUNET_MESH_LOCAL_CHANNEL_ID_SERV <= chid)
6220   {
6221     ch->dest = NULL;
6222   }
6223   else if (c == ch->root && GNUNET_MESH_LOCAL_CHANNEL_ID_SERV > chid)
6224   {
6225     ch->root = NULL;
6226   }
6227   else 
6228   {
6229     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
6230                 "  channel %X client %p (%p, %p)\n",
6231                 chid, c, ch->root, ch->dest);
6232     GNUNET_break (0);
6233   }
6234
6235   t = ch->t;
6236   channel_destroy (ch);
6237   tunnel_destroy_if_empty (t);
6238
6239   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6240   return;
6241 }
6242
6243
6244 /**
6245  * Handler for client traffic
6246  *
6247  * @param cls closure
6248  * @param client identification of the client
6249  * @param message the actual message
6250  */
6251 static void
6252 handle_local_data (void *cls, struct GNUNET_SERVER_Client *client,
6253                    const struct GNUNET_MessageHeader *message)
6254 {
6255   struct GNUNET_MESH_LocalData *msg;
6256   struct MeshClient *c;
6257   struct MeshChannel *ch;
6258   MESH_ChannelNumber chid;
6259   size_t size;
6260   int fwd;
6261
6262   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6263               "Got data from a client!\n");
6264
6265   /* Sanity check for client registration */
6266   if (NULL == (c = client_get (client)))
6267   {
6268     GNUNET_break (0);
6269     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6270     return;
6271   }
6272   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6273
6274   msg = (struct GNUNET_MESH_LocalData *) message;
6275
6276   /* Sanity check for message size */
6277   size = ntohs (message->size) - sizeof (struct GNUNET_MESH_LocalData);
6278   if (size < sizeof (struct GNUNET_MessageHeader))
6279   {
6280     GNUNET_break (0);
6281     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6282     return;
6283   }
6284
6285   /* Channel exists? */
6286   chid = ntohl (msg->id);
6287   fwd = chid < GNUNET_MESH_LOCAL_CHANNEL_ID_SERV;
6288   ch = channel_get_by_local_id (c, chid);
6289   if (NULL == ch)
6290   {
6291     GNUNET_break (0);
6292     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6293     return;
6294   }
6295
6296   /* Is the client in the channel? */
6297   if ( !( (fwd &&
6298            ch->root &&
6299            ch->root->handle == client)
6300          ||
6301           (!fwd &&
6302            ch->dest && 
6303            ch->dest->handle == client) ) )
6304   {
6305     GNUNET_break (0);
6306     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6307     return;
6308   }
6309
6310   if (fwd)
6311     ch->blocked_fwd = GNUNET_YES;
6312   else
6313     ch->blocked_bck = GNUNET_YES;
6314
6315   /* Ok, everything is correct, send the message. */
6316   {
6317     struct GNUNET_MESH_Data *payload;
6318     uint16_t p2p_size = sizeof(struct GNUNET_MESH_Data) + size;
6319     unsigned char cbuf[p2p_size];
6320     uint32_t *mid;
6321
6322     mid = fwd ? &ch->mid_send_fwd : &ch->mid_send_bck;
6323     payload = (struct GNUNET_MESH_Data *) cbuf;
6324     payload->mid = htonl (*mid);
6325     *mid = *mid + 1;
6326     memcpy (&payload[1], &msg[1], size);
6327     payload->header.size = htons (p2p_size);
6328     payload->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_DATA);
6329     payload->chid = htonl (ch->gid);
6330     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  sending on channel...\n");
6331     send_prebuilt_message_channel (&payload->header, ch, fwd);
6332
6333     if (GNUNET_YES == ch->reliable)
6334       channel_save_copy (ch, &payload->header, fwd);
6335   }
6336   if (tunnel_get_buffer (ch->t, fwd) > 0)
6337     send_local_ack (ch, c, fwd);
6338   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "receive done OK\n");
6339   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6340
6341   return;
6342 }
6343
6344
6345 /**
6346  * Handler for client's ACKs for payload traffic.
6347  *
6348  * @param cls Closure (unused).
6349  * @param client Identification of the client.
6350  * @param message The actual message.
6351  */
6352 static void
6353 handle_local_ack (void *cls, struct GNUNET_SERVER_Client *client,
6354                   const struct GNUNET_MessageHeader *message)
6355 {
6356   struct GNUNET_MESH_LocalAck *msg;
6357   struct MeshChannelReliability *rel;
6358   struct MeshChannel *ch;
6359   struct MeshClient *c;
6360   MESH_ChannelNumber chid;
6361   int fwd;
6362
6363   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a local ACK\n");
6364
6365   /* Sanity check for client registration */
6366   if (NULL == (c = client_get (client)))
6367   {
6368     GNUNET_break (0);
6369     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6370     return;
6371   }
6372   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6373
6374   msg = (struct GNUNET_MESH_LocalAck *) message;
6375
6376   /* Channel exists? */
6377   chid = ntohl (msg->channel_id);
6378   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on channel %X\n", chid);
6379   ch = channel_get_by_local_id (c, chid);
6380   if (NULL == ch)
6381   {
6382     GNUNET_break (0);
6383     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Channel %X unknown.\n", chid);
6384     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "  for client %u.\n", c->id);
6385     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6386     return;
6387   }
6388
6389   fwd = chid < GNUNET_MESH_LOCAL_CHANNEL_ID_SERV;
6390   rel = fwd ? ch->fwd_rel : ch->bck_rel;
6391
6392   rel->client_ready = GNUNET_YES;
6393   channel_send_client_buffered_data (ch, c, rel);
6394   channel_send_connection_ack (ch, 64 - rel->n_recv, fwd);
6395
6396   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6397
6398   return;
6399 }
6400
6401
6402 /**
6403  * Iterator over all tunnels to send a monitoring client info about each tunnel.
6404  *
6405  * @param cls Closure (client handle).
6406  * @param key Key (hashed tunnel ID, unused).
6407  * @param value Tunnel info.
6408  *
6409  * @return GNUNET_YES, to keep iterating.
6410  */
6411 // static int
6412 // monitor_all_tunnels_iterator (void *cls,
6413 //                               const struct GNUNET_HashCode * key,
6414 //                               void *value)
6415 // {
6416 //   struct GNUNET_SERVER_Client *client = cls;
6417 //   struct MeshChannel *ch = value;
6418 //   struct GNUNET_MESH_LocalMonitor *msg;
6419 // 
6420 //   msg = GNUNET_malloc (sizeof(struct GNUNET_MESH_LocalMonitor));
6421 //   msg->channel_id = htonl (ch->gid);
6422 //   msg->header.size = htons (sizeof (struct GNUNET_MESH_LocalMonitor));
6423 //   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_INFO_TUNNELS);
6424 // 
6425 //   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
6426 //               "*  sending info about tunnel %s\n",
6427 //               GNUNET_i2s (&msg->owner));
6428 // 
6429 //   GNUNET_SERVER_notification_context_unicast (nc, client,
6430 //                                               &msg->header, GNUNET_NO);
6431 //   return GNUNET_YES;
6432 // }
6433
6434
6435 /**
6436  * Handler for client's MONITOR request.
6437  *
6438  * @param cls Closure (unused).
6439  * @param client Identification of the client.
6440  * @param message The actual message.
6441  */
6442 static void
6443 handle_local_get_tunnels (void *cls, struct GNUNET_SERVER_Client *client,
6444                           const struct GNUNET_MessageHeader *message)
6445 {
6446   struct MeshClient *c;
6447
6448   /* Sanity check for client registration */
6449   if (NULL == (c = client_get (client)))
6450   {
6451     GNUNET_break (0);
6452     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6453     return;
6454   }
6455
6456   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
6457               "Received get tunnels request from client %u\n",
6458               c->id);
6459 //   GNUNET_CONTAINER_multihashmap_iterate (tunnels,
6460 //                                          monitor_all_tunnels_iterator,
6461 //                                          client);
6462   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
6463               "Get tunnels request from client %u completed\n",
6464               c->id);
6465   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6466 }
6467
6468
6469 /**
6470  * Handler for client's MONITOR_TUNNEL request.
6471  *
6472  * @param cls Closure (unused).
6473  * @param client Identification of the client.
6474  * @param message The actual message.
6475  */
6476 static void
6477 handle_local_show_tunnel (void *cls, struct GNUNET_SERVER_Client *client,
6478                           const struct GNUNET_MessageHeader *message)
6479 {
6480   const struct GNUNET_MESH_LocalMonitor *msg;
6481   struct GNUNET_MESH_LocalMonitor *resp;
6482   struct MeshClient *c;
6483   struct MeshChannel *ch;
6484
6485   /* Sanity check for client registration */
6486   if (NULL == (c = client_get (client)))
6487   {
6488     GNUNET_break (0);
6489     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6490     return;
6491   }
6492
6493   msg = (struct GNUNET_MESH_LocalMonitor *) message;
6494   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
6495               "Received tunnel info request from client %u for tunnel %s[%X]\n",
6496               c->id,
6497               &msg->owner,
6498               ntohl (msg->channel_id));
6499 //   ch = channel_get (&msg->owner, ntohl (msg->channel_id));
6500   ch = NULL; // FIXME
6501   if (NULL == ch)
6502   {
6503     /* We don't know the tunnel */
6504     struct GNUNET_MESH_LocalMonitor warn;
6505
6506     warn = *msg;
6507     GNUNET_SERVER_notification_context_unicast (nc, client,
6508                                                 &warn.header,
6509                                                 GNUNET_NO);
6510     GNUNET_SERVER_receive_done (client, GNUNET_OK);
6511     return;
6512   }
6513
6514   /* Initialize context */
6515   resp = GNUNET_malloc (sizeof (struct GNUNET_MESH_LocalMonitor));
6516   *resp = *msg;
6517   resp->header.size = htons (sizeof (struct GNUNET_MESH_LocalMonitor));
6518   GNUNET_SERVER_notification_context_unicast (nc, c->handle,
6519                                               &resp->header, GNUNET_NO);
6520   GNUNET_free (resp);
6521
6522   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
6523               "Monitor tunnel request from client %u completed\n",
6524               c->id);
6525   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6526 }
6527
6528
6529 /**
6530  * Functions to handle messages from clients
6531  */
6532 static struct GNUNET_SERVER_MessageHandler client_handlers[] = {
6533   {&handle_local_new_client, NULL,
6534    GNUNET_MESSAGE_TYPE_MESH_LOCAL_CONNECT, 0},
6535   {&handle_local_channel_create, NULL,
6536    GNUNET_MESSAGE_TYPE_MESH_CHANNEL_CREATE,
6537    sizeof (struct GNUNET_MESH_ChannelMessage)},
6538   {&handle_local_channel_destroy, NULL,
6539    GNUNET_MESSAGE_TYPE_MESH_CHANNEL_DESTROY,
6540    sizeof (struct GNUNET_MESH_ChannelMessage)},
6541   {&handle_local_data, NULL,
6542    GNUNET_MESSAGE_TYPE_MESH_LOCAL_DATA, 0},
6543   {&handle_local_ack, NULL,
6544    GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK,
6545    sizeof (struct GNUNET_MESH_LocalAck)},
6546   {&handle_local_get_tunnels, NULL,
6547    GNUNET_MESSAGE_TYPE_MESH_LOCAL_INFO_TUNNELS,
6548    sizeof (struct GNUNET_MessageHeader)},
6549   {&handle_local_show_tunnel, NULL,
6550    GNUNET_MESSAGE_TYPE_MESH_LOCAL_INFO_TUNNEL,
6551      sizeof (struct GNUNET_MESH_LocalMonitor)},
6552   {NULL, NULL, 0, 0}
6553 };
6554
6555
6556 /**
6557  * Method called whenever a given peer connects.
6558  *
6559  * @param cls closure
6560  * @param peer peer identity this notification is about
6561  */
6562 static void
6563 core_connect (void *cls, const struct GNUNET_PeerIdentity *peer)
6564 {
6565   struct MeshPeer *pi;
6566   struct MeshPeerPath *path;
6567
6568   DEBUG_CONN ("Peer connected\n");
6569   DEBUG_CONN ("     %s\n", GNUNET_i2s (&my_full_id));
6570   pi = peer_get (peer);
6571   if (myid == pi->id)
6572   {
6573     DEBUG_CONN ("     (self)\n");
6574     path = path_new (1);
6575   }
6576   else
6577   {
6578     DEBUG_CONN ("     %s\n", GNUNET_i2s (peer));
6579     path = path_new (2);
6580     path->peers[1] = pi->id;
6581     GNUNET_PEER_change_rc (pi->id, 1);
6582     GNUNET_STATISTICS_update (stats, "# peers", 1, GNUNET_NO);
6583   }
6584   path->peers[0] = myid;
6585   GNUNET_PEER_change_rc (myid, 1);
6586   peer_add_path (pi, path, GNUNET_YES);
6587
6588   pi->connections = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_YES);
6589   return;
6590 }
6591
6592
6593 /**
6594  * Method called whenever a peer disconnects.
6595  *
6596  * @param cls closure
6597  * @param peer peer identity this notification is about
6598  */
6599 static void
6600 core_disconnect (void *cls, const struct GNUNET_PeerIdentity *peer)
6601 {
6602   struct MeshPeer *pi;
6603
6604   DEBUG_CONN ("Peer disconnected\n");
6605   pi = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
6606   if (NULL == pi)
6607   {
6608     GNUNET_break (0);
6609     return;
6610   }
6611
6612   peer_remove_path (pi, myid, pi->id);
6613
6614   GNUNET_CONTAINER_multihashmap_iterate (pi->connections,
6615                                          connection_broken,
6616                                          pi);
6617   GNUNET_CONTAINER_multihashmap_destroy (pi->connections);
6618   pi->connections = NULL;
6619   if (myid == pi->id)
6620   {
6621     DEBUG_CONN ("     (self)\n");
6622   }
6623   GNUNET_STATISTICS_update (stats, "# peers", -1, GNUNET_NO);
6624
6625   return;
6626 }
6627
6628
6629 /**
6630  * Install server (service) handlers and start listening to clients.
6631  */
6632 static void
6633 server_init (void)
6634 {
6635   GNUNET_SERVER_add_handlers (server_handle, client_handlers);
6636   GNUNET_SERVER_connect_notify (server_handle,
6637                                 &handle_local_client_connect, NULL);
6638   GNUNET_SERVER_disconnect_notify (server_handle,
6639                                    &handle_local_client_disconnect, NULL);
6640   nc = GNUNET_SERVER_notification_context_create (server_handle, 1);
6641
6642   clients_head = NULL;
6643   clients_tail = NULL;
6644   next_client_id = 0;
6645   GNUNET_SERVER_resume (server_handle);
6646 }
6647
6648
6649 /**
6650  * To be called on core init/fail.
6651  *
6652  * @param cls Closure (config)
6653  * @param identity the public identity of this peer
6654  */
6655 static void
6656 core_init (void *cls, 
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   if (0 != memcmp (identity, &my_full_id, sizeof (my_full_id)))
6664   {
6665     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _("Wrong CORE service\n"));
6666     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
6667                 " core id %s\n",
6668                 GNUNET_i2s (identity));
6669     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
6670                 " my id %s\n",
6671                 GNUNET_i2s (&my_full_id));
6672     GNUNET_CORE_disconnect (core_handle);
6673     core_handle = GNUNET_CORE_connect (c, /* Main configuration */
6674                                        NULL,      /* Closure passed to MESH functions */
6675                                        &core_init,        /* Call core_init once connected */
6676                                        &core_connect,     /* Handle connects */
6677                                        &core_disconnect,  /* remove peers on disconnects */
6678                                        NULL,      /* Don't notify about all incoming messages */
6679                                        GNUNET_NO, /* For header only in notification */
6680                                        NULL,      /* Don't notify about all outbound messages */
6681                                        GNUNET_NO, /* For header-only out notification */
6682                                        core_handlers);    /* Register these handlers */
6683     if (10 < i++)
6684       GNUNET_abort();
6685   }
6686   server_init ();
6687   return;
6688 }
6689
6690
6691 /******************************************************************************/
6692 /************************      MAIN FUNCTIONS      ****************************/
6693 /******************************************************************************/
6694
6695 /**
6696  * Iterator over tunnel hash map entries to destroy the tunnel during shutdown.
6697  *
6698  * @param cls closure
6699  * @param key current key code
6700  * @param value value in the hash map
6701  * @return GNUNET_YES if we should continue to iterate,
6702  *         GNUNET_NO if not.
6703  */
6704 static int
6705 shutdown_tunnel (void *cls, const struct GNUNET_HashCode * key, void *value)
6706 {
6707   struct MeshPeer *p = value;
6708   struct MeshTunnel2 *t = p->tunnel;
6709
6710   if (NULL != t)
6711     tunnel_destroy (t);
6712   return GNUNET_YES;
6713 }
6714
6715
6716 /**
6717  * Task run during shutdown.
6718  *
6719  * @param cls unused
6720  * @param tc unused
6721  */
6722 static void
6723 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
6724 {
6725   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shutting down\n");
6726
6727   if (core_handle != NULL)
6728   {
6729     GNUNET_CORE_disconnect (core_handle);
6730     core_handle = NULL;
6731   }
6732   GNUNET_CONTAINER_multihashmap_iterate (peers, &shutdown_tunnel, NULL);
6733   if (dht_handle != NULL)
6734   {
6735     GNUNET_DHT_disconnect (dht_handle);
6736     dht_handle = NULL;
6737   }
6738   if (nc != NULL)
6739   {
6740     GNUNET_SERVER_notification_context_destroy (nc);
6741     nc = NULL;
6742   }
6743   if (GNUNET_SCHEDULER_NO_TASK != announce_id_task)
6744   {
6745     GNUNET_SCHEDULER_cancel (announce_id_task);
6746     announce_id_task = GNUNET_SCHEDULER_NO_TASK;
6747   }
6748   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shut down\n");
6749 }
6750
6751
6752 /**
6753  * Process mesh requests.
6754  *
6755  * @param cls closure
6756  * @param server the initialized server
6757  * @param c configuration to use
6758  */
6759 static void
6760 run (void *cls, struct GNUNET_SERVER_Handle *server,
6761      const struct GNUNET_CONFIGURATION_Handle *c)
6762 {
6763   char *keyfile;
6764   struct GNUNET_CRYPTO_EccPrivateKey *pk;
6765
6766   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "starting to run\n");
6767   server_handle = server;
6768   GNUNET_SERVER_suspend (server_handle);
6769
6770   if (GNUNET_OK !=
6771       GNUNET_CONFIGURATION_get_value_filename (c, "PEER", "PRIVATE_KEY",
6772                                                &keyfile))
6773   {
6774     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
6775                 _
6776                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
6777                 "mesh", "peer/privatekey");
6778     GNUNET_SCHEDULER_shutdown ();
6779     return;
6780   }
6781
6782   if (GNUNET_OK !=
6783       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "REFRESH_CONNECTION_TIME",
6784                                            &refresh_connection_time))
6785   {
6786     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
6787                 _
6788                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
6789                 "mesh", "refresh path time");
6790     GNUNET_SCHEDULER_shutdown ();
6791     return;
6792   }
6793
6794   if (GNUNET_OK !=
6795       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "ID_ANNOUNCE_TIME",
6796                                            &id_announce_time))
6797   {
6798     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
6799                 _
6800                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
6801                 "mesh", "id announce time");
6802     GNUNET_SCHEDULER_shutdown ();
6803     return;
6804   }
6805
6806   if (GNUNET_OK !=
6807       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "CONNECT_TIMEOUT",
6808                                            &connect_timeout))
6809   {
6810     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
6811                 _
6812                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
6813                 "mesh", "connect timeout");
6814     GNUNET_SCHEDULER_shutdown ();
6815     return;
6816   }
6817
6818   if (GNUNET_OK !=
6819       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_MSGS_QUEUE",
6820                                              &max_msgs_queue))
6821   {
6822     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
6823                 _
6824                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
6825                 "mesh", "max msgs queue");
6826     GNUNET_SCHEDULER_shutdown ();
6827     return;
6828   }
6829
6830   if (GNUNET_OK !=
6831       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_CONNECTIONS",
6832                                              &max_connections))
6833   {
6834     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
6835                 _
6836                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
6837                 "mesh", "max tunnels");
6838     GNUNET_SCHEDULER_shutdown ();
6839     return;
6840   }
6841
6842   if (GNUNET_OK !=
6843       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DEFAULT_TTL",
6844                                              &default_ttl))
6845   {
6846     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
6847                 _
6848                 ("%s service is lacking key configuration settings (%s). Using default (%u).\n"),
6849                 "mesh", "default ttl", 64);
6850     default_ttl = 64;
6851   }
6852
6853   if (GNUNET_OK !=
6854       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_PEERS",
6855                                              &max_peers))
6856   {
6857     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
6858                 _("%s service is lacking key configuration settings (%s). Using default (%u).\n"),
6859                 "mesh", "max peers", 1000);
6860     max_peers = 1000;
6861   }
6862
6863   if (GNUNET_OK !=
6864       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DROP_PERCENT",
6865                                              &drop_percent))
6866   {
6867     drop_percent = 0;
6868   }
6869   else
6870   {
6871     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
6872                 "Mesh is running with drop mode enabled. "
6873                 "This is NOT a good idea! "
6874                 "Remove the DROP_PERCENT option from your configuration.\n");
6875   }
6876
6877   if (GNUNET_OK !=
6878       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DHT_REPLICATION_LEVEL",
6879                                              &dht_replication_level))
6880   {
6881     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
6882                 _
6883                 ("%s service is lacking key configuration settings (%s). Using default (%u).\n"),
6884                 "mesh", "dht replication level", 3);
6885     dht_replication_level = 3;
6886   }
6887
6888   connections = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_YES);
6889   peers = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
6890   ports = GNUNET_CONTAINER_multihashmap32_create (32);
6891
6892   dht_handle = GNUNET_DHT_connect (c, 64);
6893   if (NULL == dht_handle)
6894   {
6895     GNUNET_break (0);
6896   }
6897   stats = GNUNET_STATISTICS_create ("mesh", c);
6898
6899   /* Scheduled the task to clean up when shutdown is called */
6900   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
6901                                 NULL);
6902   pk = GNUNET_CRYPTO_ecc_key_create_from_file (keyfile);
6903   GNUNET_free (keyfile);
6904   GNUNET_assert (NULL != pk);
6905   my_private_key = pk;
6906   GNUNET_CRYPTO_ecc_key_get_public (my_private_key, &my_public_key);
6907   GNUNET_CRYPTO_hash (&my_public_key, sizeof (my_public_key),
6908                       &my_full_id.hashPubKey);
6909   myid = GNUNET_PEER_intern (&my_full_id);
6910   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
6911               "Mesh for peer [%s] starting\n",
6912               GNUNET_i2s(&my_full_id));
6913
6914   core_handle = GNUNET_CORE_connect (c, /* Main configuration */
6915                                      NULL,      /* Closure passed to MESH functions */
6916                                      &core_init,        /* Call core_init once connected */
6917                                      &core_connect,     /* Handle connects */
6918                                      &core_disconnect,  /* remove peers on disconnects */
6919                                      NULL,      /* Don't notify about all incoming messages */
6920                                      GNUNET_NO, /* For header only in notification */
6921                                      NULL,      /* Don't notify about all outbound messages */
6922                                      GNUNET_NO, /* For header-only out notification */
6923                                      core_handlers);    /* Register these handlers */
6924   if (NULL == core_handle)
6925   {
6926     GNUNET_break (0);
6927     GNUNET_SCHEDULER_shutdown ();
6928     return;
6929   }
6930   announce_id_task = GNUNET_SCHEDULER_add_now (&announce_id, cls);
6931   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Mesh service running\n");
6932 }
6933
6934
6935 /**
6936  * The main function for the mesh service.
6937  *
6938  * @param argc number of arguments from the command line
6939  * @param argv command line arguments
6940  * @return 0 ok, 1 on error
6941  */
6942 int
6943 main (int argc, char *const *argv)
6944 {
6945   int ret;
6946   int r;
6947
6948   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "main()\n");
6949   r = GNUNET_SERVICE_run (argc, argv, "mesh", GNUNET_SERVICE_OPTION_NONE, &run,
6950                           NULL);
6951   ret = (GNUNET_OK == r) ? 0 : 1;
6952   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "main() END\n");
6953
6954   INTERVAL_SHOW;
6955
6956   return ret;
6957 }