File: DummySecureWebSocketServer.java

package info (click to toggle)
openjdk-21 21.0.8%2B9-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 823,976 kB
  • sloc: java: 5,613,338; xml: 1,643,607; cpp: 1,296,296; ansic: 420,291; asm: 404,850; objc: 20,994; sh: 15,271; javascript: 11,245; python: 6,895; makefile: 2,362; perl: 357; awk: 351; sed: 172; jsp: 24; csh: 3
file content (610 lines) | stat: -rw-r--r-- 22,754 bytes parent folder | download | duplicates (15)
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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
/*
 * Copyright (c) 2020, Oracle and/or its affiliates. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.
 *
 * This code 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
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 */

import javax.net.ServerSocketFactory;
import javax.net.ssl.SSLServerSocketFactory;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UncheckedIOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.ServerSocket;
import java.net.SocketAddress;
import java.net.SocketOption;
import java.net.StandardSocketOptions;
import java.net.URI;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.ClosedByInterruptException;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.CharacterCodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Base64;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.BiFunction;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import static java.lang.String.format;
import static java.lang.System.err;
import static java.nio.charset.StandardCharsets.ISO_8859_1;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.util.Arrays.asList;
import static java.util.Objects.requireNonNull;

/**
 * Dummy WebSocket Server, which supports TLS.
 * By default the dummy webserver uses a plain TCP connection,
 * but it can use a TLS connection if secure() is called before
 * open(). It will use the default SSL context.
 *
 * Performs simpler version of the WebSocket Opening Handshake over HTTP (i.e.
 * no proxying, cookies, etc.) Supports sequential connections, one at a time,
 * i.e. in order for a client to connect to the server the previous client must
 * disconnect first.
 *
 * Expected client request:
 *
 *     GET /chat HTTP/1.1
 *     Host: server.example.com
 *     Upgrade: websocket
 *     Connection: Upgrade
 *     Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
 *     Origin: http://example.com
 *     Sec-WebSocket-Protocol: chat, superchat
 *     Sec-WebSocket-Version: 13
 *
 * This server response:
 *
 *     HTTP/1.1 101 Switching Protocols
 *     Upgrade: websocket
 *     Connection: Upgrade
 *     Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
 *     Sec-WebSocket-Protocol: chat
 */
public class DummySecureWebSocketServer implements Closeable {

    /**
     * Emulates some of the SocketChannel APIs over a Socket
     * instance.
     */
    public static class WebSocketChannel implements AutoCloseable {
        interface Reader {
            int read(ByteBuffer buf) throws IOException;
        }
        interface Writer {
            void write(ByteBuffer buf) throws IOException;
        }
        interface Config {
            <T> void setOption(SocketOption<T> option, T value) throws IOException;
        }
        interface Closer {
            void close() throws IOException;
        }
        final AutoCloseable channel;
        final Reader reader;
        final Writer writer;
        final Config config;
        final Closer closer;
        WebSocketChannel(AutoCloseable channel, Reader reader, Writer writer, Config config, Closer closer) {
            this.channel = channel;
            this.reader = reader;
            this.writer = writer;
            this.config = config;
            this.closer = closer;
        }
        public void close() throws IOException {
            closer.close();
        }
        public String toString() {
            return channel.toString();
        }
        public int read(ByteBuffer bb) throws IOException {
            return reader.read(bb);
        }
        public void write(ByteBuffer bb) throws IOException {
            writer.write(bb);
        }
        public <T> void setOption(SocketOption<T> option, T value) throws IOException {
            config.setOption(option, value);
        }
        public static WebSocketChannel of(Socket s) {
            Reader reader = (bb) -> DummySecureWebSocketServer.read(s.getInputStream(), bb);
            Writer writer = (bb) -> DummySecureWebSocketServer.write(s.getOutputStream(), bb);
            return new WebSocketChannel(s, reader, writer, s::setOption, s::close);
        }
    }

