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