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