aboutsummaryrefslogtreecommitdiff
path: root/src/org/gnunet/mesh/Mesh.java
blob: b272b0b75685054532e0a3c844a347ae66305d81 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
/*
 This file is part of GNUnet.
 (C) 2011, 2012 Christian Grothoff (and other contributing authors)

 GNUnet is free software; you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published
 by the Free Software Foundation; either version 3, or (at your
 option) any later version.

 GNUnet is distributed in the hope that it will be useful, but
 WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with GNUnet; see the file COPYING.  If not, write to the
 Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 Boston, MA 02111-1307, USA.
 */

package org.gnunet.mesh;

import org.gnunet.construct.Construct;
import org.gnunet.mq.ClientMessageQueue;
import org.gnunet.mq.Envelope;
import org.gnunet.mq.MessageQueue;
import org.gnunet.requests.Request;
import org.gnunet.requests.RequestQueue;
import org.gnunet.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * Mesh API
 *
 * @author Florian Dold
 */
public class Mesh {
    /**
     * Class logger.
     */
    private static final Logger logger = LoggerFactory
            .getLogger(Mesh.class);

    /**
     * For tunnels created by the client, the bit in this
     * mask is always set.
     */
    private static final int TUNNEL_ID_CLI = 0x80000000;

    /**
     * For tunnels created by the server, the bit in this
     * mask is always set.
     */
    private static final int TUNNEL_ID_SERV = 0xB0000000;

    /**
     * Disable buffering on intermediate nodes (for minimum latency).
     * Yes/No.
     */
    private static final int OPTION_NOBUFFER = 1;

    /**
     * Enable tunnel reliability, lost messages will be retransmitted.
     * Yes/No.
     */
    private static final int OPTION_RELIABLE = 2;

    /**
     * Client connected to the mesh service
     */
    private final Client client;

    /**
     * Message queue for the client.
     */
    private final ClientMessageQueue client_mq;

    /**
     * Called whenever a tunnel was destroyed.
     */
    private TunnelEndHandler tunnelEndHandler;

    /**
     * Message handler for messages received through
     * a tunnel.
     */
    private MeshRunabout messageReceiver;

    /**
     * Ports that we listen on.
     */
    private int[] ports;

    /**
     * Handler for inbound tunnels.
     */
    private InboundTunnelHandler inboundTunnelHandler;

    /**
     * Mapping from the tunnel's ID to the tunnel object.
     */
    private Map<Integer,Tunnel> tunnelMap = new HashMap<>();

    /**
     * Counter for generating fresh tunnel ID's
     * when creating new tunnels.
     */
    int next_tid = 1;

    /**
     * A tunnel to a remote peer.
     * @param <T> type of context data for the tunnel
     */
    public class Tunnel<T> extends MessageQueue {
        private T context;
        private final int opt;
        public final PeerIdentity peer;
        public final int port;
        protected int tunnelId;
        private boolean receive_done_expected = false;
        int ack_count = 0;

        /**
         * Create a new tunnel (we're initiator and will be allowed to add/remove peers
         * and to broadcast).
         *
         * @param context tunnel context
         * @param peer peer identity the tunnel should go to
         * @param port Port number.
         * @param nobuffer Flag for disabling buffering on relay nodes.
         * @param reliable Flag for end-to-end reliability.
         */
        public Tunnel(PeerIdentity peer, int port, boolean nobuffer, boolean reliable, T context)
        {
            this(peer, 0, port, nobuffer, reliable);
            TunnelCreateMessage tcm = new TunnelCreateMessage();
            tcm.otherEnd = peer;
            tcm.opt = opt;
            tcm.port = port;
            tcm.tunnel_id = tunnelId;
            client_mq.send(tcm);
        }

        /**
         * Private tunnel constructor, for creating tunnel objects for
         * incoming tunnels.
         *
         * @param peer
         * @param tunnelId
         * @param port
         * @param nobuffer
         * @param reliable
         */
        private Tunnel(PeerIdentity peer, int tunnelId, int port, boolean nobuffer, boolean reliable) {
            int my_opt = 0;
            if (reliable)
                my_opt |= OPTION_RELIABLE;
            if (nobuffer)
                my_opt |= OPTION_NOBUFFER;
            if (0 == tunnelId)
                this.tunnelId = ((next_tid++) | TUNNEL_ID_CLI) & ~TUNNEL_ID_SERV;
            else
                this.tunnelId = tunnelId;
            this.peer = peer;
            this.port = port;
            this.opt = my_opt;
        }

