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