    /**
     * Emulates some of the ServerSocketChannel APIs over a ServerSocket
     * instance.
     */
    public static class WebServerSocketChannel implements AutoCloseable {
        interface Accepter {
            WebSocketChannel accept() throws IOException;
        }
        interface Binder {
            void bind(SocketAddress address) throws IOException;
        }
        interface Config {
            <T> void setOption(SocketOption<T> option, T value) throws IOException;
        }
        interface Closer {
            void close() throws IOException;
        }
        interface Addressable {
            SocketAddress getLocalAddress() throws IOException;
        }
        final AutoCloseable server;
        final Accepter accepter;
        final Binder binder;
        final Addressable address;
        final Config config;
        final Closer closer;
        WebServerSocketChannel(AutoCloseable server,
                               Accepter accepter,
                               Binder binder,
                               Addressable address,
                               Config config,
                               Closer closer) {
            this.server = server;
            this.accepter = accepter;
            this.binder = binder;
            this.address = address;
            this.config = config;
            this.closer = closer;
        }
        public void close() throws IOException {
            closer.close();
        }
        public String toString() {
            return server.toString();
        }
        public WebSocketChannel accept() throws IOException {
            return accepter.accept();
        }
        public void bind(SocketAddress address) throws IOException {
            binder.bind(address);
        }
        public <T> void setOption(SocketOption<T> option, T value) throws IOException {
            config.setOption(option, value);
        }
        public SocketAddress getLocalAddress()  throws IOException {
            return address.getLocalAddress();
        }
        public static WebServerSocketChannel of(ServerSocket ss) {
            Accepter a = () -> WebSocketChannel.of(ss.accept());
            return new WebServerSocketChannel(ss, a, ss::bind, ss::getLocalSocketAddress, ss::setOption, ss::close);
        }
    }

    // Creates a secure WebServerSocketChannel
    static WebServerSocketChannel openWSS() throws IOException {
       return WebServerSocketChannel.of(SSLServerSocketFactory.getDefault().createServerSocket());
    }

    // Creates a plain WebServerSocketChannel
    static WebServerSocketChannel openWS() throws IOException {
        return WebServerSocketChannel.of(ServerSocketFactory.getDefault().createServerSocket());
    }


    static int read(InputStream str, ByteBuffer buffer) throws IOException {
        int len = Math.min(buffer.remaining(), 1024);
        if (len <= 0) return 0;
        byte[] bytes = new byte[len];
        int res = 0;
        if (buffer.hasRemaining()) {
            len = Math.min(len, buffer.remaining());
            int n = str.read(bytes, 0, len);
            if (n > 0) {
                buffer.put(bytes, 0, n);
                res += n;
            } else if (res > 0) {
                return res;
            } else {
                return n;
            }
        }
        return res;
    }

    static void write(OutputStream str, ByteBuffer buffer) throws IOException {
        int len = Math.min(buffer.remaining(), 1024);
        if (len <= 0) return;
        byte[] bytes = new byte[len];
        int res = 0;
        int pos = buffer.position();
        while (buffer.hasRemaining()) {
            len = Math.min(len, buffer.remaining());
            buffer.get(bytes, 0, len);
            str.write(bytes, 0, len);
        }
    }

    private final AtomicBoolean started = new AtomicBoolean();
    private final Thread thread;
    private volatile WebServerSocketChannel ss;
    private volatile InetSocketAddress address;
    private volatile boolean secure;
    private ByteBuffer read = ByteBuffer.allocate(16384);
    private final CountDownLatch readReady = new CountDownLatch(1);
    private volatile boolean done;

    private static class Credentials {
        private final String name;
        private final String password;
        private Credentials(String name, String password) {
            this.name = name;
            this.password = password;
        }
        public String name() { return name; }
        public String password() { return password; }
    }

    public DummySecureWebSocketServer() {
        this(defaultMapping(), null, null);
    }

    public DummySecureWebSocketServer(String username, String password) {
        this(defaultMapping(), username, password);
    }

    public DummySecureWebSocketServer(BiFunction<List<String>,Credentials,List<String>> mapping,
                                String username,
                                String password) {
        requireNonNull(mapping);
        Credentials credentials = username != null ?
                new Credentials(username, password) : null;

        thread = new Thread(() -> {
            try {
                while (!Thread.currentThread().isInterrupted() && !done) {
                    err.println("Accepting next connection at: " + ss);
                    WebSocketChannel channel = ss.accept();
                    err.println("Accepted: " + channel);
                    try {
                        channel.setOption(StandardSocketOptions.TCP_NODELAY, true);
                        while (!done) {
                            StringBuilder request = new StringBuilder();
                            if (!readRequest(channel, request)) {
                                throw new IOException("Bad request:[" + request + "]");
                            }
                            List<String> strings = asList(request.toString().split("\r\n"));
                            List<String> response = mapping.apply(strings, credentials);
                            writeResponse(channel, response);

                            if (response.get(0).startsWith("HTTP/1.1 401")) {
                                err.println("Sent 401 Authentication response " + channel);
                                continue;
                            } else {
                                serve(channel);
                                break;
                            }
                        }
                    } catch (IOException e) {
                        if (!done) {
                            err.println("Error in connection: " + channel + ", " + e);
                        }
                    } finally {
                        err.println("Closed: " + channel);
                        close(channel);
                        readReady.countDown();
                    }
                }
            } catch (ClosedByInterruptException ignored) {
            } catch (Throwable e) {
                if (!done) {
                    e.printStackTrace(err);
                }
            } finally {
                done = true;
                close(ss);
                err.println("Stopped at: " + getURI());
            }
        });
        thread.setName("DummySecureWebSocketServer");
        thread.setDaemon(false);
    }

