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