        public void receiveDone() {
            if (!receive_done_expected)
                throw new AssertionError("unexpected call to receiveDone");
            LocalAckMessage am = new LocalAckMessage();
            am.tid = tunnelId;
            client_mq.send(am);
            receive_done_expected = false;
        }

        public void destroy() {
            TunnelDestroyMessage m = new TunnelDestroyMessage();
            m.tunnel_id = tunnelId;
            client_mq.send(m);
        }

        @Override
        protected void sendImmediate(Envelope ev) {
            if (ack_count <= 0)
                throw new AssertionError();
            DataMessage m = new DataMessage();
            m.payload = Construct.toBinary(GnunetMessage.fromBody(ev.message));
            Envelope mesh_ev = new Envelope(m);
            client_mq.send(mesh_ev);
            ack_count -= 1;
        }

        public T getContext() {
            return context;
        }

        public void setContext(T newContext) {
            context = newContext;
        }

    }

    private class MeshMessageReceiver extends RunaboutMessageReceiver {
        public void visit(TunnelCreateMessage m) {
            Tunnel t = new Tunnel(m.otherEnd, m.tunnel_id, m.port,
                    (m.opt & OPTION_NOBUFFER) != 0, (m.opt & OPTION_NOBUFFER) != 0);
            if (inboundTunnelHandler != null) {
                inboundTunnelHandler.onInboundTunnel(t, m.otherEnd);
            }
        }

        public void visit(DataMessage m) {
            Tunnel t = tunnelMap.get(m.tid);
            if (t != null)
            {
                if (t.receive_done_expected)
                    logger.warn("got unexpected message from service");
                t.receive_done_expected = true;
                messageReceiver.visitAppropriate(Construct.parseAs(m.payload, GnunetMessage.class).body);
            }
        }

        public void visit(LocalAckMessage m) {
            Tunnel t = tunnelMap.get(m.tid);
            if (t != null)
                t.ack_count += 1;
        }

        public void visit(TunnelDestroyMessage m) {
            Tunnel t = tunnelMap.get(m.tunnel_id);
            if (t == null) {
                logger.warn("server got confused with tunnel IDs on destroy, ignoring message");
                return;
            }
            t.destroy();
            tunnelEndHandler.onTunnelEnd(t);
        }

        @Override
        public void handleError() {
            if (tunnelEndHandler != null) {
                for (Tunnel t : tunnelMap.values()) {
                    tunnelEndHandler.onTunnelEnd(t);
                }
            }
            tunnelMap.clear();
            client.reconnect();
            ClientConnectMessage ccm = new ClientConnectMessage();
            ccm.apps_list = ports;
            client_mq.send(ccm);
        }
    }

    /**
     * Connect to the mesh service.
     *
     * @param cfg                  configuration to use
     * @param inboundTunnelHandler function called when an *inbound* tunnel is created
     * @param tunnelEndHandler     function called when an *inbound* tunnel is destroyed by the
     *                             remote peer, it is *not* called if Tunnel.destroy
     *                             is called on the tunnel
     */
    public Mesh(Configuration cfg, InboundTunnelHandler inboundTunnelHandler,
                TunnelEndHandler tunnelEndHandler, MeshRunabout messageReceiver, int... ports) {
        this.tunnelEndHandler = tunnelEndHandler;
        this.messageReceiver = messageReceiver;
        this.ports = ports;
        this.inboundTunnelHandler = inboundTunnelHandler;

        client = new Client("mesh", cfg);
        client_mq = new ClientMessageQueue(client, new MeshMessageReceiver());
        ClientConnectMessage ccm = new ClientConnectMessage();
        ccm.apps_list = ports;
        client_mq.send(ccm);
    }

    /**
     * Disconnect from the mesh service.
     * All tunnels will be destroyed.
     * All tunnel disconnect callbacks will be called on any still connected peers, notifying
     * about their disconnection.
     */
    public void disconnect() {
        client_mq.destroy();
        client.disconnect();
    }
}