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