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