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