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