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