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