moving to new, fixed-size encoding of public and private ECC keys everywhere, also...
[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 /**
4274  * Handler for mesh network traffic going from the origin to a peer
4275  *
4276  * @param t Tunnel on which we got this message.
4277  * @param message Data message.
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_unicast (struct MeshTunnel2 *t, const struct GNUNET_MESH_Data *message)
4284 {
4285   return handle_data (t, message, GNUNET_YES);
4286 }
4287
4288
4289 /**
4290  * Handler for mesh network traffic towards the owner of a tunnel.
4291  *
4292  * @param t Tunnel on which we got this message.
4293  * @param message Data message.
4294  *
4295  * @return GNUNET_OK to keep the connection open,
4296  *         GNUNET_SYSERR to close it (signal serious error)
4297  */
4298 static int
4299 handle_to_orig (struct MeshTunnel2 *t, const struct GNUNET_MESH_Data *message)
4300 {
4301   return handle_data (t, message, GNUNET_NO);
4302 }
4303
4304
4305 /**
4306  * Handler for mesh network traffic end-to-end ACKs.
4307  *
4308  * @param t Tunnel on which we got this message.
4309  * @param message Data message.
4310  * @param fwd Is this a fwd ACK? (dest->orig)
4311  *
4312  * @return GNUNET_OK to keep the connection open,
4313  *         GNUNET_SYSERR to close it (signal serious error)
4314  */
4315 static int
4316 handle_data_ack (struct MeshTunnel2 *t,
4317                  const struct GNUNET_MESH_DataACK *msg, int fwd)
4318 {
4319   struct MeshChannelReliability *rel;
4320   struct MeshReliableMessage *copy;
4321   struct MeshReliableMessage *next;
4322   struct MeshChannel *ch;
4323   uint32_t ack;
4324   uint16_t type;
4325   int work;
4326
4327   type = ntohs (msg->header.type);
4328   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a %s message!\n",
4329               GNUNET_MESH_DEBUG_M2S (type));
4330   ch = channel_get (t, ntohl (msg->chid));
4331   if (NULL == ch)
4332   {
4333     GNUNET_STATISTICS_update (stats, "# ack on unknown channel", 1, GNUNET_NO);
4334     return GNUNET_OK;
4335   }
4336   ack = ntohl (msg->mid);
4337   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! %s ACK %u\n",
4338               (GNUNET_YES == fwd) ? "FWD" : "BCK", ack);
4339
4340   if (GNUNET_YES == fwd && GNUNET_MESSAGE_TYPE_MESH_UNICAST_ACK == type)
4341   {
4342     rel = ch->fwd_rel;
4343   }
4344   else if (GNUNET_NO == fwd && GNUNET_MESSAGE_TYPE_MESH_TO_ORIG_ACK == type)
4345   {
4346     rel = ch->bck_rel;
4347   }
4348   if (NULL == rel)
4349   {
4350     return GNUNET_OK;
4351   }
4352
4353   for (work = GNUNET_NO, copy = rel->head_sent; copy != NULL; copy = next)
4354   {
4355     if (GMC_is_pid_bigger (copy->mid, ack))
4356     {
4357       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!!  head %u, out!\n", copy->mid);
4358       channel_rel_free_sent (rel, msg);
4359       break;
4360     }
4361     work = GNUNET_YES;
4362     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!!  id %u\n", copy->mid);
4363     next = copy->next;
4364     rel_message_free (copy);
4365   }
4366   /* ACK client if needed */
4367 //   channel_send_ack (t, type, GNUNET_MESSAGE_TYPE_MESH_UNICAST_ACK == type);
4368
4369   /* If some message was free'd, update the retransmission delay*/
4370   if (GNUNET_YES == work)
4371   {
4372     if (GNUNET_SCHEDULER_NO_TASK != rel->retry_task)
4373     {
4374       GNUNET_SCHEDULER_cancel (rel->retry_task);
4375       if (NULL == rel->head_sent)
4376       {
4377         rel->retry_task = GNUNET_SCHEDULER_NO_TASK;
4378       }
4379       else
4380       {
4381         struct GNUNET_TIME_Absolute new_target;
4382         struct GNUNET_TIME_Relative delay;
4383
4384         delay = GNUNET_TIME_relative_multiply (rel->retry_timer,
4385                                                MESH_RETRANSMIT_MARGIN);
4386         new_target = GNUNET_TIME_absolute_add (rel->head_sent->timestamp,
4387                                                delay);
4388         delay = GNUNET_TIME_absolute_get_remaining (new_target);
4389         rel->retry_task =
4390             GNUNET_SCHEDULER_add_delayed (delay,
4391                                           &channel_retransmit_message,
4392                                           rel);
4393       }
4394     }
4395     else
4396       GNUNET_break (0);
4397   }
4398   return GNUNET_OK;
4399 }
4400
4401
4402 /**
4403  * Core handler for connection creation.
4404  *
4405  * @param cls Closure (unused).
4406  * @param peer Sender (neighbor).
4407  * @param message Message.
4408  *
4409  * @return GNUNET_OK to keep the connection open,
4410  *         GNUNET_SYSERR to close it (signal serious error)
4411  */
4412 static int
4413 handle_mesh_connection_create (void *cls,
4414                                const struct GNUNET_PeerIdentity *peer,
4415                                const struct GNUNET_MessageHeader *message)
4416 {
4417   struct GNUNET_MESH_ConnectionCreate *msg;
4418   struct GNUNET_PeerIdentity *id;
4419   struct GNUNET_HashCode *tid;
4420   struct MeshPeerPath *path;
4421   struct MeshPeer *dest_peer;
4422   struct MeshPeer *orig_peer;
4423   struct MeshConnection *c;
4424   unsigned int own_pos;
4425   uint32_t cid;
4426   uint16_t size;
4427   uint16_t i;
4428
4429   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received a connection create msg\n");
4430
4431   /* Check size */
4432   size = ntohs (message->size);
4433   if (size < sizeof (struct GNUNET_MESH_ConnectionCreate))
4434   {
4435     GNUNET_break_op (0);
4436     return GNUNET_OK;
4437   }
4438
4439   /* Calculate hops */
4440   size -= sizeof (struct GNUNET_MESH_ConnectionCreate);
4441   if (size % sizeof (struct GNUNET_PeerIdentity))
4442   {
4443     GNUNET_break_op (0);
4444     return GNUNET_OK;
4445   }
4446   size /= sizeof (struct GNUNET_PeerIdentity);
4447   if (1 > size)
4448   {
4449     GNUNET_break_op (0);
4450     return GNUNET_OK;
4451   }
4452   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "    path has %u hops.\n", size);
4453
4454   /* Get parameters */
4455   msg = (struct GNUNET_MESH_ConnectionCreate *) message;
4456   cid = ntohl (msg->cid);
4457   tid = &msg->tid;
4458   id = (struct GNUNET_PeerIdentity *) &msg[1];
4459   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4460               "    connection %s[%X] (%s).\n",
4461               GNUNET_h2s (tid), cid, GNUNET_i2s (id));
4462
4463   /* Create connection */
4464   c = connection_get (tid, cid);
4465   if (NULL == c)
4466   {
4467     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Creating connection\n");
4468     c = connection_new (tid, cid);
4469     if (NULL == c)
4470       return GNUNET_OK;
4471   }
4472   connection_reset_timeout (c, GNUNET_YES);
4473   tunnel_change_state (c->t,  MESH_TUNNEL_WAITING);
4474
4475   /* Remember peers */
4476   dest_peer = peer_get (&id[size - 1]);
4477   orig_peer = peer_get (&id[0]);
4478
4479   /* Create path */
4480   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Creating path...\n");
4481   path = path_new (size);
4482   own_pos = 0;
4483   for (i = 0; i < size; i++)
4484   {
4485     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  ... adding %s\n",
4486                 GNUNET_i2s (&id[i]));
4487     path->peers[i] = GNUNET_PEER_intern (&id[i]);
4488     if (path->peers[i] == myid)
4489       own_pos = i;
4490   }
4491   if (own_pos == 0 && path->peers[own_pos] != myid)
4492   {
4493     /* create path: self not found in path through self */
4494     GNUNET_break_op (0);
4495     path_destroy (path);
4496     connection_destroy (c);
4497     return GNUNET_OK;
4498   }
4499   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Own position: %u\n", own_pos);
4500   path_add_to_peers (path, GNUNET_NO);
4501   c->path = path;
4502   c->own_pos = own_pos;
4503
4504   /* Is it a connection to us? */
4505   if (own_pos == size - 1)
4506   {
4507     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  It's for us!\n");
4508     peer_add_path_to_origin (orig_peer, path, GNUNET_YES);
4509
4510     send_connection_ack (c);
4511
4512     /* Keep tunnel alive in direction dest->owner*/
4513     connection_reset_timeout (c, GNUNET_NO); 
4514   }
4515   else
4516   {
4517     /* It's for somebody else! Retransmit. */
4518     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Retransmitting.\n");
4519     peer_add_path (dest_peer, path_duplicate (path), GNUNET_NO);
4520     peer_add_path_to_origin (orig_peer, path, GNUNET_NO);
4521     send_prebuilt_message_connection (message, c, NULL, GNUNET_YES);
4522   }
4523   return GNUNET_OK;
4524 }
4525
4526
4527 /**
4528  * Core handler for path ACKs
4529  *
4530  * @param cls closure
4531  * @param message message
4532  * @param peer peer identity this notification is about
4533  *
4534  * @return GNUNET_OK to keep the connection open,
4535  *         GNUNET_SYSERR to close it (signal serious error)
4536  */
4537 static int
4538 handle_mesh_connection_ack (void *cls, const struct GNUNET_PeerIdentity *peer,
4539                             const struct GNUNET_MessageHeader *message)
4540 {
4541   struct GNUNET_MESH_ConnectionACK *msg;
4542   struct MeshPeerPath *p;
4543   struct MeshConnection *c;
4544   uint32_t cid;
4545
4546   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received a connection ACK msg\n");
4547   msg = (struct GNUNET_MESH_ConnectionACK *) message;
4548   cid = ntohl(msg->cid);
4549   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on connection %s[%X]\n",
4550               GNUNET_h2s (&msg->tid), cid);
4551   c = connection_get (&msg->tid, cid);
4552   if (NULL == c)
4553   {
4554     GNUNET_STATISTICS_update (stats, "# control on unknown connection",
4555                               1, GNUNET_NO);
4556     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  don't know the connection!\n");
4557     return GNUNET_OK;
4558   }
4559
4560   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  via peer %s\n",
4561               GNUNET_i2s (peer));
4562
4563   /* Add path to peers? */
4564   p = c->path;
4565   if (NULL != p)
4566   {
4567     path_add_to_peers (p, GNUNET_YES);
4568   }
4569   else
4570   {
4571     GNUNET_break (0);
4572   }
4573   connection_change_state (c, MESH_CONNECTION_READY);
4574   connection_reset_timeout (c, GNUNET_NO);
4575
4576   /* Message for us? */
4577   if (NULL != c->t->channel_head)
4578   {
4579     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  It's for us!\n");
4580     if (3 <= tunnel_count_connections(c->t) && NULL != c->t->peer->dhtget)
4581     {
4582       GNUNET_DHT_get_stop (c->t->peer->dhtget);
4583       c->t->peer->dhtget = NULL;
4584     }
4585     //connection_send_ack (c, GNUNET_NO); /* FIXME */
4586     return GNUNET_OK;
4587   }
4588
4589   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  not for us, retransmitting...\n");
4590   send_prebuilt_message_connection (message, c, NULL, GNUNET_NO);
4591   return GNUNET_OK;
4592 }
4593
4594
4595 /**
4596  * Core handler for notifications of broken paths
4597  *
4598  * @param cls Closure (unused).
4599  * @param peer Peer identity of sending neighbor.
4600  * @param message Message.
4601  *
4602  * @return GNUNET_OK to keep the connection open,
4603  *         GNUNET_SYSERR to close it (signal serious error)
4604  */
4605 static int
4606 handle_mesh_connection_broken (void *cls, const struct GNUNET_PeerIdentity *peer,
4607                                const struct GNUNET_MessageHeader *message)
4608 {
4609   struct GNUNET_MESH_ConnectionBroken *msg;
4610   struct MeshConnection *c;
4611
4612   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4613               "Received a CONNECTION BROKEN msg from %s\n", GNUNET_i2s (peer));
4614   msg = (struct GNUNET_MESH_ConnectionBroken *) message;
4615   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  regarding %s\n",
4616               GNUNET_i2s (&msg->peer1));
4617   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  regarding %s\n",
4618               GNUNET_i2s (&msg->peer2));
4619   c = connection_get (&msg->tid, ntohl (msg->cid));
4620   if (NULL == c)
4621   {
4622     GNUNET_break_op (0);
4623     return GNUNET_OK;
4624   }
4625   tunnel_notify_connection_broken (c->t, GNUNET_PEER_search (&msg->peer1),
4626                                    GNUNET_PEER_search (&msg->peer2));
4627   return GNUNET_OK;
4628
4629 }
4630
4631
4632 /**
4633  * Core handler for tunnel destruction
4634  *
4635  * @param cls Closure (unused).
4636  * @param peer Peer identity of sending neighbor.
4637  * @param message Message.
4638  *
4639  * @return GNUNET_OK to keep the connection open,
4640  *         GNUNET_SYSERR to close it (signal serious error)
4641  */
4642 static int
4643 handle_mesh_connection_destroy (void *cls,
4644                                 const struct GNUNET_PeerIdentity *peer,
4645                                 const struct GNUNET_MessageHeader *message)
4646 {
4647   struct GNUNET_MESH_ConnectionDestroy *msg;
4648   struct MeshConnection *c;
4649   GNUNET_PEER_Id id;
4650   int fwd;
4651
4652   msg = (struct GNUNET_MESH_ConnectionDestroy *) message;
4653   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4654               "Got a CONNECTION DESTROY message from %s\n",
4655               GNUNET_i2s (peer));
4656   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4657               "  for connection %s[%X]\n",
4658               GNUNET_h2s (&msg->tid), ntohl (msg->cid));
4659   c = connection_get (&msg->tid, ntohl (msg->cid));
4660   if (NULL == c)
4661   {
4662     /* Probably already got the message from another path,
4663      * destroyed the tunnel and retransmitted to children.
4664      * Safe to ignore.
4665      */
4666     GNUNET_STATISTICS_update (stats, "# control on unknown tunnel",
4667                               1, GNUNET_NO);
4668     return GNUNET_OK;
4669   }
4670   id = GNUNET_PEER_search (peer);
4671   if (id == connection_get_prev_hop (c)->id)
4672     fwd = GNUNET_YES;
4673   else if (id == connection_get_next_hop (c)->id)
4674     fwd = GNUNET_NO;
4675   else
4676   {
4677     GNUNET_break_op (0);
4678     return GNUNET_OK;
4679   }
4680   send_prebuilt_message_connection (message, c, NULL, fwd);
4681   c->destroy = GNUNET_YES;
4682
4683   return GNUNET_OK;
4684 }
4685
4686
4687 /**
4688  * Generic handler for mesh network encrypted traffic.
4689  *
4690  * @param peer Peer identity this notification is about.
4691  * @param message Encrypted message.
4692  * @param fwd Is this FWD traffic? GNUNET_YES : GNUNET_NO;
4693  *
4694  * @return GNUNET_OK to keep the connection open,
4695  *         GNUNET_SYSERR to close it (signal serious error)
4696  */
4697 static int
4698 handle_mesh_encrypted (const struct GNUNET_PeerIdentity *peer,
4699                        const struct GNUNET_MESH_Encrypted *msg,
4700                        int fwd)
4701 {
4702   struct MeshConnection *c;
4703   struct MeshTunnel2 *t;
4704   struct MeshPeer *neighbor;
4705   struct MeshFlowControl *fc;
4706   uint32_t pid;
4707   uint32_t ttl;
4708   uint16_t type;
4709   size_t size;
4710
4711   /* Check size */
4712   size = ntohs (msg->header.size);
4713   if (size <
4714       sizeof (struct GNUNET_MESH_Encrypted) +
4715       sizeof (struct GNUNET_MessageHeader))
4716   {
4717     GNUNET_break (0);
4718     return GNUNET_OK;
4719   }
4720   type = ntohs (msg->header.type);
4721   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a %s message from %s\n",
4722               GNUNET_MESH_DEBUG_M2S (type), GNUNET_i2s (peer));
4723
4724   /* Check connection */
4725   c = connection_get (&msg->tid, ntohl (msg->cid));
4726   if (NULL == c)
4727   {
4728     GNUNET_STATISTICS_update (stats, "# unknown connection", 1, GNUNET_NO);
4729     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "WARNING connection unknown\n");
4730     return GNUNET_OK;
4731   }
4732   t = c->t;
4733   fc = fwd ? c->fwd_fc : c->bck_fc;
4734
4735   /* Check if origin is as expected */
4736   neighbor = fwd ? connection_get_prev_hop (c) : connection_get_next_hop (c);
4737   if (peer_get (peer)->id != neighbor->id)
4738   {
4739     GNUNET_break_op (0);
4740     return GNUNET_OK;
4741   }
4742
4743   /* Check PID */
4744   pid = ntohl (msg->pid);
4745   if (GMC_is_pid_bigger (pid, fc->last_ack_sent))
4746   {
4747     GNUNET_STATISTICS_update (stats, "# unsolicited message", 1, GNUNET_NO);
4748     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4749                 "WARNING Received PID %u, (prev %u), ACK %u\n",
4750                 pid, fc->last_pid_recv, fc->last_ack_sent);
4751     return GNUNET_OK;
4752   }
4753   if (GNUNET_NO == GMC_is_pid_bigger (pid, fc->last_pid_recv))
4754   {
4755     GNUNET_STATISTICS_update (stats, "# duplicate PID", 1, GNUNET_NO);
4756     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4757                 " Pid %u not expected (%u+), dropping!\n",
4758                 pid, fc->last_pid_recv + 1);
4759     return GNUNET_OK;
4760   }
4761   if (MESH_CONNECTION_SENT == c->state)
4762     connection_change_state (c, MESH_CONNECTION_READY);
4763   connection_reset_timeout (c, fwd);
4764   fc->last_pid_recv = pid;
4765
4766   /* Is this message for us? */
4767   if (NULL != c->t->channel_head)
4768   {
4769     size_t dsize = size - sizeof (struct GNUNET_MESH_Encrypted);
4770     char cbuf[dsize];
4771     struct GNUNET_MESH_Data *dmsg;
4772
4773     /* TODO signature verification */
4774     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  it's for us!\n");
4775     GNUNET_STATISTICS_update (stats, "# messages received", 1, GNUNET_NO);
4776
4777     fc->last_pid_recv = pid;
4778     tunnel_decrypt (t, cbuf, &msg[1], dsize, msg->iv, fwd);
4779     dmsg = (struct GNUNET_MESH_Data *) cbuf;
4780     handle_data (t, dmsg, fwd);
4781     connection_send_ack (c, fwd);
4782     return GNUNET_OK;
4783   }
4784
4785   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  not for us, retransmitting...\n");
4786   ttl = ntohl (msg->ttl);
4787   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   ttl: %u\n", ttl);
4788   if (ttl == 0)
4789   {
4790     GNUNET_STATISTICS_update (stats, "# TTL drops", 1, GNUNET_NO);
4791     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, " TTL is 0, DROPPING!\n");
4792     connection_send_ack (c, fwd);
4793     return GNUNET_OK;
4794   }
4795   GNUNET_STATISTICS_update (stats, "# messages forwarded", 1, GNUNET_NO);
4796
4797   send_prebuilt_message_connection (&msg->header, c, NULL, fwd);
4798   connection_send_ack (c, fwd);
4799
4800   return GNUNET_OK;
4801 }
4802
4803
4804 /**
4805  * Core handler for mesh network traffic going orig->dest.
4806  *
4807  * @param cls Closure (unused).
4808  * @param message Message received.
4809  * @param peer Peer who sent the message.
4810  *
4811  * @return GNUNET_OK to keep the connection open,
4812  *         GNUNET_SYSERR to close it (signal serious error)
4813  */
4814 static int
4815 handle_mesh_fwd (void *cls, const struct GNUNET_PeerIdentity *peer,
4816                      const struct GNUNET_MessageHeader *message)
4817 {
4818   return handle_mesh_encrypted (peer,
4819                                 (struct GNUNET_MESH_Encrypted *)message,
4820                                 GNUNET_YES);
4821 }
4822
4823 /**
4824  * Core handler for mesh network traffic going dest->orig.
4825  *
4826  * @param cls Closure (unused).
4827  * @param message Message received.
4828  * @param peer Peer who sent the message.
4829  *
4830  * @return GNUNET_OK to keep the connection open,
4831  *         GNUNET_SYSERR to close it (signal serious error)
4832  */
4833 static int
4834 handle_mesh_bck (void *cls, const struct GNUNET_PeerIdentity *peer,
4835                      const struct GNUNET_MessageHeader *message)
4836 {
4837   return handle_mesh_encrypted (peer,
4838                                 (struct GNUNET_MESH_Encrypted *)message,
4839                                 GNUNET_NO);
4840 }
4841
4842
4843 /**
4844  * Core handler for mesh network traffic point-to-point acks.
4845  *
4846  * @param cls closure
4847  * @param message message
4848  * @param peer peer identity this notification is about
4849  *
4850  * @return GNUNET_OK to keep the connection open,
4851  *         GNUNET_SYSERR to close it (signal serious error)
4852  */
4853 static int
4854 handle_mesh_ack (void *cls, const struct GNUNET_PeerIdentity *peer,
4855                  const struct GNUNET_MessageHeader *message)
4856 {
4857   struct GNUNET_MESH_ACK *msg;
4858   struct MeshConnection *c;
4859   struct MeshFlowControl *fc;
4860   GNUNET_PEER_Id id;
4861   uint32_t ack;
4862
4863   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got an ACK packet from %s!\n",
4864               GNUNET_i2s (peer));
4865   msg = (struct GNUNET_MESH_ACK *) message;
4866
4867   c = connection_get (&msg->tid, ntohl (msg->cid));
4868
4869   if (NULL == c)
4870   {
4871     GNUNET_STATISTICS_update (stats, "# ack on unknown connection", 1,
4872                               GNUNET_NO);
4873     return GNUNET_OK;
4874   }
4875
4876   ack = ntohl (msg->ack);
4877   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  ACK %u\n", ack);
4878
4879   /* Is this a forward or backward ACK? */
4880   id = GNUNET_PEER_search (peer);
4881   if (connection_get_next_hop (c)->id == id)
4882   {
4883     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  FWD ACK\n");
4884     fc = c->fwd_fc;
4885   }
4886   else if (connection_get_prev_hop (c)->id == id)
4887   {
4888     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  BCK ACK\n");
4889     fc = c->bck_fc;
4890   }
4891   else
4892   {
4893     GNUNET_break_op (0);
4894     return GNUNET_OK;
4895   }
4896
4897   /* Cancel polling if the ACK is bigger than before. */
4898   if (GNUNET_SCHEDULER_NO_TASK != fc->poll_task &&
4899       GMC_is_pid_bigger (ack, fc->last_ack_recv))
4900   {
4901     GNUNET_SCHEDULER_cancel (fc->poll_task);
4902     fc->poll_task = GNUNET_SCHEDULER_NO_TASK;
4903     fc->poll_time = GNUNET_TIME_UNIT_SECONDS;
4904   }
4905
4906   fc->last_ack_recv = ack;
4907   connection_unlock_queue (c, fc == c->fwd_fc);
4908
4909   return GNUNET_OK;
4910 }
4911
4912
4913 /**
4914  * Core handler for mesh network traffic point-to-point ack polls.
4915  *
4916  * @param cls closure
4917  * @param message message
4918  * @param peer peer identity this notification is about
4919  *
4920  * @return GNUNET_OK to keep the connection open,
4921  *         GNUNET_SYSERR to close it (signal serious error)
4922  */
4923 static int
4924 handle_mesh_poll (void *cls, const struct GNUNET_PeerIdentity *peer,
4925                   const struct GNUNET_MessageHeader *message)
4926 {
4927   struct GNUNET_MESH_Poll *msg;
4928   struct MeshConnection *c;
4929   struct MeshFlowControl *fc;
4930   GNUNET_PEER_Id id;
4931   uint32_t pid;
4932
4933   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a POLL packet from %s!\n",
4934               GNUNET_i2s (peer));
4935
4936   msg = (struct GNUNET_MESH_Poll *) message;
4937
4938   c = connection_get (&msg->tid, ntohl (msg->cid));
4939
4940   if (NULL == c)
4941   {
4942     GNUNET_STATISTICS_update (stats, "# poll on unknown connection", 1,
4943                               GNUNET_NO);
4944     GNUNET_break_op (0);
4945     return GNUNET_OK;
4946   }
4947
4948   /* Is this a forward or backward ACK? */
4949   id = GNUNET_PEER_search (peer);
4950   if (connection_get_next_hop (c)->id == id)
4951   {
4952     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  FWD ACK\n");
4953     fc = c->fwd_fc;
4954   }
4955   else if (connection_get_prev_hop (c)->id == id)
4956   {
4957     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  BCK ACK\n");
4958     fc = c->bck_fc;
4959   }
4960   else
4961   {
4962     GNUNET_break_op (0);
4963     return GNUNET_OK;
4964   }
4965
4966   pid = ntohl (msg->pid);
4967   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  PID %u, OLD %u\n",
4968               pid, fc->last_pid_recv);
4969   fc->last_pid_recv = pid;
4970   connection_send_ack (c, fc == c->fwd_fc);
4971
4972   return GNUNET_OK;
4973 }
4974
4975
4976 /**
4977  * Core handler for mesh keepalives.
4978  *
4979  * @param cls closure
4980  * @param message message
4981  * @param peer peer identity this notification is about
4982  * @return GNUNET_OK to keep the connection open,
4983  *         GNUNET_SYSERR to close it (signal serious error)
4984  *
4985  * TODO: Check who we got this from, to validate route.
4986  */
4987 static int
4988 handle_mesh_keepalive (void *cls, const struct GNUNET_PeerIdentity *peer,
4989                        const struct GNUNET_MessageHeader *message)
4990 {
4991   struct GNUNET_MESH_ConnectionKeepAlive *msg;
4992   struct MeshConnection *c;
4993   struct MeshPeer *neighbor;
4994   int fwd;
4995
4996   msg = (struct GNUNET_MESH_ConnectionKeepAlive *) message;
4997   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a keepalive packet from %s\n",
4998               GNUNET_i2s (peer));
4999
5000   c = connection_get (&msg->tid, ntohl (msg->cid));
5001   if (NULL == c)
5002   {
5003     GNUNET_STATISTICS_update (stats, "# keepalive on unknown connection", 1,
5004                               GNUNET_NO);
5005     return GNUNET_OK;
5006   }
5007
5008   fwd = GNUNET_MESSAGE_TYPE_MESH_FWD_KEEPALIVE == ntohs (message->type) ? 
5009         GNUNET_YES : GNUNET_NO;
5010
5011   /* Check if origin is as expected */
5012   neighbor = fwd ? connection_get_prev_hop (c) : connection_get_next_hop (c);
5013   if (peer_get (peer)->id != neighbor->id)
5014   {
5015     GNUNET_break_op (0);
5016     return GNUNET_OK;
5017   }
5018
5019   connection_change_state (c, MESH_CONNECTION_READY);
5020   connection_reset_timeout (c, fwd);
5021
5022   if (NULL != c->t->channel_head)
5023     return GNUNET_OK;
5024
5025   GNUNET_STATISTICS_update (stats, "# keepalives forwarded", 1, GNUNET_NO);
5026   send_prebuilt_message_connection (message, c, NULL, fwd);
5027
5028   return GNUNET_OK;
5029 }
5030
5031
5032
5033 /**
5034  * Functions to handle messages from core
5035  */
5036 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
5037   {&handle_mesh_connection_create, GNUNET_MESSAGE_TYPE_MESH_CONNECTION_CREATE,
5038     0},
5039   {&handle_mesh_connection_ack, GNUNET_MESSAGE_TYPE_MESH_CONNECTION_ACK,
5040     sizeof (struct GNUNET_MESH_ConnectionACK)},
5041   {&handle_mesh_connection_broken, GNUNET_MESSAGE_TYPE_MESH_CONNECTION_BROKEN,
5042     sizeof (struct GNUNET_MESH_ConnectionBroken)},
5043   {&handle_mesh_connection_destroy, GNUNET_MESSAGE_TYPE_MESH_CONNECTION_DESTROY,
5044     sizeof (struct GNUNET_MESH_ConnectionDestroy)},
5045   {&handle_mesh_keepalive, GNUNET_MESSAGE_TYPE_MESH_FWD_KEEPALIVE,
5046     sizeof (struct GNUNET_MESH_ConnectionKeepAlive)},
5047   {&handle_mesh_keepalive, GNUNET_MESSAGE_TYPE_MESH_BCK_KEEPALIVE,
5048     sizeof (struct GNUNET_MESH_ConnectionKeepAlive)},
5049   {&handle_mesh_ack, GNUNET_MESSAGE_TYPE_MESH_ACK,
5050     sizeof (struct GNUNET_MESH_ACK)},
5051   {&handle_mesh_poll, GNUNET_MESSAGE_TYPE_MESH_POLL,
5052     sizeof (struct GNUNET_MESH_Poll)},
5053   {&handle_mesh_fwd, GNUNET_MESSAGE_TYPE_MESH_FWD, 0},
5054   {&handle_mesh_bck, GNUNET_MESSAGE_TYPE_MESH_BCK, 0},
5055   {NULL, 0, 0}
5056 };
5057
5058
5059 /**
5060  * Function to process paths received for a new peer addition. The recorded
5061  * paths form the initial tunnel, which can be optimized later.
5062  * Called on each result obtained for the DHT search.
5063  *
5064  * @param cls closure
5065  * @param exp when will this value expire
5066  * @param key key of the result
5067  * @param get_path path of the get request
5068  * @param get_path_length lenght of get_path
5069  * @param put_path path of the put request
5070  * @param put_path_length length of the put_path
5071  * @param type type of the result
5072  * @param size number of bytes in data
5073  * @param data pointer to the result data
5074  */
5075 static void
5076 dht_get_id_handler (void *cls, struct GNUNET_TIME_Absolute exp,
5077                     const struct GNUNET_HashCode * key,
5078                     const struct GNUNET_PeerIdentity *get_path,
5079                     unsigned int get_path_length,
5080                     const struct GNUNET_PeerIdentity *put_path,
5081                     unsigned int put_path_length, enum GNUNET_BLOCK_Type type,
5082                     size_t size, const void *data)
5083 {
5084   struct MeshPeer *peer = cls;
5085   struct MeshPeerPath *p;
5086   struct MeshConnection *c;
5087   struct GNUNET_PeerIdentity pi;
5088   int i;
5089
5090   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got results from DHT!\n");
5091   GNUNET_PEER_resolve (peer->id, &pi);
5092   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  for %s\n", GNUNET_i2s (&pi));
5093
5094   p = path_build_from_dht (get_path, get_path_length,
5095                            put_path, put_path_length);
5096   path_add_to_peers (p, GNUNET_NO);
5097   path_destroy (p);
5098
5099   /* Count connections */
5100   for (c = peer->tunnel->connection_head, i = 0; NULL != c; c = c->next, i++);
5101
5102   /* If we already have 3 (or more (?!)) connections, it's enough */
5103   if (3 <= i)
5104     return;
5105
5106   if (peer->tunnel->state == MESH_TUNNEL_SEARCHING)
5107   {
5108     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " ... connect!\n");
5109     peer_connect (peer);
5110   }
5111   return;
5112 }
5113
5114
5115 /******************************************************************************/
5116 /*********************       MESH LOCAL HANDLES      **************************/
5117 /******************************************************************************/
5118
5119
5120 /**
5121  * Handler for client connection.
5122  *
5123  * @param cls Closure (unused).
5124  * @param client Client handler.
5125  */
5126 static void
5127 handle_local_client_connect (void *cls, struct GNUNET_SERVER_Client *client)
5128 {
5129   struct MeshClient *c;
5130
5131   if (NULL == client)
5132     return;
5133   c = GNUNET_malloc (sizeof (struct MeshClient));
5134   c->handle = client;
5135   c->id = next_client_id++; /* overflow not important: just for debug */
5136   GNUNET_SERVER_client_keep (client);
5137   GNUNET_SERVER_client_set_user_context (client, c);
5138   GNUNET_CONTAINER_DLL_insert (clients_head, clients_tail, c);
5139 }
5140
5141
5142 /**
5143  * Handler for client disconnection
5144  *
5145  * @param cls closure
5146  * @param client identification of the client; NULL
5147  *        for the last call when the server is destroyed
5148  */
5149 static void
5150 handle_local_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
5151 {
5152   struct MeshClient *c;
5153   struct MeshClient *next;
5154
5155   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "client disconnected: %p\n", client);
5156   if (client == NULL)
5157   {
5158     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   (SERVER DOWN)\n");
5159     return;
5160   }
5161
5162   c = client_get (client);
5163   if (NULL != c)
5164   {
5165     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "matching client found (%u, %p)\n",
5166                 c->id, c);
5167     GNUNET_SERVER_client_drop (c->handle);
5168     c->shutting_down = GNUNET_YES;
5169     if (NULL != c->own_channels)
5170     {
5171       GNUNET_CONTAINER_multihashmap32_iterate (c->own_channels,
5172                                                &channel_destroy_iterator, c);
5173       GNUNET_CONTAINER_multihashmap32_destroy (c->own_channels);
5174     }
5175
5176     if (NULL != c->incoming_channels)
5177     {
5178       GNUNET_CONTAINER_multihashmap32_iterate (c->incoming_channels,
5179                                                &channel_destroy_iterator, c);
5180       GNUNET_CONTAINER_multihashmap32_destroy (c->incoming_channels);
5181     }
5182
5183     if (NULL != c->ports)
5184     {
5185       GNUNET_CONTAINER_multihashmap32_iterate (c->ports,
5186                                                &client_release_ports, c);
5187       GNUNET_CONTAINER_multihashmap32_destroy (c->ports);
5188     }
5189     next = c->next;
5190     GNUNET_CONTAINER_DLL_remove (clients_head, clients_tail, c);
5191     GNUNET_STATISTICS_update (stats, "# clients", -1, GNUNET_NO);
5192     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  client free (%p)\n", c);
5193     GNUNET_free (c);
5194     c = next;
5195   }
5196   else
5197   {
5198     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, " context NULL!\n");
5199   }
5200   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "done!\n");
5201   return;
5202 }
5203
5204
5205 /**
5206  * Handler for new clients
5207  *
5208  * @param cls closure
5209  * @param client identification of the client
5210  * @param message the actual message, which includes messages the client wants
5211  */
5212 static void
5213 handle_local_new_client (void *cls, struct GNUNET_SERVER_Client *client,
5214                          const struct GNUNET_MessageHeader *message)
5215 {
5216   struct GNUNET_MESH_ClientConnect *cc_msg;
5217   struct MeshClient *c;
5218   unsigned int size;
5219   uint32_t *p;
5220   unsigned int i;
5221
5222   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new client connected %p\n", client);
5223
5224   /* Check data sanity */
5225   size = ntohs (message->size) - sizeof (struct GNUNET_MESH_ClientConnect);
5226   cc_msg = (struct GNUNET_MESH_ClientConnect *) message;
5227   if (0 != (size % sizeof (uint32_t)))
5228   {
5229     GNUNET_break (0);
5230     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5231     return;
5232   }
5233   size /= sizeof (uint32_t);
5234
5235   /* Initialize new client structure */
5236   c = GNUNET_SERVER_client_get_user_context (client, struct MeshClient);
5237   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  client id %u\n", c->id);
5238   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  client has %u ports\n", size);
5239   if (size > 0)
5240   {
5241     uint32_t u32;
5242
5243     p = (uint32_t *) &cc_msg[1];
5244     c->ports = GNUNET_CONTAINER_multihashmap32_create (size);
5245     for (i = 0; i < size; i++)
5246     {
5247       u32 = ntohl (p[i]);
5248       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "    port: %u\n", u32);
5249
5250       /* store in client's hashmap */
5251       GNUNET_CONTAINER_multihashmap32_put (c->ports, u32, c,
5252                                            GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
5253       /* store in global hashmap */
5254       /* FIXME only allow one client to have the port open,
5255        *       have a backup hashmap with waiting clients */
5256       GNUNET_CONTAINER_multihashmap32_put (ports, u32, c,
5257                                            GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
5258     }
5259   }
5260
5261   c->own_channels = GNUNET_CONTAINER_multihashmap32_create (32);
5262   c->incoming_channels = GNUNET_CONTAINER_multihashmap32_create (32);
5263   GNUNET_SERVER_notification_context_add (nc, client);
5264   GNUNET_STATISTICS_update (stats, "# clients", 1, GNUNET_NO);
5265
5266   GNUNET_SERVER_receive_done (client, GNUNET_OK);
5267   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new client processed\n");
5268 }
5269
5270
5271 /**
5272  * Handler for requests of new tunnels
5273  *
5274  * @param cls Closure.
5275  * @param client Identification of the client.
5276  * @param message The actual message.
5277  */
5278 static void
5279 handle_local_channel_create (void *cls, struct GNUNET_SERVER_Client *client,
5280                             const struct GNUNET_MessageHeader *message)
5281 {
5282   struct GNUNET_MESH_ChannelMessage *msg;
5283   struct MeshPeer *peer;
5284   struct MeshTunnel2 *t;
5285   struct MeshChannel *ch;
5286   struct MeshClient *c;
5287   MESH_ChannelNumber chid;
5288
5289   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new channel requested\n");
5290
5291   /* Sanity check for client registration */
5292   if (NULL == (c = client_get (client)))
5293   {
5294     GNUNET_break (0);
5295     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5296     return;
5297   }
5298   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
5299
5300   /* Message size sanity check */
5301   if (sizeof (struct GNUNET_MESH_ChannelMessage) != ntohs (message->size))
5302   {
5303     GNUNET_break (0);
5304     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5305     return;
5306   }
5307
5308   msg = (struct GNUNET_MESH_ChannelMessage *) message;
5309   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  towards %s:%u\n",
5310               GNUNET_i2s (&msg->peer), ntohl (msg->port));
5311   chid = ntohl (msg->channel_id);
5312
5313   /* Sanity check for duplicate channel IDs */
5314   if (NULL != channel_get_by_local_id (c, chid))
5315   {
5316     GNUNET_break (0);
5317     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5318     return;
5319   }
5320
5321   peer = peer_get (&msg->peer);
5322   if (NULL == peer->tunnel)
5323   {
5324     struct GNUNET_HashCode tid;
5325
5326     GNUNET_CRYPTO_hash_create_random (GNUNET_CRYPTO_QUALITY_NONCE, &tid);
5327     peer->tunnel = tunnel_new (&tid);
5328   }
5329   t = peer->tunnel;
5330
5331   /* Create channel */
5332   ch = channel_new (t, c, chid);
5333   if (NULL == ch)
5334   {
5335     GNUNET_break (0);
5336     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5337     return;
5338   }
5339   ch->port = ntohl (msg->port);
5340   channel_set_options (ch, ntohl (msg->opt));
5341   if (GNUNET_YES == ch->reliable)
5342   {
5343     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! Reliable\n");
5344     ch->fwd_rel = GNUNET_malloc (sizeof (struct MeshChannelReliability));
5345     ch->fwd_rel->ch = ch;
5346     ch->fwd_rel->expected_delay = MESH_RETRANSMIT_TIME;
5347   }
5348
5349   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "CREATED CHANNEL %s[%x]:%u (%x)\n",
5350               GNUNET_h2s (&t->id), ch->gid, ch->port, ch->lid_root);
5351   peer_connect (peer);
5352   /* FIXME send create channel */
5353
5354   GNUNET_SERVER_receive_done (client, GNUNET_OK);
5355   return;
5356 }
5357
5358
5359 /**
5360  * Handler for requests of deleting tunnels
5361  *
5362  * @param cls closure
5363  * @param client identification of the client
5364  * @param message the actual message
5365  */
5366 static void
5367 handle_local_channel_destroy (void *cls, struct GNUNET_SERVER_Client *client,
5368                              const struct GNUNET_MessageHeader *message)
5369 {
5370   struct GNUNET_MESH_ChannelMessage *tunnel_msg;
5371   struct MeshClient *c;
5372   struct MeshTunnel *t;
5373   MESH_ChannelNumber tid;
5374
5375   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5376               "Got a DESTROY TUNNEL from client!\n");
5377
5378   /* Sanity check for client registration */
5379   if (NULL == (c = client_get (client)))
5380   {
5381     GNUNET_break (0);
5382     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5383     return;
5384   }
5385   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
5386
5387   /* Message sanity check */
5388   if (sizeof (struct GNUNET_MESH_ChannelMessage) != ntohs (message->size))
5389   {
5390     GNUNET_break (0);
5391     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5392     return;
5393   }
5394
5395   tunnel_msg = (struct GNUNET_MESH_ChannelMessage *) message;
5396
5397   /* Retrieve tunnel */
5398   tid = ntohl (tunnel_msg->channel_id);
5399   t = channel_get_by_local_id (c, tid);
5400   if (NULL == t)
5401   {
5402     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "  tunnel %X not found\n", tid);
5403     GNUNET_break (0);
5404     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5405     return;
5406   }
5407
5408   /* Cleanup after the tunnel */
5409   client_delete_tunnel (c, t);
5410   if (c == t->client && GNUNET_MESH_LOCAL_CHANNEL_ID_SERV <= tid)
5411   {
5412     t->client = NULL;
5413   }
5414   else if (c == t->owner && GNUNET_MESH_LOCAL_CHANNEL_ID_SERV > tid)
5415   {
5416     peer_remove_tunnel (peer_get_short (t->dest), t);
5417     t->owner = NULL;
5418   }
5419   else 
5420   {
5421     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
5422                 "  tunnel %X client %p (%p, %p)\n",
5423                 tid, c, t->owner, t->client);
5424     GNUNET_break (0);
5425   }
5426
5427   /* The tunnel will be destroyed when the last message is transmitted. */
5428   tunnel_destroy_empty (t);
5429
5430   GNUNET_SERVER_receive_done (client, GNUNET_OK);
5431   return;
5432 }
5433
5434
5435 /**
5436  * Handler for client traffic
5437  *
5438  * @param cls closure
5439  * @param client identification of the client
5440  * @param message the actual message
5441  */
5442 static void
5443 handle_local_data (void *cls, struct GNUNET_SERVER_Client *client,
5444                    const struct GNUNET_MessageHeader *message)
5445 {
5446   struct GNUNET_MESH_LocalData *data_msg;
5447   struct MeshClient *c;
5448   struct MeshTunnel *t;
5449   struct MeshFlowControl *fc;
5450   MESH_ChannelNumber tid;
5451   size_t size;
5452
5453   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5454               "Got data from a client!\n");
5455
5456   /* Sanity check for client registration */
5457   if (NULL == (c = client_get (client)))
5458   {
5459     GNUNET_break (0);
5460     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5461     return;
5462   }
5463   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
5464
5465   data_msg = (struct GNUNET_MESH_LocalData *) message;
5466
5467   /* Sanity check for message size */
5468   size = ntohs (message->size) - sizeof (struct GNUNET_MESH_LocalData);
5469   if (size < sizeof (struct GNUNET_MessageHeader))
5470   {
5471     GNUNET_break (0);
5472     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5473     return;
5474   }
5475
5476   /* Tunnel exists? */
5477   tid = ntohl (data_msg->tid);
5478   t = channel_get_by_local_id (c, tid);
5479   if (NULL == t)
5480   {
5481     GNUNET_break (0);
5482     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5483     return;
5484   }
5485
5486   /* Is the client in the tunnel? */
5487   if ( !( (tid < GNUNET_MESH_LOCAL_CHANNEL_ID_SERV &&
5488            t->owner &&
5489            t->owner->handle == client)
5490          ||
5491           (tid >= GNUNET_MESH_LOCAL_CHANNEL_ID_SERV &&
5492            t->client && 
5493            t->client->handle == client) ) )
5494   {
5495     GNUNET_break (0);
5496     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5497     return;
5498   }
5499
5500   /* Ok, everything is correct, send the message
5501    * (pretend we got it from a mesh peer)
5502    */
5503   {
5504     struct GNUNET_MESH_Data *payload;
5505     char cbuf[sizeof(struct GNUNET_MESH_Data) + size];
5506
5507     fc = tid < GNUNET_MESH_LOCAL_CHANNEL_ID_SERV ? &t->prev_fc : &t->next_fc;
5508     if (GNUNET_YES == t->reliable)
5509     {
5510       struct MeshChannelReliability *rel;
5511       struct MeshReliableMessage *copy;
5512
5513       rel = (tid < GNUNET_MESH_LOCAL_CHANNEL_ID_SERV) ? t->fwd_rel : t->bck_rel;
5514       copy = GNUNET_malloc (sizeof (struct MeshReliableMessage)
5515                             + sizeof(struct GNUNET_MESH_Data)
5516                             + size);
5517       copy->mid = rel->mid_sent++;
5518       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! DATA %u\n", copy->mid);
5519       copy->timestamp = GNUNET_TIME_absolute_get ();
5520       copy->rel = rel;
5521       rel->n_sent++;
5522       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " n_sent %u\n", rel->n_sent);
5523       GNUNET_CONTAINER_DLL_insert_tail (rel->head_sent, rel->tail_sent, copy);
5524       if (GNUNET_SCHEDULER_NO_TASK == rel->retry_task)
5525       {
5526         rel->retry_timer =
5527             GNUNET_TIME_relative_multiply (rel->expected_delay,
5528                                            MESH_RETRANSMIT_MARGIN);
5529         rel->retry_task =
5530             GNUNET_SCHEDULER_add_delayed (rel->retry_timer,
5531                                           &tunnel_retransmit_message,
5532                                           rel);
5533       }
5534       payload = (struct GNUNET_MESH_Data *) &copy[1];
5535       payload->mid = htonl (copy->mid);
5536     }
5537     else
5538     {
5539       payload = (struct GNUNET_MESH_Data *) cbuf;
5540       payload->mid = htonl (fc->last_pid_recv + 1);
5541     }
5542     memcpy (&payload[1], &data_msg[1], size);
5543     payload->header.size = htons (sizeof (struct GNUNET_MESH_Data) + size);
5544     payload->header.type = htons (tid < GNUNET_MESH_LOCAL_CHANNEL_ID_SERV ?
5545                                   GNUNET_MESSAGE_TYPE_MESH_UNICAST :
5546                                   GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN);
5547     GNUNET_PEER_resolve(t->id.oid, &payload->oid);;
5548     payload->tid = htonl (t->id.tid);
5549     payload->ttl = htonl (default_ttl);
5550     payload->pid = htonl (fc->last_pid_recv + 1);
5551     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5552                 "  calling generic handler...\n");
5553     if (tid < GNUNET_MESH_LOCAL_CHANNEL_ID_SERV)
5554       handle_mesh_unicast (NULL, &my_full_id, &payload->header);
5555     else
5556       handle_mesh_to_orig (NULL, &my_full_id, &payload->header);
5557   }
5558   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "receive done OK\n");
5559   GNUNET_SERVER_receive_done (client, GNUNET_OK);
5560
5561   return;
5562 }
5563
5564
5565 /**
5566  * Handler for client's ACKs for payload traffic.
5567  *
5568  * @param cls Closure (unused).
5569  * @param client Identification of the client.
5570  * @param message The actual message.
5571  */
5572 static void
5573 handle_local_ack (void *cls, struct GNUNET_SERVER_Client *client,
5574                   const struct GNUNET_MessageHeader *message)
5575 {
5576   struct GNUNET_MESH_LocalAck *msg;
5577   struct MeshTunnel *t;
5578   struct MeshClient *c;
5579   MESH_ChannelNumber tid;
5580
5581   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a local ACK\n");
5582   /* Sanity check for client registration */
5583   if (NULL == (c = client_get (client)))
5584   {
5585     GNUNET_break (0);
5586     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5587     return;
5588   }
5589   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
5590
5591   msg = (struct GNUNET_MESH_LocalAck *) message;
5592
5593   /* Tunnel exists? */
5594   tid = ntohl (msg->channel_id);
5595   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %X\n", tid);
5596   t = channel_get_by_local_id (c, tid);
5597   if (NULL == t)
5598   {
5599     GNUNET_break (0);
5600     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Tunnel %X unknown.\n", tid);
5601     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "  for client %u.\n", c->id);
5602     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5603     return;
5604   }
5605
5606   /* Does client own tunnel? I.E: Is this an ACK for BCK traffic? */
5607   if (tid < GNUNET_MESH_LOCAL_CHANNEL_ID_SERV)
5608   {
5609     /* The client owns the tunnel, ACK is for data to_origin, send BCK ACK. */
5610     t->prev_fc.last_ack_recv++;
5611     tunnel_send_ack (t, GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK, GNUNET_NO);
5612   }
5613   else
5614   {
5615     /* The client doesn't own the tunnel, this ACK is for FWD traffic. */
5616     t->next_fc.last_ack_recv++;
5617     tunnel_send_ack (t, GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK, GNUNET_YES);
5618   }
5619
5620   GNUNET_SERVER_receive_done (client, GNUNET_OK);
5621
5622   return;
5623 }
5624
5625
5626
5627 /**
5628  * Iterator over all tunnels to send a monitoring client info about each tunnel.
5629  *
5630  * @param cls Closure (client handle).
5631  * @param key Key (hashed tunnel ID, unused).
5632  * @param value Tunnel info.
5633  *
5634  * @return GNUNET_YES, to keep iterating.
5635  */
5636 static int
5637 monitor_all_tunnels_iterator (void *cls,
5638                               const struct GNUNET_HashCode * key,
5639                               void *value)
5640 {
5641   struct GNUNET_SERVER_Client *client = cls;
5642   struct MeshChannel *ch = value;
5643   struct GNUNET_MESH_LocalMonitor *msg;
5644
5645   msg = GNUNET_malloc (sizeof(struct GNUNET_MESH_LocalMonitor));
5646   msg->channel_id = htonl (ch->id);
5647   msg->header.size = htons (sizeof (struct GNUNET_MESH_LocalMonitor));
5648   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_INFO_TUNNELS);
5649
5650   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
5651               "*  sending info about tunnel %s\n",
5652               GNUNET_i2s (&msg->owner));
5653
5654   GNUNET_SERVER_notification_context_unicast (nc, client,
5655                                               &msg->header, GNUNET_NO);
5656   return GNUNET_YES;
5657 }
5658
5659
5660 /**
5661  * Handler for client's MONITOR request.
5662  *
5663  * @param cls Closure (unused).
5664  * @param client Identification of the client.
5665  * @param message The actual message.
5666  */
5667 static void
5668 handle_local_get_tunnels (void *cls, struct GNUNET_SERVER_Client *client,
5669                           const struct GNUNET_MessageHeader *message)
5670 {
5671   struct MeshClient *c;
5672
5673   /* Sanity check for client registration */
5674   if (NULL == (c = client_get (client)))
5675   {
5676     GNUNET_break (0);
5677     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5678     return;
5679   }
5680
5681   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
5682               "Received get tunnels request from client %u\n",
5683               c->id);
5684   GNUNET_CONTAINER_multihashmap_iterate (tunnels,
5685                                          monitor_all_tunnels_iterator,
5686                                          client);
5687   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
5688               "Get tunnels request from client %u completed\n",
5689               c->id);
5690   GNUNET_SERVER_receive_done (client, GNUNET_OK);
5691 }
5692
5693
5694 /**
5695  * Handler for client's MONITOR_TUNNEL request.
5696  *
5697  * @param cls Closure (unused).
5698  * @param client Identification of the client.
5699  * @param message The actual message.
5700  */
5701 static void
5702 handle_local_show_tunnel (void *cls, struct GNUNET_SERVER_Client *client,
5703                           const struct GNUNET_MessageHeader *message)
5704 {
5705   const struct GNUNET_MESH_LocalMonitor *msg;
5706   struct GNUNET_MESH_LocalMonitor *resp;
5707   struct MeshClient *c;
5708   struct MeshChannel *ch;
5709
5710   /* Sanity check for client registration */
5711   if (NULL == (c = client_get (client)))
5712   {
5713     GNUNET_break (0);
5714     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5715     return;
5716   }
5717
5718   msg = (struct GNUNET_MESH_LocalMonitor *) message;
5719   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
5720               "Received tunnel info request from client %u for tunnel %s[%X]\n",
5721               c->id,
5722               &msg->owner,
5723               ntohl (msg->channel_id));
5724   ch = channel_get (&msg->owner, ntohl (msg->channel_id));
5725   if (NULL == ch)
5726   {
5727     /* We don't know the tunnel */
5728     struct GNUNET_MESH_LocalMonitor warn;
5729
5730     warn = *msg;
5731     GNUNET_SERVER_notification_context_unicast (nc, client,
5732                                                 &warn.header,
5733                                                 GNUNET_NO);
5734     GNUNET_SERVER_receive_done (client, GNUNET_OK);
5735     return;
5736   }
5737
5738   /* Initialize context */
5739   resp = GNUNET_malloc (sizeof (struct GNUNET_MESH_LocalMonitor));
5740   *resp = *msg;
5741   resp->header.size = htons (sizeof (struct GNUNET_MESH_LocalMonitor));
5742   GNUNET_SERVER_notification_context_unicast (nc, c->handle,
5743                                               &resp->header, GNUNET_NO);
5744   GNUNET_free (resp);
5745
5746   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
5747               "Monitor tunnel request from client %u completed\n",
5748               c->id);
5749   GNUNET_SERVER_receive_done (client, GNUNET_OK);
5750 }
5751
5752
5753 /**
5754  * Functions to handle messages from clients
5755  */
5756 static struct GNUNET_SERVER_MessageHandler client_handlers[] = {
5757   {&handle_local_new_client, NULL,
5758    GNUNET_MESSAGE_TYPE_MESH_LOCAL_CONNECT, 0},
5759   {&handle_local_channel_create, NULL,
5760    GNUNET_MESSAGE_TYPE_MESH_CHANNEL_CREATE,
5761    sizeof (struct GNUNET_MESH_ChannelMessage)},
5762   {&handle_local_channel_destroy, NULL,
5763    GNUNET_MESSAGE_TYPE_MESH_CHANNEL_DESTROY,
5764    sizeof (struct GNUNET_MESH_ChannelMessage)},
5765   {&handle_local_data, NULL,
5766    GNUNET_MESSAGE_TYPE_MESH_LOCAL_DATA, 0},
5767   {&handle_local_ack, NULL,
5768    GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK,
5769    sizeof (struct GNUNET_MESH_LocalAck)},
5770   {&handle_local_get_tunnels, NULL,
5771    GNUNET_MESSAGE_TYPE_MESH_LOCAL_INFO_TUNNELS,
5772    sizeof (struct GNUNET_MessageHeader)},
5773   {&handle_local_show_tunnel, NULL,
5774    GNUNET_MESSAGE_TYPE_MESH_LOCAL_INFO_TUNNEL,
5775      sizeof (struct GNUNET_MESH_LocalMonitor)},
5776   {NULL, NULL, 0, 0}
5777 };
5778
5779
5780 /**
5781  * Method called whenever a given peer connects.
5782  *
5783  * @param cls closure
5784  * @param peer peer identity this notification is about
5785  */
5786 static void
5787 core_connect (void *cls, const struct GNUNET_PeerIdentity *peer)
5788 {
5789   struct MeshPeer *peer_info;
5790   struct MeshPeerPath *path;
5791
5792   DEBUG_CONN ("Peer connected\n");
5793   DEBUG_CONN ("     %s\n", GNUNET_i2s (&my_full_id));
5794   peer_info = peer_get (peer);
5795   if (myid == peer_info->id)
5796   {
5797     DEBUG_CONN ("     (self)\n");
5798     path = path_new (1);
5799   }
5800   else
5801   {
5802     DEBUG_CONN ("     %s\n", GNUNET_i2s (peer));
5803     path = path_new (2);
5804     path->peers[1] = peer_info->id;
5805     GNUNET_PEER_change_rc (peer_info->id, 1);
5806     GNUNET_STATISTICS_update (stats, "# peers", 1, GNUNET_NO);
5807   }
5808   path->peers[0] = myid;
5809   GNUNET_PEER_change_rc (myid, 1);
5810   peer_add_path (peer_info, path, GNUNET_YES);
5811   return;
5812 }
5813
5814
5815 /**
5816  * Method called whenever a peer disconnects.
5817  *
5818  * @param cls closure
5819  * @param peer peer identity this notification is about
5820  */
5821 static void
5822 core_disconnect (void *cls, const struct GNUNET_PeerIdentity *peer)
5823 {
5824   struct MeshPeer *pi;
5825   struct MeshPeerQueue *q;
5826   struct MeshPeerQueue *n;
5827   struct MeshFlowControl *fc;
5828
5829   DEBUG_CONN ("Peer disconnected\n");
5830   pi = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
5831   if (NULL == pi)
5832   {
5833     GNUNET_break (0);
5834     return;
5835   }
5836   fc = pi->fc;
5837   if (NULL != fc)
5838   {
5839     GNUNET_break (0);
5840     return;
5841   }
5842   pi->fc = NULL;
5843
5844   q = fc->queue_head;
5845   while (NULL != q)
5846   {
5847       n = q->next;
5848       queue_destroy (q, GNUNET_YES);
5849       q = n;
5850   }
5851   if (NULL != fc->core_transmit)
5852     GNUNET_CORE_notify_transmit_ready_cancel (fc->core_transmit);
5853   if (GNUNET_SCHEDULER_NO_TASK != fc->poll_task)
5854     GNUNET_SCHEDULER_cancel (fc->poll_task);
5855
5856   peer_remove_path (pi, pi->id, myid);
5857   if (myid == pi->id)
5858   {
5859     DEBUG_CONN ("     (self)\n");
5860   }
5861   GNUNET_STATISTICS_update (stats, "# peers", -1, GNUNET_NO);
5862   GNUNET_free (fc);
5863
5864   return;
5865 }
5866
5867
5868 /**
5869  * Install server (service) handlers and start listening to clients.
5870  */
5871 static void
5872 server_init (void)
5873 {
5874   GNUNET_SERVER_add_handlers (server_handle, client_handlers);
5875   GNUNET_SERVER_connect_notify (server_handle,
5876                                 &handle_local_client_connect, NULL);
5877   GNUNET_SERVER_disconnect_notify (server_handle,
5878                                    &handle_local_client_disconnect, NULL);
5879   nc = GNUNET_SERVER_notification_context_create (server_handle, 1);
5880
5881   clients_head = NULL;
5882   clients_tail = NULL;
5883   next_client_id = 0;
5884   GNUNET_SERVER_resume (server_handle);
5885 }
5886
5887
5888 /**
5889  * To be called on core init/fail.
5890  *
5891  * @param cls Closure (config)
5892  * @param server handle to the server for this service
5893  * @param identity the public identity of this peer
5894  */
5895 static void
5896 core_init (void *cls, struct GNUNET_CORE_Handle *server,
5897            const struct GNUNET_PeerIdentity *identity)
5898 {
5899   const struct GNUNET_CONFIGURATION_Handle *c = cls;
5900   static int i = 0;
5901
5902   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Core init\n");
5903   GNUNET_break (core_handle == server);
5904   if (0 != memcmp (identity, &my_full_id, sizeof (my_full_id)) ||
5905     NULL == server)
5906   {
5907     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _("Wrong CORE service\n"));
5908     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
5909                 " core id %s\n",
5910                 GNUNET_i2s (identity));
5911     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
5912                 " my id %s\n",
5913                 GNUNET_i2s (&my_full_id));
5914     GNUNET_CORE_disconnect (core_handle);
5915     core_handle = GNUNET_CORE_connect (c, /* Main configuration */
5916                                        NULL,      /* Closure passed to MESH functions */
5917                                        &core_init,        /* Call core_init once connected */
5918                                        &core_connect,     /* Handle connects */
5919                                        &core_disconnect,  /* remove peers on disconnects */
5920                                        NULL,      /* Don't notify about all incoming messages */
5921                                        GNUNET_NO, /* For header only in notification */
5922                                        NULL,      /* Don't notify about all outbound messages */
5923                                        GNUNET_NO, /* For header-only out notification */
5924                                        core_handlers);    /* Register these handlers */
5925     if (10 < i++)
5926       GNUNET_abort();
5927   }
5928   server_init ();
5929   return;
5930 }
5931
5932
5933 /******************************************************************************/
5934 /************************      MAIN FUNCTIONS      ****************************/
5935 /******************************************************************************/
5936
5937 /**
5938  * Iterator over tunnel hash map entries to destroy the tunnel during shutdown.
5939  *
5940  * @param cls closure
5941  * @param key current key code
5942  * @param value value in the hash map
5943  * @return GNUNET_YES if we should continue to iterate,
5944  *         GNUNET_NO if not.
5945  */
5946 static int
5947 shutdown_tunnel (void *cls, const struct GNUNET_HashCode * key, void *value)
5948 {
5949   struct MeshTunnel2 *t = value;
5950
5951   tunnel_destroy (t);
5952   return GNUNET_YES;
5953 }
5954
5955 /**
5956  * Iterator over peer hash map entries to destroy the tunnel during shutdown.
5957  *
5958  * @param cls closure
5959  * @param key current key code
5960  * @param value value in the hash map
5961  * @return GNUNET_YES if we should continue to iterate,
5962  *         GNUNET_NO if not.
5963  */
5964 static int
5965 shutdown_peer (void *cls, const struct GNUNET_HashCode * key, void *value)
5966 {
5967   struct MeshPeer *p = value;
5968   struct MeshPeerQueue *q;
5969   struct MeshPeerQueue *n;
5970
5971   q = p->fc->queue_head;
5972   while (NULL != q)
5973   {
5974       n = q->next;
5975       if (q->peer == p)
5976       {
5977         queue_destroy(q, GNUNET_YES);
5978       }
5979       q = n;
5980   }
5981   peer_destroy (p);
5982   return GNUNET_YES;
5983 }
5984
5985
5986 /**
5987  * Task run during shutdown.
5988  *
5989  * @param cls unused
5990  * @param tc unused
5991  */
5992 static void
5993 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
5994 {
5995   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shutting down\n");
5996
5997   if (core_handle != NULL)
5998   {
5999     GNUNET_CORE_disconnect (core_handle);
6000     core_handle = NULL;
6001   }
6002   GNUNET_CONTAINER_multihashmap_iterate (tunnels, &shutdown_tunnel, NULL);
6003   GNUNET_CONTAINER_multihashmap_iterate (peers, &shutdown_peer, NULL);
6004   if (dht_handle != NULL)
6005   {
6006     GNUNET_DHT_disconnect (dht_handle);
6007     dht_handle = NULL;
6008   }
6009   if (nc != NULL)
6010   {
6011     GNUNET_SERVER_notification_context_destroy (nc);
6012     nc = NULL;
6013   }
6014   if (GNUNET_SCHEDULER_NO_TASK != announce_id_task)
6015   {
6016     GNUNET_SCHEDULER_cancel (announce_id_task);
6017     announce_id_task = GNUNET_SCHEDULER_NO_TASK;
6018   }
6019   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shut down\n");
6020 }
6021
6022
6023 /**
6024  * Process mesh requests.
6025  *
6026  * @param cls closure
6027  * @param server the initialized server
6028  * @param c configuration to use
6029  */
6030 static void
6031 run (void *cls, struct GNUNET_SERVER_Handle *server,
6032      const struct GNUNET_CONFIGURATION_Handle *c)
6033 {
6034   char *keyfile;
6035   struct GNUNET_CRYPTO_EccPrivateKey *pk;
6036
6037   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "starting to run\n");
6038   server_handle = server;
6039   GNUNET_SERVER_suspend (server_handle);
6040
6041   if (GNUNET_OK !=
6042       GNUNET_CONFIGURATION_get_value_filename (c, "PEER", "PRIVATE_KEY",
6043                                                &keyfile))
6044   {
6045     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
6046                 _
6047                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
6048                 "mesh", "peer/privatekey");
6049     GNUNET_SCHEDULER_shutdown ();
6050     return;
6051   }
6052
6053   if (GNUNET_OK !=
6054       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "REFRESH_CONNECTION_TIME",
6055                                            &refresh_connection_time))
6056   {
6057     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
6058                 _
6059                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
6060                 "mesh", "refresh path time");
6061     GNUNET_SCHEDULER_shutdown ();
6062     return;
6063   }
6064
6065   if (GNUNET_OK !=
6066       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "ID_ANNOUNCE_TIME",
6067                                            &id_announce_time))
6068   {
6069     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
6070                 _
6071                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
6072                 "mesh", "id announce time");
6073     GNUNET_SCHEDULER_shutdown ();
6074     return;
6075   }
6076
6077   if (GNUNET_OK !=
6078       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "CONNECT_TIMEOUT",
6079                                            &connect_timeout))
6080   {
6081     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
6082                 _
6083                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
6084                 "mesh", "connect timeout");
6085     GNUNET_SCHEDULER_shutdown ();
6086     return;
6087   }
6088
6089   if (GNUNET_OK !=
6090       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_MSGS_QUEUE",
6091                                              &max_msgs_queue))
6092   {
6093     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
6094                 _
6095                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
6096                 "mesh", "max msgs queue");
6097     GNUNET_SCHEDULER_shutdown ();
6098     return;
6099   }
6100
6101   if (GNUNET_OK !=
6102       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_TUNNELS",
6103                                              &max_tunnels))
6104   {
6105     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
6106                 _
6107                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
6108                 "mesh", "max tunnels");
6109     GNUNET_SCHEDULER_shutdown ();
6110     return;
6111   }
6112
6113   if (GNUNET_OK !=
6114       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DEFAULT_TTL",
6115                                              &default_ttl))
6116   {
6117     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
6118                 _
6119                 ("%s service is lacking key configuration settings (%s). Using default (%u).\n"),
6120                 "mesh", "default ttl", 64);
6121     default_ttl = 64;
6122   }
6123
6124   if (GNUNET_OK !=
6125       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_PEERS",
6126                                              &max_peers))
6127   {
6128     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
6129                 _("%s service is lacking key configuration settings (%s). Using default (%u).\n"),
6130                 "mesh", "max peers", 1000);
6131     max_peers = 1000;
6132   }
6133
6134   if (GNUNET_OK !=
6135       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DROP_PERCENT",
6136                                              &drop_percent))
6137   {
6138     drop_percent = 0;
6139   }
6140   else
6141   {
6142     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
6143                 "Mesh is running with drop mode enabled. "
6144                 "This is NOT a good idea! "
6145                 "Remove the DROP_PERCENT option from your configuration.\n");
6146   }
6147
6148   if (GNUNET_OK !=
6149       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DHT_REPLICATION_LEVEL",
6150                                              &dht_replication_level))
6151   {
6152     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
6153                 _
6154                 ("%s service is lacking key configuration settings (%s). Using default (%u).\n"),
6155                 "mesh", "dht replication level", 3);
6156     dht_replication_level = 3;
6157   }
6158
6159   tunnels = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
6160   peers = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
6161   ports = GNUNET_CONTAINER_multihashmap32_create (32);
6162
6163   dht_handle = GNUNET_DHT_connect (c, 64);
6164   if (NULL == dht_handle)
6165   {
6166     GNUNET_break (0);
6167   }
6168   stats = GNUNET_STATISTICS_create ("mesh", c);
6169
6170   /* Scheduled the task to clean up when shutdown is called */
6171   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
6172                                 NULL);
6173   pk = GNUNET_CRYPTO_ecc_key_create_from_file (keyfile);
6174   GNUNET_free (keyfile);
6175   GNUNET_assert (NULL != pk);
6176   my_private_key = pk;
6177   GNUNET_CRYPTO_ecc_key_get_public (my_private_key, &my_public_key);
6178   GNUNET_CRYPTO_hash (&my_public_key, sizeof (my_public_key),
6179                       &my_full_id.hashPubKey);
6180   myid = GNUNET_PEER_intern (&my_full_id);
6181   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
6182               "Mesh for peer [%s] starting\n",
6183               GNUNET_i2s(&my_full_id));
6184
6185   core_handle = GNUNET_CORE_connect (c, /* Main configuration */
6186                                      NULL,      /* Closure passed to MESH functions */
6187                                      &core_init,        /* Call core_init once connected */
6188                                      &core_connect,     /* Handle connects */
6189                                      &core_disconnect,  /* remove peers on disconnects */
6190                                      NULL,      /* Don't notify about all incoming messages */
6191                                      GNUNET_NO, /* For header only in notification */
6192                                      NULL,      /* Don't notify about all outbound messages */
6193                                      GNUNET_NO, /* For header-only out notification */
6194                                      core_handlers);    /* Register these handlers */
6195   if (NULL == core_handle)
6196   {
6197     GNUNET_break (0);
6198     GNUNET_SCHEDULER_shutdown ();
6199     return;
6200   }
6201   announce_id_task = GNUNET_SCHEDULER_add_now (&announce_id, cls);
6202   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Mesh service running\n");
6203 }
6204
6205
6206 /**
6207  * The main function for the mesh service.
6208  *
6209  * @param argc number of arguments from the command line
6210  * @param argv command line arguments
6211  * @return 0 ok, 1 on error
6212  */
6213 int
6214 main (int argc, char *const *argv)
6215 {
6216   int ret;
6217   int r;
6218
6219   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "main()\n");
6220   r = GNUNET_SERVICE_run (argc, argv, "mesh", GNUNET_SERVICE_OPTION_NONE, &run,
6221                           NULL);
6222   ret = (GNUNET_OK == r) ? 0 : 1;
6223   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "main() END\n");
6224
6225   INTERVAL_SHOW;
6226
6227   return ret;
6228 }