    // must be called before open()
    public DummySecureWebSocketServer secure() {
        secure = true;
        return this;
    }

    protected void read(WebSocketChannel ch) throws IOException {
        // Read until the thread is interrupted or an error occurred
        // or the input is shutdown
        ByteBuffer b = ByteBuffer.allocate(65536);
        while (ch.read(b) != -1) {
            b.flip();
            if (read.remaining() < b.remaining()) {
                int required = read.capacity() - read.remaining() + b.remaining();
                int log2required = 32 - Integer.numberOfLeadingZeros(required - 1);
                ByteBuffer newBuffer = ByteBuffer.allocate(1 << log2required);
                newBuffer.put(read.flip());
                read = newBuffer;
            }
            read.put(b);
            b.clear();
        }
    }

    protected void write(WebSocketChannel ch) throws IOException { }

    protected final void serve(WebSocketChannel channel)
            throws InterruptedException
    {
        Thread reader = new Thread(() -> {
            try {
                read(channel);
            } catch (IOException ignored) { }
        });
        Thread writer = new Thread(() -> {
            try {
                write(channel);
            } catch (IOException ignored) { }
        });
        reader.start();
        writer.start();
        try {
            while (!done) {
                try {
                    reader.join(500);
                } catch (InterruptedException x) {
                    if (done) {
                        close(channel);
                        break;
                    }
                }
            }
        } finally {
            reader.interrupt();
            try {
                while (!done) {
                    try {
                        writer.join(500);
                    } catch (InterruptedException x) {
                        if (done) break;
                    }
                }
            } finally {
                writer.interrupt();
            }
        }
    }

    public ByteBuffer read() throws InterruptedException {
        readReady.await();
        return read.duplicate().asReadOnlyBuffer().flip();
    }

