aboutsummaryrefslogtreecommitdiff
path: root/src/org/gnunet/util/Server.java
blob: f2db5398477d067968f3c369aa23ff26f230fe87 (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
/*
 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.util;

import org.grothoff.Runabout;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.SocketAddress;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class Server {
    private static final Logger logger = LoggerFactory
            .getLogger(Server.class);

    private final RelativeTime idleTimeout;
    private final boolean requireFound;
    private List<ServerSocketChannel> listenSockets;
    private List<ClientHandle> clients = new LinkedList<ClientHandle>();

    private MessageRunabout receivedMessagehandler;
    private List<DisconnectHandler> disconnectHandlers = new LinkedList<DisconnectHandler>();
    private ArrayList<Class> expectedMessages;

    private boolean shutdownRequested;
    private Cancelable acceptTask;

    public interface DisconnectHandler {
        void onDisconnect(ClientHandle clientHandle);
    }


    public class ClientHandle {
        private RelativeTime clientTimeout;
        private Connection connection;

        private int referenceCount = 0;
        private Connection.ReceiveHandle currentReceive;

        private boolean isMonitor;

        private ClientHandle(SocketChannel accept) {
            connection = new Connection(accept);
            clientTimeout = idleTimeout;
            // start receiving
            receiveDone(true);
        }


        /**
         * Notify us when the server has enough space to transmit
         * a message of the given size to the given client.
         *
         * @param size        requested amount of buffer space
         * @param timeout     after how long should we give up (and call
         *                    notify with buf NULL and size 0)?
         * @param transmitter callback
         * @return a handle to cancel the notification
         */
        public Cancelable notifyTransmitReady(int size, RelativeTime timeout, MessageTransmitter transmitter) {
            return connection.notifyTransmitReady(0, timeout, transmitter);
        }

        /**
         * Resume receiving from this client, we are done processing the
         * current request.  This function must be called from within each
         * message handler (or its respective continuations).
         * <p/>
         * The server does not automatically continue to receive messages to
         * support flow control.
         *
         * @param keepClient false if connection to the client should be closed
         */
        public void receiveDone(boolean keepClient) {
            if (keepClient) {
                currentReceive = connection.receive(RelativeTime.FOREVER, new MessageReceiver() {
                    @Override
                    public void process(GnunetMessage.Body msg) {
                        if (msg instanceof UnknownMessageBody) {
                            if (requireFound) {
                                logger.info("disconnecting client sending unknown message");
                                disconnect();
                            }
                            // otherwise, just ignore it
                        }
                        if (receivedMessagehandler == null) {
                            throw new AssertionError("received message, but no handler installed");
                        }
                        receivedMessagehandler.setSender(ClientHandle.this);
                        receivedMessagehandler.visitAppropriate(msg);
                    }

                    @Override
                    public void handleError() {
                        logger.warn("error receiving from client");
                        disconnect();
                    }
                });
            } else {
                disconnect();
            }

        }

        /**
         * Change the idle timeout of this particular client.
         */
        public void setTimeout(RelativeTime newTimeout) {
        }

        public void disconnect() {
            connection.disconnect();
            Server.this.clients.remove(this);
            for (DisconnectHandler dh : disconnectHandlers) {
                dh.onDisconnect(this);
            }
        }

        /**
         * Disable the warning the server issues if a message is not acknowledged
         * in a timely fashion.  Use this call if a client is intentionally delayed
         * for a while.  Only applies to the current message.
         */
        public void disableReceiveDoneWarning() {
            // todo
        }

        public void keep() {
            referenceCount++;
        }

        public void drop() {
            referenceCount--;
            if (referenceCount == 0 && shutdownRequested) {
                disconnect();
            }
        }

        public void markMonitor() {
            this.isMonitor = true;
        }
    }


    abstract static class MessageRunabout extends Runabout {
        private ClientHandle currentSender;

        /**
         * Allows implementors of MessageRunabout to get the Client that sent the message
         * currently visited.
         *
         * @return handle of the client whose message is currently being visited
         */
        public final ClientHandle getSender() {
            return currentSender;
        }

        private void setSender(ClientHandle clientHandle) {
            currentSender = clientHandle;
        }
    }


    private void doAccept(final ServerSocketChannel srv) {
        Scheduler.TaskConfiguration b = new Scheduler.TaskConfiguration(RelativeTime.FOREVER,
                new Scheduler.Task() {
                    @Override
                    public void run(Scheduler.RunContext ctx) {
                        acceptTask = null;
                        try {
                            SocketChannel cli = srv.accept();

                            if (cli != null) {
                                logger.debug("client connected");
                                cli.configureBlocking(false);
                                ClientHandle clientHandle = new ClientHandle(cli);
                                clients.add(clientHandle);
                            }

                        } catch (IOException e) {
                            throw new RuntimeException("accept failed", e);
                        }
                        doAccept(srv);
                    }
                });
        b.selectAccept(srv);
        acceptTask = b.schedule();
    }


    /**
     * Create a server listening on all specified addresses.
     *
     * @param addresses    addresses to bind on
     * @param idleTimeout  time after a client will be disconnected if idle
     * @param requireFound allow unknown messages to be received without disconnecting the client in response
     */
    public Server(List<SocketAddress> addresses, RelativeTime idleTimeout, boolean requireFound) {
        this.idleTimeout = idleTimeout;
        this.requireFound = requireFound;
        listenSockets = new ArrayList<ServerSocketChannel>(addresses.size());
        try {
            for (SocketAddress addr : addresses) {
                ServerSocketChannel socket = ServerSocketChannel.open();
                socket.configureBlocking(false);
                socket.socket().bind(addr);
                logger.debug("socket listening on {}", addr.toString());
                listenSockets.add(socket);
                doAccept(socket);
            }
        } catch (IOException e) {
            throw new RuntimeException("could not bind");
        }
    }

    public Server(RelativeTime idleTimeout, boolean requireFound) {
        this.idleTimeout = idleTimeout;
        this.requireFound = requireFound;
    }

    public void addAcceptSocket(ServerSocketChannel sock) {
        doAccept(sock);
    }

    /**
     * Pass messages that the runabout can handle to it.
     * There can only be one runabout per message type.
     * (Discrepancy with the C-API, could be changed in the future)
     *
     * @param msgRunabout handler
     */
    public void setHandler(MessageRunabout msgRunabout) {
        receivedMessagehandler = msgRunabout;
        expectedMessages = RunaboutUtil.getRunaboutVisitees(msgRunabout);
    }

    public Cancelable notifyDisconnect(final DisconnectHandler disconnectHandler) {
        this.disconnectHandlers.add(disconnectHandler);
        return new Cancelable() {
            @Override
            public void cancel() {
                Server.this.disconnectHandlers.remove(disconnectHandler);
            }
        };
    }

    /**
     * Stop the listen socket and get ready to shutdown the server
     * once only 'monitor' clients are left.
     */
    public void stopListening() {
        shutdownRequested = true;
        // todo: shut down if only monitor clients left
    }

    public void destroy() {
        for (ClientHandle h : new ArrayList<ClientHandle>(clients)) {
            h.disconnect();
        }
        acceptTask.cancel();
    }

}