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