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