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