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