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