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