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