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