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