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