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