aboutsummaryrefslogtreecommitdiffstats
path: root/jrt/src/com/yahoo/jrt/MaybeTlsCryptoEngine.java
blob: cb80440ad6f309b36b20159714bb925fe0816e42 (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
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.jrt;

import java.nio.channels.SocketChannel;

/**
 * A crypto engine that supports both tls encrypted connections and
 * unencrypted connections. The use of tls for incoming connections is
 * auto-detected using clever heuristics. The use of tls for outgoing
 * connections is controlled by the useTlsWhenClient flag given to the
 * constructor.
 */
public class MaybeTlsCryptoEngine implements CryptoEngine {

    private final TlsCryptoEngine tlsEngine;
    private final boolean useTlsWhenClient;

    public MaybeTlsCryptoEngine(TlsCryptoEngine tlsEngine, boolean useTlsWhenClient) {
        this.tlsEngine = tlsEngine;
        this.useTlsWhenClient = useTlsWhenClient;
    }

    @Override
    public CryptoSocket createClientCryptoSocket(SocketChannel channel, Spec spec) {
        if (useTlsWhenClient) {
            return tlsEngine.createClientCryptoSocket(channel, spec);
        } else {
            return new NullCryptoSocket(channel, false);
        }
    }

    @Override
    public CryptoSocket createServerCryptoSocket(SocketChannel channel) {
        return new MaybeTlsCryptoSocket(channel, tlsEngine);
    }

    @Override
    public String toString() { return "MaybeTlsCryptoEngine(useTlsWhenClient:" + useTlsWhenClient + ")"; }

    @Override
    public void close() {
        tlsEngine.close();
    }
}