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