    public void open() throws IOException {
        err.println("Starting");
        if (!started.compareAndSet(false, true)) {
            throw new IllegalStateException("Already started");
        }
        ss = secure ? openWSS() : openWS();
        try {
            ss.bind(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0));
            address = (InetSocketAddress) ss.getLocalAddress();
            thread.start();
        } catch (IOException e) {
            done = true;
            close(ss);
            throw e;
        }
        err.println("Started at: " + getURI());
    }

    @Override
    public void close() {
        err.println("Stopping: " + getURI());
        done = true;
        thread.interrupt();
        close(ss);
    }

    URI getURI() {
        if (!started.get()) {
            throw new IllegalStateException("Not yet started");
        }
        if (!secure) {
            return URI.create("ws://localhost:" + address.getPort());
        } else {
            return URI.create("wss://localhost:" + address.getPort());
        }
    }

    private boolean readRequest(WebSocketChannel channel, StringBuilder request)
            throws IOException
    {
        ByteBuffer buffer = ByteBuffer.allocate(512);
        while (channel.read(buffer) != -1) {
            // read the complete HTTP request headers, there should be no body
            CharBuffer decoded;
            buffer.flip();
            try {
                decoded = ISO_8859_1.newDecoder().decode(buffer);
            } catch (CharacterCodingException e) {
                throw new UncheckedIOException(e);
            }
            request.append(decoded);
            if (Pattern.compile("\r\n\r\n").matcher(request).find())
                return true;
            buffer.clear();
        }
        return false;
    }

    private void writeResponse(WebSocketChannel channel, List<String> response)
            throws IOException
    {
        String s = response.stream().collect(Collectors.joining("\r\n"))
                + "\r\n\r\n";
        ByteBuffer encoded;
        try {
            encoded = ISO_8859_1.newEncoder().encode(CharBuffer.wrap(s));
        } catch (CharacterCodingException e) {
            throw new UncheckedIOException(e);
        }
        while (encoded.hasRemaining()) {
            channel.write(encoded);
        }
    }

    private static BiFunction<List<String>,Credentials,List<String>> defaultMapping() {
        return (request, credentials) -> {
            List<String> response = new LinkedList<>();
            Iterator<String> iterator = request.iterator();
            if (!iterator.hasNext()) {
                throw new IllegalStateException("The request is empty");
            }
            String statusLine = iterator.next();
            if (!(statusLine.startsWith("GET /") && statusLine.endsWith(" HTTP/1.1"))) {
                throw new IllegalStateException
                        ("Unexpected status line: " + request.get(0));
            }
            response.add("HTTP/1.1 101 Switching Protocols");
            Map<String, List<String>> requestHeaders = new HashMap<>();
            while (iterator.hasNext()) {
                String header = iterator.next();
                String[] split = header.split(": ");
                if (split.length != 2) {
                    throw new IllegalStateException
                            ("Unexpected header: " + header
                                     + ", split=" + Arrays.toString(split));
                }
                requestHeaders.computeIfAbsent(split[0], k -> new ArrayList<>()).add(split[1]);

            }
            if (requestHeaders.containsKey("Sec-WebSocket-Protocol")) {
                throw new IllegalStateException("Subprotocols are not expected");
            }
            if (requestHeaders.containsKey("Sec-WebSocket-Extensions")) {
                throw new IllegalStateException("Extensions are not expected");
            }
            expectHeader(requestHeaders, "Connection", "Upgrade");
            response.add("Connection: Upgrade");
            expectHeader(requestHeaders, "Upgrade", "websocket");
            response.add("Upgrade: websocket");
            expectHeader(requestHeaders, "Sec-WebSocket-Version", "13");
            List<String> key = requestHeaders.get("Sec-WebSocket-Key");
            if (key == null || key.isEmpty()) {
                throw new IllegalStateException("Sec-WebSocket-Key is missing");
            }
            if (key.size() != 1) {
                throw new IllegalStateException("Sec-WebSocket-Key has too many values : " + key);
            }
            MessageDigest sha1 = null;
            try {
                sha1 = MessageDigest.getInstance("SHA-1");
            } catch (NoSuchAlgorithmException e) {
                throw new InternalError(e);
            }
            String x = key.get(0) + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
            sha1.update(x.getBytes(ISO_8859_1));
            String v = Base64.getEncoder().encodeToString(sha1.digest());
            response.add("Sec-WebSocket-Accept: " + v);

            // check authorization credentials, if required by the server
            if (credentials != null && !authorized(credentials, requestHeaders)) {
                response.clear();
                response.add("HTTP/1.1 401 Unauthorized");
                response.add("Content-Length: 0");
                response.add("WWW-Authenticate: Basic realm=\"dummy server realm\"");
            }

            return response;
        };
    }

    // Checks credentials in the request against those allowable by the server.
    private static boolean authorized(Credentials credentials,
                                      Map<String,List<String>> requestHeaders) {
        List<String> authorization = requestHeaders.get("Authorization");
        if (authorization == null)
            return false;

        if (authorization.size() != 1) {
            throw new IllegalStateException("Authorization unexpected count:" + authorization);
        }
        String header = authorization.get(0);
        if (!header.startsWith("Basic "))
            throw new IllegalStateException("Authorization not Basic: " + header);

        header = header.substring("Basic ".length());
        String values = new String(Base64.getDecoder().decode(header), UTF_8);
        int sep = values.indexOf(':');
        if (sep < 1) {
            throw new IllegalStateException("Authorization not colon: " +  values);
        }
        String name = values.substring(0, sep);
        String password = values.substring(sep + 1);

        if (name.equals(credentials.name()) && password.equals(credentials.password()))
            return true;

        return false;
    }

    protected static String expectHeader(Map<String, List<String>> headers,
                                         String name,
                                         String value) {
        List<String> v = headers.get(name);
        if (v == null) {
            throw new IllegalStateException(
                    format("Expected '%s' header, not present in %s",
                           name, headers));
        }
        if (!v.contains(value)) {
            throw new IllegalStateException(
                    format("Expected '%s: %s', actual: '%s: %s'",
                           name, value, name, v)
            );
        }
        return value;
    }

    private static void close(AutoCloseable... acs) {
        for (AutoCloseable ac : acs) {
            try {
                ac.close();
            } catch (Exception ignored) { }
        }
